Merge main into feat/scripts-show-color-picker

This commit is contained in:
dotCooCoo committed 2026-11-30 11:34:37 -08:00
commit 1d6aca58dd
122 files changed
+3630 -378

No files matched your search

+4 -3
View File
@@ -72,10 +72,11 @@ serde_json = { workspace = true }
thiserror = { workspace = true }
log = { workspace = true }
# Whether a recovery area folder is this account's own (`FolderStore::own_area`). Already in
# Cargo.lock (tempfile, ui-egui), so this adds no new crate.
# Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a
# file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile,
# ui-egui), so this adds no new crate.
[target.'cfg(unix)'.dependencies]
rustix = { workspace = true, features = ["std", "process"] }
rustix = { workspace = true, features = ["std", "process", "fs"] }
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`),
# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock
+5
View File
@@ -111,6 +111,7 @@ mod textedit;
pub use textedit::effective_kerning;
mod retype;
mod stepandrepeat;
pub mod textstyles;
pub(crate) mod textwrap;
pub(crate) mod threads;
@@ -327,6 +328,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(layerpanel::specs());
v.extend(draw2::specs());
v.extend(xform::specs());
v.extend(stepandrepeat::specs());
v.extend(effectcmd::specs());
v.extend(bevels::specs());
v.extend(wireframe::specs());
@@ -874,6 +876,9 @@ pub(crate) use vectorcraft_doc::range::parse_range;
/// What the fill and stroke proxies read from the selected objects, kept with the selection
/// ([`crate::doc_state::SelectionRecord`]).
pub(crate) use paint::SelectionPaints;
/// The faces and edges of Live Paint groups among objects that count with their group
/// ([`crate::DocState::live_paint_covered_kept`] keeps an empty answer).
pub(crate) use paint::live_paint_covered;
#[cfg(test)]
pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ};
@@ -3,7 +3,7 @@
//! the bridges connect, replacing the circles or added above them.
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::PathData;
use vectorcraft_pathops::addons::pathtools as pt;
@@ -34,7 +34,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Smooth Bridge",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
"{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection; a group, other than a clipping group, gives the objects inside it)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles",
has_selection,
bridge
)]
@@ -54,8 +54,8 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0),
};
let keep = switch_or(p, "keepOriginals", false, C)?;
let mut roots = checked_ids_or_selection(s, p, C)?;
// An id given twice is one circle.
let mut roots = members(&s.doc()?.doc, &checked_ids_or_selection(s, p, C)?);
// An id given twice, or a circle given with its group, is one circle.
roots.sort_unstable();
roots.dedup();
if roots.len() > pt::MAX_BRIDGED_CIRCLES {
@@ -140,6 +140,22 @@ fn bridge(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The objects `ids` names, with each group among them (a clipping group excepted) as the objects
/// inside it, at any depth.
fn members(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
fn visit(n: &Node, out: &mut Vec<NodeId>) {
match &n.kind {
NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)),
_ => out.push(n.id),
}
}
let mut out = vec![];
for n in ids.iter().filter_map(|&id| d.node(id)) {
visit(n, &mut out);
}
out
}
/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order).
fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec<NodeId> {
at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect()
@@ -354,3 +354,60 @@ fn locked_and_hidden_circles_are_not_bridged() {
s.execute("object.hide", &json!({})).unwrap();
assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge"));
}
fn group(s: &mut Session, ids: &[NodeId]) -> NodeId {
NodeId(s.execute("object.group", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap()["id"].as_u64().unwrap())
}
fn children(s: &Session, id: NodeId) -> Vec<NodeId> {
s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect()
}
#[test]
fn a_selected_group_of_circles_bridges_the_circles_inside_it() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
let g = group(&mut s, &[a, b]);
select(&mut s, &[g]);
let steps = s.doc().unwrap().history.undo.len();
let r = s.execute(BRIDGE, &json!({})).unwrap();
assert_eq!(r["id"], json!(b.0), "two circles, joined in the upper one's place");
assert_eq!(top_level(&s), [g]);
assert_eq!(children(&s, g), [b], "the outline stays in the group");
assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0);
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(children(&s, g), [a, b]);
// A group inside a group, given with one of its own circles, and a loose circle: three circles, so the reach
// applies.
let c = circle(&mut s, 300.0, 100.0, 20.0);
let outer = group(&mut s, &[g]);
let r = s.execute(BRIDGE, &json!({"ids": [outer.0, a.0, c.0], "reach": 30})).unwrap();
assert_eq!(r["ids"], json!([b.0]), "the grouped circles are joined");
assert_eq!(r["alone"], json!([c.0]), "the far circle is out of reach");
}
#[test]
fn a_selected_group_with_other_objects_or_a_clipping_group_is_refused() {
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
let square = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
let g = group(&mut s, &[a, b, square]);
let steps = s.doc().unwrap().history.undo.len();
assert!(err(&mut s, json!({"ids": [g.0]})).contains("select two or more circles to bridge"));
assert_eq!(children(&s, g), [a, b, square]);
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step");
let mut s = session();
let a = circle(&mut s, 100.0, 100.0, 20.0);
let b = circle(&mut s, 160.0, 100.0, 20.0);
let mask = circle(&mut s, 130.0, 100.0, 80.0);
select(&mut s, &[a, b, mask]);
let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let before = top_level(&s);
assert!(err(&mut s, json!({"ids": [clip.0]})).contains("select two or more circles to bridge"));
assert_eq!(top_level(&s), before);
}
+2 -2
View File
@@ -98,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Brush",
[],
None,
"{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current → {ids}",
"{name, ids?|id?} apply a brush to the strokes of the selected paths (adds a stroke if missing) and make it current; the brush settings of each path's top stroke (brush.objectOptions) are cleared, and clearing them is one undo step; when the brush is already current and applying it leaves every path as it was (its top stroke already has the brush, paint, a width above 0 and no settings of its own), nothing changes and no undo step is recorded → {ids}",
has_doc,
brush_apply
),
@@ -170,7 +170,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush Options…",
[],
None,
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update); params and a newName that leave the brush as it is change nothing and record no undo step → {name}",
has_doc,
brush_options
),
+11 -4
View File
@@ -80,10 +80,11 @@ pub(super) fn brush_apply(s: &mut Session, p: &Value) -> Result<Value> {
}
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
let stroke = stroke_paint(s);
s.edit("Apply Brush", |d, _| {
crate::cmd::colorcmds::edit_if_changed(s, "Apply Brush", |before, d| {
d.unknown.insert(brush::CURRENT_KEY.into(), json!(name));
apply_brush(d, &ids, &name, &stroke);
Ok(())
let changed = brush::current(before).as_deref() != Some(name.as_str()) || ids.iter().any(|id| before.node(*id) != d.node(*id));
Ok(((), changed))
})?;
Ok(json!({ "ids": ids_json(&ids) }))
}
@@ -213,6 +214,7 @@ fn rename_brush_strokes(d: &mut Document, lib: &mut [Brush], from: &str, to: Opt
}
}
/// Stores `lib` and applies `renames` as one undo step named `label`.
fn save_library(s: &mut Session, label: &str, mut lib: Vec<Brush>, renames: &[(String, Option<String>)]) -> Result<()> {
s.edit(label, |d, _| {
for (from, to) in renames {
@@ -503,8 +505,13 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
v["name"] = json!(name);
}
v["type"] = json!(lib[i].kind.type_id());
lib[i] = parse_brush(C, v)?;
let out = lib[i].name.clone();
let edited = parse_brush(C, v)?;
let out = edited.name.clone();
// Options that leave the brush as it is change nothing and add no undo step.
if new_name.is_none() && edited == lib[i] {
return Ok(json!({ "name": out }));
}
lib[i] = edited;
let rename = new_name.map(|nn| (name, Some(nn)));
save_library(s, "Brush Options", lib, rename.as_slice())?;
Ok(json!({ "name": out }))
+34 -7
View File
@@ -162,7 +162,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cut",
["Edit"],
Some("Cmd+X"),
"{selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
"{artboard?: index (the source artboard for copied objects), selectedArtboards?: [n…], art?: bool, lockedAndHidden?: bool (the Artboard tool chosen, as artboard.cut)} (as edit.copy) removes the objects it copies, in one undo step: a compound-path member selected on its own leaves the compound's other members in the compound (selected ruler guides go too; the Artboard tool chosen, or selectedArtboards given: artboard.cut); refused while an object of a symbol instance's art is selected",
has_selection_guides_or_artboard_tool,
cut
),
@@ -171,7 +171,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Copy",
["Edit"],
Some("Cmd+C"),
"{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
"{artboard?: index (the source artboard for copied objects; without it, the artboard containing the selection center), selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}",
has_selection_guides_or_artboard_tool,
copy
),
@@ -967,7 +967,8 @@ pub(crate) fn selection_roots(st: &crate::DocState) -> Vec<NodeId> {
}
#[cfg(test)]
ROOTS_FOUND.set(ROOTS_FOUND.get() + 1);
let roots = roots_of(&st.doc, st.selection.in_paint_order(&st.doc));
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
let roots = roots_placed(&st.doc, ids, &paths, |_, _| false);
*kept = Some((Arc::downgrade(&st.doc), st.selection.objects.clone(), roots.clone()));
roots
})
@@ -1015,7 +1016,19 @@ pub(crate) fn no_symbol_part(s: &Session) -> std::result::Result<(), String> {
pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
refuse_symbol_part(s)?;
let st = s.doc()?;
Ok(roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |_, _| true))
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
Ok(roots_placed(&st.doc, ids, &paths, |_, _| true))
}
/// The objects of `objects` that are in `doc`, in paint order as
/// [`vectorcraft_doc::Selection::in_paint_order`] gives them, with their places in the tree. One
/// walk finds the places for both the order and [`roots_placed`] ([`roots_within`] after
/// `in_paint_order` walks the tree twice).
fn placed_in_paint_order(doc: &Document, objects: &[NodeId]) -> (Vec<NodeId>, HashMap<NodeId, Vec<usize>>) {
let paths = doc.index_paths(objects.iter().copied());
let mut ids: Vec<NodeId> = objects.iter().copied().filter(|id| paths.contains_key(id)).collect();
ids.sort_by(|a, b| paths.get(a).cmp(&paths.get(b)));
(ids, paths)
}
/// [`selected_roots`] for the selected objects inside the isolated object `root`
@@ -1027,8 +1040,9 @@ pub(crate) fn selected_roots_to_transform(s: &Session) -> Result<Vec<NodeId>> {
pub(crate) fn selected_roots_inside(s: &Session, root: NodeId, members: bool) -> Result<Vec<NodeId>> {
refuse_symbol_part(s)?;
let st = s.doc()?;
let ids = st.selection.in_paint_order(&st.doc).into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
Ok(roots_within(&st.doc, ids, |compound, _| members || compound == root))
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
let ids = ids.into_iter().filter(|id| super::inside_isolation(&st.doc, root, *id)).collect();
Ok(roots_placed(&st.doc, ids, &paths, |compound, _| members || compound == root))
}
/// The top-level objects among `ids` (in paint order): compound-path members stand for their
@@ -1042,6 +1056,11 @@ pub(crate) fn roots_of(doc: &Document, ids: Vec<NodeId>) -> Vec<NodeId> {
fn roots_within(doc: &Document, ids: Vec<NodeId>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
// Every id's place in the tree, found in one walk (a lookup per id is a walk per id).
let paths = doc.index_paths(ids.iter().copied());
roots_placed(doc, ids, &paths, keep_member)
}
/// [`roots_within`] with `paths`, the places of `ids` in `doc`'s tree, found already.
fn roots_placed(doc: &Document, ids: Vec<NodeId>, paths: &HashMap<NodeId, Vec<usize>>, keep_member: impl Fn(NodeId, NodeId) -> bool) -> Vec<NodeId> {
// A compound-path member acts as its compound (compounds are one object).
let mut sel: Vec<(NodeId, Option<Vec<usize>>)> = ids
.into_iter()
@@ -1105,7 +1124,8 @@ fn copy_cut_targets(s: &Session) -> Result<(bool, Vec<NodeId>)> {
st.doc.node(compound).and_then(|n| n.children()).is_some_and(|members| !members.is_empty() && members.iter().all(|m| whole(m)))
})
};
let roots = roots_within(&st.doc, st.selection.in_paint_order(&st.doc), |compound, _member| in_isolated_compound || !all_members_whole(compound));
let (ids, paths) = placed_in_paint_order(&st.doc, &st.selection.objects);
let roots = roots_placed(&st.doc, ids, &paths, |compound, _member| in_isolated_compound || !all_members_whole(compound));
Ok((direct, roots))
}
@@ -1163,6 +1183,13 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
});
clip.source_artboard = board.map(|a| a.rect);
}
if let Some(value) = p.get("artboard") {
let board = value
.as_u64()
.and_then(|v| st.doc.artboards.get(index(v)))
.ok_or_else(|| bad("edit.copy", "`artboard` must be the index of an artboard of the document"))?;
clip.source_artboard = Some(board.rect);
}
clip.guides = guides;
s.clipboard = clip;
Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() }))
+30
View File
@@ -348,6 +348,36 @@ fn direct_selection_cut_timing() {
}
}
/// Finding the selected roots (for the menus, for Move and its siblings, for Copy and Cut, and
/// inside an isolated group) walks the tree once for the paint order and the roots together, in
/// paint order whatever order the objects were selected in.
#[test]
fn finding_the_selected_roots_walks_the_tree_once() {
let mut s = session(2_000, square);
let all = crate::tests_large_edits::layer(&s, 0);
let reversed: Vec<u64> = all.iter().rev().map(|id| id.0).collect();
s.execute("select.set", &json!({"ids": reversed})).unwrap();
type Find = fn(&Session) -> Vec<NodeId>;
let finds: [(&str, Find); 3] = [
("the selected roots", |s| selected_roots(s).unwrap()),
("the roots to transform", |s| selected_roots_to_transform(s).unwrap()),
("Copy's targets", |s| copy_cut_targets(s).unwrap().1),
];
for (what, find) in finds {
let walks = tree_walks();
assert!(find(&s) == all, "{what} in paint order");
assert_eq!(tree_walks() - walks, 1, "finding {what} walked the tree {} times", tree_walks() - walks);
}
s.execute("object.group", &json!({})).unwrap();
let group = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id;
s.execute("select.set", &json!({"ids": reversed})).unwrap();
// The first call also builds the lookup cache that the isolation check reads.
assert!(selected_roots_inside(&s, group, false).unwrap() == all, "the roots inside the group in paint order");
let walks = tree_walks();
assert!(selected_roots_inside(&s, group, false).unwrap() == all);
assert_eq!(tree_walks() - walks, 1, "finding the roots inside the group walked the tree {} times", tree_walks() - walks);
}
/// The selected roots are found once for a document version and its selected objects, however many enabled checks
/// read them, and found again after the selection changes, after an edit, and for another selection.
#[test]
+4 -2
View File
@@ -1050,11 +1050,13 @@ impl Session {
match std::fs::symlink_metadata(&path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
// A link is refused: the script's gate does not check where it leads.
Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()),
Ok(m) if !m.file_type().is_file() => return Err(crate::store::NOT_PLAIN.to_string()),
_ => {}
}
crate::file_access::check_read(&file).map_err(denied)?;
crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some)
// Read without following a link, so a link put in the file's place since the check
// above is refused too.
crate::store::read_capped_plain(&path, MAX_PROFILE_BYTES).map(Some)
})?;
let Some(bytes) = read else { return Ok(None) };
// The color profiles the file carries are installed where missing, as opening it installs
+12
View File
@@ -142,6 +142,18 @@ pub(crate) fn keep_compound_aligned(d: &mut Document, id: NodeId, sc: Scaling) {
}
}
/// [`keep_compound_aligned`] for the object at `path` in `d`'s tree, found already: the compound
/// path is read at the parent's place, without looking either object up by id.
pub(crate) fn keep_compound_aligned_at(d: &mut Document, path: &[usize], sc: Scaling) {
let Some((_, up)) = path.split_last() else { return };
if up.is_empty() || !d.node_at(up).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned) {
return;
}
if let Some(n) = d.node_mut_at(up) {
snap_object(n, sc);
}
}
/// After any edit ([`Session::edit`]): snap each pixel-aligned object that the edit changed or added
/// (its node in `doc` is not the one in `before`), with the pixel-aligned art of its linked opacity
/// mask, to the pixel grid. Objects the edit did not touch are not visited.
+26 -18
View File
@@ -66,10 +66,15 @@ pub(super) fn scaling_options(s: &Session, p: &Value) -> Scaling {
/// param, else General › Transform Pattern Tiles)? Noted in the journal when they or the art of
/// their linked opacity masks use a pattern, so a replay moves their tiles alike whatever the preference is then.
pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result<bool> {
let paths = s.doc()?.doc.index_paths(ids.iter().copied());
transform_patterns_at(s, p, ids, &paths)
}
/// [`transform_patterns`] with `paths`, the places of `ids` in the document's tree, found already.
fn transform_patterns_at(s: &mut Session, p: &Value, ids: &[NodeId], paths: &std::collections::HashMap<NodeId, Vec<usize>>) -> Result<bool> {
let on = bool_or(p, "patterns", s.prefs.transform_pattern_tiles);
let d = &s.doc()?.doc;
let mut uses = false;
let paths = d.index_paths(ids.iter().copied());
for n in ids.iter().filter_map(|id| paths.get(id)).filter_map(|p| d.node_at(p)) {
uses |= uses_pattern_with_masks(n);
}
@@ -152,7 +157,9 @@ fn apply_transform_moving_guides(
let areas = bool_or(p, "typeAreas", false);
let objects = transforms_objects(p);
let mut sc = if Scaling::factor(xf).is_some() { scaling(s, p) } else { Scaling::default() };
sc.patterns = transform_patterns(s, p, &ids)?;
// The places of `ids`, found in one walk for Transform Patterns and for the edit below.
let paths = s.doc()?.doc.index_paths(ids.iter().copied());
sc.patterns = transform_patterns_at(s, p, &ids, &paths)?;
let c = xf.as_coeffs();
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
let delta = guides.unwrap_or(Vec2::new(c[4], c[5]));
@@ -174,8 +181,6 @@ fn apply_transform_moving_guides(
// An edit normally preserves the tree positions already found here. Settling an active
// typing session can change the document before the edit closure runs, so look up again then.
let reindex = copy || (!s.previewing && crate::cmd::typing_in_progress(s));
let d = &s.doc()?.doc;
let paths = d.index_paths(ids.iter().copied());
let none = paths.is_empty() && !has_guides;
// A move of direct-selected anchors may re-map the handles beside them (`interpolate`).
let mut interpolate = None;
@@ -195,7 +200,7 @@ fn apply_transform_moving_guides(
// A move of whole objects, not of copies (which `reindex` covers): the document before it,
// and the moved objects as the transform left them, for [`moved_by`] to check after the edit.
let from = (objects && !areas && !reindex && c[..4] == [1.0, 0.0, 0.0, 1.0]).then(|| s.doc().map(|st| st.doc.clone())).transpose()?;
let mut held: Vec<(NodeId, Arc<Node>)> = vec![];
let mut held: Vec<(Vec<usize>, Arc<Node>)> = vec![];
let targets = s.edit(label, |d, sel| {
let mut targets = match &kept {
// The document becomes the snapshot with the kept copies, untransformed, and the
@@ -235,11 +240,12 @@ fn apply_transform_moving_guides(
}
// Holding them makes any later change to them copy them first, which `moved_by` sees.
if from.is_some() {
held = targets.iter().filter_map(|id| Some((*id, node_arc(d, paths.get(id)?)?))).collect();
held = targets.iter().filter_map(|id| paths.get(id)).filter_map(|p| Some((p.clone(), node_arc(d, p)?))).collect();
}
if objects {
for id in &targets {
super::pixelgrid::keep_compound_aligned(d, *id, sc);
// The transforms above leave every object at its place, so `paths` still holds them.
for p in targets.iter().filter_map(|id| paths.get(id)) {
super::pixelgrid::keep_compound_aligned_at(d, p, sc);
}
// Moving all of the tile art moves the tile as far.
if let Some(before) = tile_art {
@@ -288,20 +294,22 @@ fn node_arc(d: &Document, path: &[usize]) -> Option<Arc<Node>> {
}
/// The [`crate::Moved`] of a move by `by` that took `from` to the document of `st`, given the moved
/// objects as the transform left them (`held`). `None` unless every moved object is still that
/// node, none is a member of a blend (whose spine follows its members), and every object the
/// selection shows, the key object and the key anchor's object included, is a moved object or
/// inside one. A pass after the transform that changes a moved object, such as the one that snaps
/// moved pixel-aligned objects to the pixel grid again ([`super::pixelgrid::refresh`]), copies it
/// first, so it is no longer that node.
fn moved_by(from: &Arc<Document>, st: &crate::DocState, held: &[(NodeId, Arc<Node>)], by: Vec2) -> Option<crate::Moved> {
/// objects as the transform left them (`held`, each with its index path). `None` unless every moved
/// object is still that node at its path, none is a member of a blend (whose spine follows its
/// members), and every object the selection shows, the key object and the key anchor's object
/// included, is a moved object or inside one. A pass after the transform that changes a moved
/// object, such as the one that snaps moved pixel-aligned objects to the pixel grid again
/// ([`super::pixelgrid::refresh`]), copies it first, so it is no longer that node. The checks read
/// the nodes at their paths and look nothing up by id.
fn moved_by(from: &Arc<Document>, st: &crate::DocState, held: &[(Vec<usize>, Arc<Node>)], by: Vec2) -> Option<crate::Moved> {
let d = &st.doc;
let unchanged = |(id, n): &(NodeId, Arc<Node>)| d.node(*id).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n)));
let unchanged = |(p, n): &(Vec<usize>, Arc<Node>)| d.node_at(p).is_some_and(|now| std::ptr::eq(now, Arc::as_ptr(n)));
if held.is_empty() || !held.iter().all(unchanged) {
return None;
}
let in_blend = |id: NodeId| d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Blend { .. }));
if held.iter().any(|(id, _)| in_blend(*id)) {
// The node at each path is the moved object, so its parent is the node one level up.
let in_blend = |p: &[usize]| p.split_last().and_then(|(_, up)| d.node_at(up)).is_some_and(|parent| matches!(parent.kind, NodeKind::Blend { .. }));
if held.iter().any(|(p, _)| in_blend(p)) {
return None;
}
let mut moved = std::collections::HashSet::new();
+41 -4
View File
@@ -185,14 +185,27 @@ fn can_change_mask(s: &Session) -> std::result::Result<(), String> {
/// most one outermost object, which it masks with `ids` (a call's `ids` stand in for the selection
/// here). A targeted layer is one subject root however many objects it selects. `make` itself
/// refuses any single target in those modes, a layer included, so a selection with a target counts
/// as one object.
/// as one object. The check sorts the selection into paint order for its outermost objects only when it has one
/// subject root and no target.
fn can_make(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
let Some(st) = s.active() else { return Ok(()) };
let roots = super::appearance::subject_roots(s).map_or(0, |r| r.len());
let outermost = super::edit::outermost(&st.doc, st.selection.in_paint_order(&st.doc)).len();
let targeted = st.selection.target.is_some();
if roots == 1 && (outermost <= 1 || targeted) { super::maskedit::can_edit_mask(s) } else { Ok(()) }
if roots != 1 {
return Ok(());
}
let one = st.selection.target.is_some() || {
#[cfg(test)]
OUTERMOST_FOUND.set(OUTERMOST_FOUND.get() + 1);
super::edit::outermost(&st.doc, st.selection.in_paint_order(&st.doc)).len() <= 1
};
if one { super::maskedit::can_edit_mask(s) } else { Ok(()) }
}
#[cfg(test)]
thread_local! {
/// How many times [`can_make`] found the selection's outermost objects on this thread.
static OUTERMOST_FOUND: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
@@ -485,6 +498,12 @@ impl Session {
_ => TransparencyInfo::default(),
}
}
/// The first of the objects the Transparency panel shows ([`TransparencyInfo::ids`]), without comparing their
/// values.
pub fn transparency_target(&self) -> Option<NodeId> {
transparency_targets(self, &Value::Null).ok()?.first().copied()
}
}
fn info(s: &mut Session, p: &Value) -> Result<Value> {
@@ -759,4 +778,22 @@ mod tests {
let back = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(back.node(NodeId(a)).unwrap().extras().mask, d.node(NodeId(a)).unwrap().extras().mask);
}
/// Make Opacity Mask's check sorts the selection for its outermost objects only when the selection has one
/// subject root; with several roots it is enabled without that sort.
#[test]
fn the_make_check_sorts_only_a_selection_with_one_root() {
let (mut s, a, b) = session_with_two();
let found = || OUTERMOST_FOUND.get();
select(&mut s, &[a, b]);
let before = found();
assert_eq!(can_make(&s), Ok(()));
assert_eq!(found(), before, "two roots: no paint-order sort");
select(&mut s, &[a]);
assert_eq!(can_make(&s), Ok(()));
assert_eq!(found(), before + 1, "one root: the outermost objects are found");
s.execute("select.none", &json!({})).unwrap();
assert_eq!(can_make(&s), Ok(()));
assert_eq!(found(), before + 1, "no roots: no sort");
}
}
+3 -2
View File
@@ -1470,12 +1470,13 @@ fn in_live_paint(d: &Document, id: NodeId) -> bool {
impl DocState {
/// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group.
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group,
/// else as [`DocState::live_paint_covered_kept`] keeps it for this version of the document.
pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
if self.selection_paints().is_some_and(|p| !p.in_live_paint()) {
return std::collections::HashSet::new();
}
live_paint_covered(&self.doc, ids)
self.live_paint_covered_kept(ids)
}
}
+52
View File
@@ -242,6 +242,58 @@ fn the_question_marks_read_only_the_selected_objects() {
assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection");
}
/// How many times this thread read the groups around selected objects for their Live Paint faces
/// and edges ([`DocState::live_paint_covered_kept`]).
fn cover_reads() -> usize {
crate::doc_state::LIVE_PAINT_COVER_READS.with(Cell::get)
}
/// After an edit the selection keeps no record of what it holds, and the proxies, the Stroke panel
/// and the "?" ask on every frame whether its objects lie in a Live Paint group. They read the
/// objects' groups once for each version of the document and selection, not once for each question.
/// A Live Paint group selected with one of its faces still counts the face with its group.
#[test]
fn live_paint_faces_are_looked_for_once_per_document_version() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
let ids: Vec<NodeId> = (0..20).map(|i| rect(&mut s, 10.0 + 30.0 * f64::from(i), "#ff0000", "#000000")).collect();
s.execute("select.all", &json!({})).unwrap();
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
assert!(s.active().unwrap().selection_paints().is_none(), "the edit leaves the selection without a record");
let ask = |s: &Session| {
for _ in 0..3 {
s.proxy_paints();
s.shown_stroke();
s.proxy_mixed();
s.active().unwrap().stroke_mixed();
}
};
let before = cover_reads();
ask(&s);
assert_eq!(cover_reads() - before, 1, "one read for this version of the document");
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = cover_reads();
ask(&s);
assert_eq!(cover_reads() - before, 1, "an edit reads them again, once");
s.execute("select.set", &json!({"ids": [ids[0].0, ids[1].0]})).unwrap();
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let before = cover_reads();
ask(&s);
assert_eq!(cover_reads() - before, 1, "another selection reads them again, once");
// A Live Paint group with one of its edges selected too: the edge counts with its group on every ask.
s.execute("livePaint.make", &json!({"ids": [ids[2].0, ids[3].0]})).unwrap();
let group = s.active().unwrap().selection.objects[0];
let edge = vectorcraft_tools::builder::edges(s.active().unwrap().doc.node(group).unwrap())[0].id;
s.execute("select.set", &json!({"ids": [group.0, edge.0]})).unwrap();
let st = s.active().unwrap();
let covered = live_paint_covered(&st.doc, &st.selection.objects);
assert!(covered.contains(&edge));
for _ in 0..2 {
assert_eq!(st.selection_live_paint_covered(&st.selection.objects), covered);
}
}
/// Random selections of a document with nested groups answer as a walk does.
#[test]
fn random_selections_match_a_walk_of_the_document() {
@@ -409,6 +409,7 @@ pub(super) const ALLOWED: &[&str] = &[
"object.slice.release",
"object.slice.select",
"object.slice.setRect",
"object.stepAndRepeat",
"object.tag.add",
"object.tag.remove",
"object.tag.removeAll",
+2
View File
@@ -725,6 +725,8 @@ impl Session {
for e in self.prefs.keep_folders(&mut p) {
log::warn!("{e}");
}
// Tool settings saved by an earlier version are updated once.
p.migrate_tool_settings();
// Saved gradient presets get names no built-in preset or other saved one has.
for (old, new) in super::gradpresets::rename_clashing_presets(&mut p.gradient_presets) {
log::warn!("saved gradient preset {old} is listed as {new}: another preset has its name");
+141
View File
@@ -1027,6 +1027,84 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
used.into_iter().map(|(_, u)| u).collect()
}
#[cfg(test)]
thread_local! {
/// Tests: how many objects [`several_colors`] read on this thread.
static SEVERAL_COLORS_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Whether [`used_colors`] lists more than one color for the objects `ids`. The objects are read
/// until a second color turns up.
fn several_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) -> bool {
struct Seen<'a> {
first: Option<ColorKey>,
several: bool,
patterns: Vec<&'a str>,
}
impl<'a> Seen<'a> {
fn read(&mut self, m: &'a Node) {
#[cfg(test)]
SEVERAL_COLORS_READS.with(|c| c.set(c.get() + 1));
let (first, several) = (&mut self.first, &mut self.several);
paints(
m,
&mut |c, _, _, _| {
let k = ColorKey::of(c);
match first {
None => *first = Some(k),
Some(f) => *several |= *f != k,
}
},
&mut self.patterns,
);
}
fn read_tree(&mut self, n: &'a Node, only: Option<&BTreeSet<NodeId>>) {
if self.several || only.is_some_and(|o| !o.contains(&n.id)) {
return;
}
self.read(n);
for c in n.children().into_iter().flatten() {
self.read_tree(c, only);
if self.several {
return;
}
}
}
}
let mut seen = Seen { first: None, several: false, patterns: vec![] };
for n in ids.iter().filter_map(|id| d.node(*id)) {
seen.read_tree(n, only);
if seen.several {
return true;
}
}
let mut next = 0;
while !seen.several
&& let Some(&name) = seen.patterns.get(next)
{
next += 1;
for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() {
let _ = a.try_walk(&mut |m| {
seen.read(m);
if seen.several { std::ops::ControlFlow::Break(()) } else { std::ops::ControlFlow::Continue(()) }
});
if seen.several {
break;
}
}
}
seen.several
}
impl Session {
/// Whether the objects `recolor.colors` reads without `ids` use more than one color: the
/// selection, or with nothing selected the objects Select All takes. False without a document.
pub fn several_colors_used(&self) -> bool {
let Ok((ids, only)) = scope_ids(self, &Value::Null, "recolor.colors") else { return false };
self.doc().is_ok_and(|st| several_colors(&st.doc, &ids, only.as_ref()))
}
}
/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint
/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and
/// add the patterns it is painted with to `patterns`.
@@ -2050,6 +2128,69 @@ mod tests {
assert!(has(&t, RED), "P100 read again at the top");
}
/// How many objects [`several_colors`] read on this thread.
fn several_reads() -> usize {
SEVERAL_COLORS_READS.with(std::cell::Cell::get)
}
/// Whether more than one color is used ([`Session::several_colors_used`]), checked against the
/// length of `recolor.colors`'s list, with how many objects the answer read.
fn several(s: &mut Session, what: &str) -> (bool, usize) {
let before = several_reads();
let several = s.several_colors_used();
let reads = several_reads() - before;
let listed = s.execute("recolor.colors", &json!({})).unwrap()["colors"].as_array().map_or(0, Vec::len);
assert_eq!(several, listed > 1, "{what}: {listed} colors listed");
(several, reads)
}
/// The Recolor quick action asks on every change whether the selection uses more than one
/// color. The answer matches `recolor.colors`, pattern tiles and Select All's objects included,
/// and the objects are read only until a second color turns up.
#[test]
fn several_colors_stop_at_the_second_color() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
let ids: Vec<u64> = (0..30)
.map(|i| {
let id =
s.execute("shape.rectangle", &json!({"x": 10 + 20 * i, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"ids": [id], "color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap();
id
})
.collect();
s.execute("select.all", &json!({})).unwrap();
assert_eq!(several(&mut s, "one red"), (false, 30), "one color: every object is read");
// A blue object in the middle: the objects are read up to it, from either end.
s.execute("paint.setFill", &json!({"ids": [ids[15]], "color": "#0000ff"})).unwrap();
let (found, reads) = several(&mut s, "a blue in the middle");
assert!(found && matches!(reads, 15 | 16), "{reads} objects read");
s.execute("paint.setFill", &json!({"ids": [ids[0], ids[29]], "color": "#00ff00"})).unwrap();
assert_eq!(several(&mut s, "green at both ends"), (true, 2), "the second object holds the second color");
s.execute("select.set", &json!({"ids": &ids[1..15]})).unwrap();
assert!(!several(&mut s, "the red ones").0);
s.execute("select.none", &json!({})).unwrap();
assert!(several(&mut s, "Select All's objects").0);
// A red object filled with a pattern too: its tile's color counts.
for (tile, expect) in [(BLUE, true), (RED, false)] {
let filled = NodeId(ids[1]);
s.edit("t", |d, _| {
let art = square(d, 0.0, Paint::solid(tile));
d.patterns.retain(|p| p.name != "Tile");
d.patterns.push(PatternDef::new("Tile", vec![art]));
if let Some(n) = d.node_mut(filled) {
n.appearance.set_fill(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY });
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [ids[1], ids[2]]})).unwrap();
assert_eq!(several(&mut s, "a pattern tile").0, expect, "a tile of {tile:?}");
}
}
/// A pattern tile's symbol instances charge the same limit as the art around it.
#[test]
fn pattern_tiles_charge_the_symbol_limit() {
+214
View File
@@ -0,0 +1,214 @@
//! Object › Step and Repeat: lays out copies of the selection on a grid or fills a sheet, for
//! print-and-cut work (stickers, labels).
use serde_json::{Value, json};
use vectorcraft_geom::{Rect, Vec2, rotate_deg};
use super::edit::{copy_above, selected_roots};
use super::object::group_nodes;
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_selection, switch_or};
use crate::EngineError;
use vectorcraft_doc::Scaling;
const CMD: &str = "object.stepAndRepeat";
const MAX_CELLS: usize = 10_000;
const EPS: f64 = 1e-9;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"object.stepAndRepeat",
"Step and Repeat…",
["Object", "Transform"],
None,
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}",
has_selection,
step_and_repeat
)]
}
/// Which cells of the grid are turned by 180°.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Alternate {
None,
Columns,
Rows,
}
/// One cell of a layout: its place in the grid, the offset of its top-left corner from the first
/// cell's, and whether its copy is turned by 180° about the cell's center.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Cell {
pub row: usize,
pub col: usize,
pub dx: f64,
pub dy: f64,
pub turned: bool,
}
/// How many items of `size` with `gap` between them fit in `room` (all at least 0).
pub fn fit_count(room: f64, size: f64, gap: f64) -> usize {
if !(room.is_finite() && size.is_finite() && gap.is_finite()) || size <= 0.0 || room < size - EPS {
return 0;
}
(((room + gap) / (size + gap)) + EPS).floor().max(0.0) as usize
}
/// The `(rows, columns)` of items `w` × `h` with gaps `gx`, `gy` that fit a sheet `sw` × `sh`
/// inside `margin` on every side.
pub fn fill_counts(sw: f64, sh: f64, margin: f64, w: f64, h: f64, gx: f64, gy: f64) -> (usize, usize) {
let m = margin.max(0.0);
(fit_count(sh - 2.0 * m, h, gy), fit_count(sw - 2.0 * m, w, gx))
}
/// The cells of a `rows` × `cols` grid of items `w` × `h` with gaps `gx` between columns and `gy`
/// between rows, in reading order.
pub fn layout(w: f64, h: f64, gx: f64, gy: f64, rows: usize, cols: usize, alt: Alternate) -> Vec<Cell> {
(0..rows)
.flat_map(|row| (0..cols).map(move |col| (row, col)))
.map(|(row, col)| Cell {
row,
col,
dx: col as f64 * (w + gx),
dy: row as f64 * (h + gy),
turned: match alt {
Alternate::None => false,
Alternate::Columns => col % 2 == 1,
Alternate::Rows => row % 2 == 1,
},
})
.collect()
}
fn count_param(p: &Value, key: &str) -> Result<usize> {
match p.get(key).filter(|v| !v.is_null()) {
None => Ok(1),
Some(v) => v
.as_u64()
.filter(|n| (1..=MAX_CELLS as u64).contains(n))
.map(|n| n as usize)
.ok_or_else(|| bad(CMD, format!("`{key}` must be a whole number from 1 to {MAX_CELLS}"))),
}
}
fn sheet_param(p: &Value) -> Result<Option<Rect>> {
let Some(v) = p.get("sheet").filter(|v| !v.is_null()) else { return Ok(None) };
let n = |k: &str| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).ok_or_else(|| bad(CMD, format!("`sheet.{k}` must be a number")));
let (x, y, w, h) = (n("x")?, n("y")?, n("width")?, n("height")?);
if w <= 0.0 || h <= 0.0 {
return Err(bad(CMD, "`sheet` needs a positive width and height"));
}
Ok(Some(Rect::new(x, y, x + w, y + h)))
}
fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["gap", "gapX", "gapY", "margin"], CMD)?;
check_switches(p, &["patterns"], CMD)?;
let fill = switch_or(p, "fill", false, CMD)?;
let alt = match p.get("rotate").filter(|v| !v.is_null()) {
None => Alternate::None,
Some(v) => match v.as_str() {
Some("none") => Alternate::None,
Some("columns") => Alternate::Columns,
Some("rows") => Alternate::Rows,
_ => return Err(bad(CMD, "`rotate` must be \"none\", \"columns\" or \"rows\"")),
},
};
let gap = super::f64_or(p, "gap", 0.0);
let (gx, gy) = (super::f64_or(p, "gapX", gap), super::f64_or(p, "gapY", gap));
let margin = super::f64_or(p, "margin", 0.0);
if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) {
return Err(bad(CMD, "gaps and margin must be finite"));
}
let (rows, cols) = if fill { (1, 1) } else { (count_param(p, "rows")?, count_param(p, "columns")?) };
let sheet = sheet_param(p)?;
let mut roots = selected_roots(s)?;
if roots.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
}
let d = &s.doc()?.doc;
let cut = match p.get("cutId").filter(|v| !v.is_null()) {
None => None,
Some(v) => {
let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutId` must be an object id"))?);
let held = roots.iter().filter_map(|r| d.node(*r)).any(|n| {
let mut found = false;
n.walk(&mut |c| found |= c.id == id);
found
});
if !held {
return Err(bad(CMD, "`cutId` must be part of the selection"));
}
Some(id)
}
};
let measured = cut.map_or_else(|| roots.clone(), |id| vec![id]);
let b = d.bounds_of(&measured, false);
let b = b.ok_or_else(|| EngineError::Other("the selection has no bounds".into()))?;
let (w, h) = (b.width(), b.height());
if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 {
return Err(EngineError::Other("the selection has no area to repeat".into()));
}
let anchor = if fill {
let sheet = sheet.or_else(|| {
let c = d.bounds_of(&roots, false).unwrap_or(b).center();
d.artboards.iter().find(|a| a.rect.contains(c)).or_else(|| d.artboards.first()).map(|a| a.rect)
});
let sheet = sheet.ok_or_else(|| EngineError::Other("no sheet to fill".into()))?;
Some((sheet, margin.max(0.0)))
} else {
None
};
let (rows, cols) = match anchor {
Some((sh, m)) => fill_counts(sh.width(), sh.height(), m, w, h, gx, gy),
None => (rows, cols),
};
if rows == 0 || cols == 0 {
return Err(EngineError::Other("the selection does not fit the sheet".into()));
}
if rows.saturating_mul(cols) > MAX_CELLS {
return Err(bad(CMD, format!("more than {MAX_CELLS} copies")));
}
let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0));
let cells = layout(w, h, gx, gy, rows, cols, alt);
let center = b.center().to_vec2();
let place = |c: &Cell| -> Affine {
let t = Affine::translate(origin + Vec2::new(c.dx, c.dy));
if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t }
};
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() };
let ids = s.edit("Step and Repeat", |d, sel| {
if roots.len() > 1 {
roots = vec![group_nodes(d, &roots)?];
}
let mut copied: Vec<NodeId> = vec![];
let mut first = Affine::IDENTITY;
for c in &cells {
let m = place(c);
if c.row == 0 && c.col == 0 {
first = m;
continue;
}
let copies = copy_above(d, &roots, |_, _, n| {
n.transform(m, sc);
super::object::keep_pixel_aligned(n, sc);
})?;
copied.extend(copies);
}
if first != Affine::IDENTITY {
for id in &roots {
if let Some(n) = d.node_mut(*id) {
n.transform(first, sc);
super::object::keep_pixel_aligned(n, sc);
}
}
}
let mut out: Vec<NodeId> = roots.clone();
out.extend(copied);
sel.set(out.iter().copied());
Ok(out)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "rows": rows, "columns": cols, "count": ids.len() }))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,178 @@
use serde_json::json;
use super::*;
const A4: (f64, f64) = (210.0, 297.0);
#[test]
fn fills_a4_with_50_by_30_items_and_3_gap() {
assert_eq!(fill_counts(A4.0, A4.1, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 4));
assert_eq!(fill_counts(A4.0, A4.1, 5.0, 50.0, 30.0, 3.0, 3.0), (8, 3));
assert_eq!(fill_counts(40.0, 297.0, 0.0, 50.0, 30.0, 3.0, 3.0), (9, 0));
}
#[test]
fn layout_places_cells_at_the_pitch_and_alternates_rotation() {
let c = layout(50.0, 30.0, 3.0, 3.0, 9, 4, Alternate::Columns);
assert_eq!(c.len(), 36);
let at = |r: usize, k: usize| c[r * 4 + k];
assert_eq!((at(0, 0).dx, at(0, 0).dy), (0.0, 0.0));
assert_eq!((at(2, 3).dx, at(2, 3).dy), (159.0, 66.0));
assert_eq!(c.iter().filter(|c| c.turned).count(), 18);
assert!(at(4, 1).turned && at(4, 3).turned && !at(4, 0).turned && !at(4, 2).turned);
let rows = layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::Rows);
assert_eq!(rows.iter().map(|c| c.turned).collect::<Vec<_>>(), [false, false, true, true, false, false]);
assert!(layout(50.0, 30.0, 3.0, 3.0, 3, 2, Alternate::None).iter().all(|c| !c.turned));
}
fn setup() -> (Session, u64) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap();
(s, id)
}
fn bounds(s: &Session, id: u64) -> (f64, f64, f64, f64) {
let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
(b.x0, b.y0, b.x1, b.y1)
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn creates_the_grid_in_one_undo_step_and_undoes_cleanly() {
let (mut s, _) = setup();
let (before, steps) = (s.doc().unwrap().doc.clone(), undo_steps(&s));
let r = s.execute(CMD, &json!({"rows": 2, "columns": 3, "gap": 3})).unwrap();
assert_eq!((r["count"].clone(), r["rows"].clone(), r["columns"].clone()), (json!(6), json!(2), json!(3)));
assert_eq!(undo_steps(&s), steps + 1);
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
assert_eq!(bounds(&s, ids[0]), (0.0, 0.0, 50.0, 30.0));
assert_eq!(bounds(&s, ids[4]), (53.0, 33.0, 103.0, 63.0));
assert_eq!(bounds(&s, ids[5]), (106.0, 33.0, 156.0, 63.0));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(undo_steps(&s), steps);
let d = &s.doc().unwrap().doc;
assert_eq!(d.artboards.len(), before.artboards.len());
assert!(d.node(NodeId(ids[0])).is_some());
assert!(ids[1..].iter().all(|i| d.node(NodeId(*i)).is_none()));
}
#[test]
fn fill_sheet_with_margin_moves_the_first_copy_to_the_corner() {
let (mut s, _) = setup();
let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 0})).unwrap();
assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(9), json!(4), json!(36)));
let (mut s, _) = setup();
let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5})).unwrap();
assert_eq!(r["count"], json!(24));
let first = r["ids"][0].as_u64().unwrap();
assert_eq!(bounds(&s, first), (5.0, 5.0, 55.0, 35.0));
}
#[test]
fn fill_places_every_cell_from_the_original_when_it_starts_away_from_the_margin() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
s.execute("shape.rectangle", &json!({"x": 20, "y": 40, "width": 50, "height": 30})).unwrap();
let r = s.execute(CMD, &json!({"fill": true, "gap": 3, "margin": 5, "rotate": "columns"})).unwrap();
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(8), json!(3)));
assert_eq!(bounds(&s, ids[0]), (5.0, 5.0, 55.0, 35.0));
assert_eq!(bounds(&s, ids[1]), (58.0, 5.0, 108.0, 35.0));
assert_eq!(bounds(&s, ids[2]), (111.0, 5.0, 161.0, 35.0));
assert_eq!(bounds(&s, ids[3]), (5.0, 38.0, 55.0, 68.0));
}
#[test]
fn alternate_columns_turn_by_180_degrees_about_the_cell_center() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap();
let id = s.execute("shape.polygon", &json!({"cx": 25, "cy": 15, "radius": 10, "sides": 3})).unwrap()["id"].as_u64().unwrap();
let b0 = bounds(&s, id);
let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gap": 4, "rotate": "columns"})).unwrap();
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
let (w, b1) = (b0.2 - b0.0, bounds(&s, ids[1]));
assert!((b1.0 - (b0.0 + w + 4.0)).abs() < 1e-6 && ((b1.2 - b1.0) - w).abs() < 1e-6);
assert!((b1.1 - b0.1).abs() < 1e-6 && (b1.3 - b0.3).abs() < 1e-6);
let tri = |s: &Session, id: u64| format!("{:?}", s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind);
assert_ne!(tri(&s, ids[0]), tri(&s, ids[1]));
}
#[test]
fn a_cut_contour_stays_grouped_with_its_artwork_in_every_copy() {
let (mut s, art) = setup();
let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [art, cut]})).unwrap();
let r = s.execute(CMD, &json!({"rows": 1, "columns": 3, "gap": 2, "cutId": cut})).unwrap();
assert_eq!(r["count"], json!(3));
let d = &s.doc().unwrap().doc;
for id in r["ids"].as_array().unwrap() {
let n = d.node(NodeId(id.as_u64().unwrap())).unwrap();
assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }));
let mut paths = 0;
n.walk(&mut |c| paths += usize::from(matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })));
assert_eq!(paths, 2);
}
}
#[test]
fn rejects_bad_params_and_a_selection_that_does_not_fit() {
let (mut s, _) = setup();
assert!(s.execute(CMD, &json!({"rows": 0})).is_err());
assert!(s.execute(CMD, &json!({"rows": 1000, "columns": 1000})).is_err());
assert!(s.execute(CMD, &json!({"rotate": "diagonal"})).is_err());
assert!(s.execute(CMD, &json!({"cutId": 999999})).is_err());
assert!(s.execute(CMD, &json!({"fill": true, "sheet": {"x": 0, "y": 0, "width": 40, "height": 40}})).is_err());
let mut e = Session::new();
e.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert!(e.execute(CMD, &json!({})).is_err());
}
#[test]
fn fill_ignores_explicit_counts() {
let (mut s, _) = setup();
let r = s.execute(CMD, &json!({"fill": true, "rows": 0, "columns": 0, "gap": 3})).unwrap();
assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(9), json!(4)));
assert!(s.execute(CMD, &json!({"rows": 0})).is_err());
}
#[test]
fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_grid() {
let gap = |aligned: bool| {
let (mut s, id) = setup();
if aligned {
s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap();
}
let r = s.execute(CMD, &json!({"rows": 1, "columns": 2, "gapX": 0.5})).unwrap();
let ids: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect();
let (a, c) = (bounds(&s, ids[0]), bounds(&s, ids[1]));
(c.0 - a.2, c.0 - a.0)
};
assert!((gap(false).0 - 0.5).abs() < 1e-9);
let pitch = gap(true).1;
assert!((pitch - pitch.round()).abs() < 1e-9);
}
#[test]
fn fill_picks_the_artboard_of_the_selection_not_of_the_cut_contour() {
let first_x = |sheet: Option<Value>| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 100, "y": 0, "width": 100, "height": 100})).unwrap();
let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap();
let cut = s.execute("shape.rectangle", &json!({"x": 105, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [art, cut]})).unwrap();
let mut p = json!({"fill": true, "cutId": cut});
if let Some(sh) = sheet {
p["sheet"] = sh;
}
let r = s.execute(CMD, &p).unwrap();
bounds(&s, r["ids"][0].as_u64().unwrap()).0
};
let default = first_x(None);
let explicit = first_x(Some(json!({"x": 100, "y": 0, "width": 100, "height": 100})));
assert!((explicit - default - 100.0).abs() < 1e-9);
}
+167 -12
View File
@@ -4,6 +4,8 @@
//! resolves, for each area text object, the outlines of the wrap objects above it into
//! `TextObject::wrap` (text space); the layout engine subtracts them from each line's span.
use std::collections::{HashMap, HashSet};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId, NodeKind, TextWrap};
@@ -17,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Text Wrap"],
None,
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids}",
"{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; a selected type object with another selected object above it in its layer is the text to wrap, not a wrap object, and loses a wrap it had; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids (the wrap objects), warning? (no area type lies below any of them)}",
has_selection,
make
),
@@ -27,13 +29,16 @@ pub fn specs() -> Vec<CommandSpec> {
"Text Wrap Options…",
["Object", "Text Wrap"],
None,
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}",
"{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects, leaving out the type selected below them as Make does (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}",
has_selection,
options
),
]
}
/// The warning Make gives when no area type lies below any of its wrap objects in their layer.
pub const NO_AREA_TYPE_BELOW: &str = "Text Wrap: no area type lies below these objects in their layer, so no text wraps around them. Move the objects above the area type with Object › Arrange › Bring to Front. Point type does not wrap.";
/// The Offset a wrap object takes, in points.
pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive<f64> = -1000.0..=1000.0;
@@ -51,20 +56,70 @@ fn wrap_param(p: &Value, base: TextWrap, cmd: &str) -> Result<TextWrap> {
Ok(TextWrap { offset, invert: switch_or(p, "invert", base.invert, cmd)? })
}
/// The type objects of `ids` that lie below another of `ids` in their layer: the text Make wraps
/// when the wrap objects and the type are selected together. Make leaves them out of the wrap
/// objects, and takes the wrap off any of them that has one.
fn type_to_wrap(d: &Document, ids: &[NodeId]) -> HashSet<NodeId> {
let wanted: HashSet<NodeId> = ids.iter().copied().collect();
// One pass in paint order: each selected type object with its layer and place, and the place of
// the topmost selected object other than a layer in each layer.
let mut texts = vec![];
let mut top: HashMap<usize, usize> = HashMap::new();
let mut at = 0usize;
for (layer, l) in d.layers.iter().enumerate() {
l.walk(&mut |n| {
if wanted.contains(&n.id) {
match n.kind {
NodeKind::Layer { .. } => {}
NodeKind::Text(_) => {
texts.push((n.id, layer, at));
top.insert(layer, at);
}
_ => {
top.insert(layer, at);
}
}
}
at += 1;
});
}
texts.into_iter().filter(|(_, layer, at)| top.get(layer).is_some_and(|t| t > at)).map(|(id, _, _)| id).collect()
}
fn make(s: &mut Session, p: &Value) -> Result<Value> {
let ids = checked_ids_or_selection(s, p, "object.textWrap.make")?;
let w = wrap_param(p, TextWrap::default(), "object.textWrap.make")?;
s.edit("Make Text Wrap", |d, _| {
for id in &ids {
let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
if matches!(n.kind, NodeKind::Layer { .. }) {
let (objects, text, changed) = {
let d = &s.doc()?.doc;
let text = type_to_wrap(d, &ids);
let objects: Vec<NodeId> = ids.iter().copied().filter(|i| !text.contains(i)).collect();
for id in &objects {
if d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. })) {
return Err(EngineError::Other("layers can't be wrap objects".into()));
}
n.extras_mut().wrap = Some(w);
}
Ok(())
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
let changed = objects.iter().any(|i| d.node(*i).is_some_and(|n| n.extras().wrap != Some(w)))
|| text.iter().any(|i| d.node(*i).is_some_and(|n| n.extras().wrap.is_some()));
(objects, text, changed)
};
if changed {
s.edit("Make Text Wrap", |d, _| {
for id in &objects {
d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().wrap = Some(w);
}
for id in &text {
d.node_mut(*id).ok_or(EngineError::NoNode(*id))?.extras_mut().wrap = None;
}
Ok(())
})?;
}
let mut out = json!({ "ids": objects.iter().map(|i| i.0).collect::<Vec<_>>() });
let mut wraps = false;
vectorcraft_doc::text::wrap_sources(&s.doc()?.doc, |_, sources, _| wraps |= sources.iter().any(|n| objects.contains(&n.id)));
if !wraps {
out["warning"] = json!(NO_AREA_TYPE_BELOW);
}
Ok(out)
}
fn release(s: &mut Session, p: &Value) -> Result<Value> {
@@ -91,14 +146,25 @@ fn release(s: &mut Session, p: &Value) -> Result<Value> {
fn options(s: &mut Session, p: &Value) -> Result<Value> {
let ids = checked_ids_or_selection(s, p, "object.textWrap.options")?;
let current = {
// The type selected below the wrap objects is the text they wrap, as in Make.
let (ids, current) = {
let d = &s.doc()?.doc;
ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default()
let text = type_to_wrap(d, &ids);
let ids: Vec<NodeId> = ids.into_iter().filter(|i| !text.contains(i)).collect();
let current = ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default();
(ids, current)
};
if ["offset", "invert"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) {
return Ok(json!({ "offset": current.offset, "invert": current.invert }));
}
let w = wrap_param(p, current, "object.textWrap.options")?;
let changed = {
let d = &s.doc()?.doc;
ids.iter().any(|i| d.node(*i).is_some_and(|n| !matches!(n.kind, NodeKind::Layer { .. }) && n.extras().wrap != Some(w)))
};
if !changed {
return Ok(json!({ "offset": w.offset, "invert": w.invert }));
}
s.edit("Text Wrap Options", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id)
@@ -287,6 +353,95 @@ mod tests {
assert_eq!(s.execute("object.textWrap.options", &json!({"invert": true})).unwrap(), json!({"offset": 5000.0, "invert": true}));
}
fn wrap_of(s: &Session, id: u64) -> Option<vectorcraft_doc::TextWrap> {
s.doc().unwrap().doc.node(NodeId(id)).unwrap().extras().wrap
}
fn area_type(s: &mut Session) -> u64 {
s.execute("text.create", &json!({"x": 0, "y": 0, "text": "word ".repeat(300), "size": 12, "area": {"width": 400, "height": 400}}))
.unwrap()["id"]
.as_u64()
.unwrap()
}
fn ellipse(s: &mut Session) -> u64 {
s.execute("shape.ellipse", &json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()
}
/// Make with the wrap object and the area type below it selected together wraps the type: the
/// type is the text to wrap, not another wrap object (#3211).
#[test]
fn make_with_the_area_type_selected_wraps_it() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let t = area_type(&mut s);
let plain = lines(&s, t);
let c = ellipse(&mut s);
s.execute("select.set", &json!({"ids": [c, t]})).unwrap();
let r = s.execute("object.textWrap.make", &json!({})).unwrap();
assert_eq!(r, json!({"ids": [c]}), "{r}");
assert!(wrap_of(&s, c).is_some());
assert!(wrap_of(&s, t).is_none(), "the area type became a wrap object");
assert_ne!(lines(&s, t), plain, "the area type did not wrap");
// Make again with the same options changes nothing and records no undo step.
let steps = s.doc().unwrap().history.undo.len();
assert_eq!(s.execute("object.textWrap.make", &json!({})).unwrap(), json!({"ids": [c]}));
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
// Text Wrap Options with both still selected sets the wrap object's options only, and the
// type keeps wrapping; the same options again record no undo step.
let wrapped = lines(&s, t);
assert_eq!(s.execute("object.textWrap.options", &json!({"offset": 30})).unwrap()["offset"], json!(30.0));
assert_eq!(wrap_of(&s, c).map(|w| w.offset), Some(30.0));
assert!(wrap_of(&s, t).is_none(), "Options made the area type a wrap object");
assert_ne!(lines(&s, t), wrapped, "the type did not follow the new offset");
assert_ne!(lines(&s, t), plain);
let steps = s.doc().unwrap().history.undo.len();
s.execute("object.textWrap.options", &json!({"offset": 30})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
s.execute("edit.undo", &json!({})).unwrap();
// One undo takes the wrap off again.
s.execute("edit.undo", &json!({})).unwrap();
assert!(wrap_of(&s, c).is_none());
assert_eq!(lines(&s, t), plain);
}
/// Make with the object below the area type warns that no text wraps. After Bring to Front,
/// Make with both selected wraps the type, and the type that the first Make made a wrap object
/// is the text to wrap again (#3211).
#[test]
fn make_warns_when_the_object_is_below_the_type_and_wraps_after_bring_to_front() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let c = ellipse(&mut s);
let t = area_type(&mut s);
let plain = lines(&s, t);
s.execute("select.set", &json!({"ids": [c, t]})).unwrap();
let r = s.execute("object.textWrap.make", &json!({})).unwrap();
assert_eq!(r["warning"], json!(super::NO_AREA_TYPE_BELOW), "{r}");
assert_eq!(lines(&s, t), plain);
s.execute("select.set", &json!({"ids": [c]})).unwrap();
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [c, t]})).unwrap();
let r = s.execute("object.textWrap.make", &json!({})).unwrap();
assert!(r.get("warning").is_none(), "{r}");
assert!(wrap_of(&s, t).is_none(), "the area type is still a wrap object");
assert_ne!(lines(&s, t), plain, "the area type did not wrap");
}
/// Point type below a wrap object does not wrap, so Make warns.
#[test]
fn make_warns_over_point_type() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
let p = s.execute("text.create", &json!({"x": 0, "y": 100, "text": "point type", "size": 12})).unwrap()["id"].as_u64().unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 80, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [r, p]})).unwrap();
let out = s.execute("object.textWrap.make", &json!({})).unwrap();
assert_eq!(out["warning"], json!(super::NO_AREA_TYPE_BELOW), "{out}");
assert!(wrap_of(&s, r).is_some());
assert!(wrap_of(&s, p).is_none(), "the point type became a wrap object");
}
#[test]
fn text_flows_on_both_sides_of_a_centred_object() {
let mut s = Session::new();
+6 -2
View File
@@ -5,7 +5,9 @@ use super::{NodeId, Value, cmd, find_command};
/// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on
/// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art
/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none.
pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [
pub const ON_ACTIVE_ARTBOARD: [&str; 10] = [
"edit.copy",
"edit.cut",
"edit.pasteInPlace",
"edit.pasteInFront",
"edit.pasteInBack",
@@ -35,7 +37,9 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
/// ([`Session::journal_for_action`]).
const REPLAY_ONLY: [(&str, &str); 35] = [
const REPLAY_ONLY: [(&str, &str); 37] = [
("edit.copy", "artboard"),
("edit.cut", "artboard"),
("file.new", "created"),
("edit.newDocumentFromState", "created"),
("document.save", "modified"),
+34
View File
@@ -203,11 +203,23 @@ pub struct DocState {
/// The selected objects as [`crate::Session::select`] last checked them or the proxies last
/// read them, with the document they were checked in ([`SelectionRecord`]). Not saved.
pub(crate) selection_record: Option<SelectionRecord>,
/// The objects that [`DocState::live_paint_covered_kept`] last found no face or edge of a Live
/// Paint group among, with the document it read. Not saved.
outside_live_paint: std::cell::RefCell<Option<OutsideLivePaint>>,
/// The last move of the selected objects that changed nothing else they show ([`Moved`]).
/// Not saved.
pub moved: Option<Moved>,
}
/// Objects that hold no face or edge of a Live Paint group that counts with its group
/// ([`cmd::live_paint_covered`] is empty for them), with the document they were read in, held as
/// [`EmptyArtboards::doc`] holds it.
#[derive(Clone, Debug)]
struct OutsideLivePaint {
doc: std::sync::Weak<Document>,
ids: Vec<NodeId>,
}
/// A move of whole objects that took document `from` to document `to`: each object the selection
/// shows, the key object and the key anchor included, is the one in `from` moved by `by`, and
/// nothing else they are drawn from changed (no member snapped to the pixel grid, no blend spine
@@ -320,6 +332,8 @@ thread_local! {
pub(crate) static EMPTY_ARTBOARD_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many times [`DocState::any_art_to_fit`] measured a document on this thread.
pub(crate) static ART_TO_FIT_MEASURES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// Tests: how many times [`DocState::live_paint_covered_kept`] read the objects' groups on this thread.
pub(crate) static LIVE_PAINT_COVER_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
@@ -540,6 +554,7 @@ impl DocState {
measured_in_own: None,
inline_resolved: None,
selection_record: None,
outside_live_paint: Default::default(),
moved: None,
}
}
@@ -558,6 +573,25 @@ impl DocState {
pub(crate) fn selection_paints(&self) -> Option<&cmd::SelectionPaints> {
self.selection_record().and_then(|r| r.paints.as_ref())
}
/// The faces and edges of Live Paint groups among `ids` that count with their group
/// ([`cmd::live_paint_covered`]). An empty answer is kept for this version of the document and
/// these objects, so the proxies and the Stroke panel, which ask on every frame, read the
/// objects' groups once after an edit.
pub(crate) fn live_paint_covered_kept(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
let kept = |k: &OutsideLivePaint| std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&self.doc)) && k.ids == ids;
if self.outside_live_paint.try_borrow().is_ok_and(|k| k.as_ref().is_some_and(kept)) {
return std::collections::HashSet::new();
}
#[cfg(test)]
LIVE_PAINT_COVER_READS.with(|c| c.set(c.get() + 1));
let covered = cmd::live_paint_covered(&self.doc, ids);
if covered.is_empty()
&& let Ok(mut k) = self.outside_live_paint.try_borrow_mut()
{
*k = Some(OutsideLivePaint { doc: Arc::downgrade(&self.doc), ids: ids.to_vec() });
}
covered
}
/// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with
/// Lock Guides `guides_locked`. `record` is the record of the selection before, in the same
/// document: the objects that leave the selection are taken out of its paints and the objects
+10
View File
@@ -10,6 +10,9 @@ pub struct Interaction {
pub doc: Arc<Document>,
/// The selection the previews start from (shared, so a preview frame copies nothing).
pub selection: Arc<Selection>,
/// The document's [`crate::DocState::revision`] when the interaction began. The previews change the document's
/// revision, and this value stays the same until the interaction ends.
pub revision: u64,
pub preview: Option<(String, Value)>,
/// The active tool began it (a drag): a command from outside the tool runs as a step of its
/// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an
@@ -52,6 +55,13 @@ pub struct Interaction {
pub keep_on_switch: bool,
}
impl Interaction {
/// The active tool began it (a drag).
pub fn by_tool(&self) -> bool {
self.tool
}
}
/// An interaction that a command from outside the tool set aside while it runs
/// ([`crate::Session::outside_interaction`]).
#[derive(Debug)]
+36
View File
@@ -438,6 +438,12 @@ pub struct Prefs {
/// resetting the preferences keeps them; `tool.setOption` edits them.
#[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub tool_settings: std::collections::BTreeMap<String, serde_json::Map<String, Value>>,
/// The version of [`Self::tool_settings`]: [`TOOL_SETTINGS_VERSION`] once this version stores
/// or updates a tool setting, 0 while none is stored and in preferences saved without one.
/// [`Prefs::migrate_tool_settings`] updates older tool settings once. Not a Preferences dialog
/// field: resetting the preferences keeps it.
#[serde(default, skip_serializing_if = "is_zero")]
pub tool_settings_version: u32,
/// View → Perspective Grid presets: the user's (the built-in ones aren't stored). A local
/// library, not a Preferences dialog field: resetting the preferences keeps it;
/// `perspective.presets.*` edit it.
@@ -464,7 +470,36 @@ pub const KEY_HOLD_DELAY: f64 = 0.35;
/// The range of the Hold Shortcut Delay, in seconds.
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
/// The version of the tool settings these preferences write ([`Prefs::tool_settings_version`]).
/// Version 1 makes Color Swatches the Shape Builder's Pick Color From.
pub const TOOL_SETTINGS_VERSION: u32 = 1;
fn is_zero(v: &u32) -> bool {
*v == 0
}
impl Prefs {
/// Update tool settings saved by an earlier version to [`TOOL_SETTINGS_VERSION`], once. Before
/// version 1, leaving the Shape Builder saved its `pickColorFrom` whether or not it was
/// changed, so a saved `artwork` becomes `swatches`. Without tool settings, nothing changes; a
/// version newer than this one is kept.
pub fn migrate_tool_settings(&mut self) {
if self.tool_settings_version < 1
&& let Some(saved) = self.tool_settings.get_mut("shapeBuilder")
&& saved.get("pickColorFrom").and_then(Value::as_str) == Some("artwork")
{
saved.insert("pickColorFrom".into(), Value::from("swatches"));
}
self.mark_tool_settings_current();
}
/// Record that [`Self::tool_settings`], when any is stored, is in this version's form.
pub(crate) fn mark_tool_settings_current(&mut self) {
if !self.tool_settings.is_empty() {
self.tool_settings_version = self.tool_settings_version.max(TOOL_SETTINGS_VERSION);
}
}
/// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences
/// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own.
pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value {
@@ -672,6 +707,7 @@ impl Default for Prefs {
use_registration_point_for_symbol: false,
show_on_shape_creation: false,
tool_settings: Default::default(),
tool_settings_version: 0,
perspective_presets: vec![],
blend_options: None,
perspective_widget: Default::default(),
+93 -6
View File
@@ -49,6 +49,9 @@
//! `No active document`.
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
//! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at
//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an
//! error. A run that fails leaves the tool as it was.
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
//! in the object.
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
@@ -173,7 +176,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
/// written yet, how many times each path's points went stale and each path as the run last saw its
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
/// hold (the run's heap), and the `Variable` and `Dataset` objects it gave out.
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, and the tool
/// `app.selectTool` chose last.
#[derive(Default)]
pub(super) struct State {
coords: Cell<Coords>,
@@ -208,6 +212,7 @@ pub(super) struct State {
preset_bytes: Cell<u64>,
preset_limit: u64,
vars: variables::Handles,
tool: Cell<Option<&'static str>>,
}
impl State {
@@ -220,6 +225,12 @@ impl State {
pub(super) fn saving(&self) -> bool {
self.saving.get()
}
/// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool
/// when the run ends without an error.
pub(super) fn chosen_tool(&self) -> Option<&'static str> {
self.tool.get()
}
}
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
@@ -845,12 +856,24 @@ fn restore_layer(h: &Host, uid: u64, layer: Option<NodeId>, rows: &[NodeId]) ->
/// commands changed it (commands given ids select them first), direct-selected anchors, segments,
/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic
/// symbol instance or an Objects on Path group included, less the objects that are now deleted,
/// hidden or locked.
/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together
/// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s
/// changes are undone as well.
fn on_doc<T>(
h: &Host,
uid: u64,
keep_selection: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
atomically(h, |h| on_doc_steps(h, uid, keep_selection, f))
}
/// The steps of [`on_doc`].
fn on_doc_steps<T>(
h: &Host,
uid: u64,
keep_selection: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
let (index, active, before, layer, activated) = {
let s = h.session.borrow();
@@ -1029,6 +1052,69 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Bool(open))
}
/// The start of the tool names that scripts pass to `app.selectTool`, as the list at
/// <https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942> gives them.
const TOOL_NAME_PREFIX: &str = "Adobe "; // brand-ok: the start of the tool names scripts pass
/// The names on that list, without [`TOOL_NAME_PREFIX`], whose words differ from the label of the
/// VectorCraft tool they choose, with that tool's id. Names whose words are a VectorCraft tool's
/// label (`Pen Tool`) choose that tool without a row here. The pairs are VectorCraft's own.
const TOOL_NAMES: &[(&str, &str)] = &[
("Select Tool", "selection"),
("Direct Select Tool", "directSelection"),
("Direct Object Select Tool", "groupSelection"),
("Direct Lasso Tool", "lasso"),
("Path Type Tool", "typeOnPath"),
("Vertical Path Type Tool", "verticalTypeOnPath"),
("Line Tool", "lineSegment"),
("Shape Construction Regular Polygon Tool", "polygon"),
("Shape Construction Star Tool", "star"),
("Shape Construction Spiral Tool", "spiral"),
("Brush Tool", "paintbrush"),
("Freehand Tool", "pencil"),
("Freehand Smooth Tool", "smooth"),
("Freehand Erase Tool", "pathEraser"),
("Corner Join Tool", "join"),
("Knife Tool", "knife"),
("New Twirl Tool", "twirl"),
("Cyrstallize Tool", "crystallize"),
("Planar Paintbucket Tool", "livePaintBucket"),
("Planar Face Select Tool", "livePaintSelection"),
("Mesh Editing Tool", "mesh"),
("Gradient Vector Tool", "gradient"),
("Crop Tool", "artboard"),
("Slice Select Tool", "sliceSelection"),
("Scroll Tool", "hand"),
("Page Tool", "printTiling"),
];
/// The id of the tool `name` names: a tool's id (`pen`), its label (`Pen Tool`), or a name of the
/// list [`TOOL_NAME_PREFIX`] cites.
fn tool_named(name: &str) -> Option<&'static str> {
let tools = || vectorcraft_tools::catalog::all_tools();
if let Some(t) = tools().find(|t| t.id == name || t.label == name) {
return Some(t.id);
}
let rest = name.strip_prefix(TOOL_NAME_PREFIX)?;
if let Some((_, id)) = TOOL_NAMES.iter().find(|(n, _)| *n == rest) {
return vectorcraft_tools::tool_info(id).map(|t| t.id);
}
tools().find(|t| t.label == rest).map(|t| t.id)
}
/// `app.selectTool(name)`: chooses the tool `name` names ([`tool_named`]) and gives `true`. The
/// tool becomes the current tool when the run ends without an error, as a choice on the toolbar
/// does; the tool chosen last in a run is the one that counts. A name no tool has throws.
fn app_select_tool(h: &Host, a: &[Data]) -> Answer {
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("selectTool needs a tool name, as a string".into())) };
if name.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the tool name is too long".into()));
}
let id = tool_named(name).ok_or_else(|| HostError::Error(format!("No tool is named \"{name}\"")))?;
h.dom.tool.set(Some(id));
Ok(Data::Bool(true))
}
/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The
/// strings are the ones
/// <https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510>
@@ -2232,9 +2318,9 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
}
// A value the getter reports for the item's opacity sends the opacity it has, and
// `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still
// replaces the one the graph keeps for its series or kind.
// A value the getter reports for the item's opacity runs no command, unless the item is a graph
// mark or label whose graph keeps another opacity for its series or kind: then the opacity the
// item has is sent, and replaces the one the graph keeps.
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
// it would still replace the opacity a graph keeps for the item's series or kind.
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
@@ -2248,7 +2334,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
if now.is_none() || keeps_other {
refuse_protected_edit(h, item)?;
}
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
set_props(h, a, |_| now.is_some() && !keeps_other, json!({"opacity": now.unwrap_or(v)}))
}
/// The members of `BlendModes` with the blend mode each one names.
@@ -2851,6 +2937,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
("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", &[])),
("redo", method(l, app_redo), returns("undefined", &[])),
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
+8
View File
@@ -2647,7 +2647,15 @@ impl Session {
o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count()));
}
close_run(self, host, &mut report, console::Ending::Finished);
let tool = host.dom.chosen_tool();
self.end_job(job, false);
// The tool `app.selectTool` chose last becomes the current tool, as a choice on the
// toolbar makes it; the run's changes are kept when the tool cannot be chosen.
if let Some(id) = tool
&& let Err(e) = self.select_tool(id, self.last_view)
{
report["toolError"] = json!(e.to_string());
}
self.script_report = Some(report.clone());
Ok(report)
}
+1
View File
@@ -545,6 +545,7 @@ impl Session {
effect: None,
doc: st.doc.clone(),
selection: Arc::new(st.selection.clone()),
revision: st.revision,
preview: None,
tool: false,
paint,
+46
View File
@@ -219,6 +219,52 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
Ok(bytes)
}
/// What [`read_capped_plain`] tells a path that is not a plain file.
pub(crate) const NOT_PLAIN: &str = "not a plain file";
/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without
/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and
/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check
/// is refused with [`NOT_PLAIN`] rather than read.
pub(crate) fn read_capped_plain(path: &Path, max: u64) -> Result<Vec<u8>, String> {
let file = open_no_link(path).map_err(|e| match std::fs::symlink_metadata(path) {
Ok(m) if !m.file_type().is_file() || reparse_point(&m) => NOT_PLAIN.to_string(),
_ => e.to_string(),
})?;
let m = file.metadata().map_err(|e| e.to_string())?;
if !m.file_type().is_file() || reparse_point(&m) {
return Err(NOT_PLAIN.to_string());
}
let mut bytes = vec![];
file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?;
if bytes.len() as u64 > max {
return Err(too_large(max));
}
Ok(bytes)
}
/// `path` opened for reading, without following a link there. A pipe put in its place does not hold
/// the open up.
#[cfg(unix)]
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
use std::os::unix::fs::OpenOptionsExt;
let flags = rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK;
std::fs::OpenOptions::new().read(true).custom_flags(flags.bits() as i32).open(path)
}
/// `path` opened for reading; a link or junction there is opened itself, not its target.
#[cfg(windows)]
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
use std::os::windows::fs::OpenOptionsExt;
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path)
}
#[cfg(not(any(unix, windows)))]
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
std::fs::File::open(path)
}
/// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and
/// [`Session::finish_plugin_loads`] install.
pub(crate) enum PluginLoad {
+71
View File
@@ -913,6 +913,77 @@ fn brush_options_rename_duplicate_and_delete_update_strokes() {
assert!(s.execute("brush.delete", &json!({"name": "5 pt. Round"})).is_err());
}
/// `brush.options` that leaves the brush as it is changes neither the document nor its revision,
/// and records no undo step, whether the library is stored or still the defaults.
#[test]
fn brush_options_that_change_nothing_record_no_undo_step() {
let mut s = session();
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.revision, st.history.undo.len())
};
let before = state(&s);
s.execute("brush.options", &json!({"name": "Arrow", "params": {}})).unwrap();
assert_eq!(state(&s), before, "unchanged options of a default library change nothing");
s.execute("brush.options", &json!({"name": "Arrow", "params": {"width": 110.25}})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1, "a changed option is one undo step");
let before = state(&s);
for p in [
json!({"name": "Arrow"}),
json!({"name": "Arrow", "params": {}}),
json!({"name": "Arrow", "params": {"width": 110.25}}),
json!({"name": "Arrow", "newName": " Arrow "}),
json!({"name": "Arrow", "newName": ""}),
] {
assert_eq!(s.execute("brush.options", &p).unwrap()["name"], "Arrow");
assert_eq!(state(&s), before, "{p} changes nothing");
}
s.execute("brush.options", &json!({"name": "Arrow", "newName": "Arrow 2"})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1, "a rename is one undo step");
}
/// `brush.apply` of the brush that the strokes and the current brush already have changes neither
/// the document nor its revision, and records no undo step.
#[test]
fn brush_apply_that_changes_nothing_records_no_undo_step() {
let mut s = session();
let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0);
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.revision, st.history.undo.len())
};
let before = state(&s);
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1);
let before = state(&s);
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap();
assert_eq!(state(&s), before, "applying the brush again changes nothing");
s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap();
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0]})).unwrap();
assert_eq!(undo_steps(&s), before.2 + 1, "making the brush current again is one undo step");
assert_eq!(s.execute("brush.list", &json!({})).unwrap()["current"], "Charcoal");
let b = rect(&mut s, 80.0, 10.0, 50.0, 50.0);
let steps = undo_steps(&s);
s.execute("brush.apply", &json!({"name": "Charcoal", "ids": [a.0, b.0]})).unwrap();
assert_eq!((brush_of(&s, a).as_deref(), brush_of(&s, b).as_deref()), (Some("Charcoal"), Some("Charcoal")));
assert_eq!(undo_steps(&s), steps + 1, "a new stroke to paint is one undo step");
}
/// Applying the current brush again to a stroke with settings of its own clears them as one undo step.
#[test]
fn brush_apply_clears_object_options_as_one_undo_step() {
let mut s = session();
let a = line(&mut s);
select(&mut s, &[a]);
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
s.execute("brush.objectOptions", &json!({"params": {"width": 50}})).unwrap();
assert_eq!(own_options(&s, a), json!({"width": 50.0}));
let steps = undo_steps(&s);
s.execute("brush.apply", &json!({"name": "Arrow"})).unwrap();
assert_eq!(own_options(&s, a), json!({}), "applying the brush clears the stroke's own settings");
assert_eq!(undo_steps(&s), steps + 1, "clearing the settings is one undo step");
}
/// A document whose brushes repeat a name opens with the later brush numbered: strokes of the name
/// keep the first brush, and renaming or deleting one brush leaves the other and its strokes alone.
#[test]
+29 -1
View File
@@ -1753,7 +1753,8 @@ fn shape_builder_swatches_keep_the_current_fill_and_the_first_covered_objects_lo
}
/// The Shape Builder tool sends the point where the drag started first and the point where it
/// ended last, so a drag from the hole into the square takes the square's look.
/// ended last, so with Pick Color From Artwork a drag from the hole into the square takes the
/// square's look.
#[test]
fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() {
let mut s = session();
@@ -1762,6 +1763,7 @@ fn shape_builder_tool_drag_from_the_hole_takes_the_look_where_it_ends() {
select_ids(&mut s, &bars.iter().copied().chain([red]).collect::<Vec<_>>());
let v = ViewInfo::default();
s.select_tool("shapeBuilder", v).unwrap();
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 85.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 120.0, 50.0), v).unwrap();
@@ -1853,6 +1855,7 @@ fn shape_builder_arrow_keys_step_the_current_fill_through_the_swatches() {
let v = ViewInfo::default();
s.select_tool("shapeBuilder", v).unwrap();
let chips = |s: &mut Session| s.overlays(v).iter().filter(|o| matches!(o, vectorcraft_tools::Overlay::Swatch { .. })).count();
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "artwork"}})).unwrap();
assert!(!s.tool_claims_key(ToolKey::Right, v), "Artwork leaves the arrows to nudging");
let values = json!({"pickColorFrom": "swatches", "cursorSwatchPreview": true});
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": values})).unwrap();
@@ -2071,6 +2074,31 @@ fn shape_builder_fill_preview_is_put_back_by_a_cancel() {
assert_eq!(s.paint.fill, before, "the cancel puts the fill back");
}
/// With the Shape Builder's default options, a fill picked while it is active (a swatch or a
/// color) fills the next merge: the tool sends `pickColorFrom: "swatches"`, and the merged shape
/// is not the red or blue of the art.
#[test]
fn shape_builder_default_merge_fills_with_the_picked_fill() {
let v = ViewInfo::default();
for pick in [json!({"swatch": "Leaf"}), json!({"color": "#ff8800"})] {
let mut s = session();
two(&mut s);
s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap();
s.select_tool("shapeBuilder", v).unwrap();
s.execute("paint.setFill", &pick).unwrap();
let picked = s.paint.fill.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 75.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 125.0, 50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 125.0, 50.0), v).unwrap();
let (cmd, params) = s.journal.last().unwrap().clone();
assert_eq!((cmd.as_str(), &params["pickColorFrom"]), ("shapeBuilder.merge", &json!("swatches")), "{pick}");
let d = &s.doc().unwrap().doc;
let fills: Vec<Paint> = d.children(d.default_layer()).into_iter().flatten().map(|n| n.appearance.fill_paint()).collect();
assert_eq!(fills, vec![picked], "{pick}: the two squares merged into one shape with the picked fill");
}
}
/// With Pick Color From Color Swatches, a merge fills with the fill chosen while the Shape Builder
/// is active, and the Gradient panel's eyedropper samples into a stop of that fill's gradient.
#[test]
+18
View File
@@ -253,6 +253,24 @@ fn transform_each_with_copy_of_50000_objects_takes_few_tree_walks() {
undo_gives_back(&mut s, &before);
}
/// A move of 10,000 selected objects walks the tree once for the paint order and the top-level
/// objects, once for Transform Patterns and the edit, and once for the selection's check after the
/// edit. It reads each object's compound path at the object's place, so the only lookups by id are
/// the range check's, one per object.
#[test]
fn moving_10000_selected_objects_walks_the_tree_three_times() {
let n = 10_000;
let mut s = session(n, square);
let ids = layer(&s, 0);
let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups());
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
let (walks, lookups) = (vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups);
assert_eq!(walks, 3, "walked the tree {walks} times");
assert!(lookups <= n as u64, "{lookups} lookups by id for {n} objects");
assert_eq!(bounds(&s, ids[n - 1]), square_at(n - 1) + vectorcraft_geom::Vec2::new(3.0, 0.0));
assert!(selected(&s, &ids));
}
#[test]
fn offset_path_of_50000_objects_takes_few_tree_walks() {
let s = session(50_000, square);
+62
View File
@@ -155,6 +155,27 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() {
assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was");
}
/// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the
/// visible bounds.
#[test]
fn control_bounds_hold_the_handles_of_a_curve() {
let (mut s, _, _) = doc();
s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap();
let out = log(
&mut s,
"var p = app.activeDocument.pageItems, c = p[0], r = p[1];\
function h(b) { return b[1] - b[3]; }\
vc.log([h(c.visibleBounds), h(c.controlBounds), c.controlBounds[0] <= c.visibleBounds[0]]);\
vc.log(String(r.controlBounds) === String(r.visibleBounds));",
);
let heights = out[0].as_array().unwrap();
let (visible, control) = (heights[0].as_f64().unwrap(), heights[1].as_f64().unwrap());
// The curve rises 75 pt and its handles 100 pt; half the stroke's weight reaches above the curve.
assert!(control - visible > 20.0 && control - visible <= 25.0 + 1e-6, "{out:?}");
assert_eq!(heights[2], json!(true), "{out:?}");
assert_eq!(out[1], json!(true), "{out:?}");
}
#[test]
fn convert_coordinate_pair_is_inverse_and_y_up() {
let mut s = Session::new();
@@ -500,6 +521,7 @@ fn assigning_the_reported_opacity_changes_nothing() {
assert_eq!(out, vec![json!(33.3333)]);
assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before);
assert_eq!(undo_steps(&s), steps);
assert_eq!(s.script_report().unwrap()["slowestCommands"], json!([]), "the assignment runs no command");
// A value close to the reported one but not equal to it is still applied.
s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap();
let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s));
@@ -560,6 +582,14 @@ fn selection_assignment_is_atomic_across_invalid_items() {
let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];");
assert!(e.contains("Cannot select PathItem"), "{e}");
assert!(s.active().unwrap().selection.objects.is_empty());
// With the valid item first and the error caught, the run sees the selection unchanged.
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems; try { d.selection = [p[1], p[0]]; vc.log('assigned'); }\
catch (e) { vc.log(String(e).indexOf('Cannot select PathItem') >= 0); } vc.log(d.selection.length);",
);
assert_eq!(out, vec![json!(true), json!(0)]);
assert!(s.active().unwrap().selection.objects.is_empty());
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
let out = log(
&mut s,
@@ -2132,6 +2162,35 @@ fn prototype_changes_cannot_forge_a_page_item() {
assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None);
}
#[test]
fn select_tool_makes_the_named_tool_current_when_the_run_ends() {
let (mut s, _, _) = doc();
assert_eq!(s.tool_id(), "selection");
// A tool's id, its label and a name in the form scripts pass all choose it; the last one counts.
assert_eq!(log(&mut s, "vc.log(app.selectTool('pen'));"), vec![json!(true)]);
assert_eq!(s.tool_id(), "pen");
log(&mut s, "app.selectTool('Rectangle Tool');");
assert_eq!(s.tool_id(), "rectangle");
log(&mut s, "app.selectTool('Adobe Ellipse Tool'); app.selectTool('Adobe Direct Select Tool');");
assert_eq!(s.tool_id(), "directSelection");
log(&mut s, "app.selectTool('Adobe Select Tool');");
assert_eq!(s.tool_id(), "selection");
// An unknown name throws, a caught error chooses nothing, and a run that fails leaves the tool.
assert!(failure(&mut s, "app.selectTool('No Such Tool');").contains("No tool is named \"No Such Tool\""));
assert!(failure(&mut s, "app.selectTool('Adobe ');").contains("No tool is named"));
let out = log(&mut s, "try { app.selectTool('pencil tool'); } catch (e) { vc.log(e.message); }");
assert_eq!(out, vec![json!("No tool is named \"pencil tool\"")]);
assert!(failure(&mut s, "app.selectTool('pen'); throw new Error('stop');").contains("stop"));
let out = log(&mut s, "try { app.selectTool(5); } catch (e) { vc.log(e.name); }");
assert_eq!(out, vec![json!("TypeError")]);
assert!(failure(&mut s, "app.selectTool(new Array(5000).join('a'));").contains("too long"));
assert_eq!(s.tool_id(), "selection");
// With no document open the tool is chosen too.
let mut empty = Session::new();
log(&mut empty, "app.selectTool('Adobe Freehand Tool');");
assert_eq!(empty.tool_id(), "pencil");
}
#[test]
fn unsupported_members_say_so() {
let (mut s, _, _) = doc();
@@ -2356,6 +2415,9 @@ fn a_collection_read_with_a_name_gives_the_named_object() {
vc.log(m);",
);
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]);
// A name the collection inherits is not looked up as an object's name when it is assigned.
let out = log(&mut s, "Object.prototype.tag = 1; var p = app.activeDocument.pageItems; p.tag = 2; vc.log(p.tag);");
assert_eq!(out, vec![json!(1)]);
}
/// A collection read with a name that is the text of a number but not an array index, such as `-1`
+1 -1
View File
@@ -235,7 +235,7 @@ fn shift_click_direct_selection_and_hover_on_a_drop_shadow_pass_through_it() {
run(&mut s, "select.set", json!({"ids": [a.0]}));
let v = ViewInfo::default();
s.select_tool("selection", v).unwrap();
assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::Move);
assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::SelectionMove);
assert_eq!(s.cursor(Point::new(110.0, 50.0), Mods::default(), v), Cursor::Arrow);
assert_eq!(s.cursor(Point::new(92.0, 50.0), Mods::default(), v), Cursor::Arrow);
}
+18
View File
@@ -157,6 +157,24 @@ fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() {
assert!(holds(&[][..], &[]));
}
#[cfg(unix)]
#[test]
fn a_plain_capped_read_refuses_a_link_and_reads_a_plain_file() {
use crate::store::{NOT_PLAIN, read_capped_plain};
let root = fresh_dir("plain-read");
let target = root.join("target.bin");
std::fs::write(&target, b"outside").unwrap();
let link = root.join("profile.vectorcraft");
std::os::unix::fs::symlink(&target, &link).unwrap();
assert_eq!(read_capped_plain(&link, 100), Err(NOT_PLAIN.to_string()));
let folder = root.join("folder");
std::fs::create_dir(&folder).unwrap();
assert_eq!(read_capped_plain(&folder, 100), Err(NOT_PLAIN.to_string()));
assert_eq!(read_capped_plain(&target, 100), Ok(b"outside".to_vec()));
assert_eq!(read_capped_plain(&target, 7), Ok(b"outside".to_vec()));
assert!(read_capped_plain(&target, 6).is_err());
}
#[test]
fn a_saved_preset_replaces_an_oversized_file_in_its_place() {
let root = fresh_dir("oversized-put");
+52
View File
@@ -698,3 +698,55 @@ fn a_parametric_shape_kind_and_its_values_set_together() {
assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing");
}
}
/// The Shape Builder picks colors from the color swatches by default: a fresh session, and saved
/// preferences that hold other Shape Builder options but no `pickColorFrom`, give `swatches`.
/// Preferences saved without `toolSettingsVersion` read a saved `artwork` as `swatches` once and
/// are then written with the version, so a later `artwork` is kept. A saved `swatches` is kept.
#[test]
fn shape_builder_pick_color_from_defaults_to_swatches_and_migrates_a_saved_artwork_once() {
let mut s = session();
select(&mut s, "shapeBuilder");
assert_eq!(s.tool_options()["pickColorFrom"], json!("swatches"), "a fresh session");
select(&mut s, "selection");
assert_eq!(s.prefs.to_json()["toolSettingsVersion"], json!(1), "stored settings are written with the version");
let load = |version: Option<u32>, saved: &Value| {
let mut prefs = Prefs::default().to_json();
prefs["toolSettings"] = json!({ "shapeBuilder": saved });
let fields = prefs.as_object_mut().unwrap();
match version {
Some(v) => fields.insert("toolSettingsVersion".into(), json!(v)),
None => fields.remove("toolSettingsVersion"),
};
let mut next = session();
next.apply_prefs(serde_json::from_str(&prefs.to_string()).unwrap());
next
};
for (version, saved, want) in [
(None, json!({"highlightFill": false}), "swatches"),
(None, json!({"pickColorFrom": "artwork"}), "swatches"),
(None, json!({"pickColorFrom": "swatches"}), "swatches"),
(Some(1), json!({"pickColorFrom": "artwork"}), "artwork"),
(Some(1), json!({"pickColorFrom": "swatches"}), "swatches"),
(Some(1), json!({"highlightFill": false}), "swatches"),
] {
let mut next = load(version, &saved);
assert_eq!(next.prefs.tool_settings_version, 1, "the version is written: {version:?} {saved}");
select(&mut next, "shapeBuilder");
assert_eq!(next.tool_options()["pickColorFrom"], json!(want), "saved {version:?} {saved}");
select(&mut next, "selection");
assert_eq!(next.prefs.tool_settings["shapeBuilder"]["pickColorFrom"], json!(want), "stored again: {version:?} {saved}");
}
// Artwork picked after the update, or in a session that started without saved settings, is
// kept at the next launch.
for mut next in [load(None, &json!({"pickColorFrom": "artwork"})), session()] {
select(&mut next, "shapeBuilder");
next.set_tool_option("pickColorFrom", &json!("artwork"));
select(&mut next, "selection");
let saved_text = serde_json::to_string(&next.prefs).unwrap();
let mut later = session();
later.apply_prefs(serde_json::from_str(&saved_text).unwrap());
select(&mut later, "shapeBuilder");
assert_eq!(later.tool_options()["pickColorFrom"], json!("artwork"), "picked after the update: {saved_text}");
}
}
+1
View File
@@ -581,6 +581,7 @@ impl Session {
}
}
}
prefs.mark_tool_settings_current();
}
/// Keep the active tool's persistent options for the next time it, or a tool sharing them, is
@@ -91,8 +91,8 @@ const INSIDE: &[(&str, &str)] = &[
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= showColorPicker textFonts \
toString typename undo unloadAction unloadAction=",
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= selectTool showColorPicker \
textFonts toString typename undo unloadAction unloadAction=",
),
("DocumentPreset.", "prototype"),
(
+54 -8
View File
@@ -338,32 +338,78 @@ fn made_content(infos: &[SlotInfo], made: Vec<Option<Made>>, laid: bool) -> Vec<
/// it, as far as strokes round type reach) as type the page draws. How many of the page's text
/// objects no made type takes, shown or not: none that holds a piece of the object has its words
/// ([`spelling`]). Past `MAX_PAIRS` comparisons nothing is marked or counted (`None`).
///
/// The page can draw two text objects as one word: a word and a letter set apart from it (a swash
/// "h" after "Spirit") come out of the page as one piece, "Spirith", that neither spells. A word
/// left that is the last word of one text object holding the piece joined to the first word of
/// another that holds it and draws after it, along the first one's lines, is theirs
/// ([`joined_by_two`]).
fn see_page_type(content: &mut [Content], shown: &[Vec<Arc<Node>>]) -> Option<usize> {
let texts = |o: &[Arc<Node>]| o.iter().filter_map(|n| if let NodeKind::Text(_) = &n.kind { Some(n.clone()) } else { None }).collect::<Vec<_>>();
// Each object's pieces of type, and the words of them that no made type holding it has yet.
let mut objects: Vec<(Vec<Rect>, Vec<String>, bool)> =
shown.iter().map(|o| (texts(o).iter().filter_map(|n| n.visual_bounds()).collect(), object_words(o), false)).collect();
let pieces: usize = objects.iter().map(|o| o.0.len()).sum();
if content.len().saturating_mul(pieces) > MAX_PAIRS {
return None;
}
let mut budget = MAX_PAIRS.checked_sub(content.len().checked_mul(pieces)?)?;
let holds = |drawn: Rect, r: &Rect| drawn.inflate(OUTLINE_REACH, OUTLINE_REACH).intersect(*r).area() >= 0.5 * r.area().max(1e-9);
for c in content {
let Content::Made(node, region, seen) = c else { continue };
// The made type holding each object, in order: where it draws and its words.
let mut holders: Vec<Vec<Arc<Holder>>> = vec![vec![]; objects.len()];
let mut seen_slots = Vec::new();
for (slot, c) in content.iter().enumerate() {
let Content::Made(node, region, _) = c else { continue };
// Hidden made type has no region: where it draws, shown, is its own box.
let Some(drawn) = region.or_else(|| node.visual_bounds()) else { continue };
let spelled = if let NodeKind::Text(t) = &node.kind { spelling(&t.plain_text()) } else { String::new() };
for (rects, words, held) in &mut objects {
let (spelled, holder) = match &node.kind {
NodeKind::Text(t) => {
let text = t.plain_text();
let [a, b, ..] = t.xf.as_coeffs();
(spelling(&text), Some(Arc::new((drawn.center(), (a, b), word_pieces(&text).map(spelling).filter(|w| !w.is_empty()).collect()))))
}
_ => (String::new(), None),
};
for ((rects, words, held), by) in objects.iter_mut().zip(&mut holders) {
if rects.iter().any(|r| holds(drawn, r)) {
*held = true;
*seen |= region.is_some();
if region.is_some() && seen_slots.last() != Some(&slot) {
seen_slots.push(slot);
}
words.retain(|w| !spelled.contains(w.as_str()));
by.extend(holder.clone());
}
}
}
for ((_, words, _), by) in objects.iter_mut().zip(&holders) {
if !words.is_empty() && !by.is_empty() {
// Each unmatched word can visit every ordered pair of holders, plus the first-holder scan.
budget = budget.checked_sub(words.len().checked_mul(by.len())?.checked_mul(by.len().checked_add(1)?)?)?;
words.retain(|w| !joined_by_two(w, by));
}
}
for slot in seen_slots {
if let Content::Made(_, _, seen) = &mut content[slot] {
*seen = true;
}
}
Some(objects.iter().filter(|(_, words, held)| !held || !words.is_empty()).count())
}
/// A made text object that holds a piece of the page's type: the centre of where it draws, the
/// way its lines run (the first column of its transform) and its words ([`spelling`]).
type Holder = (Point, (f64, f64), Vec<String>);
/// Is `word` (a [`spelling`]) the last word of one of `by` joined to the first word of another of
/// them that draws after it, along the first one's lines? Each part is a whole word of its text
/// object, so a piece is never made up of bits of words.
fn joined_by_two(word: &str, by: &[Arc<Holder>]) -> bool {
by.iter().map(Arc::as_ref).any(|(at, (a, b), first)| {
let Some(head) = first.last().filter(|h| word.len() > h.len() && word.starts_with(h.as_str())) else { return false };
let tail = &word[head.len()..];
by.iter()
.map(Arc::as_ref)
.any(|(next, _, second)| (next.x - at.x) * a + (next.y - at.y) * b > 0.0 && second.first().is_some_and(|w| w == tail))
})
}
/// What goes into each of `infos`' slots when the file's text document can't make the type of every
/// slot that shows: type made from the text document (`made`) where it can, else the page's type that
/// the text document puts where the page has it, else the page's type in a copy that a layer's or
+32
View File
@@ -8663,3 +8663,35 @@ fn trusted_editing_data_keeps_an_artboard_taller_than_its_pdf_page() {
let (_, w, read) = crate::layered_ai(&private(&art), Document::new(12000.0, 14400.0), vec![], false, true, 1.0);
assert!(!read, "the uncapped dimension must still match: {w:?}");
}
/// The page's "2014" drawn as one piece 20 points across the art, and two text objects "20" and
/// "14" anchored at `twenty` and `fourteen`, set in the bundled Source Sans 3 at 14 points (a digit
/// 6.958 points wide) so that where they draw doesn't hang on the fonts installed.
fn word_of_two_text_objects(fourteen: f64, twenty: f64) -> crate::import::Imported {
let stories = [("20\r", 0, (twenty, 8180.0), (0.0, 0.0), 0.0), ("14\r", 0, (fourteen, 8180.0), (0.0, 0.0), 0.0)];
let doc = text_document(&stories).replacen("/0 (Helvetica)", "/0 (SourceSans3-Regular)", 1);
let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc);
let page = "0 1 0 0 setcmykcolor /SourceSans3-Regular findfont 14 scalefont setfont 20 61.5 moveto (2014) show";
import(&eps(page, &art)).unwrap()
}
/// The page can draw two text objects as one word: "20" and "14" set one after the other come out
/// of the page as one piece, "2014", that neither spells. The word is the last word of the one
/// joined to the first word of the one after it, so the page's type is theirs and nothing is noted
/// as left out.
#[test]
fn a_word_the_page_draws_from_two_text_objects_in_a_row_is_their_type() {
let r = word_of_two_text_objects(8161.5 + 13.916, 8161.5);
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
let texts: Vec<String> = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect();
assert_eq!(texts, ["20", "14"], "{:?}", r.warnings);
assert!(!r.warnings.iter().any(|w| crate::is_loss(w)), "{:?}", r.warnings);
}
/// The two text objects the other way round ("14" before "20") don't make the page's "2014": its
/// word keeps the loss note.
#[test]
fn two_text_objects_the_other_way_round_arent_the_word_the_page_draws() {
let r = word_of_two_text_objects(8161.5, 8161.5 + 13.916);
assert!(r.warnings.iter().any(|w| w.contains("some of the page's type has no text object in the layers")), "{:?}", r.warnings);
}
+20
View File
@@ -966,6 +966,26 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() {
);
}
#[test]
fn an_unavailable_member_hides_the_member_its_parent_class_has() {
let mut r = realm(1_000_000);
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into())));
let class = |name: &str, parent: Option<&str>, member: HostMember| HostClass {
name: name.into(),
parent: parent.map(Into::into),
members: vec![("size".to_string(), member)],
info: Vec::new(),
index: None,
construct: None,
};
let classes = vec![class("Base", None, HostMember::Get(value)), class("Leaf", Some("Base"), HostMember::Unavailable(missing))];
let objects = vec![("it".into(), host_ref("Leaf", &[1.0])), ("base".into(), host_ref("Base", &[2.0]))];
r.define_host_classes(classes, objects).unwrap();
r.start("[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), base.hasOwnProperty('size')].join()").unwrap();
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into()));
}
#[test]
fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it() {
let mut r = realm(1_000_000);
+1 -1
View File
@@ -514,7 +514,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"text_wrap",
"Text wrap",
"Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.",
"Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). A type object in `ids` below another of them is the text to wrap, not a wrap object. A `warning` says when no area type lies below them. `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.",
obj(
json!({
"ids": {"type": "array", "items": {"type": "integer"}},
+1 -1
View File
@@ -1192,7 +1192,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"tool.options",
"Tool Options…",
"",
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `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 `command` running type.pathOptions; 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 sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, Line truncated
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `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 `command` running type.pathOptions; 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 sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, Line truncated
),
(
"ui.colorGuideOptions",
+1 -1
View File
@@ -202,7 +202,7 @@ features! {
ScriptuiDrawing "scriptui.drawing" Dialogs,
ScriptuiPalette "scriptui.palette" HostOnly,
ScriptuiWindow "scriptui.window" Dialogs,
SelectTool "selectTool" HostOnly,
SelectTool "selectTool" Dom,
Socket "socket" HostOnly,
UnitValue "unitValue" Language,
Xml "xml" Language,
+1 -1
View File
@@ -1596,7 +1596,7 @@ fn declarations_past_a_limit_hold_from_where_they_stand() {
fn application_methods_are_features_not_members() {
let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n");
assert!(r.members.is_empty(), "{:?}", r.members);
assert_eq!(r.needs, [Need::MenuCommands, Need::HostOnly]);
assert_eq!(r.needs, [Need::Dom, Need::MenuCommands]);
}
#[test]
+4 -3
View File
@@ -66,11 +66,12 @@ pub struct ShapeBuilderOptions {
/// region as if an invisible edge closed it. When it is off, the path cuts the regions it crosses
/// as a line does.
pub open_filled_as_closed: bool,
/// Pick Color From Color Swatches (`pickColorFrom: "swatches"`; off: `"artwork"`): a merge
/// Pick Color From Color Swatches (`pickColorFrom: "swatches"`, on; off: `"artwork"`): a merge
/// fills the new shape with the current fill, and the Left and Right arrow keys step the current
/// fill through the document's color swatches. With Artwork, the shape takes the look of the
/// object where the drag starts, else of the one where it ends, else of the front-most selected
/// object.
/// object. A saved `pickColorFrom` is kept, except that preferences saved by an earlier version
/// read a saved Artwork as Color Swatches once; preferences without one take Color Swatches.
pub swatches: bool,
/// Cursor Swatch Preview (`cursorSwatchPreview`, off): with Color Swatches, the current fill
/// and the swatches before and after it show as chips above the pointer while no drag is on.
@@ -105,7 +106,7 @@ impl Default for ShapeBuilderOptions {
fn default() -> Self {
Self {
open_filled_as_closed: true,
swatches: false,
swatches: true,
cursor_swatch_preview: false,
straight_line: false,
highlight_fill: true,
+2
View File
@@ -17,6 +17,8 @@ pub enum Cursor {
GroupSelection,
/// Alt-dragging a copy with the Selection or Direct Selection tool: a double arrowhead.
SelectionCopy,
/// The Selection arrow over movable artwork.
SelectionMove,
Move,
Crosshair,
ResizeH,
+10 -1
View File
@@ -129,11 +129,20 @@ shown_when = [
hotspot = "The arrow's tip."
look = "Arrow with a small x badge (nothing to select)."
[[cursor]]
id = "SelectionMove"
group = "Selection"
shown_when = [
"The Selection tool over a selected object or its movable source artwork, or over its visible centre point without Cmd/Ctrl held.",
"The Selection tool over artwork while Alt is held, before the copy drag begins.",
]
hotspot = "The arrow's tip."
look = "The Selection arrow with a small move badge."
[[cursor]]
id = "Move"
group = "Selection"
shown_when = [
"The Selection tool over a selected object, or over any object with Alt held (once an Alt-drag starts, SelectionCopy shows).",
"The shape tools over a selected object's centre point (Attributes › Show Center), before a press there moves it (while the drag runs the arrow is plain, SelectionCopy with Alt, ArrowHollow while it snaps).",
"Reshape over a path or while dragging.",
"Inside the Free Transform and Crop Image boxes.",
+46 -2
View File
@@ -136,7 +136,9 @@ fn neighbours(sp: &SubPath, i: usize) -> [Option<usize>; 2] {
/// Move anchor `i` of `sp` to `q` as the Curvature tool drags a point: only the two segments at it
/// change. A smooth anchor takes the Curvature tool's own handles ([`smooth_handles`]: along the
/// circle through it and its neighbours; at an end of an open path the one [`end_handle`] into the
/// curve). The neighbours' handles on those segments, and a corner's own
/// curve), each no longer than [`fit_to_tangent`] allows against the neighbor's handle on its
/// segment, so a point dragged far out narrows toward it instead of swinging wide around that
/// circle (#6192). The neighbors' handles on those segments, and a corner's own
/// handles, keep their directions, their lengths scaling with their segment's chord, so the
/// segments beyond don't move and a corner without handles keeps none.
///
@@ -163,7 +165,7 @@ pub fn curvature_move(sp: &mut SubPath, i: usize, q: Point) -> bool {
match ends {
[Some(prev), Some(next)] => {
if let Some((h_in, h_out)) = smooth_handles(prev.p, q, next.p) {
(m.h_in, m.h_out) = (h_in, h_out);
(m.h_in, m.h_out) = (fit_to_tangent(q, h_in, prev.p, prev.h_out), fit_to_tangent(q, h_out, next.p, next.h_in));
}
}
// An end of an open path has one segment: its handle only, and a corner like the
@@ -179,6 +181,48 @@ pub fn curvature_move(sp: &mut SubPath, i: usize, q: Point) -> bool {
true
}
/// cos 75°: [`fit_to_tangent`] shortens a handle in full up to a turn of 150°, and less toward a
/// half turn.
const FADE_HALF_TURN: f64 = 0.258_819_045_102_520_8;
/// Handle `h` of the point `q` on its segment to `b`, whose handle there is `hb`, shortened toward
/// the handle of the circular arc tangent to both handle lines: `2/3 · (1 − tan²(θ/4))` of `q`'s
/// distance `r` to where the lines meet, `θ` the turn between them. A longer handle swings the
/// segment out past `b`'s tangent line. The shortening applies in full while the lines meet at
/// least half the chord ahead of `b` and the turn is at most 150°, and fades to none as the meeting
/// point comes back to `b` or the turn nears a half turn, so the handle changes continuously as `q`
/// moves. Where `b` is on the circle [`smooth_handles`]
/// follows, the arc is the circle's and `h` is unchanged; `h` is also unchanged when `b` has no
/// handle there or the lines are parallel.
fn fit_to_tangent(q: Point, h: Point, b: Point, hb: Point) -> Point {
let (d, t) = (h - q, hb - b);
let (ld, lt) = (d.hypot(), t.hypot());
let w = b - q;
let chord = w.hypot();
if !(ld > 1e-9 && lt > 1e-9 && chord > 1e-9) {
return h;
}
let (d, t) = (d / ld, t / lt);
let den = d.cross(t);
if den.abs() <= 1e-12 {
return h;
}
// q + r·d = b + s·t.
let (r, s) = (w.cross(t) / den, w.cross(d) / den);
// The curve leaves `b` along `t` and comes into `q` along −d.
let cos_half = ((1.0 - t.dot(d)) / 2.0).clamp(0.0, 1.0).sqrt();
// A circular arc under a half turn meets its tangents at least half its chord out. Toward a
// half turn the lines meet ever further away, on one side or the other, and the shortening
// fades out.
let weight = (2.0 * s / chord).clamp(0.0, 1.0) * (cos_half / FADE_HALF_TURN).min(1.0);
let tan2 = (1.0 - cos_half) / (1.0 + cos_half);
let cap = 2.0 / 3.0 * (1.0 - tan2) * r.abs();
if !(weight > 0.0 && cap.is_finite() && ld > cap) {
return h;
}
q + d * (ld + (cap - ld) * weight)
}
/// Add a smooth anchor at `t` on segment `seg` of `sp` without changing its shape: the new anchor's
/// index. On a straight segment its handles lie along it, each a third of its own part of the
/// segment ([`curvature_smooth`]: a line is a circle's limit), so a drag bends the line evenly; a drag then moves it as a
+92
View File
@@ -139,6 +139,98 @@ fn moving_a_corner_without_handles_keeps_its_sides_straight() {
assert_eq!(sp.anchors[0], Anchor::corner(pt(80.0, 70.0)));
}
/// A circle's top point dragged far up stretches it into a shape that narrows from its sides
/// toward the point (#6192), instead of swinging out wider than the circle first. The moved point
/// stays smooth, and its segments meet the neighbors' unchanged tangents.
#[test]
fn stretching_a_circle_narrows_toward_the_dragged_point() {
let k = 100.0 * 0.552_284_749_830_793_4;
let circle = SubPath::new(
vec![
Anchor::with_handles(pt(0.0, -100.0), pt(-k, -100.0), pt(k, -100.0)),
Anchor::with_handles(pt(100.0, 0.0), pt(100.0, -k), pt(100.0, k)),
Anchor::with_handles(pt(0.0, 100.0), pt(k, 100.0), pt(-k, 100.0)),
Anchor::with_handles(pt(-100.0, 0.0), pt(-100.0, k), pt(-100.0, -k)),
],
true,
);
// On the circle, the neighbors' tangents match it, and the point keeps the circle's handles.
let mut near = circle.clone();
assert!(curvature_move(&mut near, 0, pt(0.0, -100.0)));
for (a, b) in near.anchors.iter().zip(&circle.anchors) {
assert!(a.h_in.distance(b.h_in) < 1e-6 && a.h_out.distance(b.h_out) < 1e-6, "{a:?} != {b:?}");
}
for top in [-150.0, -250.0, -400.0, -800.0] {
let mut sp = circle.clone();
assert!(curvature_move(&mut sp, 0, pt(0.0, top)));
let a = sp.anchors[0];
assert_eq!(a.kind, AnchorKind::Smooth);
assert!(collinear(a.h_in - a.p, a.h_out - a.p) && (a.h_in - a.p).dot(a.h_out - a.p) < 0.0);
// Segment 0 runs from the top to the right point, segment 3 from the left point to the top.
for (seg, side) in [(0, 1.0), (3, -1.0)] {
let c = sp.segment(seg);
let mut last: Option<f64> = None;
for j in 0..=200 {
let t = j as f64 / 200.0;
let p = c.eval(if side > 0.0 { t } else { 1.0 - t });
assert!(p.x.abs() <= 100.0 + 1e-9, "top {top}: segment {seg} swings out to x = {}", p.x);
// From the top down to the side the width only grows.
if let Some(l) = last {
assert!(p.x.abs() >= l - 1e-9, "top {top}: segment {seg} narrows again at t = {t}");
}
last = Some(p.x.abs());
}
}
}
}
/// The moved point's handles change continuously while it crosses a neighbor's tangent line, while
/// the line its own handle runs along passes through the neighbor, and while the two lines turn
/// parallel.
#[test]
fn a_moved_point_s_handles_change_continuously() {
let handles = |sp: &SubPath, q: Point| -> (Vec2, Vec2) {
let mut sp = sp.clone();
assert!(curvature_move(&mut sp, 1, q));
(sp.anchors[1].h_in - q, sp.anchors[1].h_out - q)
};
let near = |a: (Vec2, Vec2), b: (Vec2, Vec2)| (a.0 - b.0).hypot() < 0.05 && (a.1 - b.1).hypot() < 0.05;
// The neighbor's handle points away from the moved point: its line passes through it at y = 0.
let away = SubPath::new(
vec![
Anchor::corner(pt(-100.0, 0.0)),
Anchor::with_handles(pt(0.0, -20.0), pt(-30.0, -20.0), pt(30.0, -20.0)),
Anchor::with_handles(pt(100.0, 0.0), pt(200.0, 10.0), pt(0.0, -10.0)),
],
false,
);
assert!(near(handles(&away, pt(0.0, -0.001)), handles(&away, pt(0.0, 0.001))));
// The neighbor's handle runs the same way as the moved point's: their lines are parallel at x = 0.
let parallel = SubPath::new(
vec![
Anchor::corner(pt(-100.0, 0.0)),
Anchor::with_handles(pt(0.0, -50.0), pt(-30.0, -50.0), pt(30.0, -50.0)),
Anchor::with_handles(pt(100.0, 0.0), pt(150.0, 0.0), pt(50.0, 0.0)),
],
false,
);
assert!(near(handles(&parallel, pt(-0.001, -50.0)), handles(&parallel, pt(0.001, -50.0))));
// A circle's top dragged across the right point's tangent line, x = 100.
let k = 100.0 * 0.552_284_749_830_793_4;
let circle = SubPath::new(
vec![
Anchor::with_handles(pt(-100.0, 0.0), pt(-100.0, k), pt(-100.0, -k)),
Anchor::with_handles(pt(0.0, -100.0), pt(-k, -100.0), pt(k, -100.0)),
Anchor::with_handles(pt(100.0, 0.0), pt(100.0, -k), pt(100.0, k)),
Anchor::with_handles(pt(0.0, 100.0), pt(k, 100.0), pt(-k, 100.0)),
],
true,
);
for y in [-150.0, -300.0] {
assert!(near(handles(&circle, pt(99.999, y)), handles(&circle, pt(100.001, y))), "y {y}");
}
}
#[test]
fn going_on_from_an_end_keeps_the_old_segments() {
let before = wave();
+3 -3
View File
@@ -1552,7 +1552,7 @@ impl Tool for SelectionTool {
// take the pointer too (on a thin box the centre lies within a handle's reach), and with
// Cmd/Ctrl held the press selects the object behind instead.
if near_selected && !m.cmd && hit_center(cx, p, cx.point_tol()).is_some() {
return Cursor::Move;
return Cursor::SelectionMove;
}
// View → Snap to Point: over an anchor a press would grab the object by, the arrow turns
// hollow.
@@ -1560,11 +1560,11 @@ impl Tool for SelectionTool {
return Cursor::ArrowHollow;
}
if selected_source_hit(cx, p).is_some() {
return Cursor::Move;
return Cursor::SelectionMove;
}
if let Some(h) = hit_test(cx.doc, p, cx.selection_hit_options()) {
if selected_under(cx, &h, h.top_object(cx.isolation)).is_some() || m.alt {
return Cursor::Move;
return Cursor::SelectionMove;
}
return Cursor::Arrow;
}
+9 -9
View File
@@ -17,7 +17,7 @@ fn a_press_on_a_selected_shaper_source_moves_it_while_a_mask_is_edited() {
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
for x in [75.0, 125.0] {
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::Move, "at {x}");
assert_eq!(t.cursor(&c, Point::new(x, 350.0), Mods::default()), Cursor::SelectionMove, "at {x}");
let down = t.pointer(&c, &ev(PointerKind::Down, x, 350.0));
assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "at {x}: {down:?}");
let drag = t.pointer(&c, &ev(PointerKind::Drag, x + 20.0, 350.0));
@@ -45,7 +45,7 @@ fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() {
s.set([rect, ids[1]]);
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move);
assert_eq!(t.cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::SelectionMove);
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 350.0));
assert!(!down.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.set")), "{down:?}");
let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 350.0));
@@ -55,7 +55,7 @@ fn a_selected_shaper_source_moves_after_other_objects_and_behind_front_art() {
d.insert(Some(layer), 2, Node::path(front, square, Appearance::default_art())).unwrap();
s.set([ids[1]]);
let c = ToolContext { isolation: Some(layer), ..cx(&d, &s, &p) };
assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::Move);
assert_ne!(SelectionTool::default().cursor(&c, Point::new(125.0, 350.0), Mods::default()), Cursor::SelectionMove);
let down = SelectionTool::default().pointer(&c, &ev(PointerKind::Down, 125.0, 350.0));
assert!(down.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([front.0]))), "{down:?}");
}
@@ -1042,7 +1042,7 @@ fn hidden_box_handles_take_no_press_while_anchors_are_selected() {
s.anchors.entry(id).or_default().insert((0, 1));
let c = cx(&d, &s, &p);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::Move);
assert_eq!(t.cursor(&c, top_middle, Mods::default()), Cursor::SelectionMove);
let down = t.pointer(&c, &ev(PointerKind::Down, 150.0, 100.0));
assert!(!down.contains(&Action::Begin("Scale".into())), "{down:?}");
assert!(!crate::select::bbox_handle_at(&c, top_middle));
@@ -3006,9 +3006,9 @@ fn a_press_on_the_centre_point_moves_an_unfilled_shape() {
let c = ToolContext { path_only: true, ..cx(&d, &s, &p) };
let centre = Point::new(150.0, 150.0);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::Move);
assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::SelectionMove);
// Cmd/Ctrl selects the object behind, not the centre point, so the pointer says neither.
assert_ne!(t.cursor(&c, centre, Mods { cmd: true, ..Mods::default() }), Cursor::Move);
assert_ne!(t.cursor(&c, centre, Mods { cmd: true, ..Mods::default() }), Cursor::SelectionMove);
assert!(t.pointer(&c, &ev(PointerKind::Down, centre.x, centre.y)).is_empty());
let a = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 160.0));
assert_eq!(a.first(), Some(&Action::Begin("Move".into())), "{a:?}");
@@ -3102,7 +3102,7 @@ fn a_ruler_guide_under_the_centre_point_keeps_the_pointer() {
assert!(hit_center(&c, centre, c.point_tol()).is_some());
let mut t = SelectionTool::default();
let cursor = t.cursor(&c, centre, Mods::default());
assert_ne!(cursor, Cursor::Move, "the guide's cursor, not the move arrow");
assert_ne!(cursor, Cursor::SelectionMove, "the guide's cursor, not the move arrow");
let down = t.pointer(&c, &ev(PointerKind::Down, centre.x, centre.y));
let drag = t.pointer(&c, &ev(PointerKind::Drag, 170.0, 150.0));
assert!(drag.iter().any(|a| matches!(a, Action::Preview(cmd, _) if cmd == "guide.move")), "the guide drags: {down:?} {drag:?}");
@@ -3177,7 +3177,7 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
s.set(picked.iter().copied());
let c = cx(&d, &s, &p);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "{picked:?}");
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::SelectionMove, "{picked:?}");
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
assert!(!is_select(&down), "{picked:?}: {down:?}");
let drag = t.pointer(&c, &ev(PointerKind::Drag, 145.0, 125.0));
@@ -3218,7 +3218,7 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() {
s.anchors.insert(a, [(0, 0), (0, 1), (0, 2), (0, 3)].into_iter().collect());
let c = cx(&d, &s, &p);
let mut t = SelectionTool::default();
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::Move, "every anchor");
assert_eq!(t.cursor(&c, Point::new(125.0, 125.0), Mods::default()), Cursor::SelectionMove, "every anchor");
let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0));
assert!(!is_select(&down), "every anchor: {down:?}");
}
+1
View File
@@ -104,6 +104,7 @@ vectorcraft-testkit = { workspace = true }
vectorcraft-tools = { workspace = true, features = ["testing"] }
# A variable font built in code (no font file is committed).
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
vectorcraft-plugins = { workspace = true, features = ["test-steady"] }
wat = { workspace = true }
[build-dependencies]
+50 -2
View File
@@ -40,8 +40,8 @@ fn params(fields: &DialogFields) -> Value {
/// Opens Smooth Bridge's dialog on the command's defaults.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
// The reach applies to three or more circles; two are bridged at any distance. Counted once, before a preview
// replaces the selection with its result.
let many = app.session.doc().map(|doc| doc.selection.objects.len() > 2).unwrap_or(true);
// replaces the selection with its result, with a selected group counting the objects inside it.
let many = app.session.doc().map(|doc| members(&doc.doc, &doc.selection.objects) > 2).unwrap_or(true);
let fields = DialogFields::from_pairs([
("radius", FieldValue::Number(RADIUS)),
("constantGap", FieldValue::Bool(false)),
@@ -72,6 +72,24 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
})
}
/// How many objects the command bridges for objects `ids`: each one, or for a group (a clipping group excepted) the
/// objects inside it, at any depth; an object given twice, or with its group, counts once.
fn members(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> usize {
fn visit(n: &vectorcraft_doc::Node, out: &mut std::collections::BTreeSet<vectorcraft_doc::NodeId>) {
match &n.kind {
vectorcraft_doc::NodeKind::Group { children, clip: false } => children.iter().for_each(|c| visit(c, out)),
_ => {
out.insert(n.id);
}
}
}
let mut out = std::collections::BTreeSet::new();
for n in ids.iter().filter_map(|&id| doc.node(id)) {
visit(n, &mut out);
}
out.len()
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
@@ -158,6 +176,36 @@ mod tests {
assert_eq!(geometry(&panel.app()), original);
}
#[test]
fn reach_counts_the_circles_inside_a_selected_group() {
use crate::tests::panel_harness::Panel;
for (xs, many) in [(&[100.0, 124.0][..], false), (&[100.0, 124.0, 148.0][..], true)] {
let mut app = bridge_app(xs);
let ids: Vec<u64> = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect();
let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [group]})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
panel.frame();
assert_eq!(panel.enabled("Reach"), many, "{} circles in the group", xs.len());
panel.click("OK");
panel.frame();
let inside = panel.app().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(group)).unwrap().children().unwrap().len();
assert_eq!(inside, 1, "the circles in the group became one shape");
}
// A group of two circles selected together with one of them: still two circles.
let mut app = bridge_app(&[100.0, 124.0]);
let ids: Vec<u64> = app.session.doc().unwrap().selection.objects.iter().map(|id| id.0).collect();
let group = app.run("object.group", json!({ "ids": ids })).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [group, ids[0]]})).unwrap();
assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2);
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
panel.frame();
assert!(!panel.enabled("Reach"), "a circle selected with its group counts once");
}
#[test]
fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
+16 -1
View File
@@ -140,6 +140,7 @@ impl VectorcraftApp {
text_nodes: Default::default(),
momentary: None,
hand: None,
zoom_tool: None,
selection_box: None,
selection_bounds: None,
selection_marks: None,
@@ -380,7 +381,12 @@ impl VectorcraftApp {
}
/// A window's raw input, before egui and the keys read it (the host's `raw_input_hook`).
pub fn raw_input(&self, ctx: &egui::Context, raw: &mut egui::RawInput) {
pub fn raw_input(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// AppKit consumes the key-down and winit can already have queued its key-up.
// Poll before the runtime orders the press and release in this frame's input.
if let Some(menu) = self.services.native_menu.as_mut() {
menu.poll(ctx);
}
crate::type_editing::keep_layout_text(self, ctx, raw);
}
@@ -717,7 +723,13 @@ impl VectorcraftApp {
export_progress::show(self, ui);
// After every window this pass may open, and before the palette's field takes the keyboard.
panel_docking::close_overlays_for_modal(self, &ctx);
let drawn_document = self.session.active().map(|st| (st.uid, st.revision));
dialogs::host::pump(self, &ctx);
// The canvas has already painted. A dialog can apply or roll back its preview
// on the final input frame, with no further mouse movement to wake the window.
if self.session.active().map(|st| (st.uid, st.revision)) != drawn_document {
ctx.request_repaint();
}
prefs_dialog::show(self, ui);
crate::shortcut_editor::show(self, ui);
credits::open_taken_link(self);
@@ -824,6 +836,9 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print
root.escape_leaves_fields = true;
// A held key repeats its command (Cmd+= keeps zooming in).
root.shortcuts_repeat = true;
// The wheel steps a focused number field only while the pointer is over it; elsewhere it scrolls what is under the
// pointer.
root.pointer_scoped_field_wheel = true;
root
}
+2 -1
View File
@@ -129,11 +129,12 @@ impl VectorcraftApp {
/// document without artboards they get neither.
fn add_active_artboard(&self, id: &str, params: &mut Value) {
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
let clipboard_command = paste || matches!(id, "edit.copy" | "edit.cut");
if (vectorcraft_engine::ON_ACTIVE_ARTBOARD.contains(&id) || id == "command.batch")
&& params.get("artboard").is_none()
&& !(paste && params.get("artboards").is_some())
&& self.view().is_some()
&& let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !paste)
&& let Some(n) = self.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0 || !clipboard_command)
&& let Some(p) = params.as_object_mut()
{
let picked = panels::artboards::picked(self, n);
+2
View File
@@ -82,6 +82,8 @@ pub struct CanvasCache {
/// passes; the tool adapter takes it out for its call and puts it back.
pub momentary: Option<craft::ui::canvas::Momentary>,
pub hand: Option<craft::ui::canvas::HandTool>,
/// The selected Zoom tool keeps its press and drag rectangle between canvas passes.
pub zoom_tool: Option<craft::ui::canvas::ZoomTool>,
/// [`VectorcraftApp::selection_box`] for (document uid, revision, Use Preview Bounds and
/// Measure Type by Glyph Bounds).
pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option<vectorcraft_doc::OrientedBox>)>,
+2 -2
View File
@@ -31,7 +31,7 @@ pub(super) fn checker_of(setup: &vectorcraft_doc::DocSetup) -> Checker {
}
/// The page frames of document `st` seen through `view`: one per artboard, named "01 - name" with the
/// Artboard tool or several boards, filled with its paper or the transparency grid (nothing in Outline).
/// Artboard tool or several boards, filled with its paper or the transparency grid (white in Outline).
/// Empty while the artboards are hidden.
pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, view: &View, outline: bool) -> Vec<PageFrame> {
if !shows_artboards(app) {
@@ -51,7 +51,7 @@ pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, vi
frame = frame.name(format!("{:02} - {}", i + 1, ab.name));
}
if outline {
frame
frame.fill(DataColor::new(Color32::WHITE))
} else if grid {
frame.checker(checker_of(setup))
} else {
+2 -2
View File
@@ -47,13 +47,13 @@ fn shift_clicking_a_name_toggles_selection_and_a_plain_click_activates() {
}
#[test]
fn outline_has_a_white_canvas_line_edges_and_no_paper() {
fn outline_has_white_artboards_on_a_white_canvas_with_line_edges() {
let _view = crate::testing::DefaultProofView::new();
let app = app_with(2);
let st = app.session.active().unwrap();
assert_eq!(pasteboard_color(&app, st, true), PasteboardColor::Custom(DataColor::new(Color32::WHITE)));
assert_eq!(border(true), PageBorder::Line);
assert!(frames_of(&app, true).iter().all(|f| f.fill.is_none()));
assert!(frames_of(&app, true).iter().all(|f| f.fill == Some(PageFill::Color(DataColor::new(Color32::WHITE)))));
assert_eq!(pasteboard_color(&app, st, false), PasteboardColor::Default);
assert_eq!(border(false), PageBorder::DropShadow);
assert!(frames_of(&app, false).iter().all(|f| f.fill.is_some()));
+10 -5
View File
@@ -73,15 +73,20 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
}
}
/// What the start screen's user did.
/// What the start screen's user did. A command that fails says why in the status bar (#6160).
fn run_action(app: &mut VectorcraftApp, action: StartAction) {
fn run(app: &mut VectorcraftApp, id: &str, params: serde_json::Value) {
if let Err(e) = app.run(id, params) {
app.status(e);
}
}
match action {
StartAction::New => drop(app.run("file.newDialog", json!({}))),
StartAction::Open => drop(app.run("file.open", json!({}))),
StartAction::New => run(app, "file.newDialog", json!({})),
StartAction::Open => run(app, "file.open", json!({})),
// A failure is reported to the user there.
StartAction::OpenRecent(path) => drop(crate::io::open_reporting(app, &path.to_string_lossy())),
StartAction::UseTemplate(name) => drop(app.run("file.new", json!({ "preset": name }))),
StartAction::ClearRecent => drop(app.run("file.clearRecent", json!({}))),
StartAction::UseTemplate(name) => run(app, "file.new", json!({ "preset": name })),
StartAction::ClearRecent => run(app, "file.clearRecent", json!({})),
StartAction::RemoveRecent(path) => app.ui.recent_files.retain(|recent| std::path::Path::new(recent) != path),
StartAction::RevealRecent(path) => {
// PLAN: `io::export` is a private module of `io`; `reveal_path` needs a re-export from io.rs (unowned).
+69
View File
@@ -426,6 +426,23 @@ fn a_click_activates_its_artboard_and_paste_in_place_goes_onto_it() {
assert_eq!((b.x0, b.y0), (boards[2].x0 + 10.0, boards[2].y0 + 15.0));
}
/// Copy uses the active board as its origin even when selected art lies on a different board.
#[test]
fn copy_and_paste_use_the_active_source_and_destination_artboards() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3})).unwrap();
let boards: Vec<_> = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
let origin = Point::new(boards[1].x0 + 10.0, boards[1].y0 + 15.0);
app.run("shape.rectangle", json!({"x": origin.x, "y": origin.y, "width": 20, "height": 20})).unwrap();
app.views[0].artboard = 0;
app.run("edit.copy", json!({})).unwrap();
app.views[0].artboard = 2;
let pasted = app.run("edit.pasteInPlace", json!({})).unwrap();
let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap());
let bounds = app.session.active().unwrap().doc.bounds_of(&[id], false).unwrap();
assert_eq!(bounds.origin(), origin + (boards[2].origin() - boards[0].origin()));
}
/// A Shift-click with the Selection tool on an empty spot inside an artboard makes it the active
/// one and keeps the selection, and Align to Artboard then aligns the objects to it unless the
/// call names another artboard.
@@ -880,6 +897,58 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() {
assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it");
}
/// A Selection tool move builds the menus' states again twice, in the frame of its press and in the frame of its
/// release, which commits the move. The frame the move begins in and the frames of its previews, which change the
/// document's revision, keep them. The menus are also built again when a process-wide catalog changes, so the fonts
/// and plug-ins are held steady against tests running alongside for the whole run, and the move runs again on a new
/// app, at most 20 times, until the other catalogs held still through it.
#[test]
fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() {
let fonts = vectorcraft_text::FontDb::global();
let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins());
let catalogs = || {
(
crate::menus::plugin_revision(),
fonts.generation(),
fonts.installed_fonts_ready(),
crate::scripts_menu::revision(),
crate::dialogs::proof_setup::saved_revision(),
)
};
let run = || {
let (mut app, ctx, xf) = rectangle_tool();
let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap()["id"].as_u64().unwrap();
app.select_tool("selection");
app.session.execute("select.set", &json!({"ids": [id]})).unwrap();
let (from, to) = (xf.to_screen(Point::new(130.0, 115.0)), xf.to_screen(Point::new(170.0, 135.0)));
app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
for _ in 0..2 {
app_step(&mut app, &ctx, vec![]);
}
let none = egui::Modifiers::NONE;
let mut steps = vec![vec![primary(from, true, none)]];
steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))]));
steps.push(vec![primary(to, false, none)]);
steps.extend([vec![], vec![], vec![]]);
let mut rebuilt = vec![];
for events in steps {
let before = app.menus.rebuilds;
app_step(&mut app, &ctx, events);
rebuilt.push(app.menus.rebuilds - before);
}
(app, rebuilt)
};
let (app, rebuilt) = (0..20)
.find_map(|_| {
let before = catalogs();
let out = run();
(catalogs() == before).then_some(out)
})
.unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs"));
assert_eq!(drawn_paths(&app), vec![Rect::new(140.0, 120.0, 200.0, 150.0)], "the drag moves the rectangle");
assert_eq!(rebuilt, [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], "rebuilds in each frame: press, 8 moves, release, 3 idle");
}
/// #6369: only the selection box remains over the temporary halftone, and the original
/// selection's outlines come back when Preview is turned off or the dialog is cancelled.
#[test]
@@ -139,3 +139,57 @@ fn a_hand_drag_held_near_the_edge_does_not_scroll_on() {
assert_eq!(center(&app), c0);
frame(&mut app, &ctx, vec![button(edge, false)]);
}
#[test]
fn a_freehand_stroke_at_the_edge_keeps_the_artwork_stationary() {
let (mut app, ctx, original) = zoomed_in("pencil");
let rect = app.canvas_view().unwrap().rect;
let start = rect.center() - vec2(120.0, 60.0);
let edge = pos2(rect.right() - 2.0, start.y + 40.0);
let initial = center(&app);
let nodes = |app: &VectorcraftApp| {
let mut count = 0;
app.session.active().unwrap().doc.walk(|_| count += 1);
count
};
let before = nodes(&app);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(15.0, 25.0))]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]);
for _ in 0..5 {
frame(&mut app, &ctx, vec![]);
assert_eq!(center(&app), initial);
}
frame(&mut app, &ctx, vec![button(edge, false)]);
assert!(nodes(&app) > before, "the pencil drew a new path");
assert!(app.session.active().unwrap().doc.node(original).is_some());
}
#[test]
fn selected_zoom_tool_clicks_option_clicks_and_drags_a_marquee() {
let (mut app, ctx, _) = zoomed_in("zoom");
app.session.prefs.animated_zoom = false;
let rect = app.canvas_view().unwrap().rect;
let position = rect.center();
let zoom = |app: &VectorcraftApp| app.view().unwrap().zoom;
let initial = zoom(&app);
for pressed in [true, false] {
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(position), button(position, pressed)]);
}
let enlarged = zoom(&app);
assert!(enlarged > initial, "click should zoom in: {initial} -> {enlarged}");
let modifiers = egui::Modifiers::ALT;
for pressed in [true, false] {
let event = egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers };
frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(modifiers), event]);
}
frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
let reduced = zoom(&app);
assert!(reduced < enlarged, "Option-click should zoom out: {enlarged} -> {reduced}");
let start = position - vec2(90.0, 65.0);
let end = position + vec2(80.0, 55.0);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]);
frame(&mut app, &ctx, vec![button(end, false)]);
assert!(zoom(&app) > reduced, "the marquee should fit its region to the view");
}
+20 -6
View File
@@ -590,7 +590,9 @@ impl CanvasTool for SessionTool<'_> {
}
fn autoscrolls(&self) -> bool {
!self.carrying.get() && !self.view_only()
// Sampled freehand tools trace the pointer on the artwork. Scrolling
// under a held pen would extend the stroke without another sample.
!self.carrying.get() && !self.view_only() && !self.app().session.tool_wants_samples()
}
fn view_only(&self) -> bool {
@@ -651,18 +653,30 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too
let mut picked = ToolHostResponse::default();
let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) {
picked
} else if app.session.tool_id() == "hand" && app.ui.screen_mode != 3 && app.ui.rearrange_placement.is_none() {
} else if matches!(app.session.tool_id(), "hand" | "zoom") && app.ui.screen_mode != 3 && app.ui.rearrange_placement.is_none() {
let options = crate::app::view::navigation(&app.session.prefs);
let mut hand = app.canvas.hand.take().unwrap_or_else(|| craft::ui::canvas::HandTool::new(options));
hand.options = options;
let response = host_run(app, ui, pass, &mut hand);
let response = if app.session.tool_id() == "zoom" {
app.canvas.hand = None;
let mut zoom = app.canvas.zoom_tool.take().unwrap_or_else(|| craft::ui::canvas::ZoomTool::new(options));
zoom.options = options;
let response = host_run(app, ui, pass, &mut zoom);
app.canvas.zoom_tool = Some(zoom);
response
} else {
app.canvas.zoom_tool = None;
let mut hand = app.canvas.hand.take().unwrap_or_else(|| craft::ui::canvas::HandTool::new(options));
hand.options = options;
let response = host_run(app, ui, pass, &mut hand);
app.canvas.hand = Some(hand);
response
};
if response.gesture.is_some() && !view_tool_held(app) && ui.input(|i| i.pointer.primary_down() || i.pointer.primary_pressed()) {
crate::shortcuts::note_tool_use(app);
}
app.canvas.hand = Some(hand);
response
} else {
app.canvas.hand = None;
app.canvas.zoom_tool = None;
let mut tool = SessionTool::new(app, view_info, ui);
let response = host_run_session(&mut tool, ui, pass);
drop(tool);
+3 -1
View File
@@ -89,6 +89,7 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor {
Cursor::DirectAnchorSelected => tool("cursor-direct-anchor-selected", TIP, None),
Cursor::ReshapeSegment => tool("cursor-reshape-segment", TIP, None),
Cursor::GroupSelection => badged(CursorBadge::Add),
Cursor::SelectionMove => badged(CursorBadge::Move),
Cursor::SelectionCopy => badged(CursorBadge::Copy),
Cursor::Move => system(CursorIcon::Move),
Cursor::Crosshair => PaintedCursor::Crosshair.into(),
@@ -195,7 +196,7 @@ pub(crate) fn request_busy(app: &crate::VectorcraftApp, ctx: &egui::Context) {
/// Every cursor with a look: its own, or the one it borrows.
#[cfg(test)]
const GLYPHS: [Cursor; 99] = [
const GLYPHS: [Cursor; 100] = [
Cursor::Hand,
Cursor::HandGrab,
Cursor::ZoomIn,
@@ -207,6 +208,7 @@ const GLYPHS: [Cursor; 99] = [
Cursor::ReshapeSegment,
Cursor::GroupSelection,
Cursor::SelectionCopy,
Cursor::SelectionMove,
Cursor::Move,
Cursor::Crosshair,
Cursor::ResizeH,
+1
View File
@@ -148,6 +148,7 @@ pub mod slices;
pub mod smart_punctuation;
pub(crate) mod smooth_slider;
pub mod spot_colors;
pub mod step_repeat;
pub mod svg_filter;
pub(crate) mod svg_options;
pub mod swatch_conflict;
+5
View File
@@ -350,9 +350,14 @@ fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map<String, Value>
// Free Distort's Reset puts the corners back on the box, wherever they were when it opened.
let reset_to = (id == super::free_distort::FREE_DISTORT)
.then(|| form::fields_of(&rows, &Map::from_iter([("corners".to_string(), json!(super::free_distort::IDENTITY))])));
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
let dialog = HostedParamDialog::new(&ctx, "effect", fields, move |f| {
let rows = effect_params(&cx, f);
let dialog = ParamDialog::new("effect", title.clone(), rows).values(Bind::bound(f)).previews(true);
let dialog = match canvas {
Some(canvas) => dialog.canvas(canvas),
None => dialog,
};
let dialog = match &reset_to {
Some(target) => dialog.reset_to(target.clone()),
None => dialog,
+60 -9
View File
@@ -114,11 +114,19 @@ pub(super) fn render_preview(
app: &mut VectorcraftApp,
ctx: &egui::Context,
doc: &vectorcraft_engine::doc::Document,
) -> Option<Arc<egui::ColorImage>> {
render_page_preview(&mut app.canvas.renderer, ctx.pixels_per_point(), doc)
}
fn render_page_preview(
renderer: &mut vectorcraft_render::Renderer,
pixels_per_point: f32,
doc: &vectorcraft_engine::doc::Document,
) -> Option<Arc<egui::ColorImage>> {
let region = doc.artboards.first()?.rect;
let px = PREVIEW_PX * ctx.pixels_per_point() as f64;
let px = PREVIEW_PX * pixels_per_point as f64;
let scale = px / region.width().max(region.height()).max(1.0);
let img = app.canvas.renderer.render_region(doc, region, scale, true);
let img = renderer.render_region(doc, region, scale, true);
Some(Arc::new(crate::canvas::color_image(&img)))
}
@@ -286,6 +294,8 @@ pub(super) struct ImportPdfDialog {
/// The preview shown for a (page, crop, text) revision; `None` for a page that could not be read, which is
/// not asked for again.
preview: Option<(Revision, Option<Arc<egui::ColorImage>>)>,
/// One preview at a time. Page changes coalesce while the worker finishes.
pending_preview: Option<(Revision, std::sync::mpsc::Receiver<Option<Arc<egui::ColorImage>>>)>,
/// Why the last password did not open the file.
password_error: Option<String>,
/// The OK the pump has not answered.
@@ -294,7 +304,7 @@ pub(super) struct ImportPdfDialog {
impl ImportPdfDialog {
fn new(s: State) -> Self {
ImportPdfDialog { id: dialog_id(KIND), s, preview: None, password_error: None, held: HeldAnswer::new() }
ImportPdfDialog { id: dialog_id(KIND), s, preview: None, pending_preview: None, password_error: None, held: HeldAnswer::new() }
}
/// The preview to render next: the revision of the shown page, crop and text, when the stored one differs.
@@ -700,7 +710,14 @@ fn confirm(app: &mut VectorcraftApp, s: &State) -> Result<(), String> {
if s.links_on() {
p["linkPages"] = json!(true);
}
io::open_document(app, &s.name, &s.file.bytes, s.path.clone(), &p).map(|_| ())
if crate::opening::available()
&& let Some(path) = s.path.as_deref()
{
crate::opening::start_with(app, path, s.file.bytes.clone(), p);
Ok(())
} else {
io::open_document(app, &s.name, &s.file.bytes, s.path.clone(), &p).map(|_| ())
}
};
// Asked only for the password, the dialog showed no Text choice to keep; the choice for a `.ai`
// or `.ait` file is not kept for PDFs.
@@ -711,10 +728,10 @@ fn confirm(app: &mut VectorcraftApp, s: &State) -> Result<(), String> {
}
/// The preview of the page and boxes `s` shows; `None` for a page that can't be read.
fn preview_image(app: &mut VectorcraftApp, ctx: &egui::Context, s: &State) -> Option<Arc<egui::ColorImage>> {
fn preview_image(renderer: &mut vectorcraft_render::Renderer, pixels_per_point: f32, s: &State) -> Option<Arc<egui::ColorImage>> {
let opts = fileio::LoadOptions { crop: s.crop, password: s.password(), text_as: s.preview_text_as(), ..Default::default() };
let (doc, _) = fileio::page_document(&s.file.bytes, s.page().saturating_sub(1), &opts).ok()?;
render_preview(app, ctx, &doc)
render_page_preview(renderer, pixels_per_point, &doc)
}
/// The host pump: judges the OK the dialog holds (opening or placing the file; a refusal keeps the dialog open with
@@ -730,10 +747,44 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
dialog.answer_ok(answer);
}
});
return;
}
let wanted = dialogs.with(|host| host.get::<ImportPdfDialog>().and_then(|d| Some((d.wanted_preview()?, d.s.clone()))));
if let Some((revision, s)) = wanted {
let image = preview_image(app, ctx, &s);
let wanted = dialogs.with(|host| {
let dialog = host.get_mut::<ImportPdfDialog>()?;
if let Some((revision, pending)) = &dialog.pending_preview {
let image = match pending.try_recv() {
Ok(image) => image,
Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
Err(std::sync::mpsc::TryRecvError::Empty) => return None,
};
if dialog.wanted_preview() == Some(*revision) {
dialog.set_preview(*revision, image);
}
dialog.pending_preview = None;
}
Some((dialog.wanted_preview()?, dialog.s.clone()))
});
let Some((revision, state)) = wanted else { return };
let pixels_per_point = ctx.pixels_per_point();
if crate::opening::available() {
let (sender, pending) = std::sync::mpsc::channel();
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<ImportPdfDialog>() {
dialog.pending_preview = Some((revision, pending));
}
});
let wake = ctx.clone();
let scope = vectorcraft_engine::file_access::ScopeHandle::capture();
app.jobs().spawn(
"vectorcraft-pdf-preview",
Box::new(move || {
let image = scope.run(|| preview_image(&mut vectorcraft_render::Renderer::new(), pixels_per_point, &state));
let _ = sender.send(image);
wake.request_repaint();
}),
);
} else {
let image = preview_image(&mut app.canvas.renderer, pixels_per_point, &state);
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<ImportPdfDialog>() {
dialog.set_preview(revision, image);
+6 -1
View File
@@ -4,7 +4,8 @@ use super::path_ops::PathOp;
use super::simplify_slider::StripKind;
use super::{
blend_options, dimension, flare_options, graph_data, graph_design, graph_type, indexed_color, live_paint_gaps, object_mosaic, option_form,
path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, transform, transform_each, width_point,
path_ops, perspective_grid, perspective_presets, saved_names, shapes, simplify_slider, smooth_slider, step_repeat, transform, transform_each,
width_point,
};
use crate::VectorcraftApp;
@@ -15,6 +16,8 @@ pub(crate) struct ObjectDialogs {
pub transform: Option<transform::Open>,
/// The open Transform Each dialog's preview record.
pub each: Option<transform_each::Open>,
/// The open Step and Repeat dialog's preview record.
pub step: Option<step_repeat::Open>,
/// The open Average, Average & Join, Offset Path and Simplify dialogs' preview records.
pub path: Vec<path_ops::Open>,
/// The open Split Into Grid dialog's record.
@@ -46,6 +49,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
sync(app);
transform::pump(app, ctx);
transform_each::pump(app, ctx);
step_repeat::pump(app, ctx);
path_ops::pump(app, ctx);
shapes::pump(app, ctx);
flare_options::pump(app, ctx);
@@ -73,6 +77,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> bool {
}
match id {
"object.transformEach" => transform_each::open(app),
step_repeat::CMD => step_repeat::open(app),
"path.average" => path_ops::open(app, PathOp::Average),
"path.averageJoin" => path_ops::open(app, PathOp::AverageJoin),
"object.path.offsetPath" => path_ops::open(app, PathOp::OffsetPath),
+1 -1
View File
@@ -631,7 +631,7 @@ pub(super) mod tests {
tool: "shapeBuilder",
opens_on: vec![
("openFilledAsClosed", json!(true)),
("pickColorFrom", json!("artwork")),
("pickColorFrom", json!("swatches")),
("cursorSwatchPreview", json!(false)),
("selection", json!("freeform")),
("highlightFill", json!(true)),
+14 -4
View File
@@ -42,7 +42,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use craft::menu::Node;
use craft::ui::contract::Show as _;
use craft::ui::contract::{Bind, Show as _};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, Prompt, StackDialog, dialog_id};
use craft::ui::display::{Shade, Text};
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog};
@@ -548,7 +548,13 @@ pub(super) fn heading(plugin: &str, command: Option<&str>, gone: &str) -> String
/// The builder of a hosted plug-in dialog over its values: the rows of `all` whose parameter is
/// shown for the values (`m.visible`), after the description. The rows are made again in the UI
/// language when it changes while the dialog is open; the field values stay as they are.
fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static {
fn build(
key: &'static str,
m: Manifest,
all: Arc<[Param]>,
look: Look,
canvas: Option<egui::Id>,
) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send + 'static {
let rows_in = std::sync::Mutex::new((lang(), all));
move |fields| {
let all = {
@@ -564,7 +570,10 @@ fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl
rows.push(Param::read_only_text("description", "", look.description.clone()).full_width());
}
rows.extend(all.iter().filter(|p| shown.contains(p.key.as_str())).cloned());
let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews);
let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews).values(Bind::bound(fields));
if let Some(canvas) = canvas.filter(|_| look.previews) {
dialog = dialog.canvas(canvas);
}
if let Some(ok) = look.ok {
dialog = dialog.ok_label(ok.into());
}
@@ -592,7 +601,8 @@ fn open_hosted(
close_open(app);
let all: Arc<[Param]> = form::plugin_params(&m, &values).into();
let fields = form::fields_of(&all, &values);
let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look)).instance(instance.to_string());
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look, canvas)).instance(instance.to_string());
let id = dialogs.with(|host| host.open(dialog));
Ok((id, all))
}
@@ -110,7 +110,7 @@ impl RearrangeValues {
}
/// The length unit a document unit shows as.
fn length_kind(unit: Unit) -> UnitKind {
pub(super) fn length_kind(unit: Unit) -> UnitKind {
match unit {
Unit::Picas => UnitKind::Picas,
Unit::Inches => UnitKind::Inches,
+16 -6
View File
@@ -114,22 +114,32 @@ fn rows() -> Vec<(&'static str, &'static str, &'static str, Value)> {
#[test]
fn a_3d_row_sets_its_param_previews_and_applies_in_one_step() {
// One window serves every row: Cancel, and OK followed by Undo, leave the drawing as the dialog found it, and each
// row opens the dialog again over it.
let mut shown: Option<ThreeD> = None;
for (effect, page, key, value) in rows() {
let name = format!("{effect}.{key}");
for confirm in [false, true] {
let mut h = drawn(SQUARE, effect);
let before = source(&h);
let p = json!({"effect": effect, "item": null});
let h = match shown.as_mut() {
Some(h) => {
reopen(h, p);
h
}
None => shown.insert(opened(app_with(SQUARE), p)),
};
let before = source(h);
h.set("__page", json!(page));
h.set(key, value.clone());
assert!(same(&stored(&h, effect)[key], &value), "{name}: the preview follows the row");
assert!(same(&stored(h, effect)[key], &value), "{name}: the preview follows the row");
if confirm {
h.ok();
assert!(same(&stored(&h, effect)[key], &value), "{name}: OK keeps it");
undo(&h);
assert!(same(&stored(h, effect)[key], &value), "{name}: OK keeps it");
undo(h);
} else {
h.cancel();
}
assert_eq!(doc(&h), before, "{name}: {}", if confirm { "one undo step" } else { "Cancel restores" });
assert_eq!(doc(h), before, "{name}: {}", if confirm { "one undo step" } else { "Cancel restores" });
}
}
}
+168
View File
@@ -0,0 +1,168 @@
//! Object → Step and Repeat: copies of the selection on a grid or filling a sheet, with the gaps
//! between the cut paths, every other column or row turned by 180° (`object.stepAndRepeat`),
//! previewed live on the canvas.
//!
//! Fields: `rows`, `columns`, `gapX`, `gapY` (pt), `margin` (pt), `fill` (as many as fit the
//! artboard), `rotate` (`none`, `columns` or `rows`), `cutId` (an object of the selection, or
//! empty for the selection itself).
use craft::ui::contract::Bind;
use craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::{Label, LengthUnits, UnitKind};
use serde_json::{Map, Value, json};
use super::host::{HeldOptions, open_held_with};
use super::preview::LivePreview;
use crate::VectorcraftApp;
pub(crate) const CMD: &str = "object.stepAndRepeat";
pub(crate) struct Open {
pub id: DialogId,
pub preview: LivePreview,
}
fn cut_ids(doc: &vectorcraft_doc::Document, selected: &[vectorcraft_doc::NodeId]) -> Vec<(u64, String)> {
let mut out = vec![];
for id in selected {
if let Some(n) = doc.node(*id) {
n.walk(&mut |c| out.push((c.id.0, c.display_name())));
}
}
out
}
fn cut_options(app: &VectorcraftApp) -> Vec<(String, Label)> {
let mut out = vec![(String::new(), Label::from(tl!("Selection")))];
if let Some(st) = app.session.active() {
out.extend(cut_ids(&st.doc, &st.selection.objects).into_iter().map(|(id, name)| (id.to_string(), Label::from(name))));
}
out
}
fn rows(lengths: LengthUnits, cuts: Vec<(String, Label)>) -> Vec<Param> {
let len = |key: &str, label: &'static str| Param::number(key, label, 0.0, 1.0, 2).length(lengths);
vec![
Param::new("rows", tl!("Rows"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false),
Param::new("columns", tl!("Columns"), ParamKind::int(Some(1), Some(500), 2)).enabled_when("fill", false),
len("gapX", tl!("Horizontal Gap")),
len("gapY", tl!("Vertical Gap")),
Param::new("cutId", tl!("Cut Path"), ParamKind::choice(cuts, Some(String::new()))),
Param::new("fill", tl!("Fill the Artboard"), ParamKind::bool(false)),
len("margin", tl!("Margin")).enabled_when("fill", true),
Param::new(
"rotate",
tl!("Rotate 180°"),
ParamKind::choice(
vec![
("none".into(), Label::from(tl!("None"))),
("columns".into(), Label::from(tl!("Every Other Column"))),
("rows".into(), Label::from(tl!("Every Other Row"))),
],
Some("none".into()),
),
),
]
}
pub fn fields() -> DialogFields {
DialogFields::from_pairs([
("rows", FieldValue::Int(2)),
("columns", FieldValue::Int(2)),
("gapX", FieldValue::Number(12.0)),
("gapY", FieldValue::Number(12.0)),
("margin", FieldValue::Number(0.0)),
("fill", FieldValue::Bool(false)),
("cutId", FieldValue::Text(String::new())),
("rotate", FieldValue::Text("none".into())),
])
}
fn count(f: &DialogFields, key: &str) -> u64 {
f.int(key).or_else(|| f.number(key).map(|n| n as i64)).unwrap_or(1).max(1) as u64
}
fn params(f: &DialogFields) -> Value {
let mut p = Map::new();
p.insert("rows".into(), json!(count(f, "rows")));
p.insert("columns".into(), json!(count(f, "columns")));
for k in ["gapX", "gapY", "margin"] {
p.insert(k.into(), json!(f.number(k).unwrap_or(0.0)));
}
p.insert("fill".into(), json!(f.bool("fill").unwrap_or(false)));
p.insert("rotate".into(), json!(f.text("rotate").unwrap_or("none")));
if let Some(id) = f.text("cutId").and_then(|t| t.parse::<u64>().ok()) {
p.insert("cutId".into(), json!(id));
}
Value::Object(p)
}
pub(crate) fn open(app: &mut VectorcraftApp) {
let _ = try_open(app);
}
fn try_open(app: &mut VectorcraftApp) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let lengths = LengthUnits::new(UnitKind::Points, super::rearrange_artboards::length_kind(app.session.general_unit()), 72.0);
let lengths = crate::fields::bare_points(lengths, app.session.prefs.numbers_without_units_are_points);
let cuts = cut_options(app);
let dialog = HostedParamDialog::command(&ctx, CMD, fields(), move |fields| {
ParamDialog::command(CMD, tl!("Step and Repeat"), rows(lengths, cuts.clone())).previews(true).values(Bind::bound(fields))
});
let ok = |app: &mut VectorcraftApp, result: &ParamResult| {
let mut open = app.object_dialogs.step.take().ok_or("the dialog is closed")?;
let done = std::mem::take(&mut open.preview).commit(app, CMD, params(&result.fields));
if done.is_err() {
app.object_dialogs.step = Some(open);
}
done.map(|_| ())
};
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(open) = app.object_dialogs.step.take() {
open.preview.cancel(app);
}
});
let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?;
app.object_dialogs.step = Some(Open { id, preview: LivePreview::default() });
Ok(Value::Null)
}
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut open) = app.object_dialogs.step.take() else { return };
let shown =
app.dialogs().and_then(|host| host.with(|h| h.get_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), params(d.fields())))));
if let Some((on, p)) = shown {
let _ = open.preview.run(app, on, "Step and Repeat", CMD, &p);
}
app.object_dialogs.step = Some(open);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cut_path_is_sent_only_when_one_is_chosen() {
let mut f = fields();
assert!(params(&f).get("cutId").is_none());
f.set("cutId", FieldValue::Text("42".into()));
assert_eq!(params(&f)["cutId"], json!(42));
}
#[test]
fn cut_choices_reach_objects_nested_in_groups() {
let mut s = vectorcraft_engine::Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let inner = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [inner, c]})).unwrap();
let outer = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
let doc = &s.doc().unwrap().doc;
let ids: Vec<u64> = cut_ids(doc, &[vectorcraft_doc::NodeId(outer)]).into_iter().map(|(i, _)| i).collect();
assert!([outer, inner, a, b, c].iter().all(|i| ids.contains(i)));
}
}
@@ -117,6 +117,20 @@ fn pdf_page_footer_ok_opens_the_chosen_range() {
assert_eq!(artboard_widths(h.state()), [200.0, 300.0]);
}
#[test]
fn confirming_a_desktop_pdf_import_queues_the_read_and_closes_the_dialog() {
crate::opening::tests::with_threads(|| {
let mut app = app();
io::open_bytes(&mut app, "three.pdf", &three_pages(), Some("three.pdf".into())).unwrap();
set(&mut app, "allPages", json!(false));
set(&mut app, "range", json!("2-3"));
confirm(&mut app).unwrap();
assert!(!is_open(&app));
assert_eq!(app.opening.pending.len(), 1);
assert_eq!(app.opening.pending[0].path, "three.pdf");
});
}
#[test]
fn opening_a_multi_page_pdf_asks_for_the_pages() {
let mut app = app();
+5
View File
@@ -150,11 +150,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, kind: Kind, tool: &Value) {
let document = app.session.active().map(|doc| (doc.uid, doc.reverts));
let rows = rows(app, kind, &opening);
let fields = fields_of(&rows, &opening);
let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id);
let dialog = HostedParamDialog::new(&ctx, kind.command(), fields, move |f| {
if kind == Kind::Move {
link_distance_and_angle(f);
}
let dialog = ParamDialog::new(kind.command(), kind.title(), rows.clone()).previews(true).values(Bind::bound(f));
let dialog = match canvas {
Some(canvas) => dialog.canvas(canvas),
None => dialog,
};
if kind == Kind::Move { dialog.remember(MOVE_KEY) } else { dialog }
});
// A dialog this one replaces leaves its preview behind otherwise.
+24
View File
@@ -1,6 +1,8 @@
//! Panel bodies: what the dock area ([`crate::panel_docking`]) draws inside a docked, floating or
//! flyout panel.
use craft::ui::contract::{Props as _, Scroll, ShowContainer as _};
use craft::ui::layout_components::Stack;
use egui::Ui;
use crate::state::DockTab;
@@ -13,6 +15,28 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
Some(DockTab::Properties) => panels::properties::show(app, ui),
Some(DockTab::Layers) => panels::layers::show(app, ui),
Some(DockTab::Libraries) => panels::libraries(app, ui),
None if matches!(
id,
"align"
| "attributes"
| "blend"
| "character"
| "color"
| "magicWand"
| "openType"
| "paragraph"
| "pathfinder"
| "patternOptions"
| "stroke"
| "tabs"
| "transform"
| "transparency"
) =>
{
// These panels lay out forms. Collection panels own their scrolling viewport
// and reserve their own footer outside it.
Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| panels::show_icon_panel(app, ui, id));
}
None => panels::show_icon_panel(app, ui, id),
}
}
+8 -1
View File
@@ -233,13 +233,19 @@ fn open_request<'a>(purpose: &str, folder: Option<String>, filters: impl IntoIte
/// Asks for a file to open with `request`; `then` gets its path. The web answers with the file's
/// bytes, which open as File › Open opens them (the extension decides). A cancelled picker runs
/// nothing. While it is open the reply is `{pending: "fileDialog"}`.
/// nothing, and a picker that failed (the browser could not read the file) reports why. While it is
/// open the reply is `{pending: "fileDialog"}`. While another file dialog is still open, which can
/// be a window the system placed out of sight, the reply is an error saying so (#6160): a second
/// picker would only wait behind the first.
fn ask_open(
app: &mut VectorcraftApp,
request: PickRequest,
owner: Owner,
then: impl FnOnce(&mut VectorcraftApp, String) -> Result<Value, String> + 'static,
) -> Result<Value, String> {
if app.file_dialog_open() {
return Err(file_asks::busy().into());
}
Ok(file_asks::ask(app, request, owner, move |app, picked| match picked {
Picked::Contents(files) => {
for (name, bytes) in &files {
@@ -247,6 +253,7 @@ fn ask_open(
}
Ok(Value::Null)
}
Picked::Failed(error) => Err(error),
picked => match picked.first_path() {
Some(path) => then(app, path.to_string_lossy().into_owned()),
None => Err("cancelled".into()),
+2
View File
@@ -92,6 +92,8 @@ pub use run::{check_params, run_ui_command};
pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number};
#[cfg(test)]
use slots::RECENT_FONT_IDS;
#[cfg(test)]
pub(crate) use state::WHY_OFF_ASKED;
pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state};
pub(crate) use state::{command_shortcuts, shown_state_with, why_off};
pub(crate) use submenus::PATH_EFFECTS;
+21 -7
View File
@@ -1,7 +1,9 @@
use craft::keymap::{Chord, CommandRef};
use super::context::context_items;
use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut, spelling_item_label, unlock_item_label};
use super::labels::{display_label, dynamic_label, effect_item_label, item_shortcut_in, spelling_item_label, unlock_item_label};
use super::slots::{recent_readable, recent_slot};
use super::state::{shortcut_of, shown_state};
use super::state::{command_shortcuts, shown_state};
use super::tree::{Listed, menu_tree_named};
use super::{Node, Serialize, Value, VectorcraftApp, unbound};
@@ -32,8 +34,9 @@ pub struct MenuEntry {
/// Flattened menu for `ui.menu.list`.
pub fn menu_entries(app: &VectorcraftApp) -> Vec<MenuEntry> {
let mut out = vec![];
let chord = command_shortcuts(app);
for (title, items) in menu_tree_named(app.session.prefs.font_names_in_english, &Listed::of(app)) {
flatten(app, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out);
flatten(app, &chord, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out);
}
out
}
@@ -41,7 +44,7 @@ pub fn menu_entries(app: &VectorcraftApp) -> Vec<MenuEntry> {
/// Flattened canvas context menu for `ui.contextMenu.list` (paths are its submenus).
pub fn context_entries(app: &VectorcraftApp) -> Vec<MenuEntry> {
let mut out = vec![];
flatten(app, vec![], vec![], &context_items(app), &mut out);
flatten(app, &command_shortcuts(app), vec![], vec![], &context_items(app), &mut out);
out
}
@@ -166,7 +169,15 @@ pub fn insertable_items(english_names: bool, listed: &Listed) -> Vec<InsertableI
out
}
pub(super) fn flatten(app: &VectorcraftApp, path: Vec<String>, shown: Vec<String>, nodes: &[Node], out: &mut Vec<MenuEntry>) {
/// `nodes` flattened into `out`, each item's shortcut looked up in `chord` ([`command_shortcuts`]).
pub(super) fn flatten(
app: &VectorcraftApp,
chord: &dyn Fn(&CommandRef) -> Option<Chord>,
path: Vec<String>,
shown: Vec<String>,
nodes: &[Node],
out: &mut Vec<MenuEntry>,
) {
for node in nodes {
match node {
Node::Item(it) if unbound(&it.command.id) => out.push(MenuEntry {
@@ -197,7 +208,10 @@ pub(super) fn flatten(app: &VectorcraftApp, path: Vec<String>, shown: Vec<String
command: Some(id.to_string()),
params: p.clone(),
enabled,
shortcut: item_shortcut(app, id, p).or_else(|| shortcut_of(app, id)).map(|c| c.to_string()).unwrap_or_default(),
shortcut: item_shortcut_in(chord, id, p)
.or_else(|| chord(&crate::keymap::command_of(id)))
.map(|c| c.to_string())
.unwrap_or_default(),
shown_path: shown.clone(),
})
}
@@ -209,7 +223,7 @@ pub(super) fn flatten(app: &VectorcraftApp, path: Vec<String>, shown: Vec<String
let mut s = shown.clone();
let own = super::labels::holds_plugin_commands(children) || crate::scripts_menu::is_folder(children);
s.push(if own { label.clone() } else { crate::i18n::tr(crate::i18n::current(), label).to_string() });
flatten(app, p, s, children, out);
flatten(app, chord, p, s, children, out);
}
_ => {}
}
+86 -20
View File
@@ -89,8 +89,10 @@ pub(crate) fn translate_label(english: &'static str) -> String {
/// button pressed or released or a key pressed ([`last_press`]), changes once for each, which covers what the hash
/// doesn't list (panels shown, a tool picked). While an
/// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's
/// preview, or a typing session), the revision, which each of its previews changes, is left out:
/// the hash changes as the interaction begins and as it ends.
/// preview, or a typing session), the hash takes the revision the interaction began from in place of the current one,
/// which each of its previews changes, and changes as it ends. The hash stays the same as a tool's drag begins. An
/// interaction that a dialog, a panel or the font menu begins changes the hash as it begins, since commands that check
/// for an open interaction change state then and the menus stay open while it previews.
pub(crate) fn state_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
let mut h = DefaultHasher::new();
input.hash(&mut h);
@@ -101,8 +103,9 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option<u64>) -> u64 {
let s = &app.session;
(s.journal.len(), s.active_index(), s.clipboard.is_empty(), s.tool_composing()).hash(&mut h);
if let Some(d) = s.active() {
let revision = d.interaction.is_none().then_some(d.revision);
(d.uid, revision, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h);
let revision = d.interaction.as_ref().map_or(d.revision, |it| it.revision);
let previewing = d.interaction.as_ref().is_some_and(|it| !it.by_tool());
(d.uid, revision, previewing, d.history.undo.len(), d.history.redo.len(), d.transparency_grid, d.print_tiling).hash(&mut h);
}
(app.system_paste, app.last_effect.is_some(), app.ui.recent_files.len(), app.ui.recent_files.first(), app.recent_fonts().len()).hash(&mut h);
// Apply Last Filter and Last Filter… are named after the filter that ran last.
@@ -257,7 +260,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
// The Glyphs panel menu's East Asian glyph forms read the faces that draw the selected text from the layout this keeps.
crate::panels::glyphs::refresh_form_faces(app);
let listed = Listed::of(app);
let mut build = Build { app, lang: crate::i18n::current(), states: CommandStates::new(), refs: Vec::new() };
let mut build = Build { app, lang: crate::i18n::current(), states: CommandStates::new(), refs: Vec::new(), checks: Checks::default() };
let menus: Vec<Menu> = menu_tree_named(app.session.prefs.font_names_in_english, &listed)
.into_iter()
.map(|(title, nodes)| {
@@ -267,7 +270,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
if translated { menu.english(title) } else { menu }
})
.collect();
let Build { mut states, refs, .. } = build;
let Build { mut states, refs, mut checks, .. } = build;
// The catalog is built again only when what its rows are made from changed; edits and selection changes change
// the rows' states alone.
@@ -291,7 +294,7 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) {
CatalogRows { inputs, defs, known, accepted }
}
};
row_states(app, &rows, &mut states);
row_states(app, &rows, &mut states, &mut checks);
crate::panels::panel_menu_states(app, &mut states);
let bar = MenuBar::new(menus);
@@ -395,10 +398,10 @@ fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft:
/// The state of every catalog row the tree did not set, and of the engine commands the palette lists that no row
/// names.
fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStates) {
fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStates, checks: &mut Checks) {
for d in &rows.defs {
if states.get(&d.command).is_none() {
states.set(d.command.clone(), row_state(app, &d.command, &d.label));
states.set(d.command.clone(), row_state(app, &d.command, &d.label, checks));
}
}
// The engine commands the palette lists and no row names (Asset Export's Remove and Rename) are dimmed there and say
@@ -406,11 +409,28 @@ fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStat
for c in crate::palette::listed_engine_commands().filter(|c| !rows.known.contains(c.id)) {
let command = CommandRef::new(c.id);
if states.get(&command).is_none() {
states.set(command.clone(), row_state(app, &command, c.label));
states.set(command.clone(), row_state(app, &command, c.label, checks));
}
}
}
/// What [`why_off`] answered for each command id during one rebuild. The answer depends on the id and the app's state,
/// not on the row's params, so the rows that share an id (Effect's dialogs, Window's panels, the interface languages)
/// run their command's check once.
#[derive(Default)]
struct Checks(std::collections::HashMap<String, Option<Option<String>>>);
impl Checks {
fn why_off(&mut self, app: &VectorcraftApp, id: &str) -> Option<Option<String>> {
if let Some(why) = self.0.get(id) {
return why.clone();
}
let why = why_off(app, id);
self.0.insert(id.to_owned(), why.clone());
why
}
}
/// `defs` without the commands a linked framework set defines (Undo, Redo, Cut, Copy, Paste and Tab's panels toggles):
/// the set's definition is the command's. With them, the keys each has beyond the set's, as the set's keys and those
/// (Cut, Copy and Paste's F2, F3 and F4 outside macOS).
@@ -445,10 +465,9 @@ fn linked_defaults(command: &CommandRef) -> Option<Vec<Binding>> {
/// The state of the row `command`, named `label` in the catalog: on or dimmed with its reason, checked, and its title
/// where the app shows another.
fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> CommandState {
fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str, checks: &mut Checks) -> CommandState {
let state_id = crate::keymap::state_id(command);
let why = why_off(app, state_id);
let (enabled, checked) = shown_state_with(app, state_id, &command.params, &why).unwrap_or((false, None));
let (enabled, checked) = shown_state_with(app, state_id, &command.params, &mut |id| checks.why_off(app, id)).unwrap_or((false, None));
let mut state = CommandState::new().enabled(enabled);
if let Some(on) = checked {
state = state.checked(on);
@@ -458,7 +477,7 @@ fn row_state(app: &VectorcraftApp, command: &CommandRef, label: &str) -> Command
state = state.title(shown.clone());
}
if !enabled {
state = state.hint(off_reason_with(app, command, &shown, why));
state = state.hint(off_reason_with(app, command, &shown, checks.why_off(app, state_id)));
}
state
}
@@ -493,6 +512,7 @@ struct Build<'a> {
states: CommandStates,
/// Every command reference the tree holds, its English label, and whether it is checkable.
refs: Vec<(CommandRef, String, bool)>,
checks: Checks,
}
impl Build<'_> {
@@ -548,22 +568,25 @@ impl Build<'_> {
return Some(item);
}
let (id, params) = (command.id.as_str(), &command.params);
let why = why_off(self.app, id);
let (enabled, checked) = shown_state_with(self.app, id, params, &why)?;
let (app, checks) = (self.app, &mut self.checks);
let (enabled, checked) = shown_state_with(app, id, params, &mut |id| checks.why_off(app, id))?;
let title = self.item_title(id, params, &item.label);
let mut state = CommandState::new().enabled(enabled).title(title.clone());
if let Some(on) = checked {
state = state.checked(on);
}
let mut item = item;
let tip = if id == "ui.expandDialog" && vectorcraft_engine::cmd::expand::has_appearance(&self.app.session) {
Some(crate::i18n::tr(self.lang, crate::dialogs::expand::appearance_first()).to_string())
// Expand… dimmed for appearance attributes says so in its tooltip; `why` holds what its check found, kept from
// the state above.
let appearance_first = crate::dialogs::expand::appearance_first();
let why = if id == "ui.expandDialog" { self.checks.why_off(self.app, id) } else { None };
let tip = if why.as_ref().is_some_and(|w| w.as_deref() == Some(appearance_first)) {
Some(crate::i18n::tr(self.lang, appearance_first).to_string())
} else if enabled {
None
} else {
// The reason reads the check of the command's state id, which is `id` but for the framework's own rows.
let state_id = crate::keymap::state_id(&command);
let why = if state_id == id { why } else { why_off(self.app, state_id) };
let why = self.checks.why_off(self.app, crate::keymap::state_id(&command));
Some(off_reason_with(self.app, &command, &title, why))
};
if let Some(tip) = tip {
@@ -658,6 +681,23 @@ mod tests {
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled));
}
/// A rebuild runs the check of a command that many rows share once: Effect's dialogs, Window's panels, the
/// interface languages and Envelope Distort's Release, which decides whether Make or Reset is shown.
#[test]
fn a_rebuild_checks_a_shared_command_once() {
let (mut app, ctx) = app_with_document();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap();
app.run("select.all", json!({})).unwrap();
super::super::state::WHY_OFF_ASKED.with_borrow_mut(Vec::clear);
refresh(&mut app, &ctx);
let asked = super::super::state::WHY_OFF_ASKED.take();
for id in ["effect.dialog", "window.panel", "app.language", "object.envelope.release"] {
assert_eq!(asked.iter().filter(|a| *a == id).count(), 1, "{id}");
}
assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled), "the states follow the selection");
}
/// A rebuild asks each dimmed row's command once whether it can run, for its state and its reason together.
#[test]
fn a_rebuild_checks_each_dimmed_row_once() {
@@ -677,4 +717,30 @@ mod tests {
assert!(app.menus.states.get(&CommandRef::new(id)).is_some_and(|s| !s.is_enabled()), "{id} is still dimmed");
}
}
/// A rebuild walks the selection's appearance once for Object › Expand…, for its state and its tooltip together.
#[test]
fn a_rebuild_walks_the_appearance_once_for_expand() {
let (mut app, ctx) = app_with_document();
let expand = CommandRef::new("ui.expandDialog");
let tooltip = |app: &VectorcraftApp| app.menus.bar.items().into_iter().find(|it| it.command == expand).and_then(|it| it.tooltip.clone());
let walks = |app: &mut VectorcraftApp| {
super::super::state::APPEARANCE_WALKS.set(0);
refresh(app, &ctx);
super::super::state::APPEARANCE_WALKS.get()
};
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
assert_eq!(walks(&mut app), 1, "a plain rectangle");
assert!(app.menus.states.get(&expand).is_some_and(CommandState::is_enabled));
assert_eq!(tooltip(&app), None);
app.run("appearance.addFill", json!({})).unwrap();
assert_eq!(walks(&mut app), 1, "two fills");
assert!(app.menus.states.get(&expand).is_some_and(|s| !s.is_enabled()));
assert_eq!(tooltip(&app).as_deref(), Some(crate::dialogs::expand::appearance_first()));
app.run("select.none", json!({})).unwrap();
assert_eq!(walks(&mut app), 0, "nothing selected");
// Dimmed with nothing selected, the row keeps the general reason as its tooltip, as before.
let tip = tooltip(&app);
assert!(tip.as_deref().is_some_and(|t| t != crate::dialogs::expand::appearance_first()), "{tip:?}");
}
}
-1
View File
@@ -27,7 +27,6 @@ pub(crate) fn run(app: &mut VectorcraftApp, ctx: &egui::Context) {
let gate =
Gate::default().modal(app.file_dialog_open()).recording_shortcut(recording_shortcut(app)).text_editing(ctx.egui_wants_keyboard_input());
let Some(menu) = app.services.native_menu.as_mut() else { return };
menu.poll(ctx);
menu.set_gate(gate);
let clicks = menu.take_clicks(ctx);
// A menu opening reads the Scripts folder again.
+35 -12
View File
@@ -153,13 +153,14 @@ pub(super) fn hidden_when_disabled(id: &str) -> bool {
/// Menu items another item stands in for right now: Envelope Distort's Reset with Warp and Reset
/// with Mesh take the place of Make with Warp and Make with Mesh while an envelope is selected.
fn swapped_out(app: &VectorcraftApp, id: &str) -> bool {
/// `why_off` answers [`why_off`] for Release's id.
fn swapped_out(id: &str, why_off: &mut dyn FnMut(&str) -> Option<Option<String>>) -> bool {
let reset = match id {
"object.envelope.makeWithWarp" | "object.envelope.makeWithMesh" => false,
"object.envelope.resetWithWarp" | "object.envelope.resetWithMesh" => true,
_ => return false,
};
enabled(app, "object.envelope.release") != reset
why_off("object.envelope.release").is_none() != reset
}
/// Menu items shown only with Preferences › Type › Show East Asian Options on: Type › Composite
@@ -173,16 +174,21 @@ fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool {
/// another stands in for ([`swapped_out`]) or an East Asian item with those options hidden
/// ([`east_asian_hidden`]).
pub fn shown_state(app: &VectorcraftApp, id: &str, p: &Value) -> Option<(bool, Option<bool>)> {
shown_state_with(app, id, p, &why_off(app, id))
shown_state_with(app, id, p, &mut |id| why_off(app, id))
}
/// [`shown_state`] from `why`, what [`why_off`] answered for `id`: a caller that also writes the reason a dimmed row
/// gives runs the command's check once.
pub(crate) fn shown_state_with(app: &VectorcraftApp, id: &str, p: &Value, why: &Option<Option<String>>) -> Option<(bool, Option<bool>)> {
let en = why.is_none()
/// [`shown_state`] with `why_off` answering [`why_off`] for each command id it asks about: a caller that keeps the
/// answers runs each command's check once.
pub(crate) fn shown_state_with(
app: &VectorcraftApp,
id: &str,
p: &Value,
why_off: &mut dyn FnMut(&str) -> Option<Option<String>>,
) -> Option<(bool, Option<bool>)> {
let en = why_off(id).is_none()
&& (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p))
&& (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p));
if (!en && hidden_when_disabled(id)) || swapped_out(app, id) || east_asian_hidden(app, id) {
if (!en && hidden_when_disabled(id)) || swapped_out(id, why_off) || east_asian_hidden(app, id) {
return None;
}
Some((en, checked(app, id, p)))
@@ -295,9 +301,30 @@ pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option<Option<String>>
Err(why) => Some(Some(why)),
};
}
if id == "ui.expandDialog" {
return expand_dialog_off(app);
}
(!ui_enabled(app, id)).then_some(None)
}
#[cfg(test)]
thread_local! {
/// How many times [`expand_dialog_off`] walked the selection's appearance on this thread.
pub(crate) static APPEARANCE_WALKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Why Object › Expand… can't open now: dimmed with nothing selected, and with
/// [`crate::dialogs::expand::appearance_first`] for appearance attributes, which Expand Appearance expands first
/// (#3089). The selection's appearance is walked once, for the row's state and its tooltip together.
fn expand_dialog_off(app: &VectorcraftApp) -> Option<Option<String>> {
if !app.session.active().is_some_and(|d| !d.selection.is_empty()) {
return Some(None);
}
#[cfg(test)]
APPEARANCE_WALKS.set(APPEARANCE_WALKS.get() + 1);
vectorcraft_engine::cmd::expand::has_appearance(&app.session).then(|| Some(crate::dialogs::expand::appearance_first().to_string()))
}
/// Can UI command `id` run now?
fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool {
match id {
@@ -388,10 +415,6 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool {
id if id.starts_with(crate::panels::symbols::USER_SLOT) => crate::panels::symbols::user_library(app, id).is_some(),
"ui.saveBrushLibrary" => crate::panels::brushes::has_brushes(app),
id if id.starts_with(crate::panels::brushes::USER_SLOT) => crate::panels::brushes::user_library(app, id).is_some(),
// Dimmed for appearance attributes, which Expand Appearance expands first (#3089).
"ui.expandDialog" => {
app.session.active().is_some_and(|d| !d.selection.is_empty()) && !vectorcraft_engine::cmd::expand::has_appearance(&app.session)
}
"ui.spotColors" => app.session.active().is_some(),
"ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
"ui.simplifyAuto" | "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::showing(app),
+40 -4
View File
@@ -164,15 +164,29 @@ fn snapping_menu_clicks_toggle_view_state_and_painted_checkmarks() {
assert_eq!(menu.toggled("Pixel Snapping Options…"), None);
}
/// A key press builds the menus' states again once: the frames after it, with no press, keep them.
#[test]
fn a_key_press_rebuilds_the_menus_once() {
/// An app with a new document whose installed fonts are cataloged, after the frames that build its first menus and the
/// window's keymap. It runs in a process of its own ([`crate::testing::in_own_process`]): the menus' key holds the
/// installed plug-ins' revision and the fonts' generation, which are the whole process's, so a plug-in that another test
/// installs, or a font it adds, rebuilds this app's menus. `None` in the parent process.
fn settled_app(test: &str) -> Option<(VectorcraftApp, egui::Context)> {
if !crate::testing::in_own_process(test) {
return None;
}
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
// The scan of the installed fonts, which the app starts, changes the fonts' generation when it ends: wait for it.
vectorcraft_text::FontDb::global().family_list();
app.run("file.new", json!({})).unwrap();
let ctx = crate::testing::ui_context();
for _ in 0..3 {
app_frame(&mut app, &ctx, vec![]);
}
Some((app, ctx))
}
/// A key press builds the menus' states again once: the frames after it, with no press, keep them.
#[test]
fn a_key_press_rebuilds_the_menus_once() {
let Some((mut app, ctx)) = settled_app("menus::tests::a_key_press_rebuilds_the_menus_once") else { return };
let before = app.menus.rebuilds;
for _ in 0..3 {
app_frame(&mut app, &ctx, vec![]);
@@ -187,6 +201,28 @@ fn a_key_press_rebuilds_the_menus_once() {
assert_eq!(app.menus.rebuilds, before + 1);
}
/// A font added to the fonts the whole process shares builds the menus again with no input, Type › Font then lists it,
/// and the idle frames after that keep the menus.
#[test]
fn a_new_font_rebuilds_the_menus() {
const FAMILY: &str = "Menurebuild Sans";
let Some((mut app, ctx)) = settled_app("menus::tests::a_new_font_rebuilds_the_menus") else { return };
let lists =
|app: &VectorcraftApp| app.menus.bar.items().into_iter().any(|it| it.command.id == "text.setStyle" && it.command.params["font"] == FAMILY);
assert!(!lists(&app));
let font = vectorcraft_text::test_fonts::named_copy(false, (FAMILY, "Regular", "Version 1.000", "MenurebuildSans-Regular"));
let before = app.menus.rebuilds;
assert_eq!(vectorcraft_text::FontDb::global().add_font(font.expect("the test font builds")), 1);
app_frame(&mut app, &ctx, vec![]);
assert!(app.menus.rebuilds > before, "the new font rebuilds the menus");
assert!(lists(&app), "Type › Font lists {FAMILY}");
let after = app.menus.rebuilds;
for _ in 0..3 {
app_frame(&mut app, &ctx, vec![]);
}
assert_eq!(app.menus.rebuilds, after, "idle frames keep the menus");
}
#[test]
fn help_f1_opens_discover_without_a_document() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
@@ -401,7 +437,7 @@ fn menu_entry_shown_paths_keep_script_folder_names() {
let items = vec![sub("Scripts", vec![sub("File", folder), cp("Other Script…", "ui.runScript", Value::Null)])];
let mut out = vec![];
crate::i18n::set_current(de);
flatten(&app, vec!["File".into()], vec![crate::i18n::t("File").into()], &items, &mut out);
flatten(&app, &super::command_shortcuts(&app), vec!["File".into()], vec![crate::i18n::t("File").into()], &items, &mut out);
crate::i18n::set_current(crate::i18n::Lang::EN);
let script = out.iter().find(|e| e.command.as_deref() == Some(crate::scripts_menu::COMMAND)).unwrap();
assert_eq!(script.path, ["File", "Scripts", "File"]);
+1
View File
@@ -858,6 +858,7 @@ pub(super) fn transform_items() -> Vec<Node> {
c("Shear…", "object.shear"),
Sep,
c("Transform Each…", "object.transformEach"),
c("Step and Repeat…", "object.stepAndRepeat"),
Sep,
c("Reset Bounding Box", "object.resetBoundingBox"),
cp("Rotate Bounding Box…", "object.rotateBoundingBox", json!({"angle": 0})),
+1 -1
View File
@@ -1193,7 +1193,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"tool.options",
"Tool Options…",
"",
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `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 `command` running type.pathOptions; 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 sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, Line truncated
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `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 `command` running type.pathOptions; 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 sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, Line truncated
),
(
"ui.colorGuideOptions",
+26 -9
View File
@@ -1753,8 +1753,8 @@ mod tests {
/// the menu bar, and commands that need a value no menu item gives, with a menu path of their own
/// or without one. A pick of each one it leaves
/// out (with no document, one object selected or several) changes neither the document, its
/// selection, history and layer state, nor the interface. Every [`PICK_RUNS`] query is still
/// listed.
/// selection, history and layer state, the tool's state, nor the interface. Every [`PICK_RUNS`]
/// query is still listed.
#[test]
fn the_palette_leaves_out_the_commands_a_pick_cannot_run() {
let ui_ids: std::collections::HashSet<&str> = menus::UI_COMMANDS.iter().map(|c| c.0).collect();
@@ -1785,16 +1785,33 @@ mod tests {
(st.doc.clone(), format!("{:?}", st.selection), st.history.undo.len(), st.revision, st.active_layer, st.layer_rows.clone())
});
// A modeless dialog (Find and Replace) blocks nothing, so `any_dialog_open` leaves it out: the host lists it.
(doc, app.session.script_console().lines().len(), (app.any_dialog_open(), crate::tests::picks::open_dialogs(app).len()), ui)
// The tool's own state: the tool, a gesture or an input method's text in progress, and an interaction the
// session holds open.
let tool = (app.session.tool_id().to_owned(), app.session.tool_composing(), app.session.pointer_held(), app.session.in_interaction());
(doc, app.session.script_console().lines().len(), (app.any_dialog_open(), crate::tests::picks::open_dialogs(app).len()), ui, tool)
};
let acts = |id: &str| {
[Session::new(), Fixture::Single.session(), Fixture::Multi.session()].into_iter().any(|session| {
let mut app = app_on(session);
let before = look(&app);
pick(&mut app, id);
look(&app) != before
// One app for each of the three cases, picked in one after another while a pick changes nothing that `look`
// sees; a pick that changes something is recorded, and its case starts again from a new app.
let fresh = |case: usize| {
app_on(match case {
0 => Session::new(),
1 => Fixture::Single.session(),
_ => Fixture::Multi.session(),
})
};
let mut apps: Vec<VectorcraftApp> = (0..3).map(fresh).collect();
let mut acts = |id: &str| {
let mut changed = false;
for (case, app) in apps.iter_mut().enumerate() {
let before = look(app);
pick(app, id);
if look(app) != before {
changed = true;
*app = fresh(case);
}
}
changed
};
let changed: Vec<&str> = ids.iter().copied().filter(|id| acts(id)).collect();
assert!(changed.is_empty(), "a pick of these does something: {changed:?}");
for c in &dropped {
+48 -1
View File
@@ -681,13 +681,35 @@ pub(crate) fn mixed_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (bool,
match pstate::<Option<(Key, (bool, bool))>>(ctx, "proxy-mixed") {
Some((k, mixed)) if k == key => mixed,
_ => {
let mixed = app.session.proxy_mixed();
let mixed = walk_mixed_paints(app);
set_pstate(ctx, "proxy-mixed", Some((key, mixed)));
mixed
}
}
}
/// [`mixed_paints`] for readers without a `Ui`, such as the panel menus' states: from the same cache while the app
/// has its interface context, else from a walk of the selection.
pub(crate) fn mixed_paints_now(app: &VectorcraftApp) -> (bool, bool) {
match &app.ui_ctx {
Some(ctx) => mixed_paints(app, ctx),
None => walk_mixed_paints(app),
}
}
/// [`vectorcraft_engine::Session::proxy_mixed`], which walks the selection.
fn walk_mixed_paints(app: &VectorcraftApp) -> (bool, bool) {
#[cfg(test)]
MIXED_PAINT_WALKS.set(MIXED_PAINT_WALKS.get() + 1);
app.session.proxy_mixed()
}
#[cfg(test)]
thread_local! {
/// How many times [`walk_mixed_paints`] walked the selection on this thread.
pub(crate) static MIXED_PAINT_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// The stroke the Stroke panel, Control bar and Properties show: while the Type tool edits text,
/// the selected characters' stroke, else [`vectorcraft_engine::Session::shown_stroke`].
pub(crate) fn current_stroke(app: &VectorcraftApp) -> Option<StrokeLayer> {
@@ -1108,6 +1130,31 @@ pub(crate) fn popover_body<R>(ui: &mut Ui, mut body: impl FnMut(&mut Ui) -> R) -
mod tests {
use super::*;
/// The panel menus' states (the Color and Color Wheel menus) read whether the fill and stroke differ from the
/// proxies' cache: one walk of the selection for each revision, which the proxies read too.
#[test]
fn panel_menu_states_walk_the_mixed_paints_once_per_revision() {
let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let ctx = crate::testing::ui_context();
app.adopt_context(&ctx);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
for x in [10, 60, 110] {
app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap();
}
app.run("select.all", json!({})).unwrap();
let walks = || MIXED_PAINT_WALKS.get();
let start = walks();
let mut states = CommandStates::new();
panel_menu_states(&app, &mut states);
assert_eq!(walks(), start + 1, "the menus walk the selection once");
panel_menu_states(&app, &mut states);
assert_eq!(mixed_paints(&app, &ctx), (false, false));
assert_eq!(walks(), start + 1, "the same revision is not walked again, by the menus or the proxies");
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
panel_menu_states(&app, &mut states);
assert_eq!(walks(), start + 2, "an edit is walked again");
}
#[test]
fn proxy_events_run_their_commands() {
let ran = |activated, double, swap, defaults| -> Vec<(&'static str, Value)> { proxy_commands(activated, double, swap, defaults) };
@@ -927,8 +927,10 @@ fn insert_menu_item_refuses_what_no_menu_item_runs_and_changes_nothing() {
fn every_listed_menu_item_runs_from_the_menu_what_its_step_holds() {
// The View menu's proof items change the whole process's proof view.
let _view = crate::testing::DefaultProofView::new();
// A new app for each item, all in one window.
let window = crate::testing::window_context();
for item in crate::menus::insertable_items(false, &crate::menus::Listed::default()) {
let (mut app, _) = app_with_three_moves();
let (mut app, _) = three_moves_in(new_app_in(&window));
app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": item.command, "params": item.params})).unwrap();
let held = steps(&app, 0, 0)[3].1.clone();
let start = app.session.journal.len();
@@ -89,7 +89,9 @@ fn actions_play_on_the_artboard_active_when_they_play() {
app.ui.actions.push(Action { set, ..Action::new(name, steps) }).unwrap();
set_actions(app, 0).len() - 1
};
app.view_mut().unwrap().artboard = 1;
app.run("edit.copy", json!({})).unwrap();
app.view_mut().unwrap().artboard = 0;
let align = record(&mut app, "Align Left", "object.align", json!({"horizontal": "left", "to": "artboard"}));
assert_eq!(bounds(&app, &[rect]).x0, boards[0].x0, "aligned to artboard 0 while recording");
let paste = record(&mut app, "Paste in Place", "edit.pasteInPlace", json!({}));
@@ -20,9 +20,14 @@ use crate::VectorcraftApp;
/// An app with the built-in set, in a window whose dialog host the tests drive and which has drawn its first frame, so
/// the window's keymap holds the app's commands.
pub(crate) fn new_app() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let ctx = app.ui_ctx.clone().expect("a window");
crate::testing::app_frame(&mut app, &ctx, Default::default());
new_app_in(&crate::testing::window_context())
}
/// [`new_app`] in the window of `ctx` ([`crate::testing::window_context`]), which a test can reuse for a new app at
/// each step.
pub(crate) fn new_app_in(ctx: &egui::Context) -> VectorcraftApp {
let mut app = crate::testing::windowed_in(VectorcraftApp::new(Session::new(), Default::default()), ctx);
crate::testing::app_frame(&mut app, ctx, Default::default());
app
}
@@ -251,7 +256,11 @@ pub(crate) fn cancel_dialog<D: StackDialog>(app: &mut VectorcraftApp) {
/// A document with one rectangle selected and the set "Moves" with one action that moves it
/// right three times, by 1, 2 and 4 pt → (the app, the rectangle's left edge as it moves).
pub(crate) fn app_with_three_moves() -> (VectorcraftApp, impl Fn(&VectorcraftApp) -> f64) {
let mut app = new_app();
three_moves_in(new_app())
}
/// [`app_with_three_moves`] made from `app`, a new app such as [`new_app_in`] gives.
pub(crate) fn three_moves_in(mut app: VectorcraftApp) -> (VectorcraftApp, impl Fn(&VectorcraftApp) -> f64) {
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let id =
vectorcraft_doc::NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
+17 -8
View File
@@ -34,8 +34,8 @@ use craft::theme::Variant;
use craft::theme::variant::Tone;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::contract::{
Bind, CollectionEvent, Entry, Props as _, RowAlign, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, TooltipSpec, clicked,
request_rename,
Bind, CollectionEvent, Entry, Props as _, RowAlign, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, TooltipSpec,
clicked, request_rename,
};
use craft::ui::dialog::StackDialog as _;
use craft::ui::display::{Divider, Shade, Text};
@@ -524,13 +524,22 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let (selection, saving) = (&mut model.selection, &mut model.saving);
let (mut export_clicked, mut footer, mut screens) = (false, None, false);
// The grid takes the room the settings, Export and the footer bar leave.
// The settings scroll in at most half the panel's height, so a long list of format rows stays reachable.
// The preset name row stays below them, in view when Save As Preset opens it.
let settings_room = ui.available_height() / 2.0;
let settings_id = ui.scope_id().with(("asset-export-settings", uid));
let footed = Stack::new().fill().footer(|ui, _| {
crate::panels::section(tl!("Export Settings")).show(ui, |ui, _| {
let (change, files_each) = settings(ui, st);
(seen.change, seen.files_each) = (change, files_each);
seen.format_3d = format_3d(ui, st, &sel_or_all(&shown_sel, &all));
seen.save = save_row(ui, saving);
});
Stack::new().id(settings_id).label(tl!("Export Settings")).fill_width().scroll(Scroll::vertical()).room_height(settings_room).show(
ui,
|ui, _| {
crate::panels::section(tl!("Export Settings")).show(ui, |ui, _| {
let (change, files_each) = settings(ui, st);
(seen.change, seen.files_each) = (change, files_each);
seen.format_3d = format_3d(ui, st, &sel_or_all(&shown_sel, &all));
});
},
);
seen.save = save_row(ui, saving);
Row::new().fill_width().align(RowAlign::End).show(ui, |ui, _| {
let label = if shown_sel.is_empty() || shown_sel.len() == all.len() {
tl!("Export").to_string()
+16 -12
View File
@@ -6,7 +6,6 @@ use std::cell::RefCell;
use std::collections::HashSet;
use std::rc::Rc;
use std::sync::{Arc, Mutex, Weak};
use std::time::SystemTime;
// PLAN: assumed the framework paths below (craft::text::ui re-exports, craft_ui widgets and runtime, craft::font_manager).
use craft::behavior::EditEvent;
@@ -47,12 +46,15 @@ use crate::font_menu;
/// attributes of the paragraph the selection starts in (else of the first paragraph).
/// Font/paragraph controls and named-style capture use this; dimensional fields use `shared_effective`.
pub(crate) fn text_style(app: &VectorcraftApp) -> Option<(CharStyle, vectorcraft_doc::ParaStyle)> {
let state = app.session.active()?;
// Hover changes the canvas, but the picker compares its next row click against the committed font.
let doc = state.interaction.as_ref().filter(|_| app.font_preview_owner.is_some()).map_or(&state.doc, |preview| &preview.doc);
if let Some((id, a, b)) = text_editing(app)
&& let Some(NodeKind::Text(t)) = app.session.active().and_then(|d| d.doc.node(id)).map(|n| &n.kind)
&& let Some(NodeKind::Text(t)) = doc.node(id).map(|n| &n.kind)
{
return Some((vectorcraft_text::edit::insertion_style(&t.runs, a, b), t.para_at(t.paragraphs_in(a, a).start).clone()));
}
let t = first_selected_text(app)?;
let NodeKind::Text(t) = &first_selected_text_node_in(state, doc)?.kind else { return None };
Some((t.first_style(), t.para_at(0).clone()))
}
@@ -68,7 +70,11 @@ pub(crate) fn first_selected_text(app: &VectorcraftApp) -> Option<&vectorcraft_d
/// their descendants, in selection order, then paint order within each selected object.
pub(crate) fn first_selected_text_node(app: &VectorcraftApp) -> Option<&vectorcraft_doc::Node> {
let st = app.session.active()?;
for node in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) {
first_selected_text_node_in(st, &st.doc)
}
fn first_selected_text_node_in<'a>(state: &DocState, doc: &'a vectorcraft_doc::Document) -> Option<&'a vectorcraft_doc::Node> {
for node in state.selection.objects.iter().filter_map(|id| doc.node(*id)) {
let mut text = None;
node.walk(&mut |n| {
if text.is_none() && matches!(n.kind, NodeKind::Text(_)) {
@@ -1219,16 +1225,14 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow
let languages: Option<Vec<(String, String)>> =
rows.contains(CharacterRows::STYLE_TOGGLES).then(|| LANGUAGES.iter().map(|(name, _, _)| (name.to_string(), name.to_string())).collect());
let catalog = vectorcraft_text::FontDb::global().catalog();
let before = font_menu::picker_settings(app);
let mut settings = before.clone();
let document = font_menu::document_family_set(app);
let recent = font_menu::recently_added_set(app, SystemTime::now());
let sets = font_menu::family_sets(Some(&document[..]), &recent[..]);
let mut hold = font_menu::hold(app);
let before = hold.settings.clone();
let sets = font_menu::family_sets(hold.document.as_deref(), &hold.recently_added);
let sample = font_menu::sample_text(app);
let unit = type_unit(app);
let mut source = FontPickerSource::new(catalog)
.settings(Bind::bound(&mut settings))
.filters(Bind::bound(&mut app.ui.font_filters))
.settings(Bind::bound(&mut hold.settings))
.filters(Bind::bound(&mut hold.filters))
.sets(&sets)
.scripts(&FontScript::ALL)
.filter_layout(FilterLayout::Toolbar);
@@ -1248,7 +1252,7 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow
controls = controls.axes(FaceAxes::new(axes, instances).italic(face_of(&current.font_style).2));
}
let out = controls.show(ui);
font_menu::store_picker_settings(app, &before, settings);
hold.store(app, &before);
let CharacterControlsOutput { picker, preview_family, edits, .. } = out;
if let Some(owner) = picker {
font_menu::apply_preview(app, owner, preview_family);
+7 -6
View File
@@ -314,14 +314,14 @@ fn target(app: &VectorcraftApp, ui: &Ui) -> Target {
target_with(app, super::active_mixed(app, ui.ctx()))
}
/// Whether the active proxy is "?", read from the session (the panel reads its per-frame cache).
/// Whether the active proxy is "?", from the proxies' cache ([`super::mixed_paints_now`]).
fn mixed_now(app: &VectorcraftApp) -> bool {
let (fill, stroke) = app.session.proxy_mixed();
let (fill, stroke) = super::mixed_paints_now(app);
if app.session.fill_active { fill } else { stroke }
}
/// [`target`] with `mixed` for a "?" active proxy: the panel reads it from its per-frame cache,
/// `ui.colorPanel` from the session.
/// `ui.colorPanel` and the panel menus through [`mixed_now`].
fn target_with(app: &VectorcraftApp, mixed: bool) -> Target {
if mixed {
return Target::Paint(None, None);
@@ -440,7 +440,7 @@ pub(crate) fn apply_output(app: &mut VectorcraftApp, out: &ColorPanelOutput) {
apply_with(app, &tgt, out);
}
/// [`target`] with the session's "?" state, for callers without the panel's pass.
/// [`target`] with the "?" state of [`mixed_now`], for callers without the panel's pass.
pub(crate) fn target_now(app: &VectorcraftApp) -> Target {
target_with(app, mixed_now(app))
}
@@ -616,8 +616,9 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
/// The checks, titles and enabled states of [`menu_rows`]: the mode the panel shows is checked, and
/// the rows that need a colour are off without one.
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
let tgt = target_now(app);
let has_color = tgt.color().is_some() || mixed_now(app);
let mixed = mixed_now(app);
let tgt = target_with(app, mixed);
let has_color = tgt.color().is_some() || mixed;
for (command, state) in ColorPanelMenu::states(LAYOUT, &app.ui.color_panel, &shown(app, &tgt), has_color) {
let state = if command == ColorPanelCommand::NewSwatch && !crate::menus::enabled(app, "swatch.new") { state.enabled(false) } else { state };
states.set(command, state);
+3 -2
View File
@@ -618,14 +618,15 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
/// without a solid color, and CSS oklch() also while the active document's RGB space is not sRGB.
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
let srgb = cms::active().rgb_is_srgb();
for item in items(&app.ui.color_wheel, srgb, target_now(app).color()) {
let color = target_now(app).color();
for item in items(&app.ui.color_wheel, srgb, color) {
let mut state = CommandState::new().title(item.label).enabled(item.enabled).checked(item.checked);
if let Some(hint) = item.hint {
state = state.hint(hint);
}
states.set(CommandRef::new(row_id(&item.id)), state);
}
let has_color = target_now(app).color().is_some();
let has_color = color.is_some();
for (notation, label) in copy_notations() {
let oklch = notation == "oklch";
let mut state = CommandState::new().title(label.to_string()).enabled(has_color && (srgb || !oklch));
+8 -2
View File
@@ -52,7 +52,12 @@ pub struct View {
/// The text of a tool's shortcut in the window's keymap, empty when it has none.
fn tool_shortcut(app: &VectorcraftApp, id: &str) -> String {
menus::shortcut_of(app, &format!("tool:{id}")).map_or_else(String::new, |chord| chord.display(crate::keymap::platform()))
tool_shortcut_in(&menus::command_shortcuts(app), id)
}
/// [`tool_shortcut`] looked up in `chord` ([`menus::command_shortcuts`]).
fn tool_shortcut_in(chord: &dyn Fn(&craft::keymap::CommandRef) -> Option<craft::keymap::Chord>, id: &str) -> String {
chord(&crate::keymap::command_of(&format!("tool:{id}"))).map_or_else(String::new, |chord| chord.display(crate::keymap::platform()))
}
/// Updates the retained results' labels, menu paths and shortcuts after the menu state changes (a
@@ -109,6 +114,7 @@ fn refresh(app: &mut VectorcraftApp) {
/// The tools, each with the entry the search ranks it by.
fn tool_hits(app: &VectorcraftApp) -> Vec<(HelpEntry, Hit)> {
let lang = crate::i18n::current();
let chord = menus::command_shortcuts(app);
vectorcraft_tools::catalog::all_tools()
.map(|tool| {
let label: String = crate::i18n::tr(lang, tool.label).into();
@@ -120,7 +126,7 @@ fn tool_hits(app: &VectorcraftApp) -> Vec<(HelpEntry, Hit)> {
id: tool.id.into(),
label,
path: vec![],
shortcut: tool_shortcut(app, tool.id),
shortcut: tool_shortcut_in(&chord, tool.id),
english_label: tool.label.into(),
english_path: vec![],
params: Value::Null,
+12 -5
View File
@@ -88,7 +88,7 @@ impl Outcome for CellOutput {
}
}
/// A row's target circle: a ring, doubled while the row is targeted, with a dot when it has an
/// A row's target circle: a ring, doubled while the row is targeted, with a diamond when it has an
/// appearance or transparency of its own ([`target_marks`]).
#[derive(Component, Props)]
#[component(sample = TargetCircle::sample)]
@@ -107,7 +107,13 @@ pub(super) struct TargetCircle {
impl TargetCircle {
fn new(document: (u64, u64), id: NodeId, targeted: bool, styled: bool) -> Self {
Self { common: Common::new(), document, id, targeted, styled, held: false, pick: None }
let state = match (targeted, styled) {
(true, true) => tl!("Target appearance: targeted, additional appearance or transparency"),
(true, false) => tl!("Target appearance: targeted, basic appearance"),
(false, true) => tl!("Target appearance: not targeted, additional appearance or transparency"),
(false, false) => tl!("Target appearance: not targeted, basic appearance"),
};
Self { common: Common::new(), document, id, targeted, styled, held: false, pick: None }.tooltip(state).description(state).selected(targeted)
}
/// A targeted circle with an appearance, for the suite.
@@ -186,12 +192,13 @@ impl Component for TargetCircle {
let draw = ui.draw();
let (ring, width) = if self.held { (cx.style.accent, StrokeWidth::Medium) } else { (cx.style.ink, StrokeWidth::Thin) };
draw.stroke(&PaintShape::Circle(center, TARGET_RADIUS), width, ring);
let (inner, dot) = target_marks(self.targeted, self.styled);
let (inner, mark) = target_marks(self.targeted, self.styled);
if let Some(radius) = inner {
draw.stroke(&PaintShape::Circle(center, radius), StrokeWidth::Thin, cx.style.ink);
}
if let Some(radius) = dot {
draw.fill(&PaintShape::Circle(center, radius), cx.style.ink);
if let Some(radius) = mark {
let points = vec![center - vec2(0.0, radius), center + vec2(radius, 0.0), center + vec2(0.0, radius), center - vec2(radius, 0.0)];
draw.stroke(&PaintShape::Polygon(points), StrokeWidth::Thin, cx.style.ink);
}
}
+10 -13
View File
@@ -246,23 +246,20 @@ fn listed_nodes(tree: &DocLayers<'_>, filter: &LayerFilter) -> Vec<NodeId> {
pub(super) const TARGET_RADIUS: f32 = 5.0;
/// The radius of the inner ring of a targeted item's target circle (the double ring).
pub(super) const TARGET_RING: f32 = 2.8;
// PLAN: the sheet keeps `TARGET_STROKE`; the circle's rings take the theme's thin stroke (`StrokeWidth::Thin`), so it is gone.
/// The radius of the dot filling the circle of an item that has an appearance of its own and is
/// not targeted.
pub(super) const TARGET_DOT: f32 = 3.2;
/// The radius of that dot inside a targeted item's inner ring: clear of the ring, so a targeted
/// item with an appearance of its own shows both (#8711).
pub(super) const TARGET_DOT_IN_RING: f32 = 1.5;
/// The radius of the outlined diamond marking an item's own appearance or transparency.
pub(super) const APPEARANCE_MARK: f32 = 2.5;
/// A mitered thin stroke extends a diamond's corner by width / sqrt(2). Radius 1 keeps
/// the diamond clear of the targeted ring's inner edge (#8711).
pub(super) const APPEARANCE_MARK_IN_RING: f32 = 1.0;
/// The marks inside a target circle's outer ring: the inner ring's radius when the item is
/// `targeted`, and the appearance dot's radius when it is `styled` (has an appearance of its own).
/// Each of the four combinations looks different, as the Layers panel's target icons do.
/// The inner target ring's radius and the own-appearance diamond's radius. Each of the four
/// combinations differs, and the diamond inside a targeted ring leaves that ring visible.
pub(super) fn target_marks(targeted: bool, styled: bool) -> (Option<f32>, Option<f32>) {
let dot = if targeted { TARGET_DOT_IN_RING } else { TARGET_DOT };
(targeted.then_some(TARGET_RING), styled.then_some(dot))
let mark = if targeted { APPEARANCE_MARK_IN_RING } else { APPEARANCE_MARK };
(targeted.then_some(TARGET_RING), styled.then_some(mark))
}
/// Whether an object's target circle is filled: its appearance is not basic (a group or layer:
/// Whether an object's target circle shows its appearance mark: its appearance is not basic (a group or layer:
/// it has fills, strokes or effects of its own) or its transparency (opacity, blend mode,
/// isolation, knockout or an opacity mask) is not the default.
pub(super) fn has_styled_target(n: &Node) -> bool {
+155 -11
View File
@@ -74,21 +74,15 @@ fn answer(app: &mut VectorcraftApp, ctx: &egui::Context, ok: bool) {
crate::dialogs::host::pump(app, ctx);
}
/// The target-mark rule: each of the four looks (neither, targeted, an appearance, both) differs,
/// and the dot sits clear of the inner ring, drawn in the theme's thin stroke, when both show.
/// The four target/appearance combinations remain distinct, with the appearance diamond clear of
/// the inner target ring in the theme's thin stroke.
#[test]
fn target_circle_marks_follow_targeted_and_styled() {
use rows::{TARGET_DOT, TARGET_DOT_IN_RING, TARGET_RING, target_marks};
use rows::{APPEARANCE_MARK, APPEARANCE_MARK_IN_RING, TARGET_RING, target_marks};
assert_eq!(target_marks(false, false), (None, None));
assert_eq!(target_marks(true, false), (Some(TARGET_RING), None));
assert_eq!(target_marks(false, true), (None, Some(TARGET_DOT)));
let (ring, dot) = target_marks(true, true);
assert_eq!((ring, dot), (Some(TARGET_RING), Some(TARGET_DOT_IN_RING)));
let thin = std::rc::Rc::new(std::cell::Cell::new(f32::INFINITY));
let seen = std::rc::Rc::clone(&thin);
let mut fixture = craft::ui::testing::Fixture::new(move |ui| seen.set(craft::ui::runtime::env::Env::of(ui).tokens.stroke.thin));
fixture.root(crate::app::root_env(&vectorcraft_engine::Prefs::default(), 1.0, None)).frame(vec![]);
assert!(TARGET_DOT_IN_RING + 0.5 < TARGET_RING - thin.get() / 2.0, "the dot covers the ring");
assert_eq!(target_marks(false, true), (None, Some(APPEARANCE_MARK)));
assert_eq!(target_marks(true, true), (Some(TARGET_RING), Some(APPEARANCE_MARK_IN_RING)));
}
/// A document with two rectangles on one layer → (app, layer, [bottom, top]).
@@ -1329,6 +1323,156 @@ fn a_target_circle_drop_after_file_revert_leaves_the_restored_appearance_in_plac
assert_eq!(fill(&panel.app(), b), red, "a target circle drag started after the revert still moves the appearance");
}
/// The cardinal four-point outline actually painted by the native cell, independently of its constants.
fn appearance_diamond(shape: &egui::Shape) -> Option<(egui::Pos2, f32, f32)> {
let egui::Shape::Path(path) = shape else { return None };
if !path.closed || path.fill != egui::Color32::TRANSPARENT || path.points.len() != 4 {
return None;
}
let c = egui::pos2((path.points[0].x + path.points[2].x) / 2.0, (path.points[0].y + path.points[2].y) / 2.0);
let r = path.points[0].distance(c);
if ![2.5, 1.0].iter().any(|expected| (r - expected).abs() < 1e-4) {
return None;
}
let expected = [c - egui::vec2(0.0, r), c + egui::vec2(r, 0.0), c + egui::vec2(0.0, r), c - egui::vec2(r, 0.0)];
path.points.iter().zip(expected).all(|(a, b)| a.distance(b) < 1e-4).then_some((c, r, path.stroke.width))
}
/// The actual native cell's marks at `name`, read from the fixture's paint output: radius, diamond, width.
fn target_marks_painted(panel: &mut crate::tests::panel_harness::Panel, name: &str) -> Vec<(f32, bool, f32)> {
let center = panel.rect(name).center();
let (shapes, _) = panel.paint_at(1.0);
let ink = shapes
.iter()
.find_map(|shape| match shape {
egui::Shape::Circle(circle) if circle.center.distance(center) < 0.01 && (circle.radius - 5.0).abs() < 1e-4 => Some(circle.stroke.color),
_ => None,
})
.expect("the cell's outer target ring");
for shape in &shapes {
if appearance_diamond(shape).is_some_and(|(at, _, _)| at.distance(center) < 0.01)
&& let egui::Shape::Path(path) = shape
{
assert_eq!(path.stroke.color, egui::epaint::ColorMode::Solid(ink), "the native marker keeps the target ring's themed ink");
assert_eq!(path.stroke.kind, egui::StrokeKind::Middle, "the diamond's stroke is centered on its outline");
}
}
let mut marks: Vec<_> = shapes
.iter()
.filter_map(|shape| match shape {
egui::Shape::Circle(circle)
if circle.center.distance(center) < 0.01 && circle.radius < 5.0 && circle.fill == egui::Color32::TRANSPARENT =>
{
Some((circle.radius, false, circle.stroke.width))
}
shape => appearance_diamond(shape).filter(|(at, _, _)| at.distance(center) < 0.01).map(|(_, r, width)| (r, true, width)),
})
.collect();
marks.sort_by(|a, b| a.0.total_cmp(&b.0));
marks
}
/// Retain #8757's historical regression name: the own-appearance diamond leaves the actual inner
/// ring visible, and neither, targeted, styled and both paint four different looks.
#[test]
fn a_targeted_circle_with_an_appearance_shows_both_ring_and_dot() {
use crate::tests::panel_harness::Panel;
let (mut app, _, [a, _]) = two_rects();
name_row(&mut app, a, "A");
let mut panel = Panel::new(app, show);
let neither = target_marks_painted(&mut panel, "Target A");
panel.click("Target A");
let targeted = target_marks_painted(&mut panel, "Target A");
panel.app().session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap();
panel.frame();
let both = target_marks_painted(&mut panel, "Target A");
panel.app().session.execute("select.none", &json!({})).unwrap();
panel.frame();
let styled = target_marks_painted(&mut panel, "Target A");
let ring = both.iter().find(|m| (m.0 - 2.8).abs() < 1e-4 && !m.1).expect("the actual inner ring");
let mark = both.iter().find(|m| m.1).expect("the actual hollow diamond");
let outer_extent = mark.0 + mark.2 * std::f32::consts::FRAC_1_SQRT_2;
assert!(outer_extent < ring.0 - ring.2 / 2.0 - 0.5, "the diamond {mark:?} covers the ring {ring:?}");
assert!((mark.0 - 1.0).abs() < 1e-4);
assert_eq!(mark.2, ring.2, "the marker retains the theme's thin stroke");
let alone = styled.iter().find(|m| m.1).expect("the standalone diamond");
assert!((alone.0 - 2.5).abs() < 1e-4);
let looks = [&neither, &targeted, &styled, &both];
for (i, x) in looks.iter().enumerate() {
for y in &looks[i + 1..] {
assert_ne!(x, y, "all four actual cell looks differ");
}
}
}
/// Hover and accessibility explain the mark without replacing the contextual row name; the same
/// native cell still targets its art, while selecting other art leaves its own appearance intact.
#[test]
fn appearance_marker_names_its_state_and_keeps_targeting_actions() {
use crate::tests::panel_harness::Panel;
struct RestoreLanguage(crate::i18n::Lang);
impl Drop for RestoreLanguage {
fn drop(&mut self) {
crate::i18n::set_current(self.0);
}
}
let _language = RestoreLanguage(crate::i18n::current());
crate::i18n::set_current(crate::i18n::Lang::EN);
let (mut app, _, [a, b]) = two_rects();
name_row(&mut app, a, "A");
name_row(&mut app, b, "B");
app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap();
let mut panel = Panel::new(app, show);
let idle = "Target appearance: not targeted, additional appearance or transparency";
let active = "Target appearance: targeted, additional appearance or transparency";
assert_eq!(panel.description("Target A").as_deref(), Some(idle));
assert_eq!(panel.description("Target B").as_deref(), Some("Target appearance: not targeted, basic appearance"));
assert_eq!(panel.toggled("Target A"), Some(craft::behavior::Mixed::Same(false)));
let before = {
let app = panel.app();
(app.session.active().unwrap().selection.clone(), undo_len(&app))
};
panel.hover("Target A");
panel.advance(2.0);
panel.frame();
let (shapes, _) = panel.paint_at(1.0);
assert!(shapes.iter().any(|s| matches!(s, egui::Shape::Text(t) if t.galley.text() == idle)), "the native tooltip explains the mark");
{
let app = panel.app();
assert_eq!((app.session.active().unwrap().selection.clone(), undo_len(&app)), before, "hover changes no selection or history");
}
panel.click("Target A");
assert_eq!(targeted(&panel.app()), (Some(a), vec![a]));
assert_eq!(panel.description("Target A").as_deref(), Some(active));
assert_eq!(panel.toggled("Target A"), Some(craft::behavior::Mixed::Same(true)));
panel.click("Target B");
assert_eq!(panel.description("Target A").as_deref(), Some(idle));
assert_eq!(panel.description("Target B").as_deref(), Some("Target appearance: targeted, basic appearance"));
assert_eq!(panel.toggled("Target B"), Some(craft::behavior::Mixed::Same(true)));
assert!(target_marks_painted(&mut panel, "Target A").iter().any(|m| m.1), "the appearance stays after targeting other art");
}
/// The marker's native cell retains appearance move and Alt-copy admission and payloads.
#[test]
fn dragging_a_target_circle_moves_or_copies_the_appearance() {
use crate::tests::panel_harness::Panel;
let (mut app, layer, [a, b]) = two_rects();
name_row(&mut app, layer, "Layer");
name_row(&mut app, a, "A");
name_row(&mut app, b, "B");
app.session.execute("transparency.set", &json!({"ids": [a.0], "opacity": 30})).unwrap();
let mut panel = Panel::new(app, show);
let opacity = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().opacity;
panel.drag("Target A", "Target B", egui::Modifiers::ALT);
{
let app = panel.app();
assert!((opacity(&app, a) - 0.3).abs() < 1e-6 && (opacity(&app, b) - 0.3).abs() < 1e-6);
}
panel.drag("Target B", "Target Layer", egui::Modifiers::NONE);
let app = panel.app();
assert!((opacity(&app, layer) - 0.3).abs() < 1e-6 && opacity(&app, b) == 1.0);
}
/// The rows find which nodes hold selected art once per revision: frames that change nothing walk no node for the
/// selection squares, and a new selection walks the tree once.
#[test]
@@ -267,6 +267,30 @@ mod tests {
Panel::new(app, show)
}
#[test]
fn scrolling_a_short_docked_form_reaches_its_last_action() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
app.run("object.pattern.make", json!({"name": "Dots"})).unwrap();
let mut panel = Panel::new(app, |app, ui| crate::dock::panel_body(app, ui, "patternOptions"));
let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0));
panel.room(viewport.size());
panel.frame();
panel.frame();
let before = panel.rect("Done");
assert!(before.center().y > viewport.bottom(), "Done starts at {before:?} in {viewport:?}");
for _ in 0..20 {
panel.scroll_at(egui::pos2(30.0, 30.0), -120.0);
panel.advance(0.2);
panel.frame();
}
let after = panel.rect("Done");
assert!(viewport.contains(after.center()), "Done moved from {before:?} to {after:?} in {viewport:?}");
panel.click("Done");
assert!(editing(&panel.app()).is_none());
}
/// Shift+Enter in the Name field renames the pattern and keeps the field active; Enter then
/// renames it again and ends the editing.
#[test]
@@ -309,4 +333,44 @@ mod tests {
assert_eq!(panel.value("Name").as_deref(), Some("Dots"));
assert!(panel.app().session.active().unwrap().doc.pattern("Dots").is_some());
}
/// The tile's width and height of the pattern "Dots".
fn tile_size(panel: &Panel) -> (f64, f64) {
let app = panel.app();
let tile = &app.session.active().unwrap().doc.pattern("Dots").unwrap().tile;
(tile.width(), tile.height())
}
/// With the Width field focused, a wheel notch steps it only while the pointer is over it: over another control,
/// or over the unfocused Height field, the wheel scrolls the panel and the tile keeps its size.
#[test]
fn the_wheel_steps_the_focused_number_field_only_under_the_pointer() {
use craft::ui::contract::Role;
let mut panel = editing_panel();
panel.room(egui::vec2(220.0, 320.0));
panel.frame();
assert_eq!(tile_size(&panel), (10.0, 10.0));
panel.click_role("Width", Role::SPIN_BUTTON);
assert!(panel.focused("Width"), "the click focuses Width");
// One notch at `at`, then the frame after the wheel gesture's gap, which ends the gesture.
let notch = |panel: &mut Panel, at: egui::Pos2| {
panel.scroll_at(at, -30.0);
panel.advance(1.0);
panel.frame();
};
let check = panel.rect("Size Tile to Art").center();
notch(&mut panel, check);
assert_eq!(tile_size(&panel), (10.0, 10.0), "a notch over Size Tile to Art leaves the focused Width alone");
assert!(panel.focused("Width"), "Width keeps the focus");
let height = panel.rect_role("Height", Role::SPIN_BUTTON).center();
notch(&mut panel, height);
assert_eq!(tile_size(&panel), (10.0, 10.0), "a notch over the unfocused Height steps neither field");
let width = panel.rect_role("Width", Role::SPIN_BUTTON).center();
notch(&mut panel, width);
assert_eq!(tile_size(&panel), (9.0, 10.0), "a notch over the focused Width steps it");
}
}
+39 -9
View File
@@ -1,13 +1,13 @@
//! The Properties panel: sections that change with the selection.
use craft::behavior::{ColumnWidth, IconId};
use craft::behavior::{ColumnWidth, IconId, Proposal};
use craft::ui::buttons::{Button, IconButton};
use craft::ui::contract::{LabelScheme, Props as _, Show as _, ShowContainer as _};
use craft::ui::contract::{BodyCx, LabelScheme, Pad, Props as _, Show as _, ShowContainer as _};
use craft::ui::layout_components::{Grid, Row, Stack};
use craft::ui::patterns::panels::Inspector;
use craft::ui::runtime::commands::CommandRef;
use craft::ui::sections::HeaderStrength;
use craft::ui::sections::{HeaderStrength, Panel};
use egui::Ui;
use serde_json::json;
use vectorcraft_doc::{LiveShape, Node, NodeKind};
@@ -27,6 +27,8 @@ pub struct PropertiesUi {
pub edited_profiled: Option<(ProfiledKey, bool)>,
/// The Quick Actions last listed, with the [`quick_actions_key`] they were listed at.
quick_actions: Option<(u64, Vec<QuickAction>)>,
/// The [`content_key`] the sections were last shown for.
content: Option<u64>,
}
/// The key of [`PropertiesUi::edited_profiled`]: (document uid, revision, active Appearance row).
@@ -63,7 +65,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// Ruler guides selected on their own (a click on one): their position.
let guides = super::transform::selected_guides(app);
let header = heading(first.as_deref(), n_sel, editing_artboards, guides.is_some());
inspector.target(key).header(header).show(ui, |ui, _| {
let content = content_key(app);
let changed = app.ui.properties_panel.content.replace(content) != Some(content);
let mut sections = |ui: &mut Ui, _: &mut BodyCx<'_>| {
// The reference panel's labels end in a colon beside fields that keep their own width.
Stack::new().fill_width().labels(LabelScheme::Form).show(ui, |ui, _| {
if editing_artboards {
@@ -77,7 +81,33 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
body(app, ui, first.as_deref(), n_sel, anchors);
}
});
});
};
// The panel `Inspector::show` makes, shown here so that new sections are measured before they are placed and the
// frame is not discarded and drawn again.
let mut panel = Panel::new(header).titled().strength(HeaderStrength::Quiet).labels(LabelScheme::Inspector).pad(Pad::None);
panel = panel.id_salt(egui::IdSalt::new(key));
if changed {
let _ = panel.measure_in(ui, Proposal::Size(ui.available_size()), &mut sections);
}
panel.show(ui, sections);
}
/// What the sections show: the document and its revision, the selection, the tool and isolation mode.
fn content_key(app: &VectorcraftApp) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
app.session.tool_id().hash(&mut h);
if let Some(st) = app.session.active() {
let selection = &st.selection;
(st.uid, st.revision, st.isolation, &selection.objects, selection.key, selection.target, &selection.slices).hash(&mut h);
for (id, anchors) in &selection.anchors {
(id, anchors.len()).hash(&mut h);
}
for (id, segments) in &selection.segments {
(id, segments.len()).hash(&mut h);
}
}
h.finish()
}
/// The document's uid: production's field ids do not change with the selection, so neither does the key and the
@@ -291,8 +321,9 @@ fn can_merge_live_paint(app: &VectorcraftApp) -> bool {
})
}
/// Whether the selection uses more than one colour (`recolor.colors`), which offers the Recolor
/// quick action; memoised per document revision.
/// Whether the selection uses more than one colour (`recolor.colors` lists more than one,
/// [`vectorcraft_engine::Session::several_colors_used`]), which offers the Recolor quick action;
/// memoised per document revision.
pub(crate) fn multi_color(app: &mut VectorcraftApp) -> bool {
let Some(st) = app.session.active() else { return false };
let key = (st.uid, st.revision);
@@ -301,8 +332,7 @@ pub(crate) fn multi_color(app: &mut VectorcraftApp) -> bool {
{
return multi;
}
let r = app.session.execute("recolor.colors", &json!({})).unwrap_or_default();
let multi = r["colors"].as_array().is_some_and(|c| c.len() > 1);
let multi = app.session.several_colors_used();
app.canvas.multi_color = Some((key, multi));
multi
}
@@ -1,10 +1,10 @@
//! The Properties panel's Document sections, shown with nothing selected.
use craft::behavior::IconId;
use craft::behavior::{EditEvent, IconId};
use craft::keymap::CommandRef;
use craft::ui::buttons::{Button, ToggleButton};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Sizing};
use craft::ui::contract::{Bind, Entry, MemoProps, MemoView, Outbox, Props as _, Show as _, ShowContainer as _, Sizing};
use craft::ui::form::Field;
use craft::ui::layout_components::{Grid, Row};
use craft::ui::pickers::Select;
@@ -17,84 +17,215 @@ use vectorcraft_doc::Unit;
use super::artboard_sections::rearrange_button;
use super::object_sections::HALVES;
use crate::VectorcraftApp;
use crate::edits::EditPath;
use crate::panels::transform;
/// The panel with nothing selected: the document's units, Document Setup and artboards, the
/// Appearance fill and stroke, the view's rulers, grids, guides and snapping, the keyboard
/// increment and Scale Strokes & Effects, and Quick Actions.
///
/// The body of every section but Appearance shows in a `MemoView` keyed on what it reads, so a
/// frame that changes none of it replays the body. What a body picks comes back through an `Outbox`
/// and runs after its section.
pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) {
let lang = crate::i18n::current();
let units = app.session.general_unit();
let unit = Unit::ALL.iter().position(|u| *u == units).unwrap_or(usize::MAX);
let artboards = app.session.active().map_or(0, |d| d.doc.artboards.len());
let mut picked_units = Vec::new();
super::section(tl!("Document")).show(ui, |ui, _| {
Field::new(tl!("Units")).show(ui, |ui, _| {
let entries: Vec<Entry<Unit>> = Unit::ALL.iter().map(|u| Entry::new(*u, u.label())).collect();
let out = Select::new(tl!("Units"), Bind::given(units), &entries).show(ui);
if let Some(u) = out.events.committed() {
app.run("document.setUnits", json!({ "units": u.label() })).ok();
}
});
Grid::new(&HALVES).show(ui, |ui, _| {
Button::command(CommandRef::new("file.documentSetup")).label(tl!("Document Setup")).sizing(Sizing::FillWidth).show(ui);
Button::command(CommandRef::with_params("tool.select", json!({ "tool": "artboard" })))
.label(tl!("Edit Artboards"))
.sizing(Sizing::FillWidth)
.show(ui);
if artboards > 1 {
rearrange_button(ui, artboards);
}
});
let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) };
let _ = MemoView::new("properties-document", document, document_body).show(ui);
});
if let Some(u) = picked_units.pop() {
app.run("document.setUnits", json!({ "units": u.label() })).ok();
}
super::section(tl!("Appearance")).show(ui, |ui, _| super::appearance_section::fill_stroke_rows(app, ui));
super::section(tl!("Rulers & Grids")).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
// The checked and enabled states and the tooltips come from the commands (Trim View turns the grid off).
for (command, icon) in [("view.rulers", "ruler"), ("view.grid", "grid-3x3"), ("view.transparencyGrid", "square-dashed")] {
ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui);
}
});
let _ = MemoView::new("properties-rulers", Language { lang }, rulers_body).show(ui);
});
super::section(tl!("Guides")).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
for (command, icon) in [("view.guides", "layout-grid"), ("view.smartGuides", "sparkles")] {
ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui);
}
});
let _ = MemoView::new("properties-guides", Language { lang }, guides_body).show(ui);
});
let mut snaps = Vec::new();
let (point, grid) = (app.ui.view.snap_to_point, app.ui.view.snap_to_grid);
super::section(tl!("Snap Options")).show(ui, |ui, _| {
let (point, grid) = (app.ui.view.snap_to_point, app.ui.view.snap_to_grid);
for (command, label, on) in [("view.snapToPoint", tl!("Snap to Point"), point), ("view.snapToGrid", tl!("Snap to Grid"), grid)] {
if Checkbox::new(Bind::given(on)).label(label).show(ui).value().is_some() {
app.run(command, json!({})).ok();
}
}
let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) };
let _ = MemoView::new("properties-snap", snap, snap_body).show(ui);
});
for command in snaps {
app.run(command, json!({})).ok();
}
let mut prefs = Vec::new();
// Read again after the Units commit above, so the key and `lengths` come from the same General unit.
let general = app.session.general_unit();
let unit = Unit::ALL.iter().position(|u| *u == general).unwrap_or(usize::MAX);
let (increment, scale) = (app.session.prefs.keyboard_increment, app.session.prefs.scale_strokes);
let (bare_points, lengths) = (app.session.prefs.numbers_without_units_are_points, crate::canvas::rulers::general_lengths(app));
super::section(tl!("Preferences")).show(ui, |ui, _| {
Field::new(tl!("Keyboard Increment")).show(ui, |ui, _| {
// PLAN: assumed `canvas::rulers::general_lengths(app) -> LengthUnits` (cv.B5b)
let lengths: LengthUnits = crate::canvas::rulers::general_lengths(app);
// The engine's own range for the preference (`prefscmds.rs`): a larger value is an error.
let out = NumberField::length(tl!("Keyboard Increment"), Bind::given(Some(app.session.prefs.keyboard_increment)), lengths)
.range(0.001..=1296.0)
.show(ui);
crate::edits::apply_edits(app, &out.edit, crate::edits::EditPath::Scope, |app, v: &Option<f64>, _| {
if let Some(value) = *v {
app.run("prefs.set", json!({ "key": "keyboardIncrement", "value": value })).ok();
}
});
});
let scale = app.session.prefs.scale_strokes;
let out = Checkbox::new(Bind::given(scale)).label(tl!("Scale Strokes & Effects")).show(ui);
if let Some(on) = out.value().copied() {
transform::set_pref(app, "scaleStrokes", on);
let picked = Outbox::new(&mut prefs);
let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked };
let _ = MemoView::new("properties-preferences", preferences, preferences_body).show(ui);
});
for pick in prefs {
match pick {
PreferencePick::Increment(event) => {
crate::edits::apply_event(app, &event, &EditPath::Scope, &mut |app, v: &Option<f64>, _| {
if let Some(value) = *v {
app.run("prefs.set", json!({ "key": "keyboardIncrement", "value": value })).ok();
}
});
}
PreferencePick::ScaleStrokes(on) => transform::set_pref(app, "scaleStrokes", on),
}
}
super::section(tl!("Quick Actions")).show(ui, |ui, _| {
let _ = MemoView::new("properties-quick-actions", Language { lang }, quick_actions_body).show(ui);
});
}
/// What a section that reads only command states reads besides them: the interface language of its labels.
#[derive(MemoProps)]
struct Language {
#[memo_props(hash = "an interface language: an index into the languages offered")]
lang: crate::i18n::Lang,
}
/// What the Document section reads: the document's units and how many artboards it has.
#[derive(MemoProps)]
struct DocumentProps<'a> {
/// The index of `units` in [`Unit::ALL`].
unit: usize,
#[memo_props(covered_by = "unit", reason = "the unit's index in Unit::ALL")]
units: Unit,
/// How many artboards the document has (Rearrange All shows for more than one).
artboards: usize,
#[memo_props(hash = "an interface language: an index into the languages offered")]
lang: crate::i18n::Lang,
/// The units chosen in the Units menu.
picked: Outbox<'a, Unit>,
}
/// The Document section's body: Units, Document Setup, Edit Artboards and Rearrange All.
fn document_body(p: &mut DocumentProps<'_>, ui: &mut Ui) {
#[cfg(test)]
tests::count_run();
Field::new(tl!("Units")).show(ui, |ui, _| {
let entries: Vec<Entry<Unit>> = Unit::ALL.iter().map(|u| Entry::new(*u, u.label())).collect();
let out = Select::new(tl!("Units"), Bind::given(p.units), &entries).show(ui);
if let Some(u) = out.events.committed() {
p.picked.send(*u);
}
});
super::section(tl!("Quick Actions")).show(ui, |ui, _| {
Grid::new(&HALVES).show(ui, |ui, _| {
// The reference panel's buttons name the dialog without the menu's ellipsis.
for (command, label) in [("file.documentSetup", tl!("Document Setup")), ("edit.preferences", tl!("Preferences"))] {
Button::command(CommandRef::new(command)).label(label).sizing(Sizing::FillWidth).show(ui);
}
});
Grid::new(&HALVES).show(ui, |ui, _| {
Button::command(CommandRef::new("file.documentSetup")).label(tl!("Document Setup")).sizing(Sizing::FillWidth).show(ui);
Button::command(CommandRef::with_params("tool.select", json!({ "tool": "artboard" })))
.label(tl!("Edit Artboards"))
.sizing(Sizing::FillWidth)
.show(ui);
if p.artboards > 1 {
rearrange_button(ui, p.artboards);
}
});
}
/// The Rulers & Grids section's body. The checked and enabled states and the tooltips come from the commands (Trim
/// View turns the grid off).
fn rulers_body(_: &mut Language, ui: &mut Ui) {
#[cfg(test)]
tests::count_run();
Row::new().show(ui, |ui, _| {
for (command, icon) in [("view.rulers", "ruler"), ("view.grid", "grid-3x3"), ("view.transparencyGrid", "square-dashed")] {
ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui);
}
});
}
/// The Guides section's body: Show Guides and Smart Guides, from their commands.
fn guides_body(_: &mut Language, ui: &mut Ui) {
#[cfg(test)]
tests::count_run();
Row::new().show(ui, |ui, _| {
for (command, icon) in [("view.guides", "layout-grid"), ("view.smartGuides", "sparkles")] {
ToggleButton::command(CommandRef::new(command)).icon(IconId::new(icon)).icon_only().show(ui);
}
});
}
/// What the Snap Options section reads: whether Snap to Point and Snap to Grid are on.
#[derive(MemoProps)]
struct SnapProps<'a> {
point: bool,
grid: bool,
#[memo_props(hash = "an interface language: an index into the languages offered")]
lang: crate::i18n::Lang,
/// The command of each checkbox clicked.
picked: Outbox<'a, &'static str>,
}
/// The Snap Options section's body: Snap to Point and Snap to Grid.
fn snap_body(p: &mut SnapProps<'_>, ui: &mut Ui) {
#[cfg(test)]
tests::count_run();
for (command, label, on) in [("view.snapToPoint", tl!("Snap to Point"), p.point), ("view.snapToGrid", tl!("Snap to Grid"), p.grid)] {
if Checkbox::new(Bind::given(on)).label(label).show(ui).value().is_some() {
p.picked.send(command);
}
}
}
/// What the Preferences section reads: the keyboard increment in the General unit, and Scale Strokes & Effects.
#[derive(MemoProps)]
struct PreferencesProps<'a> {
/// The keyboard increment, in points.
increment: f64,
/// The index of the General unit in [`Unit::ALL`].
unit: usize,
/// Numbers without units are points (Preferences › Units).
bare_points: bool,
#[memo_props(covered_by = "unit", reason = "made from the General unit and bare_points alone (canvas::rulers::lengths)")]
lengths: LengthUnits,
/// Scale Strokes & Effects is on.
scale: bool,
#[memo_props(hash = "an interface language: an index into the languages offered")]
lang: crate::i18n::Lang,
/// The keyboard increment's edits and the Scale Strokes & Effects choice.
picked: Outbox<'a, PreferencePick>,
}
/// What the Preferences section reports: an edit of the keyboard increment, or Scale Strokes & Effects turned on or
/// off.
enum PreferencePick {
Increment(EditEvent<Option<f64>>),
ScaleStrokes(bool),
}
/// The Preferences section's body: Keyboard Increment and Scale Strokes & Effects.
fn preferences_body(p: &mut PreferencesProps<'_>, ui: &mut Ui) {
#[cfg(test)]
tests::count_run();
Field::new(tl!("Keyboard Increment")).show(ui, |ui, _| {
// The engine's own range for the preference (`prefscmds.rs`): a larger value is an error.
let out = NumberField::length(tl!("Keyboard Increment"), Bind::given(Some(p.increment)), p.lengths).range(0.001..=1296.0).show(ui);
for event in out.edit.events.iter() {
p.picked.send(PreferencePick::Increment(event.clone()));
}
});
let out = Checkbox::new(Bind::given(p.scale)).label(tl!("Scale Strokes & Effects")).show(ui);
if let Some(on) = out.value().copied() {
p.picked.send(PreferencePick::ScaleStrokes(on));
}
}
/// The Quick Actions section's body: Document Setup and Preferences. The reference panel's buttons name the dialog
/// without the menu's ellipsis.
fn quick_actions_body(_: &mut Language, ui: &mut Ui) {
#[cfg(test)]
tests::count_run();
Grid::new(&HALVES).show(ui, |ui, _| {
for (command, label) in [("file.documentSetup", tl!("Document Setup")), ("edit.preferences", tl!("Preferences"))] {
Button::command(CommandRef::new(command)).label(label).sizing(Sizing::FillWidth).show(ui);
}
});
}
@@ -104,6 +235,19 @@ mod tests {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
thread_local! {
/// How many times this thread ran a memoized Document section.
static SECTION_RUNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
pub(super) fn count_run() {
SECTION_RUNS.with(|n| n.set(n.get() + 1));
}
fn runs() -> u64 {
SECTION_RUNS.with(std::cell::Cell::get)
}
#[test]
fn canceling_the_units_popup_leaves_the_document_unchanged() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
@@ -135,4 +279,79 @@ mod tests {
assert_eq!(panel.app().session.active().unwrap().doc.units, next, "Enter applies the chosen document unit");
assert_eq!(panel.app().session.general_unit(), next);
}
/// Frames that change nothing the sections show replay them instead of laying them out again. A change one of
/// them reads, from a command run elsewhere, runs it again, and it shows the change.
#[test]
fn idle_frames_replay_the_document_sections() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let mut panel = Panel::new(app, document_sections);
panel.room(egui::vec2(400.0, 1000.0));
panel.frame();
panel.frame();
let before = runs();
for _ in 0..10 {
panel.frame();
}
assert_eq!(runs() - before, 0, "idle frames run the memoized sections no more");
let point = panel.app().ui.view.snap_to_point;
panel.app().run("view.snapToPoint", json!({})).unwrap();
panel.frame();
panel.frame();
assert!(runs() > before, "a new snap setting runs the sections again");
assert_eq!(panel.app().ui.view.snap_to_point, !point);
assert_eq!(panel.toggled("Snap to Point"), Some(craft::behavior::Mixed::Same(!point)), "and the checkbox shows it");
panel.app().run("view.rulers", json!({})).unwrap();
let mut per_frame = Vec::new();
for _ in 0..12 {
let at = runs();
panel.frame();
per_frame.push(runs() - at);
}
// A toggled button animates over the next frames, and a section runs while an animation in it has not ended.
assert_eq!(per_frame[6..], [0; 6], "idle frames after a command run them no more: {per_frame:?}");
}
/// The frame that picks new units in the Units menu shows the Keyboard Increment in them: the Preferences
/// section's key reads the General unit after the pick runs, as its lengths do.
#[test]
fn the_frame_that_picks_units_shows_the_increment_in_them() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let initial = app.session.general_unit();
let mut panel = Panel::new(app, document_sections);
panel.room(egui::vec2(400.0, 1000.0));
panel.frame();
let before = panel.value("Keyboard Increment");
panel.click_role("Units", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
let enter =
|pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };
panel.frame_with(vec![enter(true), enter(false)]);
assert_ne!(panel.app().session.general_unit(), initial, "Enter applies the chosen unit");
let picked = panel.value("Keyboard Increment");
panel.frame();
let settled = panel.value("Keyboard Increment");
assert_ne!(settled, before, "the increment shows in the new unit");
assert_eq!(picked, settled, "the frame of the pick already shows the increment in the new unit");
}
/// The memoized sections still take input: a click on Snap to Grid turns it on, once, and Scale Strokes & Effects
/// sets its preference.
#[test]
fn the_memoized_sections_run_their_picks() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let grid = app.ui.view.snap_to_grid;
let scale = app.session.prefs.scale_strokes;
let mut panel = Panel::new(app, document_sections);
panel.room(egui::vec2(400.0, 1000.0));
panel.frame();
panel.click("Snap to Grid");
assert_eq!(panel.app().ui.view.snap_to_grid, !grid, "the click toggles Snap to Grid once");
panel.click("Scale Strokes & Effects");
assert_eq!(panel.app().session.prefs.scale_strokes, !scale);
}
}
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more