mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into fix/craft-libs-pin-language-packs
This commit is contained in:
commit
d368eb5359
62 files changed
+3930
-372
No files matched your search
+1
-1
@@ -124,7 +124,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips (#10659). Headline numbers unchanged.
|
||||
- 2026-12-03: View › Show Curvature Comb (`view.curvatureComb`) draws the curvature comb of the selected paths and compound paths: teeth along the normal as long as the curvature, and a line through their tips that starts again where the path turns back on itself at a cusp, a straight segment included (#10659). Headline numbers unchanged.
|
||||
|
||||
- 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied.
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ pub struct Selection {
|
||||
}
|
||||
|
||||
/// See [`Selection::symbol_part`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct SymbolPart {
|
||||
/// The symbol instance.
|
||||
pub instance: NodeId,
|
||||
|
||||
@@ -31,8 +31,8 @@ use super::super::edit::selected_roots;
|
||||
use super::super::graph::{capture_series_object_opacity, series_groups_among};
|
||||
use super::super::menucmds::whole_or;
|
||||
use super::super::object::{
|
||||
aligned_symbol_transforms, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform, scaling, transform_node,
|
||||
transform_patterns,
|
||||
aligned_symbol_transforms, choice, keep_aligned_in_with, keep_symbol_instances_aligned, object_bounds_transform, object_bounds_transform_keeping,
|
||||
refit_drawn, scaling, transform_node, transform_patterns,
|
||||
};
|
||||
use super::super::objects_on_path;
|
||||
use super::super::typecmd::refresh_bounds_of;
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swap Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected",
|
||||
"{size?: false (true: each also takes the other's width and height), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} swap the places (bounds centres) of the two selected objects, measured as object.setBounds measures them (Use Preview Bounds), as one undo step. Off unless exactly two objects are selected",
|
||||
exactly_two,
|
||||
swap
|
||||
),
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace with Top Object",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}",
|
||||
"{fit?: \"keep\" (the copy keeps its size) | \"bounds\" (scaled to the replaced object's width and height) | \"proportional\" (scaled to fit inside them, in proportion) (\"keep\"), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, keep?: false (true: the replaced objects stay, under their copies)} put a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order, as one undo step; sizes and centres are measured as object.setBounds measures them, and the copies are selected → {ids}",
|
||||
has_multi,
|
||||
replace
|
||||
),
|
||||
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Size of Each",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}",
|
||||
"{width?: pt, height?: pt (at least one; each 0.001..1000000), proportional?: false (with only one of them given, the other follows in proportion; else it stays), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the centre: the point of each object that stays put), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference} give each selected object (the top-level ones) that width and height, measured as object.setBounds measures them (Use Preview Bounds), as one undo step → {count}",
|
||||
has_selection,
|
||||
size
|
||||
),
|
||||
@@ -102,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Match Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
|
||||
"{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, corners?: the Scale Corners preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame after it is turned, with no smallest scale. The side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. A size that a target has no width or height to take, or that a stroke or an effect that does not scale keeps it from reaching, is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}",
|
||||
has_multi,
|
||||
match_objects
|
||||
),
|
||||
@@ -138,7 +138,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Sort Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}",
|
||||
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), corners?: the Scale Corners preference, ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}",
|
||||
has_multi,
|
||||
sort
|
||||
),
|
||||
@@ -173,10 +173,10 @@ fn size_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
|
||||
p.get(key).filter(|v| !v.is_null()).map(|_| number_in(p, key, 0.0, (LEAST, LIMIT), cmd)).transpose()
|
||||
}
|
||||
|
||||
/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes`
|
||||
/// and, when given, a width and height.
|
||||
fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value {
|
||||
let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes });
|
||||
/// `object.setBounds` params that centre an object on `at`, with Scale Strokes & Effects `strokes`,
|
||||
/// Scale Corners `corners` and, when given, a width and height.
|
||||
fn place(at: Point, size: Option<(f64, f64)>, strokes: bool, corners: bool) -> Value {
|
||||
let mut q = json!({ "x": at.x, "y": at.y, "reference": 4, "strokes": strokes, "corners": corners });
|
||||
if let Some((w, h)) = size {
|
||||
q["width"] = json!(w);
|
||||
q["height"] = json!(h);
|
||||
@@ -185,14 +185,15 @@ fn place(at: Point, size: Option<(f64, f64)>, strokes: bool) -> Value {
|
||||
}
|
||||
|
||||
/// Transform each object of `xfs` by its own transform as undo step `label`, strokes and effects
|
||||
/// scaling with Scale Strokes & Effects `strokes`, pattern tiles as Transform Pattern Tiles says.
|
||||
/// When every transform is (within rounding) the identity, nothing changes.
|
||||
fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, Affine)]) -> Result<()> {
|
||||
/// scaling with Scale Strokes & Effects `strokes`, corners with Scale Corners `corners`, pattern
|
||||
/// tiles as the command's params `p` or Transform Pattern Tiles say. When every transform is
|
||||
/// (within rounding) the identity, nothing changes.
|
||||
fn transform_each(s: &mut Session, label: &str, p: &Value, strokes: bool, corners: bool, xfs: &[(NodeId, Affine)]) -> Result<()> {
|
||||
let still = |xf: &Affine| xf.as_coeffs().iter().zip(Affine::IDENTITY.as_coeffs()).all(|(a, b)| (a - b).abs() <= 1e-9);
|
||||
if xfs.iter().all(|(_, xf)| still(xf)) {
|
||||
return Ok(());
|
||||
}
|
||||
let p = json!({ "strokes": strokes });
|
||||
let p = scaling_params(p, strokes, corners);
|
||||
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
|
||||
let mut sc = scaling(s, &p);
|
||||
sc.patterns = transform_patterns(s, &p, &ids)?;
|
||||
@@ -206,6 +207,17 @@ fn transform_each(s: &mut Session, label: &str, strokes: bool, xfs: &[(NodeId, A
|
||||
})
|
||||
}
|
||||
|
||||
/// The params [`scaling`] and [`transform_patterns`] read: Scale Strokes & Effects `strokes`, Scale
|
||||
/// Corners `corners`, and the `patterns` value of the command's params `p`. That one is absent on a
|
||||
/// first run, which takes the preference, and present when its journal entry is replayed.
|
||||
fn scaling_params(p: &Value, strokes: bool, corners: bool) -> Value {
|
||||
let mut q = json!({ "strokes": strokes, "corners": corners });
|
||||
if let Some(v) = p.get("patterns").filter(|v| v.is_boolean()) {
|
||||
q["patterns"] = v.clone();
|
||||
}
|
||||
q
|
||||
}
|
||||
|
||||
/// The `scaleStrokes` param, else the Scale Strokes & Effects preference. The value joins the
|
||||
/// command's journal entry, so replaying it scales the same way whatever the preference is then.
|
||||
fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
@@ -214,6 +226,14 @@ fn scale_strokes(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// The `corners` value of a replayed journal entry, else the Scale Corners preference. The value
|
||||
/// joins the command's journal entry, so replaying it scales corners the same way.
|
||||
fn scale_corners(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let on = switch_or(p, "corners", s.prefs.scale_corners, cmd)?;
|
||||
s.note_journal("corners", json!(on));
|
||||
Ok(on)
|
||||
}
|
||||
|
||||
/// The box of object `id` as `object.setBounds` measures it.
|
||||
fn box_of(s: &Session, id: NodeId) -> Result<OrientedBox> {
|
||||
s.transform_box(&[id]).ok_or_else(|| EngineError::Other("no bounds".into()))
|
||||
@@ -271,7 +291,7 @@ fn grid(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.enumerate()
|
||||
.filter_map(|(i, (id, b))| Some((*id, Affine::translate(Point::new(*xs.get(i % cols)?, *ys.get(i / cols)?) - b.center()))))
|
||||
.collect();
|
||||
transform_each(s, "Arrange in Grid", false, &xfs)?;
|
||||
transform_each(s, "Arrange in Grid", p, false, s.prefs.scale_corners, &xfs)?;
|
||||
Ok(json!({ "count": n }))
|
||||
}
|
||||
|
||||
@@ -308,7 +328,7 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !moves {
|
||||
return Ok(json!({ "count": items.len() }));
|
||||
}
|
||||
let p = json!({ "strokes": false });
|
||||
let p = scaling_params(p, false, s.prefs.scale_corners);
|
||||
let ids: Vec<NodeId> = items.iter().map(|(id, _, _)| *id).collect();
|
||||
let mut sc = scaling(s, &p);
|
||||
sc.patterns = transform_patterns(s, &p, &ids)?;
|
||||
@@ -362,12 +382,13 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.swap";
|
||||
let size = switch_or(p, "size", false, C)?;
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let corners = scale_corners(s, p, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let &[a, b] = roots.as_slice() else { return Err(bad(C, "select exactly two objects")) };
|
||||
let (ba, bb) = (box_of(s, a)?, box_of(s, b)?);
|
||||
let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes);
|
||||
let to = |o: &OrientedBox| place(o.center(), size.then(|| (o.rect.width(), o.rect.height())), strokes, corners);
|
||||
let xfs = [(a, object_bounds_transform(s, &to(&bb), a)?), (b, object_bounds_transform(s, &to(&ba), b)?)];
|
||||
transform_each(s, "Swap Objects", strokes, &xfs)?;
|
||||
transform_each(s, "Swap Objects", p, strokes, corners, &xfs)?;
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
@@ -375,6 +396,7 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.arrange.replace";
|
||||
let fit = choice(p, C, "fit", &["keep", "bounds", "proportional"])?.unwrap_or("keep");
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let corners = scale_corners(s, p, C)?;
|
||||
let keep = switch_or(p, "keep", false, C)?;
|
||||
let roots = selected_roots(s)?;
|
||||
let Some((&top, others)) = roots.split_last().filter(|(_, others)| !others.is_empty()) else {
|
||||
@@ -394,9 +416,9 @@ fn replace(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes), top)?));
|
||||
xfs.push((id, object_bounds_transform(s, &place(b.center(), size, strokes, corners), top)?));
|
||||
}
|
||||
let p = json!({ "strokes": strokes });
|
||||
let p = scaling_params(p, strokes, corners);
|
||||
let mut sc = scaling(s, &p);
|
||||
sc.patterns = transform_patterns(s, &p, &[top])?;
|
||||
let ids = s.edit("Replace with Top Object", |d, sel| {
|
||||
@@ -426,7 +448,8 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let proportional = switch_or(p, "proportional", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let mut q = json!({ "reference": reference, "strokes": strokes, "proportional": proportional && (width.is_none() || height.is_none()) });
|
||||
let corners = scale_corners(s, p, C)?;
|
||||
let mut q = json!({ "reference": reference, "strokes": strokes, "corners": corners, "proportional": proportional && (width.is_none() || height.is_none()) });
|
||||
if let Some(w) = width {
|
||||
q["width"] = json!(w);
|
||||
}
|
||||
@@ -439,7 +462,7 @@ fn size(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
xfs.push((id, object_bounds_transform(s, &q, id)?));
|
||||
}
|
||||
}
|
||||
transform_each(s, "Set Size of Each", strokes, &xfs)?;
|
||||
transform_each(s, "Set Size of Each", p, strokes, corners, &xfs)?;
|
||||
Ok(json!({ "count": xfs.len() }))
|
||||
}
|
||||
|
||||
@@ -471,6 +494,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stacking = switch_or(p, "stacking", false, C)?;
|
||||
let reference = whole_in(p, "reference", (0, 8), C)?.unwrap_or(4);
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let corners = scale_corners(s, p, C)?;
|
||||
let patterns = switch_or(p, "patterns", s.prefs.transform_pattern_tiles, C)?;
|
||||
if size == "none" && !rotate && !stacking {
|
||||
return Err(bad(C, "give `size`, `rotate` or `stacking`"));
|
||||
@@ -518,36 +542,19 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut q = q.clone();
|
||||
q["reference"] = json!(reference);
|
||||
q["strokes"] = json!(strokes);
|
||||
xf = object_bounds_transform(s, &q, id)?;
|
||||
q["corners"] = json!(corners);
|
||||
// Any scale the source's size asks for, however small.
|
||||
xf = object_bounds_transform_keeping(s, &q, id, 0.0)?;
|
||||
}
|
||||
// Rotation and the fit below keep the reference point in place.
|
||||
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
|
||||
let turned = Affine::rotate_about(-turn.to_radians(), at);
|
||||
if turn.abs() > 1e-9 {
|
||||
// Rotation uses the reference point that sizing keeps in place.
|
||||
let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize);
|
||||
xf = Affine::rotate_about(-turn.to_radians(), at) * xf;
|
||||
xf = turned * xf;
|
||||
}
|
||||
if wanted.is_some() {
|
||||
let sc = scaling(s, &json!({ "strokes": strokes }));
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let measure = |xf| {
|
||||
d.node(id).and_then(|n| {
|
||||
let mut n = n.clone();
|
||||
transform_node(&mut n, xf, sc, true);
|
||||
let frame = OrientedBox { angle: n.bbox_angle, rect: Rect::ZERO };
|
||||
effects::preview::bounds_in_with(&symbols, &n, frame.to_doc().inverse(), s.bounds_measure())
|
||||
})
|
||||
};
|
||||
let misses = |measured: Option<Rect>| {
|
||||
measured.is_none_or(|r| match size {
|
||||
"width" => (r.width() - w).abs() > 1e-6,
|
||||
"height" => (r.height() - h).abs() > 1e-6,
|
||||
_ => (r.width() - w).abs() > 1e-6 || (r.height() - h).abs() > 1e-6,
|
||||
})
|
||||
};
|
||||
// The sized and turned object, measured in its final frame, must have the size asked for.
|
||||
if misses(measure(xf)) {
|
||||
return Err(bad(C, format!("object {} can't take the requested size", id.0)));
|
||||
}
|
||||
let fit = Fit { at, refi: reference as usize, goal: match_goal(size, (w, h), b.rect), strokes, corners };
|
||||
xf = fit_turned(s, id, (xf, turned), fit).ok_or_else(|| bad(C, format!("object {} can't take the requested size", id.0)))?;
|
||||
}
|
||||
xfs.push((id, xf));
|
||||
}
|
||||
@@ -574,7 +581,7 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if xfs.is_empty() && !restack {
|
||||
return Ok(count);
|
||||
}
|
||||
let q = json!({ "strokes": strokes, "patterns": patterns });
|
||||
let q = json!({ "strokes": strokes, "corners": corners, "patterns": patterns });
|
||||
let ids: Vec<NodeId> = xfs.iter().map(|(id, _)| *id).collect();
|
||||
let mut sc = scaling(s, &q);
|
||||
sc.patterns = transform_patterns(s, &q, &ids)?;
|
||||
@@ -595,6 +602,88 @@ fn match_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// The size a target of Match Objects ends with: for `size` "width" ("height") the source's width
|
||||
/// `w` (height `h`), the other side following in proportion to the target's box `b`; for "both", the
|
||||
/// source's width and height.
|
||||
fn match_goal(size: &str, (w, h): (f64, f64), b: Rect) -> [f64; 2] {
|
||||
let follow = |side: f64, from: f64, to: f64| if from > 0.0 { side * to / from } else { side };
|
||||
match size {
|
||||
"width" => [w, follow(b.height(), b.width(), w)],
|
||||
"height" => [follow(b.width(), b.height(), h), h],
|
||||
_ => [w, h],
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`fit_turned`] fits a target of Match Objects to.
|
||||
struct Fit {
|
||||
/// The target's reference point, which stays in place.
|
||||
at: Point,
|
||||
/// That point's index on the 9-point grid.
|
||||
refi: usize,
|
||||
/// The width and height wanted ([`match_goal`]).
|
||||
goal: [f64; 2],
|
||||
/// Scale Strokes & Effects.
|
||||
strokes: bool,
|
||||
/// Scale Corners.
|
||||
corners: bool,
|
||||
}
|
||||
|
||||
/// `xf`, which sizes and turns object `id`, made to give the object the size `fit.goal` (within
|
||||
/// 1e-9 of the larger of 1 and each side) as `object.setBounds` measures it in the frame the object
|
||||
/// ends in. When it misses, for example when a stroke or an effect does not turn with the art,
|
||||
/// scales in that frame are fitted with [`refit_drawn`] from the object turned by `turned` alone,
|
||||
/// and point `fit.refi` of the fitted box goes to `fit.at`. The object is measured before Align to
|
||||
/// Pixel Grid snaps it, as every transform snaps it after. `None` when no scale gives the size.
|
||||
fn fit_turned(s: &mut Session, id: NodeId, (xf, turned): (Affine, Affine), fit: Fit) -> Option<Affine> {
|
||||
let Fit { at, refi, goal, strokes, corners } = fit;
|
||||
let sc = scaling(s, &json!({ "strokes": strokes, "corners": corners }));
|
||||
let how = s.bounds_measure();
|
||||
let d = &s.doc().ok()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let n = d.node(id)?;
|
||||
let moved = |xf: Affine| {
|
||||
let mut n = n.clone();
|
||||
n.transform(xf, sc);
|
||||
n
|
||||
};
|
||||
// The angle the object's box ends at after `xf`, as `Node::transform` sets it (a layer keeps its own).
|
||||
let angle_after = |xf: Affine| if n.is_layer() { n.bbox_angle } else { vectorcraft_doc::orient::transformed_angle(n.bbox_angle, xf) };
|
||||
// The frame the turn gives; sizing can leave the art without a width or a height to show it.
|
||||
let frame = OrientedBox { angle: angle_after(turned), rect: Rect::ZERO };
|
||||
let to_local = frame.to_doc().inverse();
|
||||
let measure = |xf: Affine| effects::preview::bounds_in_with(&symbols, &moved(xf), to_local, how);
|
||||
let tolerances = goal.map(|side| 1e-9 * side.max(1.0));
|
||||
let fits = |r: Rect| [r.width(), r.height()].into_iter().zip(goal).zip(tolerances).all(|((v, g), t)| (v - g).abs() <= t);
|
||||
let keeps_angle = |xf: Affine| vectorcraft_geom::normalize_deg(angle_after(xf) - frame.angle).abs() <= 1e-6;
|
||||
let rp = frame.to_local(at);
|
||||
// The object turned by `turned`, then scaled by `sx` and `sy` in the frame about the reference point.
|
||||
let scaled = |sx: f64, sy: f64| {
|
||||
frame.conjugate(Affine::translate(rp.to_vec2()) * Affine::scale_non_uniform(sx, sy) * Affine::translate(-rp.to_vec2())) * turned
|
||||
};
|
||||
// `xf` with point `refi` of the box as measured moved to the reference point's place: a stroke
|
||||
// or an effect that does not turn with the art moves it.
|
||||
let placed = |xf: Affine| -> Option<(Affine, Rect)> {
|
||||
let b = measure(xf)?;
|
||||
let correction = rp - vectorcraft_geom::reference_point(b, refi);
|
||||
if correction.x.abs() <= 1e-12 && correction.y.abs() <= 1e-12 {
|
||||
return Some((xf, b));
|
||||
}
|
||||
let xf = frame.conjugate(Affine::translate(correction)) * xf;
|
||||
Some((xf, measure(xf)?))
|
||||
};
|
||||
let accepts = |xf: Affine, b: Rect| fits(b) && keeps_angle(xf);
|
||||
if let Some((xf, _)) = placed(xf).filter(|(xf, b)| accepts(*xf, *b)) {
|
||||
return Some(xf);
|
||||
}
|
||||
// The sizing above can leave the art without a width or a height that the turned object needs,
|
||||
// so the fit starts again from the object as it is, turned.
|
||||
let now = measure(turned)?;
|
||||
let ratio = |g: f64, v: f64| if v > 1e-9 { g / v } else { 1.0 };
|
||||
let start = (ratio(goal[0], now.width()), ratio(goal[1], now.height()));
|
||||
let (sx, sy, _) = refit_drawn(|sx, sy| measure(scaled(sx, sy)), refi, goal, start, [true, true], Some(tolerances))?;
|
||||
placed(scaled(sx, sy)).filter(|(xf, b)| accepts(*xf, *b)).map(|(xf, _)| xf)
|
||||
}
|
||||
|
||||
/// The sets of two or more of `items` (each in the order given) whose rects overlap or touch,
|
||||
/// chains included, among items of the same key (parent). A sweep along x: only the rects still
|
||||
/// open where each one starts are compared with it.
|
||||
@@ -841,6 +930,7 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let distribute = switch_or(p, "distribute", false, C)?;
|
||||
let mut rng = Rng::new(whole_or(p, "seed", 0, C)?);
|
||||
let strokes = scale_strokes(s, p, C)?;
|
||||
let corners = scale_corners(s, p, C)?;
|
||||
let ids = checked_ids_or_selection(s, p, C)?;
|
||||
if ids.len() > MAX_OBJECTS {
|
||||
return Err(bad(C, "too many objects selected (at most 20000)"));
|
||||
@@ -923,17 +1013,17 @@ fn sort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let q = match apply {
|
||||
"x" => json!({ "x": v, "reference": 0 }),
|
||||
"y" => json!({ "y": v, "reference": 0 }),
|
||||
"width" => json!({ "width": v, "strokes": strokes }),
|
||||
"height" => json!({ "height": v, "strokes": strokes }),
|
||||
"width" => json!({ "width": v, "strokes": strokes, "corners": corners }),
|
||||
"height" => json!({ "height": v, "strokes": strokes, "corners": corners }),
|
||||
// An area: both sides in proportion; an object without one keeps its size.
|
||||
_ => {
|
||||
let (w, h) = (o.b.rect.width(), o.b.rect.height());
|
||||
let k = if w * h > 1e-12 { (v / (w * h)).sqrt() } else { 1.0 };
|
||||
json!({ "width": w * k, "height": h * k, "strokes": strokes })
|
||||
json!({ "width": w * k, "height": h * k, "strokes": strokes, "corners": corners })
|
||||
}
|
||||
};
|
||||
xfs.push((o.id, object_bounds_transform(s, &q, o.id)?));
|
||||
}
|
||||
transform_each(s, "Sort Objects", strokes, &xfs)?;
|
||||
transform_each(s, "Sort Objects", p, strokes, corners, &xfs)?;
|
||||
Ok(count)
|
||||
}
|
||||
@@ -439,6 +439,19 @@ fn match_gives_the_others_the_key_objects_size() {
|
||||
assert!(near(bounds(&s, c), (196.6666666666667, -10.0, 13.333333333333334, 40.0)), "{:?}", bounds(&s, c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_keeps_the_proportion_of_a_very_thin_target() {
|
||||
let b = Rect::new(0.0, 0.0, 1e-10, 1.0);
|
||||
let [w, h] = super::match_goal("width", (1.0, 5.0), b);
|
||||
assert_eq!(w, 1.0);
|
||||
assert!((h - 1e10).abs() <= 1.0, "{h}");
|
||||
let [w, h] = super::match_goal("height", (5.0, 1.0), Rect::new(0.0, 0.0, 1.0, 1e-10));
|
||||
assert!((w - 1e10).abs() <= 1.0, "{w}");
|
||||
assert_eq!(h, 1.0);
|
||||
// A target with no width keeps its height.
|
||||
assert_eq!(super::match_goal("width", (1.0, 5.0), Rect::new(0.0, 0.0, 0.0, 3.0)), [1.0, 3.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_takes_the_top_or_the_bottom_object_without_a_key() {
|
||||
let mut s = session();
|
||||
@@ -638,6 +651,44 @@ fn replays_the_stroke_scaling_it_ran_with(cmd: &str, p: Value) {
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", weight(&s));
|
||||
}
|
||||
|
||||
/// Running `cmd` with Scale Corners on doubles the 2 pt corner radius of a 10 pt rounded square,
|
||||
/// and replaying its journal entry after the preference is turned off scales the corners the same way.
|
||||
fn replays_the_corner_scaling_it_ran_with(cmd: &str, p: Value) {
|
||||
let mut s = session();
|
||||
let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10, "radius": 2})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
|
||||
let radius = |s: &Session| match s.doc().unwrap().doc.node(a).unwrap().live_shape() {
|
||||
Some(vectorcraft_doc::LiveShape::Rectangle { radii, xf, .. }) => radii[0] * xf.as_coeffs()[0],
|
||||
_ => panic!("not a live rectangle"),
|
||||
};
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap();
|
||||
s.execute(cmd, &p).unwrap();
|
||||
assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd}: {}", radius(&s));
|
||||
let (id, q) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(id, cmd);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
s.replay(&id, &q).unwrap();
|
||||
assert!((radius(&s) - 4.0).abs() < 1e-9, "{cmd} replayed: {}", radius(&s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_replays_with_the_corner_scaling_it_ran_with() {
|
||||
replays_the_corner_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_size_of_each_replays_with_the_corner_scaling_it_ran_with() {
|
||||
replays_the_corner_scaling_it_ran_with("addon.arrange.size", json!({"width": 20, "height": 20}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_replays_with_the_corner_scaling_it_ran_with() {
|
||||
replays_the_corner_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_stacking_leaves_a_clipping_path_in_place() {
|
||||
let mut s = session();
|
||||
@@ -664,6 +715,16 @@ fn match_size_refuses_a_target_with_no_width() {
|
||||
assert!((bounds(&s, line).height() - 20.0).abs() < 1e-6, "{:?}", bounds(&s, line));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_refuses_a_target_with_no_width_for_a_narrow_tall_source() {
|
||||
let mut s = session();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 0, "y2": 50})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 100.0, 0.0, 0.05, 100000.0);
|
||||
select(&mut s, &[line, b]);
|
||||
s.execute("select.key", &json!({"id": b.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both"})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_uses_preview_bounds_for_a_target_with_no_geometric_width() {
|
||||
let mut s = session();
|
||||
@@ -765,6 +826,169 @@ fn swap_replays_with_the_stroke_scaling_it_ran_with() {
|
||||
replays_the_stroke_scaling_it_ran_with("addon.arrange.swap", json!({"size": true}));
|
||||
}
|
||||
|
||||
/// Running `cmd` with Scale Corners on scales the 2 pt corners of two rounded squares with them,
|
||||
/// and replaying its journal entry after the preference is turned off scales them the same way.
|
||||
fn replays_the_corner_shapes_it_ran_with(cmd: &str, p: Value) {
|
||||
let mut s = session();
|
||||
let square = |s: &mut Session, x: f64, w: f64| {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": w, "height": w, "radius": 2})).unwrap()["id"].as_u64().unwrap())
|
||||
};
|
||||
let a = square(&mut s, 0.0, 10.0);
|
||||
let b = square(&mut s, 100.0, 20.0);
|
||||
let shapes = |s: &Session| {
|
||||
let mut out = vec![];
|
||||
s.doc().unwrap().doc.walk(|n| out.push(format!("{:?}", n.kind)));
|
||||
out.sort();
|
||||
out
|
||||
};
|
||||
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": true})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
s.execute(cmd, &p).unwrap();
|
||||
let ran = shapes(&s);
|
||||
let (id, q) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(id, cmd);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("prefs.set", &json!({"key": "scaleCorners", "value": false})).unwrap();
|
||||
select(&mut s, &[a, b]);
|
||||
s.replay(&id, &q).unwrap();
|
||||
assert_eq!(shapes(&s), ran, "{cmd} replayed with other corners");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_replays_two_rounded_squares_with_the_corners_it_ran_with() {
|
||||
replays_the_corner_shapes_it_ran_with("addon.arrange.match", json!({"size": "both"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_size_of_each_replays_two_rounded_squares_with_the_corners_it_ran_with() {
|
||||
replays_the_corner_shapes_it_ran_with("addon.arrange.size", json!({"width": 30, "height": 30}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_replays_two_rounded_squares_with_the_corners_it_ran_with() {
|
||||
replays_the_corner_shapes_it_ran_with("addon.arrange.swap", json!({"size": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_replays_with_the_corner_scaling_it_ran_with() {
|
||||
replays_the_corner_shapes_it_ran_with("addon.arrange.replace", json!({"fit": "bounds"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_reaches_a_size_that_pixel_alignment_then_snaps() {
|
||||
let mut s = session();
|
||||
let target = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[target]);
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let source = rect(&mut s, 100.0, 0.0, 15.5, 15.5);
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "width"})).unwrap();
|
||||
let b = bounds(&s, target);
|
||||
assert!((b.width() - 15.5).abs() <= 1.0 && (b.height() - 15.5).abs() <= 1.0, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_fits_a_transform_copy_once_the_target_is_turned() {
|
||||
for size in ["width", "both"] {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap();
|
||||
let source = rect(&mut s, 100.0, 0.0, 30.0, 20.0);
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
let wanted = s.transform_box(&[source]).unwrap();
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": size, "rotate": true, "scaleStrokes": false})).unwrap();
|
||||
let measured = s.transform_box(&[target]).unwrap();
|
||||
assert!((measured.angle - wanted.angle).abs() < 1e-6, "{size}: {measured:?}");
|
||||
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}");
|
||||
if size == "both" {
|
||||
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {measured:?} {wanted:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_fits_a_turned_target_whose_copy_fills_the_height_before_the_turn() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveV": 10, "copies": 1}})).unwrap();
|
||||
let source = rect(&mut s, 100.0, 0.0, 20.0, 5.0);
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
let wanted = s.transform_box(&[source]).unwrap();
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap();
|
||||
let measured = s.transform_box(&[target]).unwrap();
|
||||
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}");
|
||||
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_keeps_the_center_of_a_turned_target_whose_copy_stays_on_the_page() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let target = rect(&mut s, 0.0, 0.0, 2000.0, 20.0);
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 10, "copies": 1}})).unwrap();
|
||||
let center = s.transform_box(&[target]).unwrap().center();
|
||||
let source = rect(&mut s, 100.0, 100.0, 11.0, 20.0);
|
||||
s.execute("object.rotate", &json!({"angle": 180})).unwrap();
|
||||
let wanted = s.transform_box(&[source]).unwrap();
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both", "rotate": true, "scaleStrokes": false})).unwrap();
|
||||
let measured = s.transform_box(&[target]).unwrap();
|
||||
assert!((measured.rect.width() - wanted.rect.width()).abs() < 1e-6, "{measured:?} {wanted:?}");
|
||||
assert!((measured.rect.height() - wanted.rect.height()).abs() < 1e-6, "{measured:?} {wanted:?}");
|
||||
assert!((measured.center() - center).hypot() < 1e-6, "{measured:?} {center:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_refuses_a_width_below_a_fixed_transform_copy() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "item": null, "params": {"moveH": 100000.05, "copies": 1}})).unwrap();
|
||||
let before = s.transform_box(&[target]).unwrap();
|
||||
assert!((before.rect.width() - 100020.05).abs() < 1e-6, "{before:?}");
|
||||
let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0);
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
let out = s.execute("addon.arrange.match", &json!({"size": "both", "scaleStrokes": false}));
|
||||
assert!(out.is_err(), "{out:?} {:?}", s.transform_box(&[target]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_refuses_dimensions_a_fixed_rotated_copy_cannot_reach_together() {
|
||||
let mut s = session();
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let target = rect(&mut s, 0.0, 0.0, 20.0, 20.0);
|
||||
s.execute(
|
||||
"effect.apply",
|
||||
&json!({"effect": "distort.transform", "item": null, "params": {"rotate": 90, "reference": 4, "moveH": 99990.05, "copies": 1}}),
|
||||
)
|
||||
.unwrap();
|
||||
let source = rect(&mut s, 0.0, 100.0, 100000.0, 20.0);
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
refuses(&mut s, "addon.arrange.match", &[json!({"size": "both", "scaleStrokes": false})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_size_takes_a_huge_object_down_to_a_point() {
|
||||
let mut s = session();
|
||||
let target = rect(&mut s, 0.0, 0.0, 20000.0, 20000.0);
|
||||
let source = rect(&mut s, 100.0, 0.0, 1.0, 1.0);
|
||||
select(&mut s, &[target, source]);
|
||||
s.execute("select.key", &json!({"id": source.0})).unwrap();
|
||||
s.execute("addon.arrange.match", &json!({"size": "both"})).unwrap();
|
||||
let b = bounds(&s, target);
|
||||
assert!((b.width() - 1.0).abs() < 1e-6 && (b.height() - 1.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_refuses_bad_params() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -29,6 +29,14 @@ const ENVELOPES: &str = "CDR envelopes were not applied, and the shapes under th
|
||||
const LENSES: &str = "CDR lenses and object transparency were not applied, and the objects they are on show opaque";
|
||||
const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the import limits, were left out";
|
||||
const DAMAGED: &str = "damaged parts of the drawing were left out";
|
||||
/// Shown with [`UNSUPPORTED_OBJECTS`] or [`TOO_DEEP`]: `craft-cdr` opens a PowerClip frame whose
|
||||
/// contents were all left out as a plain shape. Its warnings name neither the kinds of objects
|
||||
/// left out nor the frames that lost their contents, so this line is shown whenever objects were
|
||||
/// left out. Once `craft-cdr` reports which frames lost their contents, show it only for those.
|
||||
const EMPTY_FRAMES: &str = "CDR PowerClip frames whose contents were left out opened empty, as plain shapes";
|
||||
/// The first version, in hundreds, whose PowerClip frames `craft-cdr` reads: earlier versions
|
||||
/// store their objects' styles inline, and the reader opens none of them as frames.
|
||||
const FRAMES_FROM: u16 = 400;
|
||||
const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard";
|
||||
|
||||
const CMX_UNSUPPORTED_OBJECTS: &str =
|
||||
@@ -103,7 +111,11 @@ pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec<String>)> {
|
||||
}
|
||||
why => err(format!("this CDR drawing can't be read ({why})")),
|
||||
})?;
|
||||
Ok(build(&d, note, PAGES_CUT))
|
||||
let (doc, mut warnings) = build(&d, note, PAGES_CUT);
|
||||
if d.version >= FRAMES_FROM && d.warnings.iter().any(|w| matches!(w, Warning::UnsupportedObjects | Warning::TooDeep)) {
|
||||
warnings.push(EMPTY_FRAMES.to_string());
|
||||
}
|
||||
Ok((doc, warnings))
|
||||
}
|
||||
|
||||
/// Is `bytes` a `.cmx` file, of any byte order or coordinate size?
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignPro
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
|
||||
@@ -176,8 +176,8 @@ impl LoadOptions {
|
||||
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
|
||||
}
|
||||
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
|
||||
/// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default,
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible
|
||||
/// `.ai` with Illustrator private data opens on its trim boxes by default,
|
||||
/// with the bleed around them. An explicit crop-box request uses its crop box.
|
||||
fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result<ImportOptions> {
|
||||
let pages = match &self.pages {
|
||||
@@ -257,7 +257,7 @@ pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool {
|
||||
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
|
||||
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
|
||||
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box;
|
||||
/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the
|
||||
/// a PDF-compatible `.ai` that names no box gets its trim box, as it opens), in a row from the
|
||||
/// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box,
|
||||
/// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the
|
||||
/// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens
|
||||
@@ -289,8 +289,9 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa
|
||||
Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?,
|
||||
};
|
||||
let bounding = o.crop == CropTo::Bounding;
|
||||
// A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]).
|
||||
let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop };
|
||||
// A PDF-compatible `.ai` that names no box opens on its trim boxes ([`LoadOptions::import_options`]);
|
||||
// an explicit crop-box request keeps its crop boxes.
|
||||
let crop = if !o.explicit_crop_box && o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop };
|
||||
let mut doc = Document::new(1.0, 1.0);
|
||||
let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?;
|
||||
doc.artboards.clear();
|
||||
|
||||
@@ -89,6 +89,8 @@ fn versions_3_and_4_open_and_place_as_editable_art() {
|
||||
assert_eq!(r["format"], "cdr", "{version} {name}");
|
||||
let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect();
|
||||
assert!(w.iter().any(|w| w.contains("text, bitmaps")) && !w.iter().any(|w| w.contains("damaged")), "{version}: {w:?}");
|
||||
// The reader opens PowerClip frames from version 4 on.
|
||||
assert_eq!(w.iter().any(|w| w.contains("PowerClip")), version >= 400, "{version}: {w:?}");
|
||||
}
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0), "{version}");
|
||||
@@ -535,6 +537,35 @@ fn containers_open_as_clipping_groups() {
|
||||
assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })));
|
||||
}
|
||||
|
||||
/// A container whose clipped group holds only objects the reader leaves out (a bitmap here), or
|
||||
/// whose group holds a container of that same group, opens as a plain shape, and the warnings
|
||||
/// say that such frames opened empty.
|
||||
#[test]
|
||||
fn containers_whose_contents_were_left_out_are_named_in_the_warnings() {
|
||||
let v = V(1100);
|
||||
let rect = |w: f64, extra: Vec<(u32, Vec<u8>)>| {
|
||||
let mut args = vec![(30, v.rect(w, w, 0.0))];
|
||||
args.extend(extra);
|
||||
synth::object(v, 1, &args, None)
|
||||
};
|
||||
let open = |clipped: Vec<synth::Node>| {
|
||||
let doc = list(b"doc ", vec![synth::clpt(vec![(5, clipped)])]);
|
||||
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(5)])])]);
|
||||
super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap()
|
||||
};
|
||||
let frames = "PowerClip frames whose contents were left out opened empty";
|
||||
let (doc, warnings) = open(vec![synth::object(v, 5, &[(30, v.rect(10.0, 10.0, 0.0))], None)]);
|
||||
let p = paths(&doc);
|
||||
let [frame] = p.as_slice() else { panic!("{p:?}") };
|
||||
assert!(matches!(frame.kind, NodeKind::Path { clipping: false, .. }), "{:?}", frame.kind);
|
||||
assert!(warnings.iter().any(|w| w.contains("text, bitmaps")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}");
|
||||
// The inner container names the group already being read, so it is left out at the limit.
|
||||
let (_, warnings) = open(vec![rect(10.0, vec![synth::container(5)])]);
|
||||
assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains(frames)), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// An object with a lens or transparency opens opaque, and the warnings say so.
|
||||
#[test]
|
||||
fn lenses_and_transparency_are_named_in_the_warnings() {
|
||||
|
||||
@@ -377,6 +377,11 @@ impl DocSettings {
|
||||
/// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id.
|
||||
fn layout_params(&mut self, l: &Value, cmd: &str, replaying: bool) -> Result<()> {
|
||||
let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column");
|
||||
// The columns that rows give the artboards as they are now, which a layout that replaces the
|
||||
// rows without its own `columns` keeps.
|
||||
if self.grid_rows().is_some() {
|
||||
self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX);
|
||||
}
|
||||
if let Some(id) = l.as_str() {
|
||||
self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?;
|
||||
if self.layout != ArtboardLayout::GridByColumn {
|
||||
|
||||
@@ -33,7 +33,7 @@ mod transform;
|
||||
|
||||
pub(crate) use align::choice;
|
||||
pub(crate) use arrange::group_nodes;
|
||||
pub(crate) use bounds::{bounds_rewrite, object_bounds_transform};
|
||||
pub(crate) use bounds::{bounds_rewrite, object_bounds_transform, object_bounds_transform_keeping, refit_drawn};
|
||||
pub use commands::specs;
|
||||
pub(super) use compound::{as_clipping_path, copy_transparency, make_clipping_path, release_clip};
|
||||
pub(crate) use pixelgrid::{
|
||||
|
||||
@@ -45,7 +45,13 @@ pub(crate) fn bounds_rewrite(s: &Session, cmd: &str, params: &Value) -> Option<(
|
||||
/// `object.setBounds` measures them (Use Preview Bounds, `strokes`, `reference`, `proportional`),
|
||||
/// whatever anchors are direct-selected. The art keeps at least 1e-4 of its width and height.
|
||||
pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Result<Affine> {
|
||||
match bounds_transform(s, p, vec![id], 1e-4, false)? {
|
||||
object_bounds_transform_keeping(s, p, id, 1e-4)
|
||||
}
|
||||
|
||||
/// [`object_bounds_transform`] with the art keeping at least `least` of its width and height
|
||||
/// (0: any scale the values ask for).
|
||||
pub(crate) fn object_bounds_transform_keeping(s: &Session, p: &Value, id: NodeId, least: f64) -> Result<Affine> {
|
||||
match bounds_transform(s, p, vec![id], least, false)? {
|
||||
Bounds::Objects(_, xf) => Ok(xf),
|
||||
Bounds::Anchors(..) => Err(EngineError::Other("no bounds".into())),
|
||||
}
|
||||
@@ -163,7 +169,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
// smaller than that reach. Strokes and effects that scale shrink the reach with the art, so
|
||||
// the search then starts from the size wanted over the size as drawn.
|
||||
let seed = |s: f64, size: f64, now: f64| if s <= 0.0 && size > 0.0 && now > 1e-9 { size / now } else { s };
|
||||
refit_drawn(measure, refi, [w, h], (seed(sx, w, v.width()), seed(sy, h, v.height())), [g.width() > 1e-9, g.height() > 1e-9])
|
||||
refit_drawn(measure, refi, [w, h], (seed(sx, w, v.width()), seed(sy, h, v.height())), [g.width() > 1e-9, g.height() > 1e-9], None)
|
||||
} else {
|
||||
Spans::measure(d, &ids, &frame, strokes).refit(rp, refi, [w, h], (sx, sy, new_rp))
|
||||
};
|
||||
@@ -186,26 +192,31 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
/// change with the y scale and the height with the x scale (a geometry effect can turn the art). A
|
||||
/// scale that `free` marks false stays as it is. The search stops when both sizes are within 1e-9
|
||||
/// of the sizes wanted (of the largest of 1 and those sizes), when no scale moves, when `measure`
|
||||
/// finds no box, or after 16 steps, and returns the scales that came nearest. `None` when `measure`
|
||||
/// finds no box for `start`.
|
||||
fn refit_drawn(
|
||||
/// finds no box, or after 16 steps. It returns the scales whose box met both stopping tolerances,
|
||||
/// and otherwise the scales whose box came nearest. `None` when `measure`
|
||||
/// finds no box for `start`. Each stopping tolerance in `tolerances`, when given, is capped at
|
||||
/// the default tolerance.
|
||||
pub(crate) fn refit_drawn(
|
||||
measure: impl Fn(f64, f64) -> Option<Rect>,
|
||||
refi: usize,
|
||||
size: [f64; 2],
|
||||
start: (f64, f64),
|
||||
free: [bool; 2],
|
||||
tolerances: Option<[f64; 2]>,
|
||||
) -> Option<(f64, f64, Point)> {
|
||||
let [w, h] = size;
|
||||
let tolerance = 1e-9 * w.max(h).max(1.0);
|
||||
let tolerances = tolerances.unwrap_or([tolerance; 2]).map(|t| t.min(tolerance));
|
||||
let miss = |b: Rect| (b.width() - w).abs() + (b.height() - h).abs();
|
||||
let met = |b: Rect| (b.width() - w).abs() <= tolerances[0] && (b.height() - h).abs() <= tolerances[1];
|
||||
let (mut sx, mut sy) = start;
|
||||
let mut b = measure(sx, sy)?;
|
||||
let mut best = (sx, sy, b);
|
||||
for _ in 0..16 {
|
||||
let f = [b.width() - w, b.height() - h];
|
||||
if f[0].abs() <= tolerance && f[1].abs() <= tolerance {
|
||||
if met(b) {
|
||||
break;
|
||||
}
|
||||
let f = [b.width() - w, b.height() - h];
|
||||
// How the width and the height change with the x scale (`a`) and the y scale (`c`).
|
||||
let change = |x: bool| -> Option<[f64; 2]> {
|
||||
let (on, s) = if x { (free[0], sx) } else { (free[1], sy) };
|
||||
@@ -235,7 +246,8 @@ fn refit_drawn(
|
||||
}
|
||||
let Some(next) = measure(nx, ny) else { break };
|
||||
(sx, sy, b) = (nx, ny, next);
|
||||
if miss(b) < miss(best.2) {
|
||||
// A box that meets both tolerances wins over a nearer sum that misses one of them.
|
||||
if met(b) || miss(b) < miss(best.2) {
|
||||
best = (sx, sy, b);
|
||||
}
|
||||
}
|
||||
@@ -291,3 +303,28 @@ fn scaling_box(d: &Document, ids: &[NodeId], frame: &OrientedBox) -> Option<Rect
|
||||
vectorcraft_geom::union_opt(acc, b)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Rect, refit_drawn};
|
||||
|
||||
#[test]
|
||||
fn refit_drawn_prefers_the_box_that_meets_both_tolerances() {
|
||||
// The start box is 2e-6 too wide (outside the 1e-9 width tolerance). The step lands on the
|
||||
// right width with the height 3e-6 too tall (inside the 1e-4 height tolerance), a larger
|
||||
// summed miss than the start's.
|
||||
let measure = |sx: f64, _sy: f64| {
|
||||
let width = 0.05 * sx + 2e-6;
|
||||
let height = if sx < 1.0 { 100_000.000_003 } else { 100_000.0 };
|
||||
Some(Rect::new(0.0, 0.0, width, height))
|
||||
};
|
||||
let tolerances = [1e-9, 1e-4];
|
||||
let Some((sx, _, _)) = refit_drawn(measure, 0, [0.05, 100_000.0], (1.0, 1.0), [true, false], Some(tolerances)) else {
|
||||
panic!("refit_drawn found no box");
|
||||
};
|
||||
assert!(sx < 1.0, "the start scale came back: {sx}");
|
||||
let Some(b) = measure(sx, 1.0) else { panic!("no box") };
|
||||
assert!((b.width() - 0.05).abs() <= tolerances[0], "width {}", b.width());
|
||||
assert!((b.height() - 100_000.0).abs() <= tolerances[1], "height {}", b.height());
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Run Script",
|
||||
[],
|
||||
None,
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properti
Line truncated
|
||||
"{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); Document.rasterize, Document.imageCapture, Document.saveAs and Document.exportFile forward command warnings to the Script Console with the method name; app.open reads ancillary files only within the script's read grants, without inherited link permissions; $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with both the color and its model unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist,
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Script Palette Event",
|
||||
[],
|
||||
None,
|
||||
"{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler",
|
||||
"{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, and a change only if no click or close of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when a script added or removed the list's items, or changed an item's text, by then, even if the list again holds the same texts; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; when a waiting event's run cannot begin in the app, the status bar shows the error and the events in line wait until the next input in the window, another script.palette.event, or a change to a document's unsaved state, drag or undo group, to the active document, or to the recoveryFolder or recoveryOffForComplex preference; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error; an event whose run starts and finds its control, or a group above it, disabled or hidden by a getter read for the palette, or whose `enabled` or `visible` state a getter gives, runs no handler",
|
||||
always,
|
||||
palette_event
|
||||
),
|
||||
|
||||
@@ -5,12 +5,14 @@
|
||||
//! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the
|
||||
//! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and
|
||||
//! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel.
|
||||
//! `app.showColorPicker(color)` ([`show_color_picker`]) opens the Color Picker on a color and
|
||||
//! returns the color picked for OK, or a new object of the color it was given for Cancel.
|
||||
//!
|
||||
//! In the app the run waits at the call for the person's answer, and spends no fuel while it
|
||||
//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with
|
||||
//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no
|
||||
//! answer left, or with the next answer for another kind of dialog, ends the run. The report's
|
||||
//! `dialogs` lists each dialog and its answer.
|
||||
//! waits; every dialog but the Color Picker also has Stop, which ends the run and puts
|
||||
//! everything back. A run with nobody to ask takes its answers, in order, from `script.run`'s
|
||||
//! `answers`; a call with no answer left, or with the next answer for another kind of dialog,
|
||||
//! ends the run. The report's `dialogs` lists each dialog and its answer.
|
||||
//!
|
||||
//! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`],
|
||||
//! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and
|
||||
@@ -21,6 +23,7 @@ use std::collections::VecDeque;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind};
|
||||
|
||||
use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep};
|
||||
@@ -51,22 +54,34 @@ pub enum DialogKind {
|
||||
Prompt,
|
||||
/// A ScriptUI dialog's `show()` ([`super::scriptui`]).
|
||||
Window,
|
||||
/// `app.showColorPicker`.
|
||||
ColorPicker,
|
||||
}
|
||||
|
||||
impl DialogKind {
|
||||
/// The function's name, which is also the `kind` of an answer and of a report's dialog.
|
||||
/// The `kind` of an answer and of a report's dialog, which is also the function's name for
|
||||
/// `alert`, `confirm` and `prompt`.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Alert => "alert",
|
||||
Self::Confirm => "confirm",
|
||||
Self::Prompt => "prompt",
|
||||
Self::Window => "window",
|
||||
Self::ColorPicker => "colorPicker",
|
||||
}
|
||||
}
|
||||
|
||||
/// The function's name, as its errors give it.
|
||||
fn function(self) -> &'static str {
|
||||
match self {
|
||||
Self::ColorPicker => "showColorPicker",
|
||||
k => k.id(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A dialog a script opened, which waits for its answer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ScriptDialog {
|
||||
pub kind: DialogKind,
|
||||
pub message: String,
|
||||
@@ -78,10 +93,15 @@ pub struct ScriptDialog {
|
||||
pub no_as_default: bool,
|
||||
/// `prompt`: the text its field starts with.
|
||||
pub preset: String,
|
||||
/// `showColorPicker`: the color the picker starts with. `None` for the other dialogs.
|
||||
pub color: Option<Color>,
|
||||
/// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app
|
||||
/// gives an RGB pick back as CMYK. False for the other dialogs.
|
||||
pub cmyk_document: bool,
|
||||
}
|
||||
|
||||
/// The answer to a [`ScriptDialog`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum DialogAnswer {
|
||||
/// OK, for `alert`.
|
||||
Ok,
|
||||
@@ -91,6 +111,8 @@ pub enum DialogAnswer {
|
||||
Prompt(Option<String>),
|
||||
/// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask.
|
||||
Window(Vec<UiStep>),
|
||||
/// OK with the color picked, or Cancel (`None`), for `showColorPicker`.
|
||||
ColorPicker(Option<Color>),
|
||||
}
|
||||
|
||||
impl DialogAnswer {
|
||||
@@ -100,30 +122,101 @@ impl DialogAnswer {
|
||||
Self::Confirm(_) => DialogKind::Confirm,
|
||||
Self::Prompt(_) => DialogKind::Prompt,
|
||||
Self::Window(_) => DialogKind::Window,
|
||||
Self::ColorPicker(_) => DialogKind::ColorPicker,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the function returns.
|
||||
fn data(&self) -> Data {
|
||||
/// What the function returns for dialog `d`: for Cancel in the Color Picker, the color it
|
||||
/// started with.
|
||||
fn data(&self, d: &ScriptDialog) -> Data {
|
||||
match self {
|
||||
Self::Ok | Self::Window(_) => Data::Undefined,
|
||||
Self::Confirm(b) => Data::Bool(*b),
|
||||
Self::Prompt(Some(t)) => Data::String(t.clone()),
|
||||
Self::Prompt(None) => Data::Null,
|
||||
Self::ColorPicker(picked) => picked.or(d.color).as_ref().map_or(Data::Null, super::dom::color_data),
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer as a report gives it: `"ok"`, a boolean, a string or `null`.
|
||||
/// The answer as a report gives it: `"ok"`, a boolean, a string, a color as the paint commands
|
||||
/// take it, or `null`.
|
||||
fn json(&self) -> Value {
|
||||
match self {
|
||||
Self::Ok => json!("ok"),
|
||||
Self::Confirm(b) => json!(b),
|
||||
Self::Prompt(t) => json!(t),
|
||||
Self::Window(steps) => json!(steps.len()),
|
||||
Self::ColorPicker(c) => c.as_ref().map_or(Value::Null, color_json),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` as the paint commands take it.
|
||||
fn color_json(c: &Color) -> Value {
|
||||
serde_json::to_value(c).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// Are `c`'s components in their ranges: 0 to 1, and for Lab, L from 0 to 100 and a and b from
|
||||
/// -128 to 128, as a script's `LabColor` takes them?
|
||||
fn in_range(c: &Color) -> bool {
|
||||
let unit = |v: &[f32]| v.iter().all(|x| (0.0..=1.0).contains(x));
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => unit(&[r, g, b]),
|
||||
Color::Cmyk { c, m, y, k } => unit(&[c, m, y, k]),
|
||||
Color::Gray { k } => unit(&[k]),
|
||||
Color::Lab { l, a, b } => (0.0..=100.0).contains(&l) && [a, b].iter().all(|x| (-128.0..=128.0).contains(x)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color of a `colorPicker` answer, each component in its range ([`in_range`]). A color key
|
||||
/// such as `"rgb 300 0 0"` is checked as written, since reading it as a key puts its components
|
||||
/// into their ranges. An array or object is checked as written too, in f64 and with the scale
|
||||
/// [`crate::cmd::color_value`] reads it in, so that a component just past a limit is not rounded
|
||||
/// onto it when it narrows to f32.
|
||||
fn answer_color(v: &Value) -> Option<Color> {
|
||||
// Parsed as f64, so that a value just past a limit is not rounded onto it.
|
||||
let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x));
|
||||
let num = |o: &serde_json::Map<String, Value>, key: &str| o.get(key).and_then(Value::as_f64);
|
||||
let written_in_range = match v {
|
||||
Value::String(s) if Color::from_hex(s).is_none() => {
|
||||
let mut it = s.split_whitespace();
|
||||
let model = it.next()?.to_ascii_lowercase();
|
||||
let n: Vec<f64> = it.map(|t| t.parse::<f64>().ok().filter(|x| x.is_finite())).collect::<Option<_>>()?;
|
||||
match (model.as_str(), n.as_slice()) {
|
||||
("rgb", [_, _, _]) => within(&n, 0.0, 255.0),
|
||||
("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0),
|
||||
("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Value::Array(a) if a.len() >= 3 => within(&[a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?], 0.0, 1.0),
|
||||
Value::Object(o) => {
|
||||
if let (Some(c), Some(m), Some(y), Some(k)) = (num(o, "c"), num(o, "m"), num(o, "y"), num(o, "k")) {
|
||||
let scale = if [c, m, y, k].iter().any(|x| *x > 1.0) { 100.0 } else { 1.0 };
|
||||
within(&[c, m, y, k], 0.0, scale)
|
||||
} else if let Some(g) = o.get("gray") {
|
||||
let g = g.as_f64()?;
|
||||
within(&[if g > 1.0 { g / 100.0 } else { g }], 0.0, 1.0)
|
||||
} else if let (Some(l), Some(a), Some(b), None) = (num(o, "l"), num(o, "a"), num(o, "b"), o.get("model")) {
|
||||
within(&[l], 0.0, 100.0) && within(&[a, b], -128.0, 128.0)
|
||||
} else {
|
||||
match o.get("model").and_then(Value::as_str) {
|
||||
Some("rgb") => within(&[num(o, "r")?, num(o, "g")?, num(o, "b")?], 0.0, 1.0),
|
||||
Some("cmyk") => within(&[num(o, "c")?, num(o, "m")?, num(o, "y")?, num(o, "k")?], 0.0, 1.0),
|
||||
Some("gray") => within(&[num(o, "k")?], 0.0, 1.0),
|
||||
Some("lab") => within(&[num(o, "l")?], 0.0, 100.0) && within(&[num(o, "a")?, num(o, "b")?], -128.0, 128.0),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
if !written_in_range {
|
||||
return None;
|
||||
}
|
||||
crate::cmd::color_value(v).filter(in_range)
|
||||
}
|
||||
|
||||
/// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together
|
||||
/// is a line break; every other control character, and with `lines` false every line break too,
|
||||
/// shows as its Unicode Control Picture, as the Script Console shows it.
|
||||
@@ -156,9 +249,10 @@ pub fn cut_to(text: &str, max: usize) -> &str {
|
||||
}
|
||||
|
||||
/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value:
|
||||
/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}`
|
||||
/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an
|
||||
/// empty list.
|
||||
/// true | false}`, `{kind: "prompt", value: text | null}`, `{kind: "window", value: [step, ...]}`
|
||||
/// ([`super::scriptui`]) and `{kind: "colorPicker", value: color | null}`, the color in any form
|
||||
/// the paint commands take. An empty object, which the parameter took before dialogs existed, is
|
||||
/// an empty list.
|
||||
pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, String> {
|
||||
let list = match v {
|
||||
None => return Ok(Vec::new()),
|
||||
@@ -196,7 +290,12 @@ fn known_answer(o: &Map<String, Value>) -> Result<DialogAnswer, &'static str> {
|
||||
(Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))),
|
||||
(Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"),
|
||||
(Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"),
|
||||
_ => Err("must have `kind` alert, confirm, prompt or window"),
|
||||
(Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)),
|
||||
(Some("colorPicker"), v) => match answer_color(v) {
|
||||
Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))),
|
||||
None => Err("is a color picker's answer, whose `value` must be a color or null"),
|
||||
},
|
||||
_ => Err("must have `kind` alert, confirm, prompt, window or colorPicker"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,9 +564,10 @@ impl Dialogs {
|
||||
}
|
||||
let Some(d) = waiting.take() else { return false };
|
||||
drop(waiting);
|
||||
let data = answer.data(&d);
|
||||
let on_yes = self.on_yes.take();
|
||||
// A confirm the app opened returns `undefined` to the call that opened it.
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { answer.data() };
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { data };
|
||||
if answer == DialogAnswer::Confirm(true) {
|
||||
self.approved.set(on_yes);
|
||||
}
|
||||
@@ -523,13 +623,16 @@ impl Dialogs {
|
||||
fn record(&self, d: &ScriptDialog, answer: Value) {
|
||||
let mut r = Map::new();
|
||||
r.insert("kind".into(), json!(d.kind.id()));
|
||||
r.insert("message".into(), json!(d.message));
|
||||
r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE)));
|
||||
if d.kind != DialogKind::ColorPicker {
|
||||
r.insert("message".into(), json!(d.message));
|
||||
r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE)));
|
||||
}
|
||||
match d.kind {
|
||||
DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)),
|
||||
DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)),
|
||||
DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)),
|
||||
DialogKind::Window => None,
|
||||
DialogKind::ColorPicker => r.insert("color".into(), d.color.as_ref().map_or(Value::Null, color_json)),
|
||||
};
|
||||
r.insert("answer".into(), answer);
|
||||
self.push_record(Value::Object(r));
|
||||
@@ -584,7 +687,8 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
host.charge_call(args.iter().map(super::data_size).sum())?;
|
||||
let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) };
|
||||
let (title, error_icon, no_as_default, preset) = match kind {
|
||||
DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()),
|
||||
// `showColorPicker` opens through `show_color_picker`, not here.
|
||||
DialogKind::Alert | DialogKind::ColorPicker => (text(args, 1), flag(args, 2), false, String::new()),
|
||||
DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()),
|
||||
DialogKind::Prompt => {
|
||||
let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) };
|
||||
@@ -601,7 +705,33 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
if preset.len() > MAX_PROMPT_BYTES {
|
||||
return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB")));
|
||||
}
|
||||
let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset };
|
||||
wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false })
|
||||
}
|
||||
|
||||
/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK,
|
||||
/// and a new object of `color` for Cancel.
|
||||
pub(super) fn show_color_picker(host: &Host, color: Color) -> Result<Data, HostError> {
|
||||
// During a slice the session holds the run's working copy, whose active document may be one
|
||||
// the script made; between slices the app sees the documents as they were before the run.
|
||||
let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk);
|
||||
let dialog = ScriptDialog {
|
||||
kind: DialogKind::ColorPicker,
|
||||
message: String::new(),
|
||||
title: None,
|
||||
error_icon: false,
|
||||
no_as_default: false,
|
||||
preset: String::new(),
|
||||
color: Some(color),
|
||||
cmyk_document,
|
||||
};
|
||||
wait_or_answer(host, dialog)
|
||||
}
|
||||
|
||||
/// Opens `dialog`: in the app the run waits at it, and a run with nobody to ask takes the next of
|
||||
/// `answers`.
|
||||
fn wait_or_answer(host: &Host, dialog: ScriptDialog) -> Result<Data, HostError> {
|
||||
let kind = dialog.kind;
|
||||
let name = kind.function();
|
||||
let d = &host.dialogs;
|
||||
if d.framed {
|
||||
if !d.can_wait.get() {
|
||||
@@ -616,11 +746,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
|
||||
match next {
|
||||
Some(a) if a.kind() == kind => {
|
||||
d.record(&dialog, a.json());
|
||||
Ok(a.data())
|
||||
Ok(a.data(&dialog))
|
||||
}
|
||||
Some(a) => {
|
||||
d.record(&dialog, json!("missing"));
|
||||
Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id())))
|
||||
Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {}", a.kind().id(), kind.id())))
|
||||
}
|
||||
None => {
|
||||
d.record(&dialog, json!("missing"));
|
||||
|
||||
@@ -117,6 +117,7 @@ mod tracing;
|
||||
mod transform;
|
||||
mod variables;
|
||||
|
||||
pub(super) use colors::of_color as color_data;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
|
||||
@@ -1155,6 +1156,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `app.showColorPicker(color)`: the Color Picker on `color`, which must be an `RGBColor`,
|
||||
/// `CMYKColor`, `GrayColor` or `LabColor` ([`super::dialogs::show_color_picker`]).
|
||||
fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer {
|
||||
let color = colors::solid(arg(a, 1), "showColorPicker's color")?;
|
||||
super::dialogs::show_color_picker(h, color)
|
||||
}
|
||||
|
||||
/// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one that starts
|
||||
/// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a
|
||||
/// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files.
|
||||
@@ -3381,6 +3389,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("selection", property(l, app_selection, app_set_selection), typed("*")),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("showColorPicker", method(l, app_show_color_picker), returns("Color", &[("color", "Color")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("selectTool", method(l, app_select_tool), returns("boolean", &[("toolName", "string")])),
|
||||
("undo", method(l, app_undo), returns("undefined", &[])),
|
||||
|
||||
@@ -13,7 +13,10 @@
|
||||
//! VectorCraft's own rules, which the help pages do not state: components left out count as 0;
|
||||
//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b`
|
||||
//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page
|
||||
//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! says. A color read from an object gives that object the same color when it is assigned back.
|
||||
//! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it
|
||||
//! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to
|
||||
//! any other paint gives white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not
|
||||
//! assigned yet.
|
||||
|
||||
use std::rc::Rc;
|
||||
@@ -66,7 +69,7 @@ fn shown(v: f32, scale: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// The color object for a solid color.
|
||||
fn of_color(c: &Color) -> Data {
|
||||
pub(in crate::script) fn of_color(c: &Color) -> Data {
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]),
|
||||
Color::Cmyk { c, m, y, k } => color_object(
|
||||
@@ -149,6 +152,18 @@ pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result<Option<Color
|
||||
}))
|
||||
}
|
||||
|
||||
/// The solid color a script gave `what`, checked as [`assigned`] checks it: a `NoColor`, a
|
||||
/// `GradientColor`, a `SpotColor` or a `PatternColor` throws a `TypeError`.
|
||||
pub(super) fn solid(d: &Data, what: &str) -> std::result::Result<Color, HostError> {
|
||||
let not_solid = || HostError::Type(format!("{what} must be an RGBColor, CMYKColor, GrayColor or LabColor"));
|
||||
match assigned(d, what) {
|
||||
Ok(Some(c)) => Ok(c),
|
||||
// A NoColor, or one of the LATER classes, which `assigned` refuses with a plain error.
|
||||
Ok(None) | Err(HostError::Error(_)) => Err(not_solid()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// `color` as `paint.setFill` and `paint.setStroke` take it.
|
||||
pub(super) fn param(color: &Color) -> Value {
|
||||
serde_json::to_value(color).unwrap_or(Value::Null)
|
||||
|
||||
@@ -839,7 +839,8 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
/// `removeAll()`: deletes every object the collection lists (those inside another listed one go
|
||||
/// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or
|
||||
/// one on a locked artboard stops it before anything is deleted, as the document's
|
||||
/// `pageItems.removeAll()` is stopped.
|
||||
/// `pageItems.removeAll()` is stopped, and so does an image the deletion would leave first in an
|
||||
/// ordinary group named as a tracing.
|
||||
fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
|
||||
|
||||
@@ -170,6 +170,8 @@ fn path_ref(h: &super::Host, item: Item) -> Data {
|
||||
|
||||
/// The index of the first point of each subpath of `subs`, followed by the number of points.
|
||||
fn starts(subs: &[SubPath]) -> Vec<usize> {
|
||||
#[cfg(test)]
|
||||
crate::script::LAYOUTS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
let mut out = Vec::with_capacity(subs.len() + 1);
|
||||
let mut n = 0;
|
||||
for sp in subs {
|
||||
@@ -1902,18 +1904,17 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
.filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())]))
|
||||
.flatten()
|
||||
.collect();
|
||||
let partial = sel.partial(item.id).filter(|_| !held);
|
||||
let mut picked = Vec::new();
|
||||
let mut offset = 0;
|
||||
for (s, sp) in pd.subpaths.iter().enumerate() {
|
||||
for j in 0..sp.anchors.len() {
|
||||
if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) {
|
||||
picked.push(offset + j);
|
||||
}
|
||||
}
|
||||
offset += sp.anchors.len();
|
||||
let firsts = starts(&pd.subpaths);
|
||||
match sel.partial(item.id).filter(|_| !held) {
|
||||
// Direct-selected anchors that no selected segment ends at, in subpath and anchor
|
||||
// order, which is the order of `pathPoints`.
|
||||
Some(anchors) => anchors
|
||||
.iter()
|
||||
.filter(|&&(s, j)| pd.subpaths.get(s).is_some_and(|sp| j < sp.anchors.len()) && !ends.contains(&(s, j)))
|
||||
.filter_map(|(s, j)| firsts.get(*s).map(|first| first + j))
|
||||
.collect(),
|
||||
None => (0..firsts.last().copied().unwrap_or(0)).collect(),
|
||||
}
|
||||
picked
|
||||
})?;
|
||||
h.charge_call(picked.len() as u64)?;
|
||||
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
|
||||
|
||||
@@ -279,6 +279,8 @@ fn set_warning(h: &Host, on: bool) -> Answer {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
if !h.dialogs.ask(question, OnYes::ExternalScriptWarningOff) {
|
||||
return Err(HostError::Error(WARNING_OFF_NEEDS_A_PERSON.into()));
|
||||
|
||||
@@ -3188,6 +3188,9 @@ thread_local! {
|
||||
pub(crate) static TEST_GROWTH_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
|
||||
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: how many times the object model worked out where the points of each subpath of a
|
||||
/// path start.
|
||||
pub(crate) static LAYOUTS_BUILT: Cell<u64> = const { Cell::new(0) };
|
||||
/// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`].
|
||||
pub(crate) static TEST_ENGINE_HEAP: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`].
|
||||
|
||||
@@ -236,6 +236,17 @@ impl Palettes {
|
||||
None
|
||||
}
|
||||
|
||||
/// Drops the events at the front of the line that [`Palettes::next`] would drop, so that the
|
||||
/// line is empty or starts with an event that can still run.
|
||||
fn drop_stale(&mut self) {
|
||||
while let Some(q) = self.waiting.front() {
|
||||
if self.resolved(q.clone()).is_some() {
|
||||
break;
|
||||
}
|
||||
self.waiting.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
/// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other
|
||||
/// engines' palettes keep their places in line. Events whose file access scopes do not cover
|
||||
/// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest
|
||||
@@ -252,7 +263,13 @@ impl Palettes {
|
||||
|
||||
/// The taken event `q` given to its control in its palette, and that palette, or `None` when it
|
||||
/// is dropped ([`Palettes::next`]).
|
||||
fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> {
|
||||
fn checked(&self, q: Queued) -> Option<(ScriptPalette, Queued)> {
|
||||
let (p, q) = self.resolved(q)?;
|
||||
Some((p.clone(), q))
|
||||
}
|
||||
|
||||
/// [`Palettes::checked`] without the copy of the palette.
|
||||
fn resolved(&self, mut q: Queued) -> Option<(&ScriptPalette, Queued)> {
|
||||
let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?;
|
||||
if let Some(c) = control_of(&mut q.event) {
|
||||
*c = p.dialog.index_of(q.element?)?;
|
||||
@@ -271,7 +288,7 @@ impl Palettes {
|
||||
} else {
|
||||
q.event = scriptui::check_event(&p.dialog, q.event).ok()?;
|
||||
}
|
||||
Some((p.clone(), q))
|
||||
Some((p, q))
|
||||
}
|
||||
|
||||
/// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()`
|
||||
@@ -414,6 +431,12 @@ impl Session {
|
||||
self.script_palettes.waiting.len()
|
||||
}
|
||||
|
||||
/// The number of the last palette event put in line, which an event added, or merged into a
|
||||
/// waiting one, changes.
|
||||
pub fn script_palette_last_ticket(&self) -> u64 {
|
||||
self.script_palettes.last_ticket
|
||||
}
|
||||
|
||||
/// The changes that wait for a run, as (palette id, the id of the control they change).
|
||||
pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> {
|
||||
self.script_palettes
|
||||
@@ -456,7 +479,12 @@ impl Session {
|
||||
/// run is going or no event waits; otherwise the run's name, or the error that ended it before
|
||||
/// it began. An open edit that cannot be settled gives its error, and the events keep waiting.
|
||||
pub fn script_palette_start(&mut self) -> Option<Result<String>> {
|
||||
if self.script_running() || self.script_palettes.waiting.is_empty() {
|
||||
if self.script_running() {
|
||||
return None;
|
||||
}
|
||||
// Events that can no longer run do not settle the open edit.
|
||||
self.script_palettes.drop_stale();
|
||||
if self.script_palettes.waiting.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// An event waits while a drag or an undo group is open, which a run cannot start in.
|
||||
@@ -507,6 +535,9 @@ impl Session {
|
||||
let want = self.script_palettes.last_ticket;
|
||||
let mut mine = None;
|
||||
loop {
|
||||
if !self.script_running() {
|
||||
self.script_palettes.drop_stale();
|
||||
}
|
||||
if !self.script_running()
|
||||
&& !self.script_palettes.waiting.is_empty()
|
||||
&& let Err(e) = self.settle_for_script()
|
||||
|
||||
@@ -731,6 +731,68 @@ fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() {
|
||||
assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_of_a_file_with_editing_data_keep_an_explicit_crop_box() {
|
||||
let dir = Folder::new("open-pdf-link-pages-explicit-crop");
|
||||
let src = dir.file("editable.ai");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
s.execute(
|
||||
"file.saveAs",
|
||||
&json!({"path": src, "format": "ai", "preserveEditing": true,
|
||||
"bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(vectorcraft_pdf::has_illustrator_data(&std::fs::read(&src).unwrap(), None));
|
||||
let board = |s: &Session| {
|
||||
let r = s.doc().unwrap().doc.artboards[0].rect;
|
||||
(r.width(), r.height())
|
||||
};
|
||||
// No box named: the trim box, as the file opens as art.
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap();
|
||||
assert_eq!(board(&s), (100.0, 50.0));
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap();
|
||||
assert_eq!(board(&s), (100.0, 50.0));
|
||||
// An explicit crop box is the crop box, which takes in the bleed.
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "crop"})).unwrap();
|
||||
let (w, h) = board(&s);
|
||||
assert!(w > 100.0 && h > 50.0, "{w} x {h}");
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "crop": "crop"})).unwrap();
|
||||
assert_eq!(board(&s), (w, h));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_with_only_a_native_attachment_default_to_crop_boxes() {
|
||||
let dir = Folder::new("open-pdf-link-pages-native-crop");
|
||||
let src = dir.file("editable.pdf");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
s.execute(
|
||||
"document.exportPdf",
|
||||
&json!({"path": src, "preserveEditing": true,
|
||||
"bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}),
|
||||
)
|
||||
.unwrap();
|
||||
let bytes = std::fs::read(&src).unwrap();
|
||||
assert!(vectorcraft_pdf::editing(&bytes).is_some_and(|e| e.intact));
|
||||
assert!(!vectorcraft_pdf::has_illustrator_data(&bytes, None));
|
||||
let board = |s: &Session| {
|
||||
let r = s.doc().unwrap().doc.artboards[0].rect;
|
||||
(r.width(), r.height())
|
||||
};
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap();
|
||||
let (w, h) = board(&s);
|
||||
assert!(w > 100.0 && h > 50.0, "{w} x {h}");
|
||||
for key in ["cropTo", "crop"] {
|
||||
let mut params = json!({"path": src, "linkPages": true});
|
||||
params[key] = json!("crop");
|
||||
s.execute("document.open", ¶ms).unwrap();
|
||||
assert_eq!(board(&s), (w, h), "{key}");
|
||||
}
|
||||
s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap();
|
||||
assert_eq!(board(&s), (100.0, 50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, pdf};
|
||||
|
||||
@@ -177,6 +177,8 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
|
||||
@@ -343,3 +345,103 @@ fn a_dialog_in_a_callback_throws_in_the_app() {
|
||||
assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}");
|
||||
assert_eq!(r["dialogCount"], 0);
|
||||
}
|
||||
|
||||
/// `showColorPicker` with an RGB red, the answer, and the run's log line for the color it returns.
|
||||
const PICK_RED: &str = "var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());";
|
||||
|
||||
#[test]
|
||||
fn a_run_with_nobody_to_ask_takes_the_picked_color_from_answers() {
|
||||
let mut s = one_doc();
|
||||
let source = format!("{PICK_RED} var g = new GrayColor(); g.gray = 40; var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join());");
|
||||
let r = headless(&mut s, &source, answers(&[json!({"kind": "colorPicker", "value": "#00FF00"}), json!({"kind": "colorPicker", "value": null})]))
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!(["RGBColor,0,255,0", "GrayColor,40"]), "OK gives the picked color, Cancel the color given: {r}");
|
||||
let dialogs = r["dialogs"].as_array().unwrap();
|
||||
assert_eq!(dialogs.len(), 2);
|
||||
assert!(dialogs.iter().all(|d| d["kind"] == "colorPicker" && d["color"].is_object() && d.get("message").is_none()), "{r}");
|
||||
assert_eq!(dialogs[1]["answer"], Value::Null, "Cancel is listed as null");
|
||||
let cmyk = headless(
|
||||
&mut s,
|
||||
"var c = new CMYKColor(); c.cyan = 20; vc.log(app.showColorPicker(c).typename);",
|
||||
answers(&[json!({"kind": "colorPicker", "value": {"c": 0, "m": 100, "y": 100, "k": 0}})]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(cmyk["log"], json!(["CMYKColor"]), "the picked color keeps its own model: {cmyk}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_picker_ends_the_run_when_no_answer_is_left() {
|
||||
let mut s = one_doc();
|
||||
let before = art(&s);
|
||||
let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});";
|
||||
for (given, says) in [(json!([]), "no answer left"), (answers(&[json!({"kind": "prompt", "value": "x"})]), "is for prompt, not colorPicker")] {
|
||||
let source = format!("{edit} try {{ {PICK_RED} }} catch (e) {{ vc.log('caught'); }}");
|
||||
let e = headless(&mut s, &source, given).unwrap_err().to_string();
|
||||
assert!(e.contains("showColorPicker") && e.contains(says), "{e}");
|
||||
assert_eq!(art(&s), before, "the run's edit goes back");
|
||||
let report = s.script_report().unwrap();
|
||||
assert_eq!(report["log"], json!([]), "a missing answer cannot be caught");
|
||||
assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}");
|
||||
}
|
||||
let a = headless(&mut s, "alert('x');", answers(&[json!({"kind": "colorPicker", "value": null})])).unwrap_err().to_string();
|
||||
assert!(a.contains("is for colorPicker, not alert"), "{a}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_picker_refuses_what_is_not_a_solid_color() {
|
||||
let mut s = one_doc();
|
||||
let source = "var out = []; [undefined, 'red', new NoColor(), {typename: 'SpotColor', tint: 100}].forEach(function (c) {\
|
||||
try { app.showColorPicker(c); out.push('opened'); } catch (e) { out.push(e.name); } });\
|
||||
try { var big = new RGBColor(); big.red = 300; app.showColorPicker(big); } catch (e) { out.push(e.name); } vc.log(out.join());";
|
||||
let r = headless(&mut s, source, json!([])).unwrap();
|
||||
assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}");
|
||||
assert_eq!(r["dialogCount"], 0, "no picker opened");
|
||||
for bad in [
|
||||
json!("not a color"),
|
||||
json!([255, 0, 0]),
|
||||
json!({"model": "lab", "l": 120, "a": 0, "b": 0}),
|
||||
json!(true),
|
||||
json!("rgb 300 0 0"),
|
||||
json!("cmyk 0 0 0 101"),
|
||||
json!("gray -1"),
|
||||
json!("lab 50 200 0"),
|
||||
json!("rgb 255.000001 0 0"),
|
||||
json!([1.00000001, 0, 0]),
|
||||
json!({"c": 100.000001, "m": 0, "y": 0, "k": 0}),
|
||||
json!({"gray": 100.000001}),
|
||||
json!({"l": 100.000001, "a": 0, "b": 0}),
|
||||
json!({"model": "rgb", "r": 1.00000001, "g": 0, "b": 0}),
|
||||
json!({"model": "lab", "l": 50, "a": -128.000001, "b": 0}),
|
||||
] {
|
||||
let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string();
|
||||
assert!(e.contains("color picker's answer"), "{bad}: {e}");
|
||||
}
|
||||
for good in [
|
||||
json!("rgb 255 0 0"),
|
||||
json!("cmyk 0 100 100 0"),
|
||||
json!("gray 100"),
|
||||
json!("lab 50 -128 128"),
|
||||
json!([1, 0, 0]),
|
||||
json!({"c": 0, "m": 100, "y": 100, "k": 0}),
|
||||
json!({"gray": 100}),
|
||||
json!({"l": 100, "a": -128, "b": 128}),
|
||||
json!({"model": "rgb", "r": 1, "g": 0, "b": 0}),
|
||||
] {
|
||||
assert!(headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": good})])).is_ok(), "{good}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_framed_run_waits_at_the_color_picker() {
|
||||
let mut s = one_doc();
|
||||
framed(&mut s, &format!("{PICK_RED} var q = app.showColorPicker(p); vc.log(q.green);"));
|
||||
let d = s.script_dialog().unwrap();
|
||||
assert_eq!((d.kind, d.color), (DialogKind::ColorPicker, Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))));
|
||||
assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused");
|
||||
assert!(s.script_answer(DialogAnswer::ColorPicker(Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)))));
|
||||
assert!(pump(&mut s).is_none());
|
||||
assert_eq!(s.script_dialog().unwrap().color, Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "it opens on the color it is given");
|
||||
assert!(s.script_answer(DialogAnswer::ColorPicker(None)));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!(["RGBColor,0,0,255", 0]), "{r}");
|
||||
}
|
||||
@@ -1541,6 +1541,22 @@ fn a_listed_preset_keeps_more_rows_than_artboards() {
|
||||
assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4);
|
||||
}
|
||||
|
||||
/// A layout that replaces the rows keeps the columns the rows gave the artboards there are now,
|
||||
/// whether or not the change of artboards came with a layout of its own.
|
||||
#[test]
|
||||
fn replacing_rows_keeps_the_columns_of_the_artboards_there_are_now() {
|
||||
use crate::cmd::newdoc::{ArtboardLayout, DocSettings};
|
||||
let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() };
|
||||
let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap();
|
||||
for change in [json!({"artboards": 9}), json!({"artboards": 9, "artboardLayout": {"spacing": 20}})] {
|
||||
let more = settings.clone().with_params(&change, "file.new").unwrap();
|
||||
for layout in [json!("gridByRow"), json!({"layout": "gridByRow"})] {
|
||||
let by_row = more.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap();
|
||||
assert_eq!(by_row.grid_columns(), 3, "{change} then {layout}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_documents_throw_on_every_member() {
|
||||
let (mut s, _, _) = doc();
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{LineCap, LineJoin};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_geom::path::AnchorKind;
|
||||
|
||||
use crate::*;
|
||||
@@ -420,6 +421,9 @@ fn path_point_setters_edit_one_anchor() {
|
||||
for i in [0, 2, 3] {
|
||||
assert_eq!(anchors[i], anchors_before[i], "point {i} did not change");
|
||||
}
|
||||
// The 300 pt tall document's y runs down, so script y 285 is document y 15.
|
||||
let edited = &anchors[1];
|
||||
assert_eq!((edited.p, edited.h_in, edited.h_out), (Point::new(45.0, 15.0), Point::new(35.0, 15.0), Point::new(55.0, 15.0)));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints.index('a');").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].pointType = 'SMOOTH';").contains("PointType"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 'x'];").contains("finite"));
|
||||
@@ -2385,6 +2389,95 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() {
|
||||
assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command");
|
||||
}
|
||||
|
||||
/// Reading and moving each point of a path with many subpaths works out where the subpaths' points
|
||||
/// start a few times for the whole loop, not once or more for each point.
|
||||
#[test]
|
||||
fn reading_and_moving_points_counts_the_subpaths_a_few_times() {
|
||||
let (mut s, _, _) = doc();
|
||||
let d: String = (0..500).map(|i| format!("M{x} 10 L{x} 20 ", x = i % 300)).collect();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
crate::script::LAYOUTS_BUILT.with(|n| n.set(0));
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var pp = app.activeDocument.pathItems[0].pathPoints;\
|
||||
for (var i = 0; i < pp.length; i++) { var q = pp[i]; q.anchor = [q.anchor[0], q.anchor[1] + 1]; }\
|
||||
vc.log(pp.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(1000)]);
|
||||
let built = crate::script::LAYOUTS_BUILT.with(std::cell::Cell::get);
|
||||
assert!(built < 10, "{built} layouts for 1000 points");
|
||||
let n = node(&s, id);
|
||||
let ys: Vec<f64> = n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).map(|an| an.p.y).collect();
|
||||
assert_eq!(ys.len(), 1000);
|
||||
assert!(ys.iter().all(|&y| y == 9.0 || y == 19.0), "every point moved up");
|
||||
}
|
||||
|
||||
/// `selectedPathPoints` lists the direct-selected anchors of a path with several subpaths in the
|
||||
/// order of `pathPoints`, whatever order they were selected in.
|
||||
#[test]
|
||||
fn selected_path_points_follow_the_order_of_path_points_across_subpaths() {
|
||||
let (mut s, _, _) = doc();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L10 0 L10 10 M20 0 L30 0"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[1, 1], [0, 2], [0, 0]], "mode": "set"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var sp = app.activeDocument.pathItems[0].selectedPathPoints, x = [];\
|
||||
for (var i = 0; i < sp.length; i++) x.push(sp[i].anchor[0]); vc.log(x);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([0, 10, 30])]);
|
||||
}
|
||||
|
||||
/// `pageItems` and `pathItems` find a name that reads as a number but is not an index, and such a
|
||||
/// key that nothing has reads as `undefined`.
|
||||
#[test]
|
||||
fn collections_find_names_that_read_as_numbers() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "name": "1.5"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, g = d.pageItems, p = d.pathItems;\
|
||||
vc.log([g['-1'].name, g[1.5].name, '-1' in g, p['-1'].name, p[-1].name, '1.5' in p]);\
|
||||
vc.log([g[-2] === undefined, '-2' in p, p[2.5] === undefined, p[0].name, p[1].name]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["-1", "1.5", true, "-1", "-1", true]), json!([true, false, true, "-1", "1.5"])]);
|
||||
}
|
||||
|
||||
/// `typename` of a point or a point list throws for one that is stale, as the other members do.
|
||||
#[test]
|
||||
fn stale_points_throw_on_typename() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var pp = app.activeDocument.pathItems[0].pathPoints, q = pp[3]; vc.log(q.typename); pp[0].remove();\
|
||||
try { q.typename; vc.log('read'); } catch (e) { vc.log(e.message); }\
|
||||
var p = app.activeDocument.pathItems[0], ps = p.pathPoints; vc.log(ps.typename); p.remove();\
|
||||
try { ps.typename; vc.log('read'); } catch (e) { vc.log(e.message); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!("PathPoint"), json!("Stale path point"), json!("PathPoints"), json!("Stale page item")]);
|
||||
}
|
||||
|
||||
/// A path the creators make in a document whose ids are past 2^53 is the new path, not one whose
|
||||
/// id a double rounds to.
|
||||
#[test]
|
||||
fn made_paths_keep_ids_past_two_to_the_53() {
|
||||
let (mut s, _, _) = doc();
|
||||
let big = 1u64 << 53;
|
||||
s.edit("Raise Ids", |d, _| {
|
||||
d.raise_next_id(big);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let old = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
|
||||
assert_eq!(old.0, big);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
log(&mut s, "var p = app.activeDocument.pathItems; p.add().name = 'made'; p.rectangle(50, 50, 10, 10, true).name = 'reversed';");
|
||||
assert_eq!(node(&s, old).name, None);
|
||||
assert_eq!(node(&s, NodeId(big + 1)).name.as_deref(), Some("made"));
|
||||
assert_eq!(node(&s, NodeId(big + 2)).name.as_deref(), Some("reversed"));
|
||||
}
|
||||
|
||||
/// A point change made before a call that fails and is put back, here a new document whose
|
||||
/// profile cannot be read, is kept.
|
||||
#[test]
|
||||
|
||||
@@ -104,6 +104,8 @@ fn yes_to_the_confirm_turns_the_warning_off() {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(s.script_dialog_turns_warning_off());
|
||||
|
||||
@@ -135,6 +135,45 @@ fn added_group_named_as_seam_fills_is_counted() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `groupItems.removeAll()` of a group and the document's `compoundPathItems.removeAll()` refuse
|
||||
/// to leave an image at the bottom of an ordinary group named as a tracing, before the document
|
||||
/// changes.
|
||||
#[test]
|
||||
fn group_and_compound_remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
|
||||
let compound = "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20), d.pathItems.rectangle(40, 40, 5, 5)];\
|
||||
vc.run('object.compoundPath.make'); return d.pageItems[0]; })()";
|
||||
let group = "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group'); return d.pageItems[0]; })()";
|
||||
for (name, bottom, list) in
|
||||
[("group-remove-all-groups", group, "groupItems[0].groupItems"), ("remove-all-compounds", compound, "compoundPathItems")]
|
||||
{
|
||||
let base = folder(name);
|
||||
let (mut s, _) = session(&base, false);
|
||||
log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\
|
||||
var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);"
|
||||
),
|
||||
);
|
||||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"var d = app.activeDocument, m = ''; try {{ d.{list}.removeAll(); }} catch (e) {{ m = e.message; }}\
|
||||
vc.log(m); vc.log(d.pageItems[0].typename);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem")], "{list}");
|
||||
assert!(traces(&s).is_empty(), "{list}");
|
||||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{list}");
|
||||
assert_eq!(undo_steps(&s), steps, "{list}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_image_resolution_is_one_number_or_none() {
|
||||
let base = folder("resolution");
|
||||
|
||||
@@ -563,6 +563,32 @@ fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() {
|
||||
assert_eq!(s.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_of_clicks_that_can_no_longer_run_does_not_settle_the_open_edit() {
|
||||
let mut s = one_doc();
|
||||
run_in_app(
|
||||
&mut s,
|
||||
"#targetengine switches\nvar p = new Window('palette'); var off = p.add('button', undefined, 'Off'); \
|
||||
var go = p.add('button', undefined, 'Go'); off.onClick = function () { go.enabled = false; vc.log('off'); }; \
|
||||
go.onClick = function () { vc.log('go'); }; p.show();",
|
||||
);
|
||||
let id = only_palette(&s);
|
||||
assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true);
|
||||
assert!(pump(&mut s).is_none());
|
||||
assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added));
|
||||
assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added));
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(true)));
|
||||
pump(&mut s).unwrap().unwrap();
|
||||
assert!(s.script_palette_start().expect("the first click starts its run").is_ok());
|
||||
assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["off"]));
|
||||
// Settling would fail here, so a start that tries to settle gives an error.
|
||||
SETTLE_FAILS.with(|f| f.set(true));
|
||||
let started = s.script_palette_start();
|
||||
SETTLE_FAILS.with(|f| f.set(false));
|
||||
assert!(started.is_none(), "the stale click does not settle the open edit: {:?}", started.map(|r| r.map_err(|e| e.to_string())));
|
||||
assert_eq!(s.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_during_another_run_runs_after_it() {
|
||||
let mut s = one_doc();
|
||||
|
||||
@@ -112,7 +112,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \
|
||||
executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \
|
||||
invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \
|
||||
printerList redo redraw selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= \
|
||||
printerList redo redraw selection selection= selectTool showColorPicker textFonts toString typename undo unloadAction \
|
||||
unloadAction= \
|
||||
userInteractionLevel \
|
||||
userInteractionLevel=",
|
||||
),
|
||||
|
||||
@@ -22,7 +22,7 @@ flate2 = { workspace = true }
|
||||
# file's access ACL on Linux (`keep_permissions`). Already in Cargo.lock (tempfile), so this adds
|
||||
# no new crate.
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { workspace = true, features = ["std", "fs"] }
|
||||
rustix = { workspace = true, features = ["std", "fs", "process"] }
|
||||
|
||||
[dev-dependencies]
|
||||
vectorcraft-testkit = { workspace = true }
|
||||
|
||||
+115
-6
@@ -153,13 +153,19 @@ pub fn write_atomic_checked(
|
||||
flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() }))
|
||||
};
|
||||
let open_target = |write: bool| -> io::Result<File> {
|
||||
// A missing target is created by `create_target`, after the last check. An existing one is
|
||||
// opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it.
|
||||
if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) {
|
||||
return Err(io::ErrorKind::NotFound.into());
|
||||
// Opened without `O_CREAT`: a missing target, one removed meanwhile included, is created
|
||||
// only by `create_target`, after the last check.
|
||||
#[cfg(test)]
|
||||
if write && let Some(hook) = BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take()) {
|
||||
hook();
|
||||
}
|
||||
let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY };
|
||||
Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?))
|
||||
// `O_NONBLOCK`: a FIFO at the name fails the regular-file check instead of waiting for a reader.
|
||||
let flags = if write { OFlags::WRONLY | OFlags::NONBLOCK } else { OFlags::RDONLY };
|
||||
let file = File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?);
|
||||
if write {
|
||||
protected_regular(&dir, &file)?;
|
||||
}
|
||||
Ok(file)
|
||||
};
|
||||
let create_target = || -> io::Result<File> { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) };
|
||||
match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) {
|
||||
@@ -265,6 +271,31 @@ pub fn write_atomic_checked(
|
||||
}
|
||||
}
|
||||
|
||||
/// The target [`write_atomic_checked`] opened without `O_CREAT`, checked as Linux's strictest
|
||||
/// `fs.protected_regular` checks an `O_CREAT` open of an existing file: anything but a regular
|
||||
/// file is refused, and so is a file in a sticky folder that others or the group can write to
|
||||
/// when neither this process nor the folder's owner owns it.
|
||||
#[cfg(unix)]
|
||||
fn protected_regular(dir: &std::os::fd::OwnedFd, file: &File) -> io::Result<()> {
|
||||
let (folder, opened) = (rustix::fs::fstat(dir)?, rustix::fs::fstat(file)?);
|
||||
if rustix::fs::FileType::from_raw_mode(opened.st_mode) != rustix::fs::FileType::RegularFile {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file"));
|
||||
}
|
||||
if refused_in_sticky_folder(rustix::fs::Mode::from_raw_mode(folder.st_mode), folder.st_uid, opened.st_uid, rustix::process::geteuid().as_raw()) {
|
||||
return Err(io::ErrorKind::PermissionDenied.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a file owned by `owner` in a folder with mode `folder_mode` owned by `folder_owner` is
|
||||
/// refused to the user `me`: the folder is sticky, others or the group can write to it, and
|
||||
/// neither `me` nor `folder_owner` owns the file.
|
||||
#[cfg(unix)]
|
||||
fn refused_in_sticky_folder(folder_mode: rustix::fs::Mode, folder_owner: u32, owner: u32, me: u32) -> bool {
|
||||
use rustix::fs::Mode;
|
||||
folder_mode.contains(Mode::SVTX) && folder_mode.intersects(Mode::WGRP | Mode::WOTH) && owner != me && owner != folder_owner
|
||||
}
|
||||
|
||||
/// See the Unix version. Here `allowed(path)` runs before the file is written and again after it is
|
||||
/// filled, right before it is put in place; a refusal then removes the temporary file and leaves
|
||||
/// `path` unchanged.
|
||||
@@ -784,6 +815,9 @@ thread_local! {
|
||||
/// Tests: [`write_atomic_checked`]'s folder refuses the rename.
|
||||
#[cfg(unix)]
|
||||
static RENAME_REFUSED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: run once right before [`write_atomic_checked`] opens its target for writing.
|
||||
#[cfg(unix)]
|
||||
static BEFORE_TARGET_OPEN: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// A symbolic link keeps pointing at its file: write the file it names.
|
||||
@@ -1282,6 +1316,81 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A target removed after the write starts is not created again before the last check: when its
|
||||
/// folder has moved outside by then, nothing is left there.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_checked_write_creates_no_target_removed_while_it_is_opened() {
|
||||
let (d, root, outside) = checked_folders("checked-removed-target");
|
||||
let path = root.join("inside/doc.txt");
|
||||
std::fs::write(&path, b"old").unwrap();
|
||||
let (inside, moved) = (root.join("inside"), outside.join("inside"));
|
||||
let (from, to) = (inside.clone(), moved.clone());
|
||||
BEFORE_TARGET_OPEN.with(|h| {
|
||||
*h.borrow_mut() = Some(Box::new(move || {
|
||||
std::fs::remove_file(from.join("doc.txt")).unwrap();
|
||||
std::fs::rename(&from, &to).unwrap();
|
||||
}))
|
||||
});
|
||||
RENAME_REFUSED.with(|c| c.set(true));
|
||||
let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root));
|
||||
RENAME_REFUSED.with(|c| c.set(false));
|
||||
BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take());
|
||||
assert!(r.is_err(), "{r:?}");
|
||||
assert!(!moved.join("doc.txt").exists(), "the removed target was created again");
|
||||
assert!(!inside.exists());
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// An existing regular file this process owns passes the check.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn protected_regular_allows_a_file_this_process_owns() {
|
||||
let d = std::fs::canonicalize(dir("protected-regular")).unwrap();
|
||||
std::fs::write(d.join("doc.txt"), b"old").unwrap();
|
||||
let folder: std::os::fd::OwnedFd = File::open(&d).unwrap().into();
|
||||
let file = OpenOptions::new().write(true).open(d.join("doc.txt")).unwrap();
|
||||
protected_regular(&folder, &file).unwrap();
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A FIFO at the name is not written into when the rename is refused: without a reader the
|
||||
/// write fails at once instead of waiting for one (without `O_NONBLOCK` this test does not
|
||||
/// return), and with a reader nothing reaches it.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_checked_write_does_not_write_into_a_fifo_at_its_name() {
|
||||
use rustix::fs::{Mode, OFlags};
|
||||
use std::io::Read as _;
|
||||
let (d, root, _) = checked_folders("checked-fifo");
|
||||
let path = root.join("inside/doc.txt");
|
||||
rustix::fs::mknodat(rustix::fs::CWD, &path, rustix::fs::FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap();
|
||||
RENAME_REFUSED.with(|c| c.set(true));
|
||||
let alone = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root));
|
||||
let reader = File::from(rustix::fs::open(&path, OFlags::RDONLY | OFlags::NONBLOCK, Mode::empty()).unwrap());
|
||||
let read = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root));
|
||||
RENAME_REFUSED.with(|c| c.set(false));
|
||||
assert!(alone.is_err() && read.is_err(), "{alone:?} {read:?}");
|
||||
let mut got = [0u8; 8];
|
||||
assert!((&reader).read(&mut got).map_or(true, |n| n == 0), "nothing is written into the FIFO");
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
/// A file in a sticky folder that others or the group can write to is refused when neither this
|
||||
/// user nor the folder's owner owns it.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_file_owned_by_someone_else_in_a_shared_sticky_folder_is_refused() {
|
||||
let (me, folder_owner, other) = (1000, 0, 2000);
|
||||
let mode = rustix::fs::Mode::from_raw_mode;
|
||||
assert!(refused_in_sticky_folder(mode(0o1777), folder_owner, other, me));
|
||||
assert!(refused_in_sticky_folder(mode(0o1770), folder_owner, other, me));
|
||||
assert!(!refused_in_sticky_folder(mode(0o1755), folder_owner, other, me));
|
||||
assert!(!refused_in_sticky_folder(mode(0o0777), folder_owner, other, me));
|
||||
assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, me, me));
|
||||
assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, folder_owner, me));
|
||||
}
|
||||
|
||||
/// A file created by another writer at the final check is preserved whether that check succeeds or fails.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
|
||||
@@ -236,6 +236,16 @@ pub struct CombTooth {
|
||||
/// The most teeth a curvature comb draws in all.
|
||||
pub const MAX_COMB_TEETH: usize = 20_000;
|
||||
|
||||
/// Does the direction `next` head back against the direction `previous`? A right angle
|
||||
/// whose dot product rounds a little below zero does not count.
|
||||
fn turns_back(previous: Vec2, next: Vec2) -> bool {
|
||||
let unit = |v: Vec2| {
|
||||
let v = v / v.x.abs().max(v.y.abs());
|
||||
v / v.hypot()
|
||||
};
|
||||
unit(previous).dot(unit(next)) < -1e-9
|
||||
}
|
||||
|
||||
/// The curvature comb of `sp`: `samples` teeth on each segment (at least 2), evenly spaced in `t`
|
||||
/// from 0 to 1, each `scale` times the signed curvature long ([`CombTooth`]). A straight segment
|
||||
/// gives teeth of no length, its ends included. A point of a curved segment where it has no
|
||||
@@ -243,6 +253,8 @@ pub const MAX_COMB_TEETH: usize = 20_000;
|
||||
/// with no length, a segment whose points are not finite, or a `scale` that is not finite. When
|
||||
/// `samples` teeth on every segment would pass `max_teeth`, every segment gets 2 teeth, and when
|
||||
/// that would still pass it, only every k-th segment gets teeth, spread along the whole subpath.
|
||||
/// The line through the tips starts again wherever the path turns back on itself, at a straight
|
||||
/// segment as at a curve.
|
||||
pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize) -> Vec<CombTooth> {
|
||||
let n = sp.segment_count();
|
||||
if n == 0 || !scale.is_finite() || max_teeth < 2 {
|
||||
@@ -279,8 +291,10 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize
|
||||
if line {
|
||||
// A line stored with its handles on its anchors has no speed at its ends, but a
|
||||
// direction and no curvature all along.
|
||||
// A line that turns back on the segment before it is a cusp at their anchor.
|
||||
let at = c.eval(t);
|
||||
previous_direction = None;
|
||||
start |= previous_direction.is_some_and(|previous| turns_back(previous, chord));
|
||||
previous_direction = Some(chord);
|
||||
if !at.is_finite() {
|
||||
start = true;
|
||||
continue;
|
||||
@@ -298,7 +312,7 @@ pub fn curvature_comb(sp: &SubPath, samples: usize, scale: f64, max_teeth: usize
|
||||
}
|
||||
let k = v.cross(a) / (speed * speed * speed);
|
||||
let direction = v / speed;
|
||||
start |= previous_direction.is_some_and(|previous| previous.dot(direction) < 0.0);
|
||||
start |= previous_direction.is_some_and(|previous| turns_back(previous, direction));
|
||||
previous_direction = Some(direction);
|
||||
let normal = Vec2::new(-direction.y, direction.x);
|
||||
let at = c.eval(t);
|
||||
@@ -333,8 +347,15 @@ pub fn comb_closes(sp: &SubPath, teeth: &[CombTooth]) -> bool {
|
||||
if !(last.segment + 1..n).chain(0..first.segment).all(no_length) {
|
||||
return false;
|
||||
}
|
||||
match (neighbor(sp, 0, false), neighbor(sp, n.saturating_sub(1), true)) {
|
||||
(Some((into, _)), Some((out, _))) => end_direction(into).dot(start_direction(out)) >= 0.0,
|
||||
match ((0..n).rev().find(|&i| !no_length(i)), (0..n).find(|&i| !no_length(i))) {
|
||||
(Some(into), Some(out)) => {
|
||||
let (a, b) = (sp.segment(into), sp.segment(out));
|
||||
// A straight segment's chord, as `curvature_comb` uses it, when the chord has a length.
|
||||
let chord = |i: usize, c: CubicBez| Some(c.p3 - c.p0).filter(|v| sp.segment_is_line(i) && v.hypot() > 0.0);
|
||||
let a = chord(into, a).unwrap_or_else(|| end_direction(a));
|
||||
let b = chord(out, b).unwrap_or_else(|| start_direction(b));
|
||||
!turns_back(a, b)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -415,6 +436,22 @@ mod tests {
|
||||
assert!(!comb_closes(&sp, &teeth), "an open subpath does not close");
|
||||
}
|
||||
|
||||
/// A curve that ends heading down, a straight segment back up from its end, and a curve that
|
||||
/// starts heading down again: both anchors are cusps, so the line through the tips starts again
|
||||
/// at each of them.
|
||||
#[test]
|
||||
fn the_comb_breaks_where_a_straight_segment_turns_back() {
|
||||
let a0 = Anchor { h_out: Point::new(0.0, -50.0), ..Anchor::corner(Point::new(0.0, 0.0)) };
|
||||
let a1 = Anchor { h_in: Point::new(100.0, -50.0), ..Anchor::corner(Point::new(100.0, 0.0)) };
|
||||
let a2 = Anchor { h_out: Point::new(100.0, -50.0), ..Anchor::corner(Point::new(100.0, -100.0)) };
|
||||
let a3 = Anchor { h_in: Point::new(200.0, -50.0), ..Anchor::corner(Point::new(200.0, -100.0)) };
|
||||
let sp = SubPath::new(vec![a0, a1, a2, a3], false);
|
||||
assert!(sp.segment_is_line(1));
|
||||
let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 9);
|
||||
assert_eq!(teeth.iter().map(|t| t.start).collect::<Vec<_>>(), [true, false, false, true, false, false, true, false, false]);
|
||||
}
|
||||
|
||||
/// A closed comb closes at its first anchor when the curve goes on smoothly there, even with a
|
||||
/// cusp elsewhere, and stays open when the first anchor is the cusp.
|
||||
#[test]
|
||||
@@ -436,6 +473,52 @@ mod tests {
|
||||
assert!(comb_closes(sp, &curvature_comb(sp, 5, 1000.0, MAX_COMB_TEETH)));
|
||||
}
|
||||
|
||||
/// A straight segment uses its chord at the seam even when a tiny handle points the other way.
|
||||
#[test]
|
||||
fn the_comb_stays_open_where_a_straight_segment_turns_back_at_the_seam() {
|
||||
let a0 = Anchor { h_in: Point::new(-1e-12, 0.0), h_out: Point::new(50.0, 0.0), ..Anchor::corner(Point::ORIGIN) };
|
||||
let a1 = Anchor { h_in: Point::new(100.0, 50.0), ..Anchor::corner(Point::new(100.0, 0.0)) };
|
||||
let mut sp = SubPath::new(vec![a0, a1], true);
|
||||
for line in [1, 0] {
|
||||
assert!(sp.segment_is_line(line));
|
||||
let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 6);
|
||||
assert!(teeth[0].at.distance(teeth[5].at) < 1e-9, "the teeth meet at the seam");
|
||||
assert!(!comb_closes(&sp, &teeth), "the chord reverses direction at the seam: {line}");
|
||||
sp.reverse();
|
||||
sp.anchors.rotate_right(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// A segment whose anchors sit on one point and whose handle is too short to count still has
|
||||
/// a direction at the seam, so a reversal there keeps the comb open.
|
||||
#[test]
|
||||
fn the_comb_stays_open_at_a_seam_segment_with_coincident_anchors() {
|
||||
let a0 = Anchor::corner(Point::ORIGIN);
|
||||
let a1 = Anchor::corner(Point::new(100.0, 0.0));
|
||||
let a2 = Anchor { h_out: Point::new(1e-12, 0.0), ..Anchor::corner(Point::ORIGIN) };
|
||||
let sp = SubPath::new(vec![a0, a1, a2], true);
|
||||
assert!(sp.segment_is_line(2));
|
||||
let teeth = curvature_comb(&sp, 3, 1000.0, MAX_COMB_TEETH);
|
||||
let (first, last) = (teeth.first().map(|t| t.at), teeth.last().map(|t| t.at));
|
||||
assert!(first.zip(last).is_some_and(|(f, l)| f.distance(l) < 1e-9), "the teeth meet at the seam: {teeth:?}");
|
||||
assert!(!comb_closes(&sp, &teeth), "the closing segment heads back against the first one");
|
||||
}
|
||||
|
||||
/// Large finite line directions still break the comb at a reversal inside the path and at its seam.
|
||||
#[test]
|
||||
fn the_comb_breaks_where_large_straight_segments_turn_back() {
|
||||
let sp = SubPath::polyline(&[Point::ORIGIN, Point::new(1e155, 0.0), Point::ORIGIN], false);
|
||||
let teeth = curvature_comb(&sp, 2, 1.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 4);
|
||||
assert!(teeth.iter().all(|t| t.at.is_finite() && t.tip.is_finite()), "{teeth:?}");
|
||||
assert_eq!(teeth.iter().map(|t| t.start).collect::<Vec<_>>(), [true, false, true, false]);
|
||||
let closed = SubPath::polyline(&[Point::ORIGIN, Point::new(1e155, 0.0)], true);
|
||||
let teeth = curvature_comb(&closed, 2, 1.0, MAX_COMB_TEETH);
|
||||
assert_eq!(teeth.len(), 4);
|
||||
assert!(!comb_closes(&closed, &teeth), "the closing chord reverses direction at the first anchor");
|
||||
}
|
||||
|
||||
/// A segment with no length and a handle drawn back onto its anchor do not panic and give no
|
||||
/// tooth where the curve has no direction; a scale that is not finite gives no comb.
|
||||
#[test]
|
||||
|
||||
@@ -33,6 +33,13 @@ use pattern::Mode;
|
||||
/// enough for a 1 MiB stack.
|
||||
pub(crate) const MAX_DEPTH: u32 = 600;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: the top-level function names that deciding the variables of block functions has
|
||||
/// gathered or looked up.
|
||||
pub(crate) static FUN_DECL_CHECKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Why code could not be compiled.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum CompileFail {
|
||||
@@ -409,6 +416,7 @@ impl<'a> FnCompiler<'a> {
|
||||
| Stmt::DefaultXmlNamespace(_) => {}
|
||||
}
|
||||
}
|
||||
let mut top_names: Option<HashSet<&Key>> = None;
|
||||
for (k, scope, id) in annex {
|
||||
let mut cur = Some(scope);
|
||||
let mut clash = params.contains(&k) || *k == *key_of("arguments");
|
||||
@@ -422,7 +430,18 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
if !clash {
|
||||
self.annex.insert(id);
|
||||
if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) {
|
||||
if seen.contains(&k) {
|
||||
continue;
|
||||
}
|
||||
// The top-level function names, gathered the first time a block function needs them.
|
||||
let top = top_names.get_or_insert_with(|| {
|
||||
#[cfg(test)]
|
||||
FUN_DECL_CHECKS.with(|c| c.set(c.get() + out.fun_decls.len() as u64));
|
||||
out.fun_decls.iter().map(|(name, _)| name).collect::<HashSet<&Key>>()
|
||||
});
|
||||
#[cfg(test)]
|
||||
FUN_DECL_CHECKS.with(|c| c.set(c.get() + 1));
|
||||
if !top.contains(&k) && annex_seen.insert(k.clone()) {
|
||||
out.annex_vars.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,6 +203,19 @@ fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() {
|
||||
assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_function_variables_look_up_each_top_level_function_name_once() {
|
||||
// 1,000 top-level functions and 1,000 block functions: each block function's variable is
|
||||
// decided with one lookup in the names gathered once, not by comparing it with every
|
||||
// top-level function.
|
||||
let top = (0..1_000).map(|i| format!("function t{i}() {{ return {i}; }}")).collect::<String>();
|
||||
let blocks = (0..1_000).map(|i| format!("{{ function b{i}() {{ return {i}; }} }}")).collect::<String>();
|
||||
crate::compiler::FUN_DECL_CHECKS.with(|c| c.set(0));
|
||||
assert_eq!(run(&format!("{top}{blocks}t999() + b999()")), JsValue::Number(1_998.0));
|
||||
let checks = crate::compiler::FUN_DECL_CHECKS.with(std::cell::Cell::get);
|
||||
assert_eq!(checks, 2_000, "top-level function names gathered and looked up for 1,000 block functions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_function_in_eval_in_a_default_parameter_leaves_a_parameter_of_its_name_alone() {
|
||||
// A parameter between the eval code and its variable environment has the name, so the block
|
||||
|
||||
@@ -1802,7 +1802,13 @@ fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> {
|
||||
if !slot(i, win, SHOWN)?.truthy() {
|
||||
return Ok(());
|
||||
}
|
||||
let hides = number_slot(i, win, HIDES)?;
|
||||
let (desc, ..) = describe(i, win)?;
|
||||
// A getter that hid or closed the palette leaves the host the controls it had then.
|
||||
let same = matches!(slot(i, win, PALETTE_ID)?, Value::Number(now) if now == id);
|
||||
if !same || !slot(i, win, SHOWN)?.truthy() || number_slot(i, win, HIDES)? != hides {
|
||||
return Ok(());
|
||||
}
|
||||
let f = host_fn(i, "paletteUpdate")?;
|
||||
i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?;
|
||||
Ok(())
|
||||
|
||||
@@ -1250,6 +1250,22 @@ fn a_hidden_palette_is_not_described_after_the_run() {
|
||||
assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_a_title_getter_hides_is_not_described_after_the_run() {
|
||||
let (mut r, calls) = palette_realm(Vec::new());
|
||||
r.run(
|
||||
"var p = new Window('palette', 'T'); p.add('button', undefined, 'Go'); p.show(); var hiding = false; \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (hiding) { hiding = false; p.hide(); return 'New'; } return 'T'; }});",
|
||||
)
|
||||
.unwrap();
|
||||
let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count();
|
||||
let before = updates(&calls);
|
||||
r.run("hiding = true;").unwrap();
|
||||
r.refresh_script_ui().expect("the refresh reads the title");
|
||||
assert_eq!(r.run("[hiding, p.visible].join()").unwrap(), JsValue::String("false,false".into()), "the getter ran and hid the palette");
|
||||
assert_eq!(updates(&calls), before, "the host keeps the controls the palette had when it was hidden");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
@@ -1339,19 +1355,24 @@ fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_th
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_throws_when_a_later_item_s_text_getter_changes_an_earlier_item_s_text() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]);
|
||||
// The second read of the second item's text, which compares it with the items the person saw,
|
||||
// changes the first item's text, which that comparison already took.
|
||||
r.run(
|
||||
"var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \
|
||||
l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \
|
||||
Object.defineProperty(l.items[1], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.items[0].text = 'z'; } return 'b'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into()));
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into()));
|
||||
// changes the first item's text, which that comparison already took. It also puts back a plain
|
||||
// `b` in place of its getter, so that only the first item's change can end the choice: without
|
||||
// that change, the same choice reaches `onChange`.
|
||||
for (mutate, error, got) in [(true, "a palette's list changed before the person's choice was taken", ""), (false, "none", "a")] {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]);
|
||||
r.run(&format!(
|
||||
"var mutate = {mutate}; var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \
|
||||
l.onChange = function () {{ got.push(String(l.selection)); }}; var reads = -1; var second = l.items[1]; \
|
||||
Object.defineProperty(second, 'text', {{configurable: true, get: function () {{ if (reads >= 0 && ++reads == 2) {{ \
|
||||
if (mutate) {{ l.items[0].text = 'z'; }} Object.defineProperty(second, 'text', {{value: 'b', writable: true, configurable: true}}); }} \
|
||||
return 'b'; }}}}); p.show();"
|
||||
))
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String(error.into()), "mutate: {mutate}");
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String(got.into()), "mutate: {mutate}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -271,7 +271,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"view.curvatureComb",
|
||||
"Show Curvature Comb",
|
||||
"",
|
||||
"{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on",
|
||||
"{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color that starts again where the path turns back on itself at a cusp, a straight segment included; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on",
|
||||
),
|
||||
(
|
||||
"type.hiddenCharacters",
|
||||
@@ -1030,7 +1030,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.paramDialog",
|
||||
"Command Dialog",
|
||||
"",
|
||||
"{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
"{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
),
|
||||
(
|
||||
"ui.recolorDialog",
|
||||
@@ -1144,7 +1144,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.sampleScreenColor",
|
||||
"Sample Color from Screen",
|
||||
"",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. Closing the Color Picker a `picker` sample is for, or stopping the script that opened it, ends the sample. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
),
|
||||
(
|
||||
"ui.newBrush",
|
||||
@@ -1216,7 +1216,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"tool.options",
|
||||
"Tool Options…",
|
||||
"",
|
||||
"{tool: id} what double-clicking a tool button opens. For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyl
Line truncated
|
||||
"{tool: id} what double-clicking a tool button opens (a missing or null tool is an error, and so is one that is not a string). For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush,
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.colorGuideOptions",
|
||||
|
||||
@@ -872,6 +872,8 @@ impl VectorcraftApp {
|
||||
toast::post(&ctx, &WindowKey::main(), Toast::new(t.message).tone(tone(t.level)).timeout(Some(t.seconds as f32)));
|
||||
}
|
||||
menus::native::sync(self, &ctx);
|
||||
// A palette event whose start failed tries again after this pass's input.
|
||||
crate::script_palettes::clear_failed_start(self, &ctx);
|
||||
// A palette event that waited for an undo group this pass ended starts its run next frame.
|
||||
if crate::script_palettes::can_start(self) {
|
||||
ctx.request_repaint();
|
||||
|
||||
@@ -311,6 +311,13 @@ pub struct SymbolInstances {
|
||||
/// One of them has a scale, rotation or shear that Reset Transformation would change; measured
|
||||
/// on the first read.
|
||||
pub transformed: Option<bool>,
|
||||
/// The names of the symbols they are instances of, each once and sorted; found on the first
|
||||
/// read.
|
||||
pub names: Option<Vec<String>>,
|
||||
/// The symbol the selected objects share when every one is a symbol instance, blank when they
|
||||
/// are instances of different symbols, and `None` inside when nothing is selected or one is not
|
||||
/// an instance; found on the first read.
|
||||
pub shared: Option<Option<String>>,
|
||||
}
|
||||
|
||||
/// [`CanvasCache::print_tiling`]: the print tiling of (document uid, revision).
|
||||
|
||||
@@ -31,6 +31,7 @@ use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::ColorMode;
|
||||
use vectorcraft_engine::cmd::color_value;
|
||||
use vectorcraft_engine::cmd::swatchlib;
|
||||
use vectorcraft_engine::script::DialogAnswer;
|
||||
|
||||
use super::preview::LivePreview;
|
||||
use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values};
|
||||
@@ -49,6 +50,9 @@ pub(crate) enum Target {
|
||||
Artboard { document: u64, reverts: u64, index: usize },
|
||||
/// A colour row `key` of the open dialog `parent`.
|
||||
Answer { parent: DialogId, key: String },
|
||||
/// The answer to a running script's `app.showColorPicker`, which opened it on `color`; `cmyk`:
|
||||
/// the run's active document is in CMYK.
|
||||
Script { color: Color, cmyk: bool },
|
||||
}
|
||||
|
||||
impl Target {
|
||||
@@ -60,7 +64,8 @@ impl Target {
|
||||
let (document, reverts) = match self {
|
||||
Self::Fill { document, reverts } | Self::Stroke { document, reverts } => (*document, *reverts),
|
||||
Self::Artboard { document, reverts, .. } => (Some(*document), *reverts),
|
||||
Self::Answer { .. } => return None,
|
||||
// A script's picker answers the run whichever document is active.
|
||||
Self::Answer { .. } | Self::Script { .. } => return None,
|
||||
};
|
||||
match (app.session.active(), document) {
|
||||
(None, None) => None,
|
||||
@@ -261,28 +266,13 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
};
|
||||
let dialogs = app.dialogs().ok_or("no window")?;
|
||||
let start = srgba(&color);
|
||||
let mut dialog = ColorPickerDialog::new(
|
||||
match (artboard, stroke) {
|
||||
(Some(_), _) => "artboard",
|
||||
(None, true) => "stroke",
|
||||
(None, false) => "fill",
|
||||
},
|
||||
tl!("Color Picker"),
|
||||
start,
|
||||
)
|
||||
.eyedropper(true)
|
||||
.add_to_swatches(false)
|
||||
.gamut(gamut(app))
|
||||
.working_rgb(WorkingRgb)
|
||||
.swatch_view(swatch_view(app));
|
||||
if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk)
|
||||
&& let Some(converter) = working_cmyk()
|
||||
{
|
||||
dialog = dialog.cmyk(&converter);
|
||||
}
|
||||
if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) {
|
||||
dialog = dialog.kept(model_values(&color));
|
||||
}
|
||||
let key = match (artboard, stroke) {
|
||||
(Some(_), _) => "artboard",
|
||||
(None, true) => "stroke",
|
||||
(None, false) => "fill",
|
||||
};
|
||||
let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk);
|
||||
let mut dialog = picker(app, key, &color, cmyk);
|
||||
// The host replaces a picker only for the same document and artboard.
|
||||
if let Some((document, _, index, _)) = artboard {
|
||||
dialog = dialog.instance((document, index));
|
||||
@@ -313,6 +303,69 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's
|
||||
/// swatches and libraries, and with `cmyk` (a CMYK document) the working CMYK inks.
|
||||
fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPickerDialog {
|
||||
let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color))
|
||||
.eyedropper(true)
|
||||
.add_to_swatches(false)
|
||||
.gamut(gamut(app))
|
||||
.working_rgb(WorkingRgb)
|
||||
.swatch_view(swatch_view(app));
|
||||
if cmyk && let Some(converter) = working_cmyk() {
|
||||
dialog = dialog.cmyk(&converter);
|
||||
}
|
||||
if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) {
|
||||
dialog = dialog.kept(model_values(color));
|
||||
}
|
||||
dialog
|
||||
}
|
||||
|
||||
/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`; `cmyk`:
|
||||
/// the run's own active document is in CMYK, which the session does not show between slices. It
|
||||
/// previews nothing; its OK and Cancel answer the run ([`finish`]).
|
||||
pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool) {
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
// The given colour's own values, so that OK can tell an untouched pick from another model's.
|
||||
// The Only Web Colors setting of earlier pickers is not recalled, so the colour opens as given.
|
||||
let dialog = picker(app, SCRIPT_KEY, &color, cmyk).kept(model_values(&color)).web_colors_remembered(false);
|
||||
let id = dialogs.with(|h| h.open(dialog));
|
||||
app.color_dialogs.pickers.retain(|o| o.id != id);
|
||||
let target = Target::Script { color, cmyk };
|
||||
app.color_dialogs.pickers.push(Open {
|
||||
id,
|
||||
target,
|
||||
start: srgba(&color),
|
||||
keep: false,
|
||||
preview: LivePreview::default(),
|
||||
view: Vec::new(),
|
||||
row: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// The key of the Color Picker a script opens.
|
||||
pub(crate) const SCRIPT_KEY: &str = "script";
|
||||
|
||||
/// The id of the Color Picker a running script waits at, while it is open or its answer is not
|
||||
/// yet given.
|
||||
pub(crate) fn script_picker(app: &VectorcraftApp) -> Option<DialogId> {
|
||||
app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script { .. })).map(|o| o.id)
|
||||
}
|
||||
|
||||
/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. A
|
||||
/// screen pick the picker started ends with it; a pick another owner started keeps running.
|
||||
pub(crate) fn forget_script(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(id) = script_picker(app) else { return };
|
||||
app.color_dialogs.pickers.retain(|o| o.id != id);
|
||||
screen_color::cancel_for(app, ctx, owner(id));
|
||||
if let Some(dialogs) = app.dialogs() {
|
||||
dialogs.with(|h| {
|
||||
h.cancel_by_id(ctx, id);
|
||||
let _ = h.take_by_id::<ColorPickerDialog>(id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason `ui.dialog.confirm` with `params` fails, when it would confirm a picker whose Recolor
|
||||
/// Artwork row changed since the picker opened (OK would then answer nothing). The picker stays open.
|
||||
pub(crate) fn check_confirm(app: &VectorcraftApp, host: &craft::ui::dialog::DialogHost, params: &Value) -> Result<(), String> {
|
||||
@@ -394,6 +447,7 @@ fn settle(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &craft::ui::sh
|
||||
})
|
||||
});
|
||||
let Some((current, gesture)) = live else {
|
||||
screen_color::cancel_for(app, ctx, owner(open.id));
|
||||
let result = dialogs.with(|h| h.take_by_id::<ColorPickerDialog>(open.id));
|
||||
finish(app, dialogs, open, result);
|
||||
return false;
|
||||
@@ -448,6 +502,15 @@ fn finish(
|
||||
dialogs.with(|h| h.answer_color(*parent, key, r.picked.color));
|
||||
}
|
||||
}
|
||||
// OK on the colour it opened with, in the model it opened with, gives that colour back.
|
||||
(Some(DialogResult::Ok(r)), Target::Script { color: given, cmyk }) => {
|
||||
let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given));
|
||||
let picked = if untouched { *given } else { in_model(*cmyk, color_of(&r.picked)) };
|
||||
app.session.script_answer(DialogAnswer::ColorPicker(Some(picked)));
|
||||
}
|
||||
(_, Target::Script { .. }) => {
|
||||
app.session.script_answer(DialogAnswer::ColorPicker(None));
|
||||
}
|
||||
(Some(DialogResult::Ok(r)), _) => {
|
||||
if let Err(e) = commit(app, open, preview, &r.picked) {
|
||||
app.status(e);
|
||||
@@ -462,14 +525,19 @@ fn paint_command(target: &Target, c: Color) -> (&'static str, Value) {
|
||||
match target {
|
||||
Target::Artboard { index, .. } => ("artboard.setProps", json!({ "index": index, "color": color_json(&c) })),
|
||||
Target::Stroke { .. } => ("paint.setStroke", json!({ "color": color_json(&c) })),
|
||||
Target::Fill { .. } | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })),
|
||||
Target::Fill { .. } | Target::Answer { .. } | Target::Script { .. } => ("paint.setFill", json!({ "color": color_json(&c) })),
|
||||
}
|
||||
}
|
||||
|
||||
/// The picked colour as the document takes it: an RGB colour is CMYK in a CMYK document; CMYK,
|
||||
/// grey and Lab colours stay as they are.
|
||||
/// The picked colour as the active document takes it ([`in_model`]).
|
||||
fn in_document_model(app: &VectorcraftApp, c: Color) -> Color {
|
||||
if matches!(c, Color::Rgb { .. }) && app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) {
|
||||
in_model(app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk), c)
|
||||
}
|
||||
|
||||
/// The picked colour as a document takes it: an RGB colour is CMYK in a CMYK document (`cmyk`);
|
||||
/// CMYK, grey and Lab colours stay as they are.
|
||||
fn in_model(cmyk: bool, c: Color) -> Color {
|
||||
if cmyk && matches!(c, Color::Rgb { .. }) {
|
||||
let [cy, m, y, k] = c.to_cmyk_managed(cms::active().settings().intent);
|
||||
return Color::cmyk(cy, m, y, k);
|
||||
}
|
||||
@@ -480,8 +548,9 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color {
|
||||
/// preview. Nothing previews until the colour first changes, nor without a selection (the colour
|
||||
/// then only becomes the default paint, on OK). An artboard shows it with or without a selection.
|
||||
fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) {
|
||||
// A picker over a command dialog only fills a row; the dialog previews it.
|
||||
if matches!(open.target, Target::Answer { .. }) || !open.target.in_active_document(app) {
|
||||
// A picker over a command dialog only fills a row; the dialog previews it. A script's picker
|
||||
// only answers the script.
|
||||
if matches!(open.target, Target::Answer { .. } | Target::Script { .. }) || !open.target.in_active_document(app) {
|
||||
return;
|
||||
}
|
||||
let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked)));
|
||||
|
||||
@@ -1188,4 +1188,89 @@ mod tests {
|
||||
assert!(lengths("select.object.hairlineSlivers").contains(&"width"));
|
||||
assert_eq!(length_range("object.path.cleanUp", "sliverWidth"), Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE));
|
||||
}
|
||||
|
||||
/// The dialogs `ui.inspect` lists, by id and key.
|
||||
fn inspected_kinds(app: &VectorcraftApp) -> Vec<Value> {
|
||||
let dialogs = app.dialogs().unwrap().with(|host| craft::automation::dialogs::inspect(host));
|
||||
dialogs.as_array().unwrap().iter().map(|d| json!([d["id"], d["key"]])).collect()
|
||||
}
|
||||
|
||||
/// `ui.paramDialog` without a command it can open, or with a label or params of the wrong type, is an error that
|
||||
/// opens no dialog and leaves the dialog already open in place.
|
||||
#[test]
|
||||
fn param_dialog_refuses_a_missing_empty_or_unknown_command() {
|
||||
let mut app = windowed();
|
||||
let refused = [
|
||||
(json!({}), "missing `command`"),
|
||||
(json!({"command": null, "params": {}}), "missing `command`"),
|
||||
(json!({"command": "", "params": {}}), "`command` must name a command"),
|
||||
(json!({"command": 5, "params": {}}), "`command` must be a string"),
|
||||
(json!({"command": "no.such", "params": {}}), "unknown command `no.such`"),
|
||||
(json!({"command": "gradient.presets.save", "label": 7, "params": {"name": "a"}}), "`label` must be a string"),
|
||||
(json!({"command": "gradient.presets.save", "params": ["a"]}), "`params` must be an object"),
|
||||
(json!({"command": "edit.findReplace", "params": "a"}), "`params` must be an object"),
|
||||
];
|
||||
for (params, want) in &refused {
|
||||
let e = app.run("ui.paramDialog", params.clone()).unwrap_err();
|
||||
assert!(e.contains(want), "{params}: {e}");
|
||||
assert!(app.command_dialog.open.is_none(), "{params}: no dialog opens");
|
||||
assert_eq!(inspected_kinds(&app), Vec::<Value>::new(), "{params}: ui.inspect lists no dialog");
|
||||
}
|
||||
app.run("ui.paramDialog", json!({"command": "gradient.presets.save", "label": "Gradient Preset", "params": {"name": "a"}})).unwrap();
|
||||
pump(&mut app);
|
||||
let (id, kinds) = (id_of(&app), inspected_kinds(&app));
|
||||
// Which opening of the dialog shows: the host numbers every open, so a dialog opened again has a new number.
|
||||
let shown_serial = |app: &VectorcraftApp, id: DialogId| app.dialogs().unwrap().with(|host| host.open_serial(id));
|
||||
let serial = shown_serial(&app, id);
|
||||
assert_eq!(kinds.len(), 1, "{kinds:?}");
|
||||
assert!(serial.is_some());
|
||||
for (params, want) in &refused {
|
||||
let e = app.run("ui.paramDialog", params.clone()).unwrap_err();
|
||||
assert!(e.contains(want), "{params}: {e}");
|
||||
assert_eq!(id_of(&app), id, "{params}: the open dialog stays");
|
||||
assert_eq!(shown_serial(&app, id), serial, "{params}: the same opening of the dialog stays");
|
||||
assert_eq!(inspected_kinds(&app), kinds, "{params}: ui.inspect lists the same dialog");
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.paramDialog` on the command of a plug-in still loading in the background waits for the plug-in to install and
|
||||
/// opens its dialog, as running the command waits for it.
|
||||
#[test]
|
||||
fn param_dialog_waits_for_a_plug_in_still_loading() {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let id = "test.ui.paramdialogloading";
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-ui-param-dialog-loading-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","commands":[{{"id":"look","label":"Look"}}]}}"#);
|
||||
std::fs::write(dir.join(format!("{id}.wasm")), wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap();
|
||||
let mut app = windowed();
|
||||
app.session.load_plugins_in_background(true);
|
||||
app.session.attach_plugin_store(dir.clone());
|
||||
let command = format!("plugin.{id}.look");
|
||||
let loading = app.session.plugins_loading();
|
||||
let before = vectorcraft_engine::find_command(&command).is_some();
|
||||
let opened = app.run("ui.paramDialog", json!({"command": command, "params": {}}));
|
||||
let (after, shown) = (vectorcraft_engine::find_command(&command).is_some(), app.command_dialog.open.is_some());
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(loading, "the store loads in the background");
|
||||
assert!(!before, "the plug-in's command is not registered while it loads");
|
||||
opened.unwrap();
|
||||
assert!(after, "the plug-in installed before the dialog opened");
|
||||
assert!(shown, "the plug-in's dialog opens");
|
||||
}
|
||||
|
||||
/// `tool.options` without a tool, or with one that is not a string, is an error that names the parameter.
|
||||
#[test]
|
||||
fn tool_options_refuses_a_missing_or_wrongly_typed_tool() {
|
||||
let mut app = windowed();
|
||||
for (params, want) in
|
||||
[(json!({}), "missing `tool`"), (json!({"tool": null}), "missing `tool`"), (json!({"tool": 3}), "`tool` must be a string")]
|
||||
{
|
||||
let e = app.run("tool.options", params.clone()).unwrap_err();
|
||||
assert!(e.contains(want), "{params}: {e}");
|
||||
assert_eq!(inspected_kinds(&app), Vec::<Value>::new(), "{params}: ui.inspect lists no dialog");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,7 @@
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::color_ui::ui::ColorPickerDialog;
|
||||
use craft::host::{PickRequest, Picked};
|
||||
use craft::keymap::Key;
|
||||
use craft::theme::variant::Tone;
|
||||
@@ -78,6 +79,7 @@ use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, Scr
|
||||
use vectorcraft_engine::script::printing::PreparedPrint;
|
||||
use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog};
|
||||
|
||||
use super::color_picker;
|
||||
use super::script_window::{self, ScriptWindow};
|
||||
use crate::VectorcraftApp;
|
||||
use crate::file_asks::{self, Owner};
|
||||
@@ -580,6 +582,22 @@ pub(crate) fn forget<D: StackDialog>(app: &VectorcraftApp) {
|
||||
});
|
||||
}
|
||||
|
||||
/// [`forget`] for the Color Picker a script's `app.showColorPicker` opened.
|
||||
pub(crate) fn forget_color_picker(app: &mut VectorcraftApp) {
|
||||
let Some(ctx) = app.ui_ctx.clone() else { return };
|
||||
if color_picker::script_picker(app).is_none() {
|
||||
return;
|
||||
}
|
||||
let asking = with_host(app, |host, _| host.is_open::<CloseQuestion>()).unwrap_or(false);
|
||||
color_picker::forget_script(app, &ctx);
|
||||
if asking {
|
||||
with_host(app, |host, _| {
|
||||
let _ = host.take::<CloseQuestion>();
|
||||
host.open(close_question());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.runScript`: the script at `path` or given as `source`; without either, pick a file.
|
||||
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
if p.get("path").is_some() || p.get("source").is_some() {
|
||||
@@ -760,11 +778,13 @@ pub(crate) fn open_picker(app: &VectorcraftApp, p: ScriptPicker) {
|
||||
/// Cancel shows again as it was, with the events a ScriptUI dialog has not given the script yet and
|
||||
/// the text typed in its fields. Any other open dialog stays, and quitting asks nothing yet.
|
||||
pub(crate) fn ask_to_close(app: &mut VectorcraftApp) {
|
||||
let picker = color_picker::script_picker(app);
|
||||
with_host(app, |host, _| {
|
||||
let own = [
|
||||
host.get::<ScriptNotice>().map(StackDialog::id),
|
||||
host.get::<ScriptFiles>().map(StackDialog::id),
|
||||
host.get::<ScriptWindow>().map(StackDialog::id),
|
||||
picker.filter(|&id| host.get_by_id::<ColorPickerDialog>(id).is_some()),
|
||||
];
|
||||
match own.into_iter().flatten().find(|id| host.stack().is_top(*id)) {
|
||||
Some(parent) => {
|
||||
@@ -887,6 +907,7 @@ fn answer_close(app: &mut VectorcraftApp, close: Option<DialogResult<<CloseQuest
|
||||
forget::<ScriptNotice>(app);
|
||||
forget::<ScriptFiles>(app);
|
||||
forget::<ScriptWindow>(app);
|
||||
forget_color_picker(app);
|
||||
app.sync_views();
|
||||
}
|
||||
}
|
||||
@@ -1199,6 +1220,8 @@ mod tests {
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
color: None,
|
||||
cmyk_document: false,
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
// A script's own confirm with the same text takes Yes.
|
||||
|
||||
@@ -218,6 +218,18 @@ pub(crate) fn keep_fields(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String>
|
||||
/// as the script in `w` would check it first; when one is refused, every field keeps its text,
|
||||
/// `events` stays as it was and the error is returned.
|
||||
pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String>, events: &mut Vec<UiEvent>) -> Result<(), String> {
|
||||
commit_texts_over(w, drafts, events, &[])
|
||||
}
|
||||
|
||||
/// [`commit_texts`] for fields whose earlier changes still wait to be delivered: a draft of a field
|
||||
/// whose id is in `queued` is given even when it matches the field's text, since the script reads the
|
||||
/// waiting change's text first.
|
||||
pub(crate) fn commit_texts_over(
|
||||
w: &ScriptUiDialog,
|
||||
drafts: &mut BTreeMap<u64, String>,
|
||||
events: &mut Vec<UiEvent>,
|
||||
queued: &[u64],
|
||||
) -> Result<(), String> {
|
||||
let mut given = Vec::new();
|
||||
let mut changes = Vec::new();
|
||||
for (i, n) in w.nodes.iter().enumerate() {
|
||||
@@ -230,7 +242,7 @@ pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String
|
||||
continue;
|
||||
}
|
||||
if let Some(text) = drafts.get(&n.id) {
|
||||
if *text != n.text {
|
||||
if *text != n.text || queued.contains(&n.id) {
|
||||
changes.push(check_event(w, UiEvent::Change(i, UiValue::Text(text.clone())))?);
|
||||
}
|
||||
given.push(n.id);
|
||||
@@ -336,7 +348,7 @@ impl StackDialog for ScriptWindow {
|
||||
let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open));
|
||||
// The body can run twice in a pass (measure, then paint), so it only reports what the
|
||||
// person did; the dialog applies the last run's report after the container.
|
||||
let shown = dialog.show(ui, |ui, _| controls(ui, window, drafts, waiting));
|
||||
let shown = dialog.show(ui, |ui, _| controls(ui, window, drafts, waiting, &[]));
|
||||
let pass = shown.inner.unwrap_or_default();
|
||||
if pass.layer.is_some() {
|
||||
self.layer = pass.layer;
|
||||
@@ -416,7 +428,7 @@ pub(crate) fn heading(w: &ScriptUiDialog) -> String {
|
||||
|
||||
/// Draws the visible controls of the ScriptUI window `w` at the places the engine laid them out,
|
||||
/// with the text typed in its edit fields (`drafts`); none can be used unless `usable`.
|
||||
pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap<u64, String>, usable: bool) -> Pass {
|
||||
pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap<u64, String>, usable: bool, queued: &[u64]) -> Pass {
|
||||
let (width, height) = w.size();
|
||||
let size = egui::vec2(width.max(1.0), height.max(1.0));
|
||||
let mut pass = Pass { layer: overlay::drawing_parent(ui.ctx()), ..Pass::default() };
|
||||
@@ -432,7 +444,13 @@ pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap<u64, S
|
||||
continue;
|
||||
}
|
||||
let parent = containers.get(n.parent).copied().flatten();
|
||||
let place = Place { origin, enabled: usable && n.enabled, default: w.default_element == Some(i), parent };
|
||||
let place = Place {
|
||||
origin,
|
||||
enabled: usable && n.enabled,
|
||||
default: w.default_element == Some(i),
|
||||
parent,
|
||||
queued_text: queued.contains(&n.id),
|
||||
};
|
||||
let shown = control(ui, drafts, &place, (i, n, prompt_of(w, i)));
|
||||
if let Some(slot) = containers.get_mut(i) {
|
||||
*slot = shown.container;
|
||||
@@ -453,6 +471,7 @@ struct Place {
|
||||
enabled: bool,
|
||||
default: bool,
|
||||
parent: Option<egui::Id>,
|
||||
queued_text: bool,
|
||||
}
|
||||
|
||||
/// What drawing a control gave: the event it gives, whether an edit field has the keyboard focus,
|
||||
@@ -531,7 +550,7 @@ fn control(ui: &mut Ui, drafts: &BTreeMap<u64, String>, place: &Place, (i, n, pr
|
||||
shown.event = Some(UiEvent::Click(i));
|
||||
}
|
||||
}
|
||||
UiKind::EditText => shown = edit(ui, rect, drafts, enabled, (i, n, prompt)),
|
||||
UiKind::EditText => shown = edit(ui, rect, drafts, enabled, place.queued_text, (i, n, prompt)),
|
||||
UiKind::DropDownList => {
|
||||
let entries: Vec<Entry<Option<usize>>> = n.items.iter().enumerate().map(|(k, item)| Entry::new(Some(k), item.clone())).collect();
|
||||
let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show_at(ui, rect);
|
||||
@@ -634,9 +653,15 @@ pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String {
|
||||
/// accepts, so that a text that is too long can still be typed, refused and shortened.
|
||||
pub(crate) const DRAFT_CHARS: usize = 2 * MAX_TEXT_BYTES;
|
||||
|
||||
/// The change an edit field `n` at index `i` gives when its text `text` is committed: none for a
|
||||
/// read-only field, or for the field's own text unless a change of the field waits (`queued`).
|
||||
pub(crate) fn text_change(i: usize, n: &UiNode, text: String, queued: bool) -> Option<UiEvent> {
|
||||
(!n.readonly && (text != n.text || queued)).then_some(UiEvent::Change(i, UiValue::Text(text)))
|
||||
}
|
||||
|
||||
/// An edit field: its text is kept in the dialog while it is typed and given to the script when
|
||||
/// the field loses the focus, or at Enter in a one-line field.
|
||||
fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown {
|
||||
fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled: bool, queued: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown {
|
||||
let mut text = drafts.get(&n.id).cloned().unwrap_or_else(|| n.text.clone());
|
||||
let mut field = TextField::new(screen_reader_name(n, prompt), Bind::bound(&mut text))
|
||||
.limit(DRAFT_CHARS)
|
||||
@@ -648,13 +673,15 @@ fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled:
|
||||
}
|
||||
let out = field.show_at(ui, rect);
|
||||
let focused = out.response.has_focus();
|
||||
let mut draft = (out.events.value().is_some() || text != n.text).then(|| Some(text.clone()));
|
||||
let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus();
|
||||
if committed && text != n.text && !n.readonly {
|
||||
return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true, container: None, draft: Some(None) };
|
||||
let queued = queued && (drafts.contains_key(&n.id) || out.events.value().is_some());
|
||||
let mut draft = (out.events.value().is_some() || text != n.text || queued).then(|| Some(text.clone()));
|
||||
// The focus is on the field's text part, so the text part's focus loss is the one that counts.
|
||||
let committed = out.submitted || out.events.committed().is_some() || out.text_lost_focus;
|
||||
if committed && let Some(event) = text_change(i, n, text.clone(), queued) {
|
||||
return Shown { event: Some(event), typing: true, container: None, draft: Some(None) };
|
||||
}
|
||||
// A text the script refused stays in the field until the person changes it.
|
||||
if !focused && text == n.text {
|
||||
if !focused && text == n.text && !queued {
|
||||
draft = Some(None);
|
||||
}
|
||||
Shown { event: None, typing: focused || committed, container: None, draft }
|
||||
|
||||
@@ -840,20 +840,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
|
||||
"ui.recolorDialog" => crate::dialogs::recolor::open(app, p),
|
||||
"ui.cropImage" if !selected_image(app, |_| true) => Err("select an image".into()),
|
||||
"ui.cropImage" => app.try_select_tool(vectorcraft_tools::cropimage::ID).map(|()| json!({"tool": app.session.tool_id()})),
|
||||
// Create Object Mosaic… has a dialog of its own, opened on the selected image.
|
||||
"ui.paramDialog" if s("command").as_deref() == Some(crate::dialogs::object_mosaic::COMMAND) => {
|
||||
crate::dialogs::object_mosaic::open(app, p.get("params").unwrap_or(&Value::Null))
|
||||
}
|
||||
"ui.paramDialog" => {
|
||||
let cmd = s("command").unwrap_or_default();
|
||||
let fields = p.get("params").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
// Find and Replace has a dialog of its own, which stays open from match to match.
|
||||
if cmd == crate::dialogs::find_replace::COMMAND {
|
||||
return Some(crate::dialogs::find_replace::open(app, &fields));
|
||||
}
|
||||
let label = s("label").unwrap_or(cmd.clone());
|
||||
crate::dialogs::command::open(app, &cmd, &label, fields)
|
||||
}
|
||||
"ui.paramDialog" => param_dialog(app, p),
|
||||
"effect.applyLast" => match app.last_effect.clone() {
|
||||
Some((e, params)) => app.run("effect.apply", json!({"effect": e, "params": params})),
|
||||
None => Err("no effect applied yet".into()),
|
||||
@@ -866,6 +853,46 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
|
||||
Some(r)
|
||||
}
|
||||
|
||||
/// `ui.paramDialog`: the parameter dialog of `command`. A missing, empty or unknown `command`, a `label` that is
|
||||
/// neither a string nor null and `params` that are neither an object nor null are errors, and no dialog opens or closes.
|
||||
/// A null `label` or `params` is treated as omitted.
|
||||
fn param_dialog(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
let cmd = match p.get("command") {
|
||||
None | Some(Value::Null) => return Err("missing `command`".into()),
|
||||
Some(Value::String(c)) if c.is_empty() => return Err("`command` must name a command".into()),
|
||||
Some(Value::String(c)) => c.clone(),
|
||||
Some(_) => return Err("`command` must be a string".into()),
|
||||
};
|
||||
let label = match p.get("label") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(l)) => Some(l.clone()),
|
||||
Some(_) => return Err("`label` must be a string".into()),
|
||||
};
|
||||
let fields = match p.get("params") {
|
||||
None | Some(Value::Null) => serde_json::Map::new(),
|
||||
Some(Value::Object(m)) => m.clone(),
|
||||
Some(_) => return Err("`params` must be an object".into()),
|
||||
};
|
||||
// A plug-in command is known once the plug-ins still loading are installed, as `Session::execute` waits for them.
|
||||
let known = |cmd: &str| vectorcraft_engine::find_command(cmd).is_some() || UI_COMMANDS.iter().any(|c| c.0 == cmd);
|
||||
if !known(&cmd) && app.session.plugins_loading() && vectorcraft_engine::cmd::plugin::is_command_id(&cmd) {
|
||||
app.session.finish_plugin_loads();
|
||||
}
|
||||
if !known(&cmd) {
|
||||
return Err(format!("unknown command `{cmd}`"));
|
||||
}
|
||||
// Create Object Mosaic… has a dialog of its own, opened on the selected image.
|
||||
if cmd == crate::dialogs::object_mosaic::COMMAND {
|
||||
return crate::dialogs::object_mosaic::open(app, p.get("params").unwrap_or(&Value::Null));
|
||||
}
|
||||
// Find and Replace has a dialog of its own, which stays open from match to match.
|
||||
if cmd == crate::dialogs::find_replace::COMMAND {
|
||||
return crate::dialogs::find_replace::open(app, &fields);
|
||||
}
|
||||
let label = label.unwrap_or_else(|| cmd.clone());
|
||||
crate::dialogs::command::open(app, &cmd, &label, fields)
|
||||
}
|
||||
|
||||
/// UI commands, part 7.
|
||||
fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<Value, String>> {
|
||||
let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string);
|
||||
@@ -952,7 +979,11 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
|
||||
"ui.newBrush" => crate::dialogs::new_brush::open(app, p.get("ids").cloned()),
|
||||
"ui.brushOptions" => crate::dialogs::brush_options::open(app, s("name").as_deref()),
|
||||
"ui.brushObjectOptions" => crate::dialogs::brush_options::open_object(app),
|
||||
"tool.options" => crate::toolbar::open_options(app, &s("tool").unwrap_or_default()),
|
||||
"tool.options" => match p.get("tool") {
|
||||
None | Some(Value::Null) => Err("missing `tool`".into()),
|
||||
Some(Value::String(t)) => crate::toolbar::open_options(app, t),
|
||||
Some(_) => Err("`tool` must be a string".into()),
|
||||
},
|
||||
_ => return None,
|
||||
};
|
||||
Some(r)
|
||||
|
||||
@@ -272,7 +272,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"view.curvatureComb",
|
||||
"Show Curvature Comb",
|
||||
"",
|
||||
"{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on",
|
||||
"{} toggle drawing the curvature comb of the selected paths and compound paths while edges show: 16 teeth per segment along the normal, on the outer side of the bend, each as long as the curvature there (a radius of 100 screen points gives a 20-point tooth at any zoom), with a line through their tips in the layer color that starts again where the path turns back on itself at a cusp, a straight segment included; about 20,000 teeth at most, fewer per segment on a large selection; a view setting, not saved in the document and not an undo step → true when on",
|
||||
),
|
||||
(
|
||||
"type.hiddenCharacters",
|
||||
@@ -1031,7 +1031,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.paramDialog",
|
||||
"Command Dialog",
|
||||
"",
|
||||
"{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
"{command, label?, params?} open a parameter dialog for any command. A missing, empty, non-string or unknown command, a label that is neither a string nor null, or params that are neither an object nor null is an error, and no dialog opens. A null label or params is treated as omitted. A plug-in command that is not installed yet waits for the plug-ins still loading. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). An action whose button the open tab does not show is refused: find runs on the Find and Replace tabs, replace, replaceFind and replaceAll on the Replace tab, done on every tab. After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
),
|
||||
(
|
||||
"ui.recolorDialog",
|
||||
@@ -1145,7 +1145,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.sampleScreenColor",
|
||||
"Sample Color from Screen",
|
||||
"",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
"{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. Closing the Color Picker a `picker` sample is for, or stopping the script that opened it, ends the sample. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open",
|
||||
),
|
||||
(
|
||||
"ui.newBrush",
|
||||
@@ -1217,7 +1217,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"tool.options",
|
||||
"Tool Options…",
|
||||
"",
|
||||
"{tool: id} what double-clicking a tool button opens. For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyl
Line truncated
|
||||
"{tool: id} what double-clicking a tool button opens (a missing or null tool is an error, and so is one that is not a string). For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush,
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.colorGuideOptions",
|
||||
|
||||
@@ -316,7 +316,7 @@ fn run_format_after_typing(app: &mut VectorcraftApp, mut p: Value, editing: Opti
|
||||
app.run("text.setRangeStyle", p)
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum FormatTarget {
|
||||
Objects(Vec<NodeId>, Option<SymbolPart>),
|
||||
Story(Vec<NodeId>),
|
||||
@@ -1323,9 +1323,66 @@ fn snap_to_glyph(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// What the bars' Font Size field edits, as its edit target: the document, how many times File ›
|
||||
/// Revert and Undo or Redo replaced its content (after which a node id can name another object),
|
||||
/// and the text `text.setStyle` changes ([`format_target`]): the range or story the Type tool has
|
||||
/// selected, all of the edited text at a caret, else the selected stories. The field drops a value
|
||||
/// typed and not yet committed when this changes, even where the new text has the same size.
|
||||
fn size_target(app: &VectorcraftApp) -> Option<(u64, u64, u64, FormatTarget)> {
|
||||
let st = app.session.active()?;
|
||||
// The range [`text_editing`] clamps to the stored text, or, while Real-time Drawing off leaves
|
||||
// typing unapplied, the Type tool's own offsets, which can reach into that typing, clamped to
|
||||
// the length the text has with it ([`pending_text_len`]). A caret changes the whole text
|
||||
// wherever it is ([`range_style`]); a range over the whole text keys as a caret does.
|
||||
let o = app.session.tool_options();
|
||||
let offset = |k: &str| o.get(k).and_then(Value::as_u64).map_or(0, |v| v as usize);
|
||||
let editing = text_editing(app).map(|(id, a, b)| {
|
||||
let unapplied_typing = o.get("typing").and_then(Value::as_bool) == Some(true)
|
||||
&& st.interaction.as_ref().is_some_and(|it| it.label == "Typing" && it.preview.is_some() && std::sync::Arc::ptr_eq(&it.doc, &st.doc));
|
||||
let (a, b, len) = if unapplied_typing {
|
||||
let (a, b) = (offset("start"), offset("end"));
|
||||
pending_text_len(st, id).map_or((a, b, None), |len| (a.min(len), b.min(len), Some(len)))
|
||||
} else {
|
||||
let len = st.doc.node(id).and_then(|node| match &node.kind {
|
||||
NodeKind::Text(t) => Some(vectorcraft_text::edit::runs_len(&t.runs)),
|
||||
_ => None,
|
||||
});
|
||||
(a, b, len)
|
||||
};
|
||||
if b > a && !(a == 0 && len.is_some_and(|len| b >= len)) { (id, a, b) } else { (id, 0, 0) }
|
||||
});
|
||||
Some((st.uid, st.reverts, st.history_restores, format_target(app, editing)))
|
||||
}
|
||||
|
||||
/// The byte length text `id` will have once the typing that Real-time Drawing off leaves unapplied
|
||||
/// is applied: the stored text with the `text.editRange` preview's range replaced by its runs.
|
||||
/// `None` for a frame of a threaded story, whose text can reflow from other frames, when the
|
||||
/// preview is not an edit of `id`, or when its range does not fit the stored text.
|
||||
fn pending_text_len(st: &DocState, id: NodeId) -> Option<usize> {
|
||||
if st.doc.story_of(id).len() > 1 {
|
||||
return None;
|
||||
}
|
||||
let (cmd, params) = st.interaction.as_ref()?.preview.as_ref()?;
|
||||
if cmd != "text.editRange" || params.get("id")?.as_u64()? != id.0 {
|
||||
return None;
|
||||
}
|
||||
let NodeKind::Text(text) = &st.doc.node(id)?.kind else { return None };
|
||||
let stored_len = vectorcraft_text::edit::runs_len(&text.runs);
|
||||
let start = usize::try_from(params.get("start")?.as_u64()?).ok()?;
|
||||
let end = usize::try_from(params.get("end")?.as_u64()?).ok()?;
|
||||
if end > stored_len {
|
||||
return None;
|
||||
}
|
||||
let removed_len = end.checked_sub(start)?;
|
||||
let inserted_len = params.get("runs")?.as_array()?.iter().try_fold(0usize, |len, run| len.checked_add(run.get("text")?.as_str()?.len()))?;
|
||||
stored_len.checked_sub(removed_len)?.checked_add(inserted_len)
|
||||
}
|
||||
|
||||
/// The Font Size field of the bars, named `name`: typed, stepped, scrubbed or picked from the
|
||||
/// presets, in the type unit, blank where the selected text's sizes differ.
|
||||
/// presets, in the type unit, blank where the selected text's sizes differ. A value typed and not
|
||||
/// yet committed stays with the text it was typed for ([`size_target`]).
|
||||
fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, name: &'static str) {
|
||||
let target = size_target(app);
|
||||
let unit = type_unit(app);
|
||||
let scale = unit_scale(unit);
|
||||
let units = Env::of(ui).units();
|
||||
@@ -1337,7 +1394,12 @@ fn size_field(app: &mut VectorcraftApp, ui: &mut Ui, name: &'static str) {
|
||||
})
|
||||
.collect();
|
||||
let mut size = shared_effective(app, |s| s.size).map(|v| v * scale);
|
||||
let out = NumberField::new(name, Bind::bound(&mut size)).unit_kind(unit.kind).range(0.1 * scale..=1296.0 * scale).presets(&presets).show(ui);
|
||||
let out = NumberField::new(name, Bind::bound(&mut size))
|
||||
.unit_kind(unit.kind)
|
||||
.range(0.1 * scale..=1296.0 * scale)
|
||||
.presets(&presets)
|
||||
.edit_target(&target)
|
||||
.show(ui);
|
||||
apply_edits(app, &out.edit, EditPath::Scope, |app, value, _| {
|
||||
if let Some(v) = value {
|
||||
style(app, json!({"size": v / scale}));
|
||||
|
||||
@@ -1482,3 +1482,273 @@ fn panels_work_out_the_selected_stories_once_per_frame() {
|
||||
STORIES_UNKEPT.set(false);
|
||||
assert!(reads > 1, "the fields read the list {reads} times");
|
||||
}
|
||||
|
||||
/// A drawing of controls over the app.
|
||||
type Draw = fn(&mut VectorcraftApp, &mut egui::Ui);
|
||||
|
||||
/// The Control bar's and the Contextual Task Bar's type controls, each drawn alone.
|
||||
const BARS: [(&str, Draw); 2] = [
|
||||
("Control bar", |app, ui| {
|
||||
control_bar(app, ui);
|
||||
}),
|
||||
("Contextual Task Bar", task_bar),
|
||||
];
|
||||
|
||||
/// Types `3+` into the bar's Font Size field without committing it.
|
||||
fn unfinished_size(p: &mut crate::tests::panel_harness::Panel) {
|
||||
p.focus(tl!("Font Size"));
|
||||
p.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
p.type_text("3+");
|
||||
}
|
||||
|
||||
/// Draws a frame, then types `1` and Enter into the Font Size field.
|
||||
fn finish_size(p: &mut crate::tests::panel_harness::Panel) {
|
||||
p.frame();
|
||||
p.type_text("1");
|
||||
p.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
}
|
||||
|
||||
/// Each run of the text `id` with its size.
|
||||
fn run_sizes(app: &VectorcraftApp, id: u64) -> Vec<(String, f64)> {
|
||||
block_text(app, NodeId(id)).runs.iter().map(|r| (r.text.clone(), r.style.size)).collect()
|
||||
}
|
||||
|
||||
/// A document with two text objects at 12 pt: `Ab` and `Cd`.
|
||||
fn two_texts() -> (VectorcraftApp, u64, u64) {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let a = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = app.run("text.create", json!({"x": 20, "y": 140, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
(app, a, b)
|
||||
}
|
||||
|
||||
/// The bars' Font Size field keeps a value typed and not yet committed while the text it was typed
|
||||
/// for stays selected, and drops it when other text with the same size is selected.
|
||||
#[test]
|
||||
fn an_unfinished_font_size_does_not_reach_other_selected_text() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
for (bar, draw) in BARS {
|
||||
let (mut app, a, b) = two_texts();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut p = Panel::new(app, draw);
|
||||
unfinished_size(&mut p);
|
||||
finish_size(&mut p);
|
||||
assert_eq!(run_sizes(&p.app(), a), [("Ab".to_string(), 4.0)], "{bar}: an unchanged selection keeps 3+");
|
||||
p.app().run("text.setStyle", json!({"ids": [a], "size": 12})).unwrap();
|
||||
|
||||
unfinished_size(&mut p);
|
||||
p.app().run("select.set", json!({"ids": [b]})).unwrap();
|
||||
finish_size(&mut p);
|
||||
let app = p.app();
|
||||
assert_eq!(
|
||||
(run_sizes(&app, a), run_sizes(&app, b)),
|
||||
(vec![("Ab".to_string(), 12.0)], vec![("Cd".to_string(), 1.0)]),
|
||||
"{bar}: b takes 1 pt, not 3+1"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// While the Type tool edits text, the field's value belongs to the selected characters: another
|
||||
/// range in the same text drops it. At a caret it belongs to the whole text, so moving the caret
|
||||
/// keeps it.
|
||||
#[test]
|
||||
fn an_unfinished_font_size_does_not_reach_another_text_range() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
for (bar, draw) in BARS {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Abcd", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.session.select_tool("type", Default::default()).unwrap();
|
||||
app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 1, "caret": 1}));
|
||||
let mut p = Panel::new(app, draw);
|
||||
unfinished_size(&mut p);
|
||||
p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 3, "caret": 3}));
|
||||
finish_size(&mut p);
|
||||
assert_eq!(run_sizes(&p.app(), id), [("Abcd".to_string(), 4.0)], "{bar}: a caret moved in the same text keeps 3+");
|
||||
p.app().run("text.setStyle", json!({"ids": [id], "size": 12})).unwrap();
|
||||
|
||||
p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 2, "caret": 2}));
|
||||
p.frame();
|
||||
unfinished_size(&mut p);
|
||||
p.app().run("select.all", json!({})).unwrap();
|
||||
finish_size(&mut p);
|
||||
assert_eq!(run_sizes(&p.app(), id), [("Abcd".to_string(), 4.0)], "{bar}: Select All after a caret keeps 3+");
|
||||
p.app().run("text.setStyle", json!({"ids": [id], "size": 12})).unwrap();
|
||||
|
||||
// Select All over text whose characters are all selected selects the same characters.
|
||||
p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 4}));
|
||||
p.frame();
|
||||
unfinished_size(&mut p);
|
||||
p.app().run("select.all", json!({})).unwrap();
|
||||
finish_size(&mut p);
|
||||
assert_eq!(run_sizes(&p.app(), id), [("Abcd".to_string(), 4.0)], "{bar}: Select All over the same characters keeps 3+");
|
||||
p.app().run("text.setStyle", json!({"ids": [id], "size": 12})).unwrap();
|
||||
|
||||
p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 2}));
|
||||
p.frame();
|
||||
unfinished_size(&mut p);
|
||||
p.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 2, "caret": 4}));
|
||||
finish_size(&mut p);
|
||||
let want = vec![("Ab".to_string(), 12.0), ("cd".to_string(), 1.0)];
|
||||
assert_eq!(run_sizes(&p.app(), id), want, "{bar}: the second range takes 1 pt, not 3+1");
|
||||
}
|
||||
}
|
||||
|
||||
/// Another document whose text has the same id and size drops the value.
|
||||
#[test]
|
||||
fn an_unfinished_font_size_does_not_reach_another_document() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let (mut app, a, _) = two_texts();
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let other = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(other, a, "both documents' texts have the same id");
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut p = Panel::new(app, task_bar);
|
||||
unfinished_size(&mut p);
|
||||
p.app().run("document.activate", json!({"index": 1})).unwrap();
|
||||
finish_size(&mut p);
|
||||
let second = run_sizes(&p.app(), a);
|
||||
p.app().run("document.activate", json!({"index": 0})).unwrap();
|
||||
let first = run_sizes(&p.app(), a);
|
||||
assert_eq!((first, second), (vec![("Ab".to_string(), 12.0)], vec![("Ab".to_string(), 1.0)]), "the other document takes 1 pt");
|
||||
}
|
||||
|
||||
/// File › Revert drops the value, though the restored text has the same id and size.
|
||||
#[test]
|
||||
fn an_unfinished_font_size_is_dropped_by_file_revert() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let (mut app, a, _) = two_texts();
|
||||
let dir = vectorcraft_testkit::TempDir::new("font-size-revert");
|
||||
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
|
||||
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
|
||||
app.run("file.saveAs", json!({"path": dir.join("Type.vectorcraft")})).unwrap();
|
||||
// An unsaved change for Revert to undo, leaving the text as saved.
|
||||
app.run("shape.rectangle", json!({"x": 100, "y": 200, "width": 20, "height": 20})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut p = Panel::new(app, task_bar);
|
||||
unfinished_size(&mut p);
|
||||
p.app().run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
p.app().run("select.set", json!({"ids": [a]})).unwrap();
|
||||
finish_size(&mut p);
|
||||
assert_eq!(run_sizes(&p.app(), a), [("Ab".to_string(), 1.0)], "Revert drops the unfinished value");
|
||||
}
|
||||
|
||||
/// Undo drops the value, though the text it takes away and the text made and selected after it
|
||||
/// have the same id and size.
|
||||
#[test]
|
||||
fn an_unfinished_font_size_is_dropped_by_undo() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
let a = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut p = Panel::new(app, task_bar);
|
||||
unfinished_size(&mut p);
|
||||
p.app().run("edit.undo", json!({})).unwrap();
|
||||
let b = p.app().run("text.create", json!({"x": 20, "y": 40, "text": "Cd", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(b, a, "the new text has the undone text's id");
|
||||
p.app().run("select.set", json!({"ids": [b]})).unwrap();
|
||||
finish_size(&mut p);
|
||||
assert_eq!(run_sizes(&p.app(), b), [("Cd".to_string(), 1.0)], "Undo drops the unfinished value");
|
||||
}
|
||||
|
||||
/// With Real-time Drawing off, a Type tool range that reaches into typing not applied yet is
|
||||
/// another range than the applied text it starts in.
|
||||
#[test]
|
||||
fn an_unfinished_font_size_does_not_reach_a_range_with_unapplied_typing() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.select_tool("type");
|
||||
app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
|
||||
app.session.set_tool_option("select", &json!({"start": 2, "end": 2}));
|
||||
let mut app = crate::testing::windowed(app);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
// The keymap builds in the first pass.
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]);
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![egui::Event::Text("Cd".into())]);
|
||||
assert_eq!(app.session.tool_options()["typing"], json!(true));
|
||||
assert_eq!(run_sizes(&app, id), [("Ab".to_string(), 12.0)], "the typing is not applied yet");
|
||||
app.session.set_tool_option("select", &json!({"start": 0, "end": 2}));
|
||||
let mut p = Panel::new(app, task_bar);
|
||||
unfinished_size(&mut p);
|
||||
p.app().session.set_tool_option("select", &json!({"start": 0, "end": 4}));
|
||||
finish_size(&mut p);
|
||||
assert_eq!(run_sizes(&p.app(), id), [("AbCd".to_string(), 1.0)], "the longer range takes 1 pt, not 3+1");
|
||||
}
|
||||
|
||||
/// With Real-time Drawing off, deleting a paragraph break pulls text from the next frame when
|
||||
/// typing is applied. A different range drops the unfinished size before that reflow.
|
||||
#[test]
|
||||
fn an_unfinished_font_size_does_not_reach_a_range_in_threaded_text_with_unapplied_typing() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 300})).unwrap();
|
||||
app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
|
||||
let area = json!({"x": 10, "y": 10, "text": "a\nb", "size": 12, "area": {"width": 150, "height": 20}});
|
||||
let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap();
|
||||
let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(story_frame(&app, a).plain_text(), "a\n");
|
||||
assert_eq!(story_frame(&app, b).plain_text(), "b");
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
app.select_tool("type");
|
||||
app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
|
||||
app.session.set_tool_option("select", &json!({"start": 2, "end": 2}));
|
||||
let mut app = crate::testing::windowed(app);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
// The first frame builds the keymap.
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]);
|
||||
let backspace = |pressed| egui::Event::Key {
|
||||
key: egui::Key::Backspace,
|
||||
physical_key: Some(egui::Key::Backspace),
|
||||
pressed,
|
||||
repeat: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![backspace(true), backspace(false)]);
|
||||
assert_eq!(app.session.tool_options()["typing"], json!(true));
|
||||
assert_eq!(story_frame(&app, a).plain_text(), "a\n", "the deletion is not applied yet");
|
||||
app.session.set_tool_option("select", &json!({"start": 0, "end": 1}));
|
||||
let mut p = Panel::new(app, task_bar);
|
||||
unfinished_size(&mut p);
|
||||
p.app().session.set_tool_option("select", &json!({"start": 0, "end": 2}));
|
||||
finish_size(&mut p);
|
||||
assert_eq!(run_sizes(&p.app(), a), [("ab".to_string(), 1.0)], "the longer range takes 1 pt, not 3+1");
|
||||
assert_eq!(story_frame(&p.app(), b).plain_text(), "", "the following text flows into the first frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfinished_font_size_stays_when_typing_is_kept() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
for real_time_drawing in [true, false] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
app.session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time_drawing})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 20, "y": 40, "text": "Ab", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.select_tool("type");
|
||||
app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
|
||||
app.session.set_tool_option("select", &json!({"start": 2, "end": 2}));
|
||||
let mut app = crate::testing::windowed(app);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
// The keymap builds in the first pass.
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]);
|
||||
crate::tests::synthetic::key_frame(&mut app, &ctx, vec![egui::Event::Text("Cd".into())]);
|
||||
assert_eq!(app.session.tool_options()["typing"], json!(true), "realTimeDrawing={real_time_drawing}");
|
||||
let stored_text = if real_time_drawing { "AbCd" } else { "Ab" };
|
||||
assert_eq!(run_sizes(&app, id), [(stored_text.to_string(), 12.0)], "typing before keeping, realTimeDrawing={real_time_drawing}");
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let mut p = Panel::new(app, task_bar);
|
||||
unfinished_size(&mut p);
|
||||
p.app().keep_typing().unwrap();
|
||||
assert_ne!(p.app().session.tool_options()["typing"], json!(true), "realTimeDrawing={real_time_drawing}");
|
||||
finish_size(&mut p);
|
||||
assert_eq!(run_sizes(&p.app(), id), [("AbCd".to_string(), 4.0)], "the kept typing keeps 3+, realTimeDrawing={real_time_drawing}");
|
||||
}
|
||||
}
|
||||
@@ -323,12 +323,9 @@ fn instance_flags(app: &VectorcraftApp) -> InstanceFlags {
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of the symbols the selected instances are instances of, each once.
|
||||
fn linked_symbols(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return vec![] };
|
||||
let Some(found) = selected_instances(app) else { return vec![] };
|
||||
let mut names: Vec<String> = found
|
||||
.ids
|
||||
/// The names of the symbols the instances `ids` of `doc` are instances of, each once and sorted.
|
||||
fn symbol_names(doc: &Document, ids: &[NodeId]) -> Vec<String> {
|
||||
let mut names: Vec<String> = ids
|
||||
.iter()
|
||||
.filter_map(|id| match doc.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.clone()),
|
||||
@@ -340,6 +337,15 @@ fn linked_symbols(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
names
|
||||
}
|
||||
|
||||
/// The names of the symbols the selected instances are instances of, each once, looked up once per
|
||||
/// (document uid, revision) ([`SymbolInstances::names`]).
|
||||
fn linked_symbols(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return vec![] };
|
||||
let Some(found) = selected_instances(app) else { return vec![] };
|
||||
let ids = &found.ids;
|
||||
found.names.get_or_insert_with(|| symbol_names(&doc, ids)).clone()
|
||||
}
|
||||
|
||||
/// Collect the IDs of selected instances of symbol `name` (including inside groups).
|
||||
fn selected_symbol_instances(app: &VectorcraftApp, name: &str) -> Vec<u64> {
|
||||
let mut ids = vec![];
|
||||
@@ -431,19 +437,40 @@ fn transformed_instances_selected(app: &mut VectorcraftApp) -> bool {
|
||||
*found.transformed.get_or_insert_with(|| transformed(&doc, ids))
|
||||
}
|
||||
|
||||
/// The symbols of the selected objects when every one is a symbol instance; `None` otherwise.
|
||||
fn selected_instance_symbols(app: &VectorcraftApp) -> Option<Vec<String>> {
|
||||
/// The symbol the selected objects of `st` share when every one is a symbol instance, blank when
|
||||
/// they are instances of different symbols; `None` when nothing is selected or one is not an
|
||||
/// instance.
|
||||
fn shared_symbol(st: &DocState) -> Option<String> {
|
||||
let mut shared: Option<&str> = None;
|
||||
for id in &st.selection.objects {
|
||||
let Some(NodeKind::SymbolInstance { symbol, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return None };
|
||||
if shared.is_some_and(|s| s != symbol) {
|
||||
shared = Some("");
|
||||
} else if shared.is_none() {
|
||||
shared = Some(symbol);
|
||||
}
|
||||
}
|
||||
shared.map(str::to_string)
|
||||
}
|
||||
|
||||
/// [`shared_symbol`] of the active document, kept in [`SymbolInstances::shared`] once per
|
||||
/// (document uid, revision). While that version's selection has not been walked for its instances,
|
||||
/// the walk runs only when instances alone are selected, so a selected group is not walked for the
|
||||
/// Control bar.
|
||||
fn selected_shared_symbol(app: &mut VectorcraftApp) -> Option<String> {
|
||||
let st = app.session.active()?;
|
||||
let symbols: Option<Vec<String>> = st
|
||||
.selection
|
||||
.objects
|
||||
.iter()
|
||||
.map(|id| match st.doc.node(*id).map(|n| &n.kind) {
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
symbols.filter(|s| !s.is_empty())
|
||||
let walked = match &app.canvas.symbol_instances {
|
||||
Some((key, found)) if *key == (st.uid, st.revision) => match &found.shared {
|
||||
Some(shared) => return shared.clone(),
|
||||
None => true,
|
||||
},
|
||||
_ => false,
|
||||
};
|
||||
let shared = shared_symbol(st);
|
||||
if walked || shared.is_some() {
|
||||
selected_instances(app)?.shared = Some(shared.clone());
|
||||
}
|
||||
shared
|
||||
}
|
||||
|
||||
/// The Control bar's Replace menu while symbol instances alone are selected: the document's
|
||||
@@ -456,10 +483,9 @@ fn selected_instance_symbols(app: &VectorcraftApp) -> Option<Vec<String>> {
|
||||
/// by its rank before the Transform link. Returns whether it drew them (symbol instances alone are
|
||||
/// selected).
|
||||
pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
let Some(symbols) = selected_instance_symbols(app) else { return false };
|
||||
let Some(shared) = selected_shared_symbol(app) else { return false };
|
||||
let Some(st) = app.session.active() else { return false };
|
||||
let entries: Vec<Entry<String>> = st.doc.symbols.iter().map(|s| Entry::new(s.name.clone(), s.name.clone())).collect();
|
||||
let shared = symbols.first().filter(|first| symbols.iter().all(|s| s == *first)).cloned().unwrap_or_default();
|
||||
// Reset: Reset Transformation, enabled while an instance's scale, rotation or shear differs
|
||||
// from its symbol's.
|
||||
let transformed = transformed_instances_selected(app);
|
||||
|
||||
@@ -1173,6 +1173,127 @@ fn properties_and_symbols_panels_walk_the_selection_once_per_revision() {
|
||||
assert_eq!(scans(), before + 1);
|
||||
}
|
||||
|
||||
/// The names of the symbols the selected instances are instances of, each once, found by walking
|
||||
/// every selected subtree on each call: what the cached list must match.
|
||||
fn walked_names(app: &VectorcraftApp) -> Vec<String> {
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
let mut names = vec![];
|
||||
for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) {
|
||||
n.walk(&mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
names.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
names.sort();
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// [`panel_and_bar_lookups`] of this thread.
|
||||
static PANEL_AND_BAR_LOOKUPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The lookups by id that [`panel_and_bar`] has made on this thread, without those of the menus
|
||||
/// the harness's frames rebuild.
|
||||
fn panel_and_bar_lookups() -> u64 {
|
||||
PANEL_AND_BAR_LOOKUPS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The Symbols panel and the symbol instances' controls of the Control bar.
|
||||
fn panel_and_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let before = vectorcraft_doc::path_lookups();
|
||||
show(app, ui);
|
||||
control_bar(app, ui);
|
||||
PANEL_AND_BAR_LOOKUPS.with(|n| n.set(n.get() + vectorcraft_doc::path_lookups() - before));
|
||||
}
|
||||
|
||||
/// The Symbols panel finds the names of the selected instances' symbols, and the Control bar the
|
||||
/// symbol they share, once per document revision: over idle frames with 1,024 instances selected,
|
||||
/// their draws look up at most one node per instance in all, and both follow a rename, Undo and a
|
||||
/// new selection.
|
||||
#[test]
|
||||
fn linked_symbol_names_are_found_once_per_revision() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
|
||||
for (x, name) in [(10, "S"), (60, "T")] {
|
||||
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
app.run("symbol.new", json!({"name": name})).unwrap();
|
||||
}
|
||||
// Two instances, doubled nine times.
|
||||
for _ in 0..9 {
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
app.run("edit.duplicate", json!({})).unwrap();
|
||||
}
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let instances = app.session.active().map_or(0, |st| st.selection.objects.len()) as u64;
|
||||
assert_eq!(instances, 1024);
|
||||
let mut p = harness(app, panel_and_bar);
|
||||
assert_eq!(linked_symbols(&mut p.app()), ["S", "T"]);
|
||||
let before = panel_and_bar_lookups();
|
||||
for _ in 0..10 {
|
||||
p.frame();
|
||||
}
|
||||
let lookups = panel_and_bar_lookups() - before;
|
||||
assert!(lookups <= instances, "10 idle frames looked up {lookups} nodes for {instances} selected instances");
|
||||
let check = |p: &mut Panel, want: &[&str], shared: Option<&str>, what: &str| {
|
||||
p.frame();
|
||||
let mut app = p.app();
|
||||
assert_eq!(linked_symbols(&mut app), want, "{what}");
|
||||
assert_eq!(walked_names(&app), want, "{what}: a walk of the selection agrees");
|
||||
assert_eq!(selected_shared_symbol(&mut app).as_deref(), shared, "{what}: the Control bar's symbol");
|
||||
assert_eq!(app.session.active().and_then(shared_symbol).as_deref(), shared, "{what}: a walk of the selection agrees");
|
||||
};
|
||||
check(&mut p, &["S", "T"], Some(""), "two symbols' instances");
|
||||
p.app().run("symbol.options", json!({"name": "S", "newName": "R"})).unwrap();
|
||||
check(&mut p, &["R", "T"], Some(""), "after a rename");
|
||||
p.app().run("edit.undo", json!({})).unwrap();
|
||||
check(&mut p, &["S", "T"], Some(""), "after Undo");
|
||||
let t = instance_of(&p.app(), "T").expect("a T instance");
|
||||
p.app().run("select.set", json!({"ids": [t.0]})).unwrap();
|
||||
check(&mut p, &["T"], Some("T"), "one T instance selected");
|
||||
p.app().run("symbol.options", json!({"name": "T", "newName": "U"})).unwrap();
|
||||
check(&mut p, &["U"], Some("U"), "the selected instance's symbol renamed");
|
||||
let group = p.app().run("object.group", json!({})).unwrap()["id"].clone();
|
||||
p.app().run("select.set", json!({"ids": [group]})).unwrap();
|
||||
check(&mut p, &["U"], None, "the instance in a selected group");
|
||||
p.app().run("select.none", json!({})).unwrap();
|
||||
check(&mut p, &[], None, "nothing selected");
|
||||
}
|
||||
|
||||
/// The Control bar's symbol does not walk a selected group for its instances while no reader has
|
||||
/// walked that document version, as a group never shows the symbol controls; instances alone
|
||||
/// selected are walked once, and a version already walked keeps its answer.
|
||||
#[test]
|
||||
fn the_control_bar_walks_only_a_selection_of_instances() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap();
|
||||
let inst = app.run("symbol.new", json!({"name": "S"})).unwrap()["id"].clone();
|
||||
app.run("select.set", json!({"ids": [inst]})).unwrap();
|
||||
let group = app.run("object.group", json!({})).unwrap()["id"].clone();
|
||||
app.run("select.set", json!({"ids": [group]})).unwrap();
|
||||
let before = scans();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(selected_shared_symbol(&mut app), None, "a selected group");
|
||||
}
|
||||
assert_eq!(scans(), before, "a selected group is not walked");
|
||||
assert!(has_instances_selected(&mut app), "the panel's readers walk the group");
|
||||
let lookups = vectorcraft_doc::path_lookups();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(selected_shared_symbol(&mut app), None, "a walked group");
|
||||
}
|
||||
let lookups = vectorcraft_doc::path_lookups() - lookups;
|
||||
assert!(lookups <= 1, "3 reads of a walked group's symbol looked up {lookups} nodes");
|
||||
assert_eq!(scans(), before + 1, "one walk for the group");
|
||||
app.run("select.set", json!({"ids": [inst]})).unwrap();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(selected_shared_symbol(&mut app).as_deref(), Some("S"), "a selected instance");
|
||||
}
|
||||
assert_eq!(scans(), before + 2, "one walk for the instance");
|
||||
}
|
||||
|
||||
/// The picture the panel's tile shows of an imported symbol frames the symbol's whole art.
|
||||
#[test]
|
||||
fn an_imported_symbols_thumbnail_frames_its_whole_art() {
|
||||
|
||||
@@ -433,9 +433,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let states = row_states(st);
|
||||
let sort = st.variables_sort;
|
||||
let doc_uid = st.uid;
|
||||
let reverts = st.reverts;
|
||||
let (mut acts, mut pressed) = (Vec::new(), None);
|
||||
Stack::new().fill().footer(|ui, _| pressed = footer(ui, &states)).show(ui, |ui, _| {
|
||||
data_set_bar(ui, &rows.sets, &mut acts);
|
||||
data_set_bar(ui, &rows.sets, (doc_uid, reverts), &mut acts);
|
||||
variable_table(ui, &rows.vars, sort, &states, doc_uid, &mut acts);
|
||||
Text::new(tl!("Data Sets")).role(TypeRole::Heading).show(ui);
|
||||
data_set_list(ui, &rows.sets, &mut acts);
|
||||
@@ -463,9 +464,15 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The current data set across the top: its name in a box that renames it, the list that chooses
|
||||
/// another, and the arrows that step through them.
|
||||
fn data_set_bar(ui: &mut Ui, sets: &[SetRow], acts: &mut Vec<Act>) {
|
||||
/// The current data set across the top: its name in a box that renames it when the typed name is
|
||||
/// committed (Enter or leaving the box), the list that chooses another, and the arrows that step
|
||||
/// through them. `doc` is the document's uid and how many times File › Revert replaced its
|
||||
/// content. With the current data set's name, it is the box's edit target, so a name typed or
|
||||
/// being composed and not yet committed is dropped when another document, a reverted one or a data
|
||||
/// set with another name becomes current. Data sets have no identity besides their names, so a
|
||||
/// data set that replaces the current one under the same name in the same document takes the
|
||||
/// unfinished name.
|
||||
fn data_set_bar(ui: &mut Ui, sets: &[SetRow], doc: (u64, u64), acts: &mut Vec<Act>) {
|
||||
let current = sets.iter().find(|s| s.active).map(|s| s.name.as_str());
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Field::new(tl!("Data Set")).show(ui, |ui, _| {
|
||||
@@ -477,9 +484,10 @@ fn data_set_bar(ui: &mut Ui, sets: &[SetRow], acts: &mut Vec<Act>) {
|
||||
}),
|
||||
)
|
||||
.enabled(current.is_some())
|
||||
.edit_target((doc, current))
|
||||
.show(ui)
|
||||
.events
|
||||
.landed()
|
||||
.committed()
|
||||
.cloned();
|
||||
if let (Some(from), Some(to)) = (current, typed) {
|
||||
acts.push(Act::Rename(from.to_owned(), to));
|
||||
@@ -1212,6 +1220,158 @@ mod tests {
|
||||
assert_eq!(undo_steps(&app), before + 1);
|
||||
}
|
||||
|
||||
/// A document whose one data set, "Spring", is current.
|
||||
fn add_spring(app: &mut VectorcraftApp) {
|
||||
let t = app.run("text.create", json!({"x": 10, "y": 40, "text": "Alice"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("variable.define", json!({"name": "Name", "kind": "text"})).unwrap();
|
||||
app.run("variable.bind", json!({"variable": "Name", "ids": [t]})).unwrap();
|
||||
app.run("dataset.capture", json!({})).unwrap();
|
||||
app.run("dataset.rename", json!({"name": "Data Set 1", "newName": "Spring"})).unwrap();
|
||||
}
|
||||
|
||||
/// Clicks the Data Set box and types `text` over its name without pressing Enter.
|
||||
fn start_typing(panel: &mut crate::tests::panel_harness::Panel, text: &str) {
|
||||
panel.click_role(tl!("Data Set"), craft::ui::contract::Role::TEXT_INPUT);
|
||||
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
|
||||
panel.type_text(text);
|
||||
}
|
||||
|
||||
/// A name typed into the Data Set box renames nothing until it is committed, and it is dropped
|
||||
/// when another document becomes current, even when that document's current data set has the
|
||||
/// same name: Enter there renames neither document's data set.
|
||||
#[test]
|
||||
fn an_unfinished_data_set_name_does_not_rename_another_documents_data_set() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
for _ in 0..2 {
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
add_spring(&mut app);
|
||||
}
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
let steps = undo_steps(&app);
|
||||
let mut panel = Panel::new(app, show);
|
||||
let names = |panel: &Panel| -> Vec<Vec<String>> {
|
||||
panel.app().session.documents().iter().map(|st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect()).collect()
|
||||
};
|
||||
start_typing(&mut panel, "Summer");
|
||||
assert_eq!(names(&panel), [["Spring"], ["Spring"]], "typing renames nothing before Enter");
|
||||
assert_eq!(undo_steps(&panel.app()), steps, "typing adds no undo step");
|
||||
panel.app().run("document.activate", json!({"index": 1})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let field = craft::ui::contract::Role::TEXT_INPUT;
|
||||
assert!(panel.focused_nth(field, 0), "the box keeps the focus through the switch");
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Spring"), "the box shows the other document's name");
|
||||
assert_eq!(names(&panel), [["Spring"], ["Spring"]], "switching documents renames nothing");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(names(&panel), [["Spring"], ["Spring"]], "Enter in the other document renames neither data set");
|
||||
}
|
||||
|
||||
/// A name typed into the Data Set box and not yet committed is dropped by File › Revert, which
|
||||
/// restores a data set of the same name: Enter afterwards does not rename the restored one.
|
||||
#[test]
|
||||
fn an_unfinished_data_set_name_does_not_rename_the_data_set_file_revert_restores() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
|
||||
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
add_spring(&mut app);
|
||||
let dir = vectorcraft_testkit::TempDir::new("variables-revert");
|
||||
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
|
||||
// An unsaved edit, so the revert has changes to throw away.
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
start_typing(&mut panel, "Summer");
|
||||
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring"], "the revert restores the data set");
|
||||
let steps = undo_steps(&panel.app());
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let field = craft::ui::contract::Role::TEXT_INPUT;
|
||||
assert!(panel.focused_nth(field, 0), "the box keeps the focus through the revert");
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Spring"), "the box shows the restored name");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring"], "the restored data set keeps its name");
|
||||
assert_eq!(undo_steps(&panel.app()), steps, "no rename runs");
|
||||
}
|
||||
|
||||
/// A name typed into the Data Set box and not yet committed is dropped when another data set of
|
||||
/// the same document becomes current: Enter afterwards renames neither data set. With the same
|
||||
/// data set current, Enter renames it.
|
||||
#[test]
|
||||
fn an_unfinished_data_set_name_does_not_rename_the_next_data_set() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
add_spring(&mut app);
|
||||
app.run("dataset.capture", json!({"name": "Autumn"})).unwrap();
|
||||
app.run("dataset.select", json!({"name": "Spring"})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
start_typing(&mut panel, "Summer");
|
||||
panel.app().run("dataset.next", json!({})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let field = craft::ui::contract::Role::TEXT_INPUT;
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Autumn"), "the box shows the next data set's name");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring", "Autumn"], "Enter renames neither data set");
|
||||
start_typing(&mut panel, "Winter");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring", "Winter"], "Enter renames the data set the name was typed for");
|
||||
}
|
||||
|
||||
/// A name being composed with an input method in the Data Set box is dropped when another data
|
||||
/// set becomes current: the composition's commit and Enter rename neither data set.
|
||||
#[test]
|
||||
fn a_composed_data_set_name_does_not_rename_the_next_data_set() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
add_spring(&mut app);
|
||||
app.run("dataset.capture", json!({"name": "Autumn"})).unwrap();
|
||||
app.run("dataset.select", json!({"name": "Spring"})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
panel.click_role(tl!("Data Set"), craft::ui::contract::Role::TEXT_INPUT);
|
||||
let preedit = |text: &str| egui::Event::Ime(egui::ImeEvent::Preedit { text: text.into(), active_range_chars: Some(0..text.chars().count()) });
|
||||
let field = craft::ui::contract::Role::TEXT_INPUT;
|
||||
panel.frame_with(vec![preedit("Sum")]);
|
||||
assert!(panel.value_role(tl!("Data Set"), field).is_some_and(|name| name.contains("Sum")), "the box shows the composition");
|
||||
panel.app().run("dataset.next", json!({})).unwrap();
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
assert!(panel.focused_nth(field, 0), "the box keeps the focus through the switch");
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Autumn"), "the box shows the next data set's name");
|
||||
panel.frame_with(vec![egui::Event::Ime(egui::ImeEvent::Commit("Summer".into()))]);
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Autumn"), "the commit does not reach the box");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring", "Autumn"], "the composition renames neither data set");
|
||||
}
|
||||
|
||||
/// Leaving the Data Set box with Tab commits the typed name as one undo step, and Escape puts
|
||||
/// the current name back without renaming anything.
|
||||
#[test]
|
||||
fn leaving_the_data_set_box_renames_once_and_escape_renames_nothing() {
|
||||
use crate::tests::panel_harness::Panel;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
add_spring(&mut app);
|
||||
let steps = undo_steps(&app);
|
||||
let mut panel = Panel::new(app, show);
|
||||
let field = craft::ui::contract::Role::TEXT_INPUT;
|
||||
start_typing(&mut panel, "Summer");
|
||||
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
|
||||
assert_eq!(panel.value_role(tl!("Data Set"), field).as_deref(), Some("Spring"), "Escape puts the name back");
|
||||
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring"], "Escape renames nothing");
|
||||
assert_eq!(undo_steps(&panel.app()), steps, "Escape adds no undo step");
|
||||
start_typing(&mut panel, "Summer");
|
||||
assert_eq!(set_names(&mut panel.app()), ["Spring"], "typing renames nothing");
|
||||
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
|
||||
assert_eq!(set_names(&mut panel.app()), ["Summer"], "Tab commits the typed name");
|
||||
assert_eq!(undo_steps(&panel.app()), steps + 1, "the rename is one undo step");
|
||||
}
|
||||
|
||||
/// A press on a column header sorts the list by that column, and a second press on it reverses
|
||||
/// the order, as `variable.list` reports it; sorting is not an edit.
|
||||
#[test]
|
||||
|
||||
@@ -41,6 +41,33 @@ fn remember_doc(app: &VectorcraftApp, ctx: &egui::Context) {
|
||||
ctx.data_mut(|d| d.insert_temp(doc_key(), uid));
|
||||
}
|
||||
|
||||
/// Where the owner of the running pick is kept, as a hash of its key.
|
||||
fn owner_key() -> egui::Id {
|
||||
egui::Id::unique("screen-color-owner")
|
||||
}
|
||||
|
||||
fn owner_hash(owner: impl Hash) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
owner.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn remember_owner(ctx: &egui::Context, owner: impl Hash) {
|
||||
let key = owner_hash(owner);
|
||||
ctx.data_mut(|d| d.insert_temp(owner_key(), key));
|
||||
}
|
||||
|
||||
/// Ends the running pick when `owner` started it, and drops a color `owner` has not taken yet; a
|
||||
/// pick another owner started keeps running. The next pass finishes a capture the cancel ends.
|
||||
pub(crate) fn cancel_for(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash) {
|
||||
let started_by = ctx.data(|d| d.get_temp::<u64>(owner_key()));
|
||||
if app.screen_pick.busy() && started_by == Some(owner_hash(&owner)) {
|
||||
app.screen_pick.cancel();
|
||||
ctx.request_repaint();
|
||||
}
|
||||
let _ = app.screen_pick.take(owner);
|
||||
}
|
||||
|
||||
/// The platform can capture the screen: the shell's capabilities say so and no capture has said it
|
||||
/// cannot. Without a window there is nothing to capture.
|
||||
pub fn available(app: &VectorcraftApp) -> bool {
|
||||
@@ -65,6 +92,10 @@ pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
}
|
||||
if let Some(ctx) = app.ui_ctx.clone() {
|
||||
remember_doc(app, &ctx);
|
||||
match picker {
|
||||
Some(id) => remember_owner(&ctx, crate::dialogs::color_picker::owner(id)),
|
||||
None => remember_owner(&ctx, if stroke { STROKE } else { FILL }),
|
||||
}
|
||||
}
|
||||
match picker {
|
||||
Some(id) => app.screen_pick.start(crate::dialogs::color_picker::owner(id)),
|
||||
@@ -78,6 +109,7 @@ pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
pub(crate) fn hold(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash, gesture: ScreenPickGesture) -> Option<Srgba> {
|
||||
if !app.screen_pick.busy() {
|
||||
remember_doc(app, ctx);
|
||||
remember_owner(ctx, &owner);
|
||||
}
|
||||
app.screen_pick.hold(ctx, owner, gesture)
|
||||
}
|
||||
|
||||
@@ -89,6 +89,35 @@ fn the_color_pickers_eyedropper_samples_into_it() {
|
||||
assert_eq!(paints(&app).0, "#123456");
|
||||
}
|
||||
|
||||
/// Closing the Color Picker ends the sample its eyedropper started.
|
||||
#[test]
|
||||
fn closing_the_color_picker_ends_its_sample() {
|
||||
let (mut app, ctx) = app();
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
let id = app.color_dialogs.pickers.last().unwrap().id;
|
||||
assert_eq!(hold(&mut app, &ctx, crate::dialogs::color_picker::owner(id), ScreenPickGesture::Clicked), None);
|
||||
assert!(app.screen_pick.busy());
|
||||
assert!(app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id)));
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::color_picker::pump(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
assert!(app.color_dialogs.pickers.is_empty());
|
||||
assert!(!app.screen_pick.busy(), "the sample ends with the picker");
|
||||
}
|
||||
|
||||
/// Ending a picker's pick drops the color it sampled and has not taken yet; another owner's color
|
||||
/// stays.
|
||||
#[test]
|
||||
fn ending_a_pick_drops_the_color_its_owner_has_not_taken() {
|
||||
let (mut app, ctx) = app();
|
||||
for own in [true, false] {
|
||||
assert_eq!(hold(&mut app, &ctx, "picker", ScreenPickGesture::Clicked), None);
|
||||
finish(&mut app, &ctx, Ok(srgba("#123456")));
|
||||
assert!(!app.screen_pick.busy(), "the capture finished");
|
||||
cancel_for(&mut app, &ctx, if own { "picker" } else { "other" });
|
||||
assert_eq!(take(&mut app, &ctx, "picker").is_some(), !own, "own {own}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A canceled capture changes nothing; a failed one reaches the status line.
|
||||
#[test]
|
||||
fn cancel_and_errors_leave_the_art_alone() {
|
||||
|
||||
@@ -55,12 +55,21 @@ pub(crate) struct PaletteWindow {
|
||||
/// field shows it until no change of that field waits, even while the palette's field holds the
|
||||
/// same text, since a run before the change may set the field to another one.
|
||||
pending: BTreeMap<u64, String>,
|
||||
queued_texts: Vec<u64>,
|
||||
open: bool,
|
||||
}
|
||||
|
||||
impl PaletteWindow {
|
||||
fn new(palette: ScriptPalette) -> Self {
|
||||
PaletteWindow { palette, drafts: BTreeMap::new(), draft_scopes: BTreeMap::new(), given: Vec::new(), pending: BTreeMap::new(), open: true }
|
||||
PaletteWindow {
|
||||
palette,
|
||||
drafts: BTreeMap::new(),
|
||||
draft_scopes: BTreeMap::new(),
|
||||
given: Vec::new(),
|
||||
pending: BTreeMap::new(),
|
||||
queued_texts: Vec::new(),
|
||||
open: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The palette as the session has it now. A typed text whose field the palette no longer has is
|
||||
@@ -68,6 +77,7 @@ impl PaletteWindow {
|
||||
/// [`vectorcraft_engine::Session::script_palette_changes_waiting`]).
|
||||
fn sync(&mut self, palette: ScriptPalette, waiting: &[(u64, u64)]) {
|
||||
self.palette = palette;
|
||||
self.queued_texts = waiting.iter().filter(|(id, _)| *id == self.palette.id).map(|(_, field)| *field).collect();
|
||||
script_window::keep_fields(&self.palette.dialog, &mut self.drafts);
|
||||
let (nodes, palette, given) = (&self.palette.dialog.nodes, self.palette.id, !self.given.is_empty());
|
||||
self.pending.retain(|id, _| (given || waiting.contains(&(palette, *id))) && nodes.iter().any(|n| n.id == *id));
|
||||
@@ -76,7 +86,7 @@ impl PaletteWindow {
|
||||
/// Draws the palette's controls in `ui` and takes what the person did, as its body does.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn paint(&mut self, ui: &mut Ui) {
|
||||
let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true);
|
||||
let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true, &self.queued_texts);
|
||||
self.take_pass(pass.drafts.into_iter().collect(), pass.events);
|
||||
}
|
||||
|
||||
@@ -105,8 +115,12 @@ impl PaletteWindow {
|
||||
/// the focus.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn commit_text(&mut self, i: usize, text: &str) {
|
||||
if let Some(n) = self.palette.dialog.nodes.get(i) {
|
||||
self.take_pass(vec![(n.id, None)], vec![UiEvent::Change(i, UiValue::Text(text.to_string()))]);
|
||||
let committed = shown_dialog(&self.palette.dialog, &self.pending)
|
||||
.nodes
|
||||
.get(i)
|
||||
.map(|n| (n.id, script_window::text_change(i, n, text.to_string(), self.queued_texts.contains(&n.id))));
|
||||
if let Some((id, event)) = committed {
|
||||
self.take_pass(vec![(id, None)], event.into_iter().collect());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,7 +233,7 @@ impl StackDialog for PaletteWindow {
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
|
||||
let heading = script_window::heading(&self.palette.dialog);
|
||||
let PaletteWindow { palette, drafts, pending, open, .. } = self;
|
||||
let PaletteWindow { palette, drafts, pending, queued_texts, open, .. } = self;
|
||||
let dialog = shown_dialog(&palette.dialog, pending);
|
||||
let drafts_now = &*drafts;
|
||||
// The body can run twice in a pass (measure, then paint), so the last run's report is
|
||||
@@ -228,7 +242,7 @@ impl StackDialog for PaletteWindow {
|
||||
.modeless()
|
||||
.initial_focus(Initial::Keep)
|
||||
.opened(Bind::bound(open))
|
||||
.show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true));
|
||||
.show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true, queued_texts));
|
||||
let pass = shown.inner.unwrap_or_default();
|
||||
let mut events = pass.events;
|
||||
// The close box gives the script the close; the palette stays open until the script closes
|
||||
@@ -316,7 +330,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
_ => true,
|
||||
});
|
||||
let before = at_pass.clone();
|
||||
let (batch, refused) = drafted(app, &p.dialog, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes);
|
||||
let (batch, refused) = drafted(app, p, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes);
|
||||
// A refused text keeps every later click and close out of line too.
|
||||
change_refused |= refused;
|
||||
// A text the click or close took leaves its field unless a later one was typed there.
|
||||
@@ -358,13 +372,14 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
/// events with their scopes, and whether a text was refused.
|
||||
fn drafted(
|
||||
app: &mut VectorcraftApp,
|
||||
w: &ScriptUiDialog,
|
||||
p: &ScriptPalette,
|
||||
drafts: &mut BTreeMap<u64, String>,
|
||||
events: &mut Vec<UiEvent>,
|
||||
scope: &ScopeHandle,
|
||||
pass_scope: &ScopeHandle,
|
||||
draft_scopes: &BTreeMap<u64, ScopeHandle>,
|
||||
) -> (Vec<(ScopeHandle, UiEvent)>, bool) {
|
||||
let w = &p.dialog;
|
||||
let mut refused = false;
|
||||
if let Some(e) = script_window::keep_refused(w, drafts, events) {
|
||||
app.status(e);
|
||||
@@ -375,7 +390,10 @@ fn drafted(
|
||||
if events.iter().any(closing) {
|
||||
changes.extend(events.iter().filter(|e| !closing(e)).cloned());
|
||||
let existing = changes.len();
|
||||
match script_window::commit_texts(w, drafts, &mut changes) {
|
||||
// A draft that matches its field's text still goes in line when a change of that field
|
||||
// waits, so the click reads the draft and not the waiting change.
|
||||
let queued: Vec<u64> = app.session.script_palette_changes_waiting().into_iter().filter(|(id, _)| *id == p.id).map(|(_, e)| e).collect();
|
||||
match script_window::commit_texts_over(w, drafts, &mut changes, &queued) {
|
||||
Ok(()) => {
|
||||
drop(changes.drain(..existing));
|
||||
}
|
||||
@@ -465,10 +483,38 @@ pub(crate) fn with_palette<R>(app: &VectorcraftApp, id: u64, f: impl FnOnce(&mut
|
||||
}
|
||||
|
||||
/// Whether a waiting palette event's run can start now ([`vectorcraft_engine::Session::script_palette_can_start`]):
|
||||
/// it also waits while the last run's print jobs wait to be approved or canceled, and asks for no
|
||||
/// frame meanwhile.
|
||||
/// it also waits while the last run's print jobs wait to be approved or canceled, and after a start
|
||||
/// that failed until the person's next input or a change of the edit state ([`clear_failed_start`]),
|
||||
/// and asks for no frame meanwhile.
|
||||
pub(crate) fn can_start(app: &VectorcraftApp) -> bool {
|
||||
app.session.script_palette_can_start() && !crate::script_runs::waiting_for_print(app)
|
||||
app.ui.palette_start_failed.is_none_or(|at| at != edit_state(app))
|
||||
&& app.session.script_palette_can_start()
|
||||
&& !crate::script_runs::waiting_for_print(app)
|
||||
}
|
||||
|
||||
/// What a failed start may depend on: the documents, whether each has changes, an open drag or
|
||||
/// undo group, the active one, and the palette events in line.
|
||||
fn edit_state(app: &VectorcraftApp) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
for d in app.session.documents() {
|
||||
(d.uid, d.is_dirty(), d.interaction.is_some(), d.undo_group.is_some()).hash(&mut h);
|
||||
}
|
||||
app.session.active().map(|d| d.uid).hash(&mut h);
|
||||
app.session.script_copy_first.hash(&mut h);
|
||||
app.session.prefs.recovery_off_for_complex.hash(&mut h);
|
||||
app.session.prefs.recovery_folder.hash(&mut h);
|
||||
app.session.script_palette_events_waiting().hash(&mut h);
|
||||
app.session.script_palette_last_ticket().hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Lets a waiting palette event whose start failed try again once the frame carries input, which
|
||||
/// may have changed the edit that kept it from starting.
|
||||
pub(crate) fn clear_failed_start(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
if app.ui.palette_start_failed.is_some() && ctx.input(|i| !i.events.is_empty()) {
|
||||
app.ui.palette_start_failed = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the run of the oldest waiting palette event when no run is going. → whether one started.
|
||||
@@ -485,6 +531,7 @@ pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool {
|
||||
None => false,
|
||||
Some(Ok(_)) => true,
|
||||
Some(Err(e)) => {
|
||||
app.ui.palette_start_failed = Some(edit_state(app));
|
||||
app.status(e.to_string());
|
||||
false
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to
|
||||
//! its end, while the app goes on drawing the documents as they were before the run. The status bar
|
||||
//! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with
|
||||
//! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog,
|
||||
//! waits for the person's answer. A run that prepared jobs for a printer ends with the question
|
||||
//! before they are sent. With no run going, the oldest event a ScriptUI palette waits with starts
|
||||
//! its run ([`crate::script_palettes`]).
|
||||
//! `alert`, `confirm`, `prompt`, `app.showColorPicker`, a ScriptUI dialog's `show()` or a `File` or
|
||||
//! `Folder` file dialog, waits for the person's answer. A run that prepared jobs for a printer ends
|
||||
//! with the question before they are sent. With no run going, the oldest event a ScriptUI palette
|
||||
//! waits with starts its run ([`crate::script_palettes`]).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::WindowView;
|
||||
use vectorcraft_engine::script::DialogKind;
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::dialogs::color_picker;
|
||||
use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice};
|
||||
use crate::dialogs::script_window;
|
||||
|
||||
@@ -239,13 +241,22 @@ fn ask(app: &mut VectorcraftApp) -> bool {
|
||||
}
|
||||
script_run::forget::<ScriptFiles>(app);
|
||||
if let Some(dialog) = app.session.script_dialog() {
|
||||
if script_run::can_ask(app) {
|
||||
if dialog.kind == DialogKind::ColorPicker {
|
||||
// A picker that closed this frame answers the run in its own pump.
|
||||
if color_picker::script_picker(app).is_none()
|
||||
&& !script_run::busy(app)
|
||||
&& let Some(color) = dialog.color
|
||||
{
|
||||
color_picker::open_for_script(app, color, dialog.cmyk_document);
|
||||
}
|
||||
} else if script_run::can_ask(app) {
|
||||
script_run::open_notice(app, &dialog);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// A run asked to stop no longer waits at its dialog.
|
||||
script_run::forget::<ScriptNotice>(app);
|
||||
script_run::forget_color_picker(app);
|
||||
// A run past its growth allowance asks about it first, also when its ScriptUI dialog waits
|
||||
// again.
|
||||
if app.session.script_waiting() {
|
||||
|
||||
@@ -724,6 +724,12 @@ pub struct UiState {
|
||||
#[serde(skip)]
|
||||
pub touch_drawing_tool: Option<String>,
|
||||
pub status: String,
|
||||
/// The edit state in which the last start of a waiting palette event's run failed
|
||||
/// ([`crate::script_palettes::start_next`]). The event then waits for the person's next input,
|
||||
/// or for that state to change, before it starts again, and asks for no frame meanwhile. Not
|
||||
/// saved.
|
||||
#[serde(skip)]
|
||||
pub palette_start_failed: Option<u64>,
|
||||
/// How many times [`crate::VectorcraftApp::status`] has set `status`, so that work finishing
|
||||
/// later can tell whether the line it started with is still the latest one. Not saved.
|
||||
#[serde(skip)]
|
||||
@@ -1553,6 +1559,7 @@ impl Default for UiState {
|
||||
group_tool: vectorcraft_tools::TOOL_GROUPS.iter().map(|g| g[0].id.to_string()).collect(),
|
||||
touch_drawing_tool: None,
|
||||
status: String::new(),
|
||||
palette_start_failed: None,
|
||||
status_sets: 0,
|
||||
script_print_failures: 0,
|
||||
script_print_failure_notes: Vec::new(),
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
//! A script's `alert`, `confirm` and `prompt` in the app: the dialog the run waits at, its buttons,
|
||||
//! Enter and Escape, Stop, another dialog in the way, quitting while it waits, and the same answers
|
||||
//! given by a run with nobody to ask. The helpers over the dialog host are shared with the other
|
||||
//! script tests.
|
||||
//! given by a run with nobody to ask; and the Color Picker of `app.showColorPicker`. The helpers
|
||||
//! over the dialog host are shared with the other script tests.
|
||||
|
||||
use craft::color_ui::ui::{ColorPickerDialog, PickedColor};
|
||||
use craft::ui::dialog::{DialogId, StackDialog, StandardPrompt};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use crate::dialogs::color_picker;
|
||||
use crate::dialogs::script_run::{self, CLOSE_KIND, CloseQuestion, NOTICE_KIND, ScriptNotice};
|
||||
use crate::{VectorcraftApp, menus, script_runs};
|
||||
|
||||
@@ -318,6 +320,196 @@ fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() {
|
||||
assert_eq!(framed["log"], json!([true, "p", "done"]));
|
||||
}
|
||||
|
||||
/// Is the Color Picker of the script's `app.showColorPicker` open?
|
||||
fn picker_open(app: &VectorcraftApp) -> bool {
|
||||
let id = color_picker::script_picker(app);
|
||||
id.is_some_and(|id| script_run::with_host(app, |host, _| host.get_by_id::<ColorPickerDialog>(id).is_some()).unwrap())
|
||||
}
|
||||
|
||||
/// Polls the run until it ends, or until its Color Picker is open (true).
|
||||
fn until_picker(app: &mut VectorcraftApp) -> bool {
|
||||
for _ in 0..10_000 {
|
||||
if !app.session.script_running() {
|
||||
return false;
|
||||
}
|
||||
script_runs::poll(app);
|
||||
if picker_open(app) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
panic!("the script neither ended nor opened the Color Picker");
|
||||
}
|
||||
|
||||
/// Answers the script's Color Picker with OK (or Cancel), then runs the frame's picker pump.
|
||||
fn answer_picker(app: &mut VectorcraftApp, ok: bool) {
|
||||
let id = color_picker::script_picker(app).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let done = script_run::with_host(app, |host, ctx| if ok { host.confirm_by_id(ctx, id) } else { host.cancel_by_id(ctx, id) }).unwrap();
|
||||
assert!(done);
|
||||
color_picker::pump(app, &ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_picker_waits_and_answers_the_run() {
|
||||
let mut app = app();
|
||||
// A selected object, which a picker that previews would paint.
|
||||
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap();
|
||||
let gray = "var g = new GrayColor(); g.gray = 40;";
|
||||
start(
|
||||
&mut app,
|
||||
&format!(
|
||||
"{DRAW} var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join()); \
|
||||
{gray} var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join()); var r = app.showColorPicker(g); vc.log([r.typename, r.gray].join());"
|
||||
),
|
||||
);
|
||||
assert!(until_picker(&mut app));
|
||||
assert!(!is_open::<ScriptNotice>(&app), "the picker opens in place of a notice");
|
||||
set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
app.ui.status.clear();
|
||||
color_picker::pump(&mut app, &ctx);
|
||||
// A preview would begin an edit, which the running script refuses with a status message.
|
||||
assert_eq!(app.ui.status, "", "the picker starts no preview");
|
||||
assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "the selection shows no preview");
|
||||
answer_picker(&mut app, true);
|
||||
assert!(until_picker(&mut app), "the next call opens the picker again");
|
||||
answer_picker(&mut app, true);
|
||||
assert!(until_picker(&mut app));
|
||||
answer_picker(&mut app, false);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert_eq!(
|
||||
log(&app),
|
||||
json!(["RGBColor,0,255,0", "GrayColor,40", "GrayColor,40"]),
|
||||
"OK gives the color picked, untouched its own color, Cancel the color given"
|
||||
);
|
||||
assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "OK paints nothing");
|
||||
let dialogs = app.session.script_report().unwrap()["dialogs"].clone();
|
||||
assert_eq!(dialogs[2]["answer"], Value::Null, "Cancel is listed as null");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_color_set_in_another_model_is_a_new_pick() {
|
||||
let mut app = app();
|
||||
start(&mut app, "var g = new GrayColor(); g.gray = 40; var p = app.showColorPicker(g); vc.log(p.typename);");
|
||||
assert!(until_picker(&mut app));
|
||||
// The gray's own sRGB, set as a plain color, as a screen sample sets one.
|
||||
let open = app.color_dialogs.pickers.iter().find(|o| Some(o.id) == color_picker::script_picker(&app)).map(|o| (o.id, o.start)).unwrap();
|
||||
script_run::with_host(&app, |host, _| host.get_mut_by_id::<ColorPickerDialog>(open.0).map(|d| d.set_color(PickedColor::rgb(open.1)))).unwrap();
|
||||
answer_picker(&mut app, true);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert_eq!(log(&app), json!(["RGBColor"]), "the same sRGB as a plain color is an RGB pick, not the gray the script gave");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_or_quitting_the_run_closes_its_color_picker() {
|
||||
let source = format!("{DRAW} var c = new RGBColor(); app.showColorPicker(c); vc.log('after');");
|
||||
let mut app = app();
|
||||
start(&mut app, &source);
|
||||
assert!(until_picker(&mut app));
|
||||
assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert!(!picker_open(&app), "no picker is left for the stopped run");
|
||||
assert!(color_picker::script_picker(&app).is_none());
|
||||
assert_eq!(objects(&app), 0, "the run's edit goes back");
|
||||
assert_eq!(log(&app), json!([]));
|
||||
let mut app = self::app();
|
||||
start(&mut app, &source);
|
||||
assert!(until_picker(&mut app));
|
||||
script_run::ask_to_close(&mut app);
|
||||
assert!(is_open::<CloseQuestion>(&app), "quitting asks over the picker");
|
||||
cancel(&mut app, CLOSE_KIND);
|
||||
assert!(picker_open(&app), "Cancel shows the picker again");
|
||||
script_run::ask_to_close(&mut app);
|
||||
assert!(confirm(&mut app, CLOSE_KIND));
|
||||
assert!(!app.session.script_running());
|
||||
assert!(!picker_open(&app), "no picker is left for the abandoned run");
|
||||
assert_eq!(objects(&app), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_the_run_ends_only_the_screen_pick_its_color_picker_started() {
|
||||
use craft::color_ui::ui::ScreenPickGesture;
|
||||
let source = "var c = new RGBColor(); app.showColorPicker(c);";
|
||||
for own in [true, false] {
|
||||
let mut app = app();
|
||||
start(&mut app, source);
|
||||
assert!(until_picker(&mut app));
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let id = color_picker::script_picker(&app).unwrap();
|
||||
let started = if own {
|
||||
crate::screen_color::hold(&mut app, &ctx, color_picker::owner(id), ScreenPickGesture::Clicked)
|
||||
} else {
|
||||
crate::screen_color::hold(&mut app, &ctx, "fill", ScreenPickGesture::Clicked)
|
||||
};
|
||||
assert_eq!(started, None);
|
||||
assert!(app.screen_pick.busy());
|
||||
assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert_eq!(app.screen_pick.busy(), !own, "own pick {own}: only the picker's own pick ends with it");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_color_picker_opens_on_the_scripts_color_with_only_web_colors_left_on() {
|
||||
let mut app = app();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
// A frame of the window's dialogs starts the open pickers with the app's host, whose settings
|
||||
// keep what a picker remembers.
|
||||
let frame = |app: &mut VectorcraftApp| {
|
||||
let _ = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| {
|
||||
if let Some(dialogs) = app.dialogs() {
|
||||
dialogs.with(|host| host.run(ui));
|
||||
}
|
||||
});
|
||||
};
|
||||
// A fill picker closed with Only Web Colors on, which later fill pickers recall.
|
||||
color_picker::open(&mut app, &json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
set(&app, "fill", "webColors", json!(true)).unwrap();
|
||||
let id = open_id(&app, "fill");
|
||||
assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap());
|
||||
color_picker::pump(&mut app, &ctx);
|
||||
color_picker::open(&mut app, &json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
assert_eq!(fields(&app, "fill")["webColors"], json!(true), "the next fill picker recalls Only Web Colors");
|
||||
let id = open_id(&app, "fill");
|
||||
assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap());
|
||||
color_picker::pump(&mut app, &ctx);
|
||||
// A frame without the picker drops its overlay.
|
||||
frame(&mut app);
|
||||
assert!(!script_run::busy(&app), "no picker is left open");
|
||||
start(
|
||||
&mut app,
|
||||
"var c = new RGBColor(); c.red = 18; c.green = 52; c.blue = 86; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());",
|
||||
);
|
||||
assert!(until_picker(&mut app));
|
||||
frame(&mut app);
|
||||
answer_picker(&mut app, true);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert_eq!(log(&app), json!(["RGBColor,18,52,86"]), "untouched OK gives the script's color, not its nearest web color");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_takes_the_model_of_the_document_the_script_made() {
|
||||
for (doc, made, want) in [("{}", "CMYK", "CMYKColor"), ("{\"colorMode\": \"cmyk\"}", "RGB", "RGBColor")] {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), crate::Services::default()));
|
||||
app.run("file.new", serde_json::from_str(doc).unwrap()).unwrap();
|
||||
app.session.prefs.show_external_script_warning = false;
|
||||
start(
|
||||
&mut app,
|
||||
&format!(
|
||||
"app.documents.add(DocumentColorSpace.{made}, 50, 60, 1); var c = new RGBColor(); c.red = 255; \
|
||||
var p = app.showColorPicker(c); vc.log(p.typename);"
|
||||
),
|
||||
);
|
||||
assert!(until_picker(&mut app));
|
||||
set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap();
|
||||
answer_picker(&mut app, true);
|
||||
assert!(!until_picker(&mut app));
|
||||
assert_eq!(log(&app), json!([want]), "an RGB pick in the {made} document the script made");
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the person at the keyboard turns off the external script warning: Yes from automation, set
|
||||
/// as the answer or given in a pass automation drives, is refused, the warning stays on and the
|
||||
/// question opens again; No is taken from automation.
|
||||
|
||||
@@ -260,6 +260,81 @@ fn a_click_or_close_narrows_the_scope_of_the_draft_it_commits() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_reads_a_typed_text_that_matches_the_field_while_another_change_of_it_waits() {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \
|
||||
var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();",
|
||||
);
|
||||
app.session.script_palette_event(id, UiEvent::Change(1, UiValue::Text("b".into()))).unwrap();
|
||||
// The person types the field's text back and clicks before the change to `b` is delivered.
|
||||
with_palette(&app, id, |w| w.type_text(1, "a")).unwrap();
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
let mut logs = Vec::new();
|
||||
for _ in 0..10 {
|
||||
script_runs::poll(&mut app);
|
||||
if !app.session.script_running() && app.session.script_palette_events_waiting() == 0 {
|
||||
break;
|
||||
}
|
||||
run_to_end(&mut app);
|
||||
logs.extend(app.session.script_report().unwrap()["log"].as_array().cloned().unwrap_or_default());
|
||||
}
|
||||
run_to_end(&mut app);
|
||||
if let Some(report) = app.session.script_report() {
|
||||
logs.extend(report["log"].as_array().cloned().unwrap_or_default());
|
||||
}
|
||||
assert!(logs.contains(&json!("clicked a")), "the click reads the text the person typed: {logs:?}");
|
||||
assert!(!logs.contains(&json!("clicked b")), "{logs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_loss_commits_a_restored_text_while_another_change_of_the_field_waits() {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \
|
||||
var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();",
|
||||
);
|
||||
app.session.script_palette_event(id, UiEvent::Change(1, UiValue::Text("b".into()))).unwrap();
|
||||
follow(&mut app);
|
||||
with_palette(&app, id, |w| w.type_text(1, "a")).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let paint = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let raw = egui::RawInput { events, ..Default::default() };
|
||||
crate::testing::part_frame(app, &ctx, raw, |app, ui| {
|
||||
with_palette(app, id, |w| w.paint(ui));
|
||||
});
|
||||
};
|
||||
paint(&mut app, Vec::new());
|
||||
// Tab gives the edit field, the palette's first control, the keyboard focus.
|
||||
let tab = |pressed| egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
|
||||
paint(&mut app, vec![tab(true), tab(false)]);
|
||||
paint(&mut app, Vec::new());
|
||||
let focused = ctx.memory(|m| m.focused()).expect("the edit field has the keyboard focus");
|
||||
assert!(ctx.text_edit_focused());
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten().as_deref(), Some("a"));
|
||||
// Tab moves the keyboard focus on to the Go button, and the pass after it gives the field's text to the script.
|
||||
paint(&mut app, vec![tab(true), tab(false)]);
|
||||
paint(&mut app, Vec::new());
|
||||
paint(&mut app, Vec::new());
|
||||
assert_ne!(ctx.memory(|m| m.focused()), Some(focused), "the edit field lost the keyboard focus");
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten(), None, "focus loss gives the typed text");
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1, "focus loss merges the restored text into the waiting change");
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2, "the click follows the restored text");
|
||||
for _ in 0..2 {
|
||||
assert!(script_palettes::start_next(&mut app));
|
||||
run_to_end(&mut app);
|
||||
}
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked a"]));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_typed_in_two_scopes_goes_to_the_script_in_what_both_allow() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
@@ -791,6 +866,68 @@ fn a_click_whose_run_cannot_begin_after_a_stopped_run_shows_its_own_error() {
|
||||
assert!(app.ui.status.contains("recovery copy"), "{}", app.ui.status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_whose_run_cannot_begin_asks_for_no_frame_until_the_next_input() {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine two\nvar p = new Window('palette'); p.add('button', undefined, 'A').onClick = function () { vc.log('a'); }; \
|
||||
p.add('button', undefined, 'B').onClick = function () { vc.log('b'); }; p.show();",
|
||||
);
|
||||
// The document has changes, and the session has nowhere to keep a recovery copy of it.
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.session.script_copy_first = true;
|
||||
give(&app, id, UiEvent::Click(1));
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
assert!(!script_palettes::start_next(&mut app));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1, "the second click still waits");
|
||||
assert!(!script_palettes::can_start(&app), "the failed start does not retry, nor ask for a frame, on every pass");
|
||||
// An event given without the window, as automation gives one, changes what the start depends on.
|
||||
app.session.script_palette_event(id, UiEvent::Click(1)).unwrap();
|
||||
assert!(script_palettes::can_start(&app), "a change of the edit state lets the start try again");
|
||||
assert!(!script_palettes::start_next(&mut app));
|
||||
assert!(!script_palettes::can_start(&app));
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let input = egui::RawInput { events: vec![egui::Event::PointerGone], ..Default::default() };
|
||||
crate::testing::part_frame(&mut app, &ctx, input, |app, ui| script_palettes::clear_failed_start(app, ui.ctx()));
|
||||
assert!(script_palettes::can_start(&app), "the person's next input lets the click try again");
|
||||
app.session.script_copy_first = false;
|
||||
assert!(script_palettes::start_next(&mut app));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_palette_start_retries_after_recovery_settings_change_without_input() {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine retries\nvar p = new Window('palette'); \
|
||||
for (var i = 0; i < 3; i++) { p.add('button', undefined, 'Go ' + i).onClick = function () { vc.log('clicked'); }; } p.show();",
|
||||
);
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.session.script_copy_first = true;
|
||||
for i in 1..=3 {
|
||||
give(&app, id, UiEvent::Click(i));
|
||||
}
|
||||
follow(&mut app);
|
||||
assert!(!script_palettes::start_next(&mut app));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2);
|
||||
assert!(!script_palettes::can_start(&app));
|
||||
assert_eq!(settled_delay(&mut app), std::time::Duration::MAX, "the failed start asks for no frames");
|
||||
app.session.execute("prefs.set", &json!({"key": "recoveryOffForComplex", "value": true})).unwrap();
|
||||
assert!(script_palettes::can_start(&app), "automation can change the recovery condition without window input");
|
||||
assert!(!script_palettes::start_next(&mut app), "the missing recovery store still prevents a start");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1);
|
||||
assert!(!script_palettes::can_start(&app));
|
||||
assert_eq!(settled_delay(&mut app), std::time::Duration::MAX, "a repeated failure still asks for no frames");
|
||||
app.session.script_copy_first = false;
|
||||
assert!(script_palettes::can_start(&app), "disabling the recovery prerequisite permits another attempt");
|
||||
assert!(script_palettes::start_next(&mut app));
|
||||
run_to_end(&mut app);
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"]));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -277,6 +277,15 @@ fn a_palette_click_waits_for_the_answer_to_the_last_runs_print_jobs() {
|
||||
cancel(&mut app, PRINT_KIND);
|
||||
script_runs::poll(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0, "the click's run starts once the jobs are answered");
|
||||
for _ in 0..10_000 {
|
||||
if !app.session.script_running() {
|
||||
break;
|
||||
}
|
||||
script_runs::poll(&mut app);
|
||||
}
|
||||
assert!(!app.session.script_running(), "the click's run ends");
|
||||
let report = app.session.script_report().expect("the click's run reports");
|
||||
assert_eq!(report["log"], serde_json::json!(["clicked"]), "the click's handler ran: {report}");
|
||||
}
|
||||
|
||||
/// Cancel, from anyone, drops the jobs and keeps the run's changes.
|
||||
|
||||
+1
-2
@@ -868,8 +868,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
`#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's
|
||||
selection, its page items, layers, groups, compound paths and artboards, its text frames with their text ranges and
|
||||
character and paragraph attributes, their links to each other and the stories they form, its character and
|
||||
paragraph styles, the installed fonts, each document's variables, data sets and variable libraries, and its
|
||||
linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` and `RasterItem`).
|
||||
paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries.
|
||||
`Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms.
|
||||
Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a
|
||||
document's `fullName`, `path` and `saved`, and close it with `Document.close`.
|
||||
|
||||
+48
-16
@@ -1805,8 +1805,9 @@ such a page opens from that data at the page's size.
|
||||
`linkPages: true` (File › Open's Import PDF dialog: Import PDF pages as links) opens each page `pages` picks as a
|
||||
placed document linked to that page of the file, as `file.place` with `link` places one, instead of as editable art.
|
||||
Each page gets an artboard of its `cropTo` box (`bounding`: its art's bounds; a blank page gets its crop box), in a row from the left 36 pt apart, and
|
||||
a layer named after the page (`Page 2`). A file whose first PDF page's `PieceInfo` holds a key, in `PieceInfo` itself or in a dictionary nested in it up to four dictionaries deep counting `PieceInfo`, that starts with `AIPrivateData` or `AIPDFPrivateData` gets its trim boxes for
|
||||
the `crop` box, named or by default. A page on its trim box shows its bleed box round the artboard, and the pages give the document
|
||||
a layer named after the page (`Page 2`). A file whose first PDF page's `PieceInfo` holds a key, in `PieceInfo` itself or in a dictionary nested in it up to four dictionaries deep counting `PieceInfo`, that starts with `AIPrivateData` or `AIPDFPrivateData` gets its trim boxes
|
||||
when no box is named, as it does when it opens as art. A PDF with only a VectorCraft native attachment (Preserve Editing) defaults to crop boxes for linked pages.
|
||||
`cropTo: "crop"` (or `crop: "crop"`) gives either file its crop boxes. A page on its trim box shows its bleed box round the artboard, and the pages give the document
|
||||
their bleed; the artboards are then 36 pt apart plus the bleed on both sides. The document opens in CMYK when most of those pages are painted mostly in
|
||||
CMYK, unless `colorMode` names a mode. All the pages' objects share one copy of the file. The Links panel lists each
|
||||
page, and `links.embed` makes a page editable art. The command's `linkPages` defaults to false; the dialog checks the
|
||||
@@ -3085,7 +3086,8 @@ through `$`:
|
||||
describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one),
|
||||
`app.selection` (assigning it sets the active document's selection), `app.coordinateSystem`,
|
||||
`app.redraw()`, `app.undo()`, `app.redo()`,
|
||||
`app.getIsFileOpen(path)`, `app.selectTool(name)` and `app.executeMenuCommand(name)`. `app.redraw()` returns without changing
|
||||
`app.getIsFileOpen(path)`, `app.selectTool(name)`, `app.showColorPicker(color)` (described with the dialogs
|
||||
below) and `app.executeMenuCommand(name)`. `app.redraw()` returns without changing
|
||||
anything. `app.undo()` and `app.redo()` run `edit.undo` and `edit.redo` in the active document and reach
|
||||
only the steps the run made; with no such step they change nothing, and with no document open they throw
|
||||
`No active document` (VectorCraft's own rules). After a run that succeeds, each document that was open
|
||||
@@ -3197,7 +3199,8 @@ through `$`:
|
||||
its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating
|
||||
an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before
|
||||
the document changes, as renaming such a group does. `move`, `remove()` and `zOrder` throw the same error, with
|
||||
nothing changed, when they would leave an image at the bottom of such a group. An object of
|
||||
nothing changed, when they would leave an image at the bottom of such a group, and so do `groupItems.removeAll()`
|
||||
and `compoundPathItems.removeAll()`. An object of
|
||||
another document throws `Cross-document placement is not available`, and when
|
||||
`node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and
|
||||
the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or
|
||||
@@ -3763,7 +3766,9 @@ through `$`:
|
||||
`NOSELECTION` removes it, through `select.anchorsMany`, with the other selected objects and anchors kept.
|
||||
`selectedPathPoints` lists the points that read `ANCHORPOINT`, in the order of `pathPoints`. `new RGBColor()` (0 to
|
||||
255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 white, as
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()`
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it; a gray within about 1e-14 % of white reads as
|
||||
100; assigning it to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it
|
||||
to any other paint gives white), `new LabColor()` and `new NoColor()`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes
|
||||
the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues`
|
||||
and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`.
|
||||
@@ -4429,8 +4434,10 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess
|
||||
for `prompt` and `{kind, title, controls, events, answer}` for a ScriptUI dialog's `show()` (kind `window`).
|
||||
`answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, the number `show()` returned, `"stop"`
|
||||
for a dialog the run ended at, `"missing"` for a dialog `answers` had no answer or no step for, or `"error"` for a
|
||||
`show()` that ended with an error. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list
|
||||
stopped at its limit.
|
||||
`show()` that ended with an error. `app.showColorPicker` is listed as `{kind: "colorPicker", color, answer}`, with
|
||||
the color it opened on and the color picked, `null` for Cancel, `"stop"` or `"missing"`, each color as
|
||||
`paint.setFill` takes it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at
|
||||
its limit.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}}
|
||||
@@ -4477,6 +4484,22 @@ left, when the next answer is for another kind of dialog, or when the script end
|
||||
and refuses any answers for a run in the app, where the person answers. An omitted `answers`, an empty list and an
|
||||
empty object are the same.
|
||||
|
||||
`app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at
|
||||
https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`,
|
||||
`CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a
|
||||
`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in the app,
|
||||
when the run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so
|
||||
the color's `typename` can differ from the picker's model and from the color given. An answer taken from `answers`
|
||||
keeps the color model it was given. The picker opens on the color as
|
||||
given, whatever Only Web Colors was left at in another picker. OK with both the color and its model unchanged, and Cancel, return a new object of the color the
|
||||
script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting
|
||||
end the run as they do at the other dialogs, and close the picker. They also end a screen color sample
|
||||
(`ui.sampleScreenColor` with `picker`, or the picker's eyedropper) that the picker started, and drop a sampled color
|
||||
it has not taken; a sample started for the fill, the stroke or another picker keeps running. A run with nobody to ask takes `{kind:
|
||||
"colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its
|
||||
range (a color key such as `"rgb 300 0 0"` is refused, not clamped), or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and
|
||||
`ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker.
|
||||
|
||||
```sh
|
||||
vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}'
|
||||
```
|
||||
@@ -4685,7 +4708,9 @@ visible, controls: [{index, kind, name, text, enabled, visible, value?, items?,
|
||||
waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gives a shown palette a `click`, a
|
||||
`change` or a `close`, with `control` and `value` as in a `window` answer's step (`control` can also be a control's
|
||||
index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the handler's report is later in
|
||||
`ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events in order and returns the report of
|
||||
`ui.inspect`'s `scriptReport`. When a waiting event's run cannot begin in the app, the status bar shows the error,
|
||||
and the events still in line wait until the next input in the window, another `script.palette.event`, or a change
|
||||
to a document's unsaved state, drag or undo group, to the active document, or to the `recoveryFolder` or `recoveryOffForComplex` preference. With nobody to ask, it runs the waiting events in order and returns the report of
|
||||
the run that handled this one, or its error, even when it took the place of an earlier waiting event; an event
|
||||
dropped without a run is an error. An event whose run cannot begin ends it with that error, or with this event's
|
||||
result when this one has run, and the events after it keep waiting. When an open edit cannot be finished before
|
||||
@@ -9717,7 +9742,8 @@ origin), when `t` is not from 0 to 1, when `id` is a guide, and when the path, s
|
||||
`view.curvatureComb` (View › Show Curvature Comb, or Hide Curvature Comb while it is on) turns on the curvature comb
|
||||
of the selected paths, and of each path in a selected compound path, while edges show. Each segment gets 16 evenly
|
||||
spaced teeth along the normal, on the outer side of the bend, each as long as the curvature at that point, and a line
|
||||
joins the teeth's tips, in the path's layer color. A straight segment has teeth of no length, and a point of a curve
|
||||
joins the teeth's tips, in the path's layer color. The line starts again where the path turns back on itself at a
|
||||
cusp, a straight segment included. A straight segment has teeth of no length, and a point of a curve
|
||||
where it has no direction (a handle on its anchor) has no tooth. The length is VectorCraft's own value: a bend with a
|
||||
radius of 100 screen points draws 20-point teeth at any zoom. The comb draws about 20,000 teeth at most, shared among
|
||||
the selected paths by their number of segments: a larger selection gets 2 teeth per segment, then teeth on every k-th
|
||||
@@ -14776,7 +14802,10 @@ wrong type runs no action and returns the error.
|
||||
For other command dialogs, `params.__doc` can supply a document uid. The dialog previews and confirms only while
|
||||
that document is active. Confirming after a document switch closes the dialog without running its command.
|
||||
Canceling or replacing that dialog does not cancel an interaction in another document. A supplied `__doc` must be
|
||||
an unsigned integer; omitting it preserves the command dialog's existing behavior.
|
||||
an unsigned integer; omitting it preserves the command dialog's existing behavior. `ui.paramDialog` with a missing,
|
||||
empty, non-string or unknown `command`, a `label` that is neither a string nor null, or `params` that are neither an
|
||||
object nor null is an error, and no dialog opens. A null `label` or `params` is treated as omitted. A plug-in
|
||||
command that is not installed yet waits for the plug-ins still loading before it is checked.
|
||||
|
||||
|
||||
## Justification options
|
||||
@@ -16742,7 +16771,7 @@ are also the ones an Alt smoothing drag with the Pencil, Paintbrush or Blob Brus
|
||||
in points.
|
||||
|
||||
`tool.options {tool}` opens what double-clicking the tool's button opens (its params doc lists every tool), in the
|
||||
desktop app. The Flare tool's are its Flare Tool Options (dialog `flareOptions`): `diameter` and `pathLength` (pt),
|
||||
desktop app. A missing or null `tool` is an error, and so is a `tool` that is not a string. The Flare tool's are its Flare Tool Options (dialog `flareOptions`): `diameter` and `pathLength` (pt),
|
||||
`opacity`, `brightness`, `growth`, `fuzziness`, `longest`, `rayFuzziness` and `largest` (%), `rays`, `rings`,
|
||||
`direction` (°), and `raysOn` and `ringsOn` (the Rays and Rings checkboxes; off, the flare has none). While Alt
|
||||
(Option on macOS) is held, the dialog's Cancel button reads Reset. Reset puts every option back to the tool's default,
|
||||
@@ -18766,19 +18795,22 @@ Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes sele
|
||||
top-level selected objects and is one undo step; a run that moves nothing makes no step. Places and sizes are measured
|
||||
as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds, and Group by Row, which always uses visual bounds
|
||||
with strokes and vector effects included and raster effects left out (see its row).
|
||||
Swap Objects, Replace with Top Object, Set Size of Each, Match Objects, and Sort Objects scale corner radii according
|
||||
to the `corners` parameter, which defaults to the Scale Corners preference. For these commands, the journal entry
|
||||
records the value used, and a replay of that entry scales corners the same way whatever the preference is then.
|
||||
|
||||
| Command | Parameters (default) | Does |
|
||||
|---|---|---|
|
||||
| `addon.arrange.grid` | `layout`: `grid`, `row`, `column` (`grid`); `columns`: 1…10000 (⌈√count⌉, never more than the count); `gapX` pt (10), `gapY` pt (`gapX`), each −1000000…1000000; `centerOnArtboard` (false) | Lays the objects out in their stacking order from the back, left to right and top to bottom. Each cell is as wide as the widest object in its column and as tall as the tallest in its row, and each object is centred in its cell. The grid starts at the selection's top-left, or is centred on the artboard under the selection's centre (the first artboard when none is there). → `{count}` |
|
||||
| `addon.arrange.offset` | `direction`: `row` (left to right), `column` (top to bottom) (`row`); `gap` pt, −1000000…1000000 (10; negative overlaps the objects); `order`: `stacking` (stacking order from the back), `position` (by left edge in a row, by top edge in a column; equal edges keep their stacking order) (`stacking`); `reverse` (false) | Chains the objects one after another in that order: the first stays where it is, and each later one moves only along the direction so that its left (top) edge is `gap` past the right (bottom) edge of the one before it; its place across the direction stays. An object aligned to the pixel grid snaps to it after it moves, so the gap before it can differ from `gap`, and the next one starts from where it snapped. An Objects on Path group is measured with its members put back on the path after it moves. Measured by visual bounds, a clipping group by its mask. Needs two objects or more. → `{count}` |
|
||||
| `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. |
|
||||
| `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` |
|
||||
| `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). |
|
||||
| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` |
|
||||
| `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference); `corners` (the Scale Corners preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. |
|
||||
| `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `corners` (the Scale Corners preference); `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` |
|
||||
| `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes`; `corners` (the Scale Corners preference) | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). |
|
||||
| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `corners` (the Scale Corners preference); `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame after it is turned, with no smallest scale; the side that follows in proportion follows the object's box before the match. Art that is aligned to the pixel grid is measured before it snaps. `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, a `size` that takes a width or a height the source or a target does not have, a `size` that a stroke or an effect that does not scale keeps a target from reaching, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` |
|
||||
| `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) |
|
||||
| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) |
|
||||
| `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` |
|
||||
| `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` |
|
||||
| `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `corners` (the Scale Corners preference); `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` |
|
||||
| `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group, clipping sublayer or live object (a blend, compound path, compound shape, Shaper group, Objects on Path group, Live Paint group, dimension, graph, flare, envelope, mesh, repeat, intertwine, Image Trace group, generated art group, graph series, graph design copy or clipping pieces group) that holds it, so a blend key or compound shape operand gets its marks outside the live object. In isolation mode, an object whose marks would go outside the isolated art is an error that makes no step. Selected parts of compound paths, envelopes, meshes, repeats, Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and with `corners` neither does an object whose sides are too short for any leg; a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` |
|
||||
|
||||
Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the
|
||||
|
||||
+1
-1
@@ -199,7 +199,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them); Layers own appearance has a hollow diamond and tooltip distinct from targeting/selection (#8710), retaining Hassan1305's #8757 ring-visibility fix; validation pending | 4–6 |
|
||||
| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); View › Snapping consolidates five existing toggles and Pixel Snapping Options…, retaining top-level entries and shortcuts (G13); Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors the topmost, newest objects keep their Smart Guides targets (#8531) | 12–18 |
|
||||
| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028; Recolor with Preset asks whether to limit the colors to a swatch library first); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); the stop editor offers the five Color panel modes (#7918); native port validation pending | 4–8 |
|
||||
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; View and Links controls and command access for transient missing-link canvas markers (#5547); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four stLine truncated
|
||||
| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | DWG import: DWG drawings open and place through the DXF reader (#10802; estimates unchanged); `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG export (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; View and Links controls and command access for transient missing-link canvas markers (#5547); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration reLine truncated
|
||||
| M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 |
|
||||
| M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 |
|
||||
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders done (#1880); vertical type in progress (Type › Type Orientation, #5027) | 45–60 |
|
||||
|
||||
@@ -1123,7 +1123,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`.
|
||||
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`.
|
||||
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error, and so does a `groupItems.removeAll()` or `compoundPathItems.removeAll()` that would leave an image at the bottom of such a group. `crates/engine/src/tests/script_dom_tracing.rs`.
|
||||
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
|
||||
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font, fill and stroke colors, stroke weight) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
@@ -1137,6 +1137,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel, and OK with both the color and its model unchanged, return a new object based on the color given, in its own model. Stopping the run closes the picker and ends a screen color sample the picker started. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`.
|
||||
- Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`.
|
||||
- Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`.
|
||||
@@ -1189,7 +1190,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`).
|
||||
- Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`.
|
||||
- Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`.
|
||||
- Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going, unless a run of that engine takes it first with `update()` (below), which runs the handler during that run. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes reach the same files as the run's scope, so a Cancel button can stop a loop; an event given under other roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`.
|
||||
- Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going, unless a run of that engine takes it first with `update()` (below), which runs the handler during that run. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes reach the same files as the run's scope, so a Cancel button can stop a loop; an event given under other roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. When a waiting event's run cannot begin in the app, the status bar shows the error, and the events in line wait until the next input in the window, another palette event, or a change to a document's unsaved state, drag or undo group, to the active document, or to the `recoveryFolder` or `recoveryOffForComplex` preference. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`.
|
||||
- Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`.
|
||||
- Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse.
|
||||
- Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`).
|
||||
|
||||
+1099
-104
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user