diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index f71d011ece..507caffe10 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1398097510, "producer_workflow_id": 430275079, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3", + "signer_tooling_revision": "main", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 698935efd7..6cc6f885a2 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,9 +34,9 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main with: - tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + tooling-revision: main app-name: vectorcraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 6c8d2ebe7e..0e963e43e1 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main with: - tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3 + tooling-revision: main app-name: vectorcraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 @@ -32,3 +32,4 @@ jobs: # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, # #369 and #364). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]' diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index b48c43294c..47211426f6 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -267,10 +267,13 @@ fn turned(c: &Color, degrees: f32) -> Option { } } -/// Replace a solid paint's color with what `adjust` gives for it, dropping its swatch link. +/// Replace a solid paint's color with what `adjust` gives for it, dropping its swatch link. A +/// color that comes back unchanged (an amount too small to move its components) keeps the paint +/// and its link. fn recolor_paint(p: &mut Paint, adjust: &dyn Fn(&Color) -> Option) { if let Paint::Solid { color, .. } = p && let Some(c) = adjust(color) + && c != *color { *p = Paint::solid(c); } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 0b6cbf6011..2a39d50010 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1599,6 +1599,30 @@ fn jitter_at_a_limit_keeps_the_swatch_link() { } } +/// A hue or saturation jitter too small to move a Lab color's components gives each copy the color +/// it had, and the copies keep the swatch link. +#[test] +fn jitter_too_small_to_change_a_color_keeps_the_swatch_link() { + let linked = Paint::Solid { color: Color::lab(50.0, 64.0, 0.0), swatch: Some("Spot".into()), tint: 1.0 }; + // 1e-50 degrees turns a and b by less than an f32 holds; 1e-6 points scales the chroma by + // 1 + 1.6e-8, which rounds back to the same f32 components. + type Jitter = fn(&mut [Node], f64, u64); + let jitters: [(&str, Jitter, f64); 2] = [("hue", crate::colorize::jitter_hues, 1e-50), ("saturation", crate::colorize::jitter_saturations, 1e-6)]; + for (name, jitter, amount) in jitters { + let mut copies: Vec = (0..8) + .map(|_| { + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(linked.clone()); + art + }) + .collect(); + jitter(&mut copies, amount, 7); + for n in &copies { + assert_eq!(n.appearance.fill_paint(), linked, "{name}"); + } + } +} + /// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its /// swatch links. #[test] diff --git a/crates/cad/src/expansion_test.rs b/crates/cad/src/expansion_test.rs new file mode 100644 index 0000000000..f5ae09e915 --- /dev/null +++ b/crates/cad/src/expansion_test.rs @@ -0,0 +1,22 @@ +use std::cell::Cell; + +thread_local! { + static USED: Cell = const { Cell::new(0) }; +} + +pub(crate) fn initial_used() -> u64 { + USED.with(Cell::get) +} + +pub(crate) fn with_used(used: u64, action: impl FnOnce() -> T) -> T { + struct Reset<'a>(&'a Cell, u64); + impl Drop for Reset<'_> { + fn drop(&mut self) { + self.0.set(self.1); + } + } + USED.with(|value| { + let _reset = Reset(value, value.replace(used)); + action() + }) +} diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index d951e92681..d46275a74c 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -588,6 +588,9 @@ impl<'a> Walk<'a> { clip_tests: 0, warnings: vec![], nest: 0, + #[cfg(test)] + symbol_nodes: crate::expansion_test::initial_used(), + #[cfg(not(test))] symbol_nodes: 0, generated: 0, scratch: None, @@ -740,7 +743,6 @@ impl<'a> Walk<'a> { } Some(None) => {} None => { - self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES; self.warn(SYMBOLS_LEFT_OUT); } } diff --git a/crates/cad/src/hpgl/write/tests.rs b/crates/cad/src/hpgl/write/tests.rs index b371c832db..12bfd93c7d 100644 --- a/crates/cad/src/hpgl/write/tests.rs +++ b/crates/cad/src/hpgl/write/tests.rs @@ -870,6 +870,31 @@ fn symbols_nested_too_deep_are_left_out_with_a_warning() { assert_eq!(text(&out), "IN;PU;SP0;"); } +#[test] +fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() { + let mut d = doc_with(|_| vec![]); + let leaf = stroked(&mut d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK); + let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) }); + let mut first = None; + for name in ["big", "small"] { + let id = d.alloc_id(); + first.get_or_insert(id); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); + } + let mut expected = d.clone(); + expected.remove(first.unwrap()).unwrap(); + crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || { + let actual = plot(&d, &opts(&d)); + let control = plot(&expected, &opts(&expected)); + assert!(actual.warnings.iter().any(|w| w == SYMBOLS_LEFT_OUT), "{:?}", actual.warnings); + assert_ne!(text(&control), "IN;PU;SP0;"); + assert_eq!(text(&actual), text(&control), "HP-GL keeps the later fitting instance"); + }); +} + /// A symbol instance stained by its fill draws in the stained color. #[test] fn a_stained_symbol_instance_takes_its_stain() { diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index 8aefe61a0d..b54d9022bf 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -23,6 +23,8 @@ //! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves. mod aci; +#[cfg(test)] +mod expansion_test; pub mod hpgl; pub mod import; mod scene; diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 700632313e..26025f2544 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -561,8 +561,10 @@ impl<'a> Scene<'a> { extents: None, opacity: 1.0, nest: 0, - // Tests spend all but a million of it up front. - symbol_nodes: if cfg!(test) { vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000 } else { 0 }, + #[cfg(test)] + symbol_nodes: crate::expansion_test::initial_used(), + #[cfg(not(test))] + symbol_nodes: 0, } } @@ -711,7 +713,6 @@ impl<'a> Scene<'a> { } Some(None) => {} None => { - self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES; self.warn(SYMBOLS_LEFT_OUT); } } diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index b2d5d4db3e..dd80644279 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1503,11 +1503,36 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() { let art = Node::group(d.alloc_id(), children); d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) }); } - let out = export(&d, &opts(&d)).unwrap(); + let out = crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000, || export(&d, &opts(&d)).unwrap()); assert!(entities(&out).is_empty()); assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings); } +#[test] +fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() { + let mut d = doc_with(|_| vec![]); + let leaf = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 40.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) }); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) }); + let mut first = None; + for name in ["big", "small"] { + let id = d.alloc_id(); + first.get_or_insert(id); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap(); + } + let mut expected = d.clone(); + expected.remove(first.unwrap()).unwrap(); + crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || { + let actual = export(&d, &opts(&d)).unwrap(); + let control = export(&expected, &opts(&expected)).unwrap(); + assert!(actual.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", actual.warnings); + assert!(!entities(&control).is_empty()); + assert_eq!(kinds(&actual), kinds(&control), "DXF keeps the later fitting instance"); + }); +} + #[test] fn export_bytes_match_shared_writer_goldens() { use std::path::PathBuf; diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs index 7a39d6cbb2..4038d04b42 100644 --- a/crates/doc/src/appearance/stroke_style.rs +++ b/crates/doc/src/appearance/stroke_style.rs @@ -192,14 +192,18 @@ pub enum Arrowhead { /// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as /// the other heads. LineArrow, + /// A slender filled head, a little over half as wide as it is long, whose sides bend in + /// halfway back, with a V-shaped notch in its back: the arrow of mathematical diagrams. + NotchedArrow, /// A head the user drew, with its art. Custom(Arc), } impl Arrowhead { /// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks). - pub const ALL: [Arrowhead; 41] = [ + pub const ALL: [Arrowhead; 42] = [ Arrowhead::Arrow, + Arrowhead::NotchedArrow, Arrowhead::ArrowOpen, Arrowhead::LineArrow, Arrowhead::Barbed, @@ -322,6 +326,7 @@ impl Arrowhead { Arrowhead::TriangleBar => "Triangle to Bar", Arrowhead::Oval => "Oval", Arrowhead::LineArrow => "Line Arrow", + Arrowhead::NotchedArrow => "Notched Arrow", Arrowhead::Custom(_) => "Custom", } } diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index c91348d57f..787c864b2f 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -316,7 +316,7 @@ fn profile_presets_round_trip_their_ids() { #[test] fn arrowhead_names_are_stable_and_every_one_is_listed_once() { // Saved files store these names: they may only ever be appended to. - const SAVED: [&str; 41] = [ + const SAVED: [&str; 42] = [ "Triangle", "TriangleOpen", "Circle", @@ -358,6 +358,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() { "TriangleBar", "Oval", "LineArrow", + "NotchedArrow", ]; for name in SAVED { let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap(); diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index 1047e4d0dd..bd1511ab8c 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -289,6 +289,8 @@ fn local_stop(kind: &Arrowhead) -> Stop { Arrowhead::DoubleSlash => Stop::At(1.05), Arrowhead::DoubleArrow => Stop::At(1.7), Arrowhead::HalfCircle => Stop::At(1.0), + // Between the bend in its sides and its notch, where it is wider than the line at 100 %. + Arrowhead::NotchedArrow => Stop::At(2.7), Arrowhead::Concave => Stop::At(2.6), Arrowhead::Hexagon => Stop::At(HEX / 2.0), _ => Stop::At(2.0), @@ -395,6 +397,9 @@ fn local(kind: &Arrowhead) -> BezPath { let t = FRAC_1_SQRT_2; poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]); } + // Barbs 1.2 out at the back; each side bends in at (2.1, ±0.5), as wide as the line at + // 100 %, so the sides are concave; the notch reaches 0.7 into the back. + Arrowhead::NotchedArrow => poly(&mut p, &[(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)]), Arrowhead::Custom(c) => p = c.path.to_bezpath(), // The first ten are drawn by `shape`. Arrowhead::Triangle diff --git a/crates/effects/src/stroke/tests_arrows.rs b/crates/effects/src/stroke/tests_arrows.rs index a32a70245b..2a54ddb462 100644 --- a/crates/effects/src/stroke/tests_arrows.rs +++ b/crates/effects/src/stroke/tests_arrows.rs @@ -4,20 +4,26 @@ use kurbo::{BezPath, PathEl, Point, Shape}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer}; +use vectorcraft_doc::{ArrowAlign, Arrowhead, LineCap, StrokeLayer}; -use super::stroke_pieces; +use super::{line_outline, stroke_pieces}; /// A 2 pt line along +x ending at (100, 0) with `kind` at its end, tip on the end point: heads /// of weight 2, so 8 long and 8 wide. fn head(kind: Arrowhead) -> super::Arrow { + head_and_line(kind, LineCap::Butt).0 +} + +/// [`head`] and the outline of the line under it, drawn with `cap`. +fn head_and_line(kind: Arrowhead, cap: LineCap) -> (super::Arrow, BezPath) { let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); - st.end_arrow = Some(kind); - st.arrow_align = ArrowAlign::Tip; + (st.end_arrow, st.arrow_align, st.cap) = (Some(kind), ArrowAlign::Tip, cap); let mut l = BezPath::new(); l.move_to((0.0, 0.0)); l.line_to((100.0, 0.0)); - stroke_pieces(&l, &st).heads.remove(0) + let mut p = stroke_pieces(&l, &st); + let line = line_outline(&p.line, &st, st.width, 1e-3); + (p.heads.remove(0), line) } /// The outline's closed contours as polygons (curves flattened). @@ -105,6 +111,53 @@ fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() { } } +#[test] +fn the_notched_arrow_is_slender_with_concave_sides_and_a_v_notch() { + // Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt. + let h = head(Arrowhead::NotchedArrow); + let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y); + // Six corners: the tip, a bend in each side, a barb on each side and the notch between them. + let pts: Vec = contours(&h.outline).concat(); + let corners = [(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)].map(|(x, y)| at(x, y)); + assert_eq!(pts.len(), corners.len(), "{pts:?}"); + for c in corners { + assert!(pts.iter().any(|p| p.distance(c) < 1e-9), "corner {c:?} in {pts:?}"); + } + for side in [1.0, -1.0] { + // Concave: at the bend, the straight line from the tip to the barb (0.63 out) is outside. + assert_eq!(h.outline.winding(at(2.1, side * 0.6)), 0, "side {side}"); + assert_ne!(h.outline.winding(at(2.1, side * 0.45)), 0, "side {side}"); + // Slender: 2.4 units across at the barbs, not the 4 of the other arrows. + assert_eq!(h.outline.winding(at(3.9, side * 1.2)), 0, "side {side}"); + assert_ne!(h.outline.winding(at(3.9, side * 1.1)), 0, "side {side}"); + } + // Open in the notch, solid in front of it. + assert_eq!(h.outline.winding(at(3.5, 0.0)), 0); + assert_ne!(h.outline.winding(at(3.1, 0.0)), 0); + // The line stops between the bend and the notch, 2.7 units back from the tip. + assert!((h.inset - 5.4).abs() < 1e-9, "inset {}", h.inset); +} + +#[test] +fn the_line_under_the_notched_arrow_stays_inside_it_in_front_of_the_notch() { + // With every cap, no part of the 2 pt line between the notch and the tip shows beside the + // head, though the head is barely wider than the line at its bends. + for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] { + let (h, line) = head_and_line(Arrowhead::NotchedArrow, cap); + let mut covered = 0; + for i in 0..=132 { + for j in -25..=25 { + let p = Point::new(100.0 - 6.6 + f64::from(i) * 0.05, f64::from(j) * 0.04); + if line.winding(p) != 0 { + assert_ne!(h.outline.winding(p), 0, "{cap:?}: the line shows at {p:?}"); + covered += 1; + } + } + } + assert!(covered > 500, "{cap:?}: the line reaches under the head ({covered} samples)"); + } +} + #[test] fn half_arrows_barb_on_their_own_side() { // Pointing along +x on a y-down page, left is −y. diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 4fb4537ee4..d319e0d2a4 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -253,6 +253,8 @@ pub(crate) fn item_target(s: &Session, p: &Value, cmd: &str) -> Result Result { let aligned = aligned(p, cmd)?; + // Read `target` whatever names the objects, so that a bad one is refused with `ids` or `id` too. + let contents = targets_contents(p)?; match p.get(key) { Some(Value::Null) => Ok(ItemTarget::Top), Some(v) => v @@ -260,7 +262,7 @@ pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Re .map(|i| ItemTarget::Item { index: index(i), explicit: true, aligned }) .ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))), // The active item is a row of the first selected object's own stack. - None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top), + None if p.get("ids").is_some() || p.get("id").is_some() || contents => Ok(ItemTarget::Top), // A row of a graph design's art in a series stands for nothing: the commands leave that art out. None if s.active().and_then(|st| st.selection.subjects().first().map(|id| super::graph::is_design_art(&st.doc, *id))) == Some(true) => { Ok(ItemTarget::Top) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 1ac467789c..b8136e8cf5 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -945,8 +945,8 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; let for_tool = tool_color_params(s, p, cmd, !fill)?; let p = for_tool.as_ref().unwrap_or(p); - // A bad `target` or `aligned` is refused for every kind of target: `item_target` reads no - // `target` once `id` or `ids` names an object, and selected characters read neither. + // A bad `target` or `aligned` is refused for every kind of target: selected characters take + // the paint before `item_target` reads either. super::appearance::aligned(p, cmd)?; super::appearance::targets_contents(p)?; let focus = switch_or(p, "focus", true, cmd)?; @@ -1474,8 +1474,6 @@ fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index 38ce7b6a0d..fd88ff8e27 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -513,6 +513,23 @@ fn a_bad_target_is_refused_with_an_id_or_selected_characters() { } } +/// The other commands that name their appearance item the same way refuse a bad `target` with an +/// `id` or `ids` too, and leave the document alone; a good one still edits the object. +#[test] +fn a_stroke_edit_refuses_a_bad_target_with_an_id() { + let mut s = session(); + let r = rect(&mut s, 10.0); + select(&mut s, &[r]); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"weight": 9, "target": "content", "id": r.0}), json!({"weight": 9, "target": "content", "ids": [r.0]})] { + let e = s.execute("stroke.set", &p).unwrap_err(); + assert!(e.to_string().contains("`target` must be"), "{p}: {e}"); + assert_eq!(*s.doc().unwrap().doc, *doc, "{p}"); + } + s.execute("stroke.set", &json!({"weight": 9, "target": "object", "id": r.0})).unwrap(); + assert_ne!(*s.doc().unwrap().doc, *doc); +} + /// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows /// it; the object's fill item and the other points stay as they were. #[test] diff --git a/crates/engine/src/tests/strokegeom.rs b/crates/engine/src/tests/strokegeom.rs index 524dabef3e..af3eb52936 100644 --- a/crates/engine/src/tests/strokegeom.rs +++ b/crates/engine/src/tests/strokegeom.rs @@ -2,7 +2,7 @@ //! the width-profile presets. use serde_json::json; -use vectorcraft_doc::{ArrowAlign, StrokeLayer, WidthProfile}; +use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer, WidthProfile}; use crate::*; @@ -58,6 +58,19 @@ fn profiles_come_from_the_preset_catalogue() { } } +#[test] +fn the_notched_arrow_survives_the_native_format() { + let (mut s, id) = session_with_line(); + s.execute("stroke.set", &json!({"startArrow": "NotchedArrow", "endArrow": "NotchedArrow"})).unwrap(); + let st = stroke(&s, id); + assert_eq!((st.start_arrow, st.end_arrow), (Some(Arrowhead::NotchedArrow), Some(Arrowhead::NotchedArrow))); + let doc = &s.doc().unwrap().doc; + let text = String::from_utf8(vectorcraft_format::save(doc, true)).unwrap(); + assert_eq!(text.matches("\"NotchedArrow\"").count(), 2, "saved by name"); + let back = vectorcraft_format::load(text.as_bytes()).unwrap(); + assert_eq!(back.node(id).unwrap().appearance.stroke().unwrap(), &stroke(&s, id)); +} + #[test] fn arrow_align_and_profiles_survive_the_native_format() { let (mut s, id) = session_with_line(); diff --git a/crates/text/src/fontdb/wanted.rs b/crates/text/src/fontdb/wanted.rs index 31539737ad..8d72bdc3ab 100644 --- a/crates/text/src/fontdb/wanted.rs +++ b/crates/text/src/fontdb/wanted.rs @@ -35,7 +35,7 @@ impl WantedFonts { pub fn new(fonts: &[WantedFont]) -> Self { let mut by_name: HashMap> = HashMap::new(); for (i, w) in fonts.iter().enumerate() { - let mut names = vec![w.family.to_ascii_lowercase(), norm(&w.family)]; + let mut names = vec![w.family.to_ascii_lowercase(), norm(&w.family), joined(w)]; names.extend(w.installed.as_ref().map(|c| c.to_ascii_lowercase())); names.sort(); names.dedup(); @@ -136,6 +136,22 @@ fn provides(w: &WantedFont, faces: &[FaceStyle]) -> bool { }) { return true; } - // A legacy family with another style: that style of the family. - faces.iter().find(|f| f.keys.legacy.iter().any(|(family, _)| *family == key)).is_some_and(|f| styled(&f.family)) + // A legacy family with another style: that style of the family, among every face of the + // legacy family (in a collection they can be of different families). Once installed, the + // legacy family resolves the name, and `FontDb::canonical` doesn't join it. + let mut legacy = faces.iter().filter(|f| f.keys.legacy.iter().any(|(family, _)| *family == key)).peekable(); + if legacy.peek().is_some() { + return legacy.any(|f| styled(&f.family)); + } + // A family and style split from a PostScript name by an importer that didn't have the font + // (`Gilroy-Black` → Gilroy, Black), as `FontDb::canonical` joins them again: a face whose + // PostScript name is that name, whatever family and style the file gives it. Of a cataloged + // face, `canonical` reads the PostScript name only, so a full name alone isn't enough. + let joined = joined(w); + !sk.is_empty() && faces.iter().any(|f| f.keys.postscript.contains(&joined)) +} + +/// The family and style of `w` as one normalized name (`Gilroy` and `Black` → `gilroyblack`). +fn joined(w: &WantedFont) -> String { + format!("{}{}", norm(&w.family), norm(&w.style)) } diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 4ba72ee107..261cc1c54c 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -1257,3 +1257,64 @@ fn a_name_asked_for_before_its_font_is_installed_finds_it_after_a_rescan() { } let _ = std::fs::remove_dir_all(dir); } + +/// A document names `Gilroy-Black` as the family Gilroy in the style Black. A file whose own family is +/// `Gilroy-Black`, with no style, is that face, once cataloged and in a search of a folder. +#[test] +fn a_search_finds_the_file_of_a_postscript_name_split_into_family_and_style() { + let data = named(&[(3, EN, 1, "Gilroy-Black"), (3, EN, 4, "Gilroy-Black"), (3, EN, 6, "Gilroy-Black")]); + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-split-ps", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Gilroy-Black.ttf"); + std::fs::write(&file, &data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let (face, matched) = db.resolve("Gilroy", "Black").unwrap(); + assert_eq!(matched, FontMatch::Exact, "{face:?}"); + let wanted = |style: &str| WantedFonts::new(&[WantedFont { family: "Gilroy".into(), style: style.into(), installed: None }]); + assert_eq!(wanted("Black").provided_by(&file), [0]); + assert!(wanted("Bold").provided_by(&file).is_empty(), "another style of the family is another file"); + assert!(wanted("").provided_by(&file).is_empty(), "without a style, the family alone is not the PostScript name"); + let _ = std::fs::remove_dir_all(dir); + // The search offers a file only when installing it resolves the name exactly: not when the + // joined name is only a full name, and not when a legacy family of the same name resolves it + // first, to another style. + let cases = [ + ("full-name", vec![(3, EN, 1, "Gilroy Black"), (3, EN, 4, "Gilroy Black"), (3, EN, 6, "GilroyBlk")]), + ( + "legacy", + vec![(3, EN, 1, "Gilroy"), (3, EN, 2, "Regular"), (3, EN, 16, "Gilroy Display"), (3, EN, 17, "Regular"), (3, EN, 6, "Gilroy-Black")], + ), + ]; + for (name, records) in cases { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-split-ps-{name}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join(format!("{name}.ttf")); + std::fs::write(&file, named(&records)).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let exact = db.resolve("Gilroy", "Black").is_some_and(|(_, matched)| matched == FontMatch::Exact); + assert!(!exact, "{name}: installing the file doesn't resolve Gilroy Black exactly"); + assert!(wanted("Black").provided_by(&file).is_empty(), "{name}: so the search doesn't offer it"); + let _ = std::fs::remove_dir_all(dir); + } +} + +/// In a collection whose faces share a legacy family but not a typographic one, the search looks +/// for the style asked for in each face's family, in either order. +#[test] +fn a_search_finds_a_style_among_the_faces_of_a_shared_legacy_family() { + let regular = named(&[(3, EN, 1, "Gilroy"), (3, EN, 2, "Regular"), (3, EN, 16, "Gilroy Text"), (3, EN, 17, "Regular")]); + let black = + named(&[(3, EN, 1, "Gilroy"), (3, EN, 2, "Regular"), (3, EN, 16, "Gilroy Display"), (3, EN, 17, "Black"), (3, EN, 6, "Gilroy-Black")]); + for (order, faces) in [("regular-first", [regular.clone(), black.clone()]), ("black-first", [black.clone(), regular.clone()])] { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-shared-legacy-{order}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("shared.ttc"); + std::fs::write(&file, collection(&faces)).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let (face, matched) = db.resolve("Gilroy", "Black").unwrap(); + assert_eq!(matched, FontMatch::Exact, "{order}: {face:?}"); + let wanted = WantedFonts::new(&[WantedFont { family: "Gilroy".into(), style: "Black".into(), installed: None }]); + assert_eq!(wanted.provided_by(&file), [0], "{order}"); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 66e2eea0b0..5a92f70faa 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -2,7 +2,8 @@ //! //! Add: click a segment to insert an anchor without changing the shape (Alt = delete). //! Delete: click an anchor to remove it, re-fitting the neighbouring curve (Alt = add). -//! Anchor Point: click a smooth anchor → corner; drag an anchor → pull out smooth handles; click a +//! Anchor Point: click a smooth anchor → corner; drag an anchor → pull out smooth handles (Shift +//! pressed once the drag is under way: at 45° steps round the anchor); click a //! handle end → retract that handle only (#2267); drag a handle → move it independently (Shift: at //! 45° steps round its anchor; Alt: link it with the opposite handle, the anchor made smooth, except //! when the Pen lends the tool); drag a segment → reshape the curve, a selected blend's spine's too, @@ -278,6 +279,37 @@ impl AnchorTool { cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) } + /// Where anchor `ai` is in the document a preview edits: the document as the interaction + /// began, since each preview runs on that, otherwise the document `cx` shows. + fn began_anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option { + let d = cx.interaction_doc.unwrap_or(cx.doc); + d.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) + } + + /// Where a blend's spine point `ai` is in the spine a spine edit changes: the spine pinned + /// from the document as the interaction began (otherwise the document `cx` shows), as + /// `object.blend.spine.*` pins it. + fn spine_pos(cx: &ToolContext, id: NodeId, ai: usize) -> Option { + let d = cx.interaction_doc.unwrap_or(cx.doc); + match d.node(id).map(|n| &n.kind) { + Some(vectorcraft_doc::NodeKind::Blend { children, spec }) => { + let (path, _) = vectorcraft_doc::live::pin_spine(children, spec)?; + path.subpaths.first()?.anchors.get(ai).map(|a| a.p) + } + _ => None, + } + } + + /// Where handles pulled out of an anchor to `p` go: with Shift held, at 45° steps round the + /// anchor (`anchor` finds it) from General › Constrain Angle, as the Pen pulls handles out; + /// otherwise, or when the anchor is gone, `p`. + fn pulled_out(cx: &ToolContext, p: Point, shift: bool, anchor: impl FnOnce() -> Option) -> Point { + if !shift { + return p; + } + anchor().map_or(p, |a| a + constrain_angle_from(p - a, 45.0, cx.constrain_angle)) + } + /// Nearest point of this eligible spine, in document coordinates. fn spine_point(path: &vectorcraft_geom::PathData, p: Point, tol: f64) -> Option { path.anchors() @@ -582,10 +614,15 @@ impl Tool for AnchorTool { } let preview = match self.state { State::Idle => return out, - State::Convert { id, si, ai, .. } => Action::Preview( - "path.convertAnchor".into(), - json!({"id": id.0, "subpath": si, "anchor": ai, "to": "smooth", "x": p.x, "y": p.y}), - ), + State::Convert { id, si, ai, .. } => { + // Shift pressed once the drag is under way keeps the pulled-out handles at + // 45° steps; Shift at the press moved the anchor instead (`moving`). + let q = Self::pulled_out(cx, p, ev.mods.shift, || Self::began_anchor_pos(cx, id, si, ai)); + Action::Preview( + "path.convertAnchor".into(), + json!({"id": id.0, "subpath": si, "anchor": ai, "to": "smooth", "x": q.x, "y": q.y}), + ) + } State::Move { id, si, ai, from, start, .. } => { let d = Self::move_delta(cx, start, p, ev.mods.shift); self.measure = Some((p, d.x, d.y)); @@ -598,10 +635,13 @@ impl Tool for AnchorTool { let q = from + d; Action::Preview("object.blend.spine.moveAnchor".into(), json!({"id": id.0, "anchor": ai, "x": q.x, "y": q.y})) } - State::SpineConvert { id, ai, .. } => Action::Preview( - "object.blend.spine.convertAnchor".into(), - json!({"id": id.0, "anchor": ai, "to": "smooth", "x": p.x, "y": p.y}), - ), + State::SpineConvert { id, ai, .. } => { + let q = Self::pulled_out(cx, p, ev.mods.shift, || Self::spine_pos(cx, id, ai)); + Action::Preview( + "object.blend.spine.convertAnchor".into(), + json!({"id": id.0, "anchor": ai, "to": "smooth", "x": q.x, "y": q.y}), + ) + } State::SpineHandle { id, ai, out, .. } => { // Shift keeps the handle at 45-degree steps round its anchor, as for // ordinary Anchor Point handles. The spine anchor is a blend point, not diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index b2cbd22c03..9f66d7162c 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -821,6 +821,75 @@ fn anchor_point_shift_drag_moves_the_anchor() { assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 300.0).with_mods(shift)).is_empty()); } +/// Shift pressed once a drag from an anchor is under way keeps the handles it pulls out at 45° +/// steps round the anchor, on a path and on a selected blend's spine; released, it frees them. +#[test] +fn anchor_point_shift_mid_drag_constrains_pulled_out_handles() { + let shift = Mods { shift: true, ..Mods::default() }; + // The handle point a drag's preview gives `cmd`. + let target = |a: &[Action], cmd: &str| match a.last() { + Some(Action::Preview(c, v)) if c == cmd => v["x"].as_f64().zip(v["y"].as_f64()).map(|(x, y)| Point::new(x, y)), + _ => None, + }; + // The rectangle's corner at (100, 100). + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let mut t = AnchorTool::new("anchorPoint"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 140.0, 92.0)); + assert_eq!(target(&a, "path.convertAnchor"), Some(Point::new(140.0, 92.0)), "free without Shift: {a:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 140.0, 92.0).with_mods(shift)); + let q = target(&a, "path.convertAnchor").unwrap_or_default(); + assert!((q.y - 100.0).abs() < 1e-9 && q.x > 100.0, "level with the anchor: {a:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 106.0, 140.0).with_mods(shift)); + let q = target(&a, "path.convertAnchor").unwrap_or_default(); + assert!((q.x - 100.0).abs() < 1e-9 && q.y > 100.0, "straight below the anchor: {a:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 106.0, 140.0)); + assert_eq!(target(&a, "path.convertAnchor"), Some(Point::new(106.0, 140.0)), "free again once Shift is up: {a:?}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 106.0, 140.0)), vec![Action::Commit]); + // A selected blend's spine corner at (160, 310). + let (d, _, sel) = blend_spine_doc(false); + let c = cx(&d, &sel, &p); + let mut t = AnchorTool::new("anchorPoint"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 160.0, 310.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 160.0, 340.0)); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 200.0, 318.0).with_mods(shift)); + let q = target(&a, "object.blend.spine.convertAnchor").unwrap_or_default(); + assert!((q.y - 310.0).abs() < 1e-9 && q.x > 160.0, "level with the spine point: {a:?}"); +} + +/// Shift on handles pulled out of an anchor constrains them round the anchor in the document a +/// preview edits (the document as the interaction began), not round where the last preview +/// showed it, so the handles the command makes stay on the 45° steps. +#[test] +fn anchor_point_shift_pulls_out_round_the_anchor_the_preview_edits() { + let shift = Mods { shift: true, ..Mods::default() }; + // The rectangle's corner at (100, 100) as the interaction began. + let (began, id) = doc_with_rect(); + // The document shown: every anchor moved by (10, 20), as a previewed edit left them. + let mut shown = began.clone(); + if let Some(pd) = shown.node_mut(id).and_then(|n| n.path_data_mut()) { + for sp in &mut pd.subpaths { + for a in &mut sp.anchors { + a.p = Point::new(a.p.x + 10.0, a.p.y + 20.0); + } + } + } + let (s, p) = (Selection::default(), paint()); + let mut t = AnchorTool::new("anchorPoint"); + t.pointer(&cx(&began, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + let c = ToolContext { interaction_doc: Some(&began), ..cx(&shown, &s, &p) }; + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 140.0, 92.0).with_mods(shift)); + match a.last() { + Some(Action::Preview(cmd, v)) if cmd == "path.convertAnchor" => { + let y = v["y"].as_f64().unwrap_or(f64::NAN); + assert!((y - 100.0).abs() < 1e-9, "level with the anchor as the interaction began: {a:?}"); + } + other => panic!("expected a path.convertAnchor preview, got {other:?}"), + } +} + /// #3694: Space held mid-drag on a convert moves the anchor, handles and all. #[test] fn anchor_point_space_mid_drag_moves_the_anchor() { diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 9e4d188ddc..52df74f8cf 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -33,6 +33,7 @@ use vectorcraft_engine::doc::Document; use super::cleanup::Positional; use crate::VectorcraftApp; +use crate::edits::{EditPath, apply_edits}; use crate::menus::{Sep, c, cp}; use crate::panels::empty_state; @@ -302,31 +303,39 @@ pub(crate) fn open_dialog(app: &mut VectorcraftApp) -> Result { } /// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle -/// they all fold at (empty when they differ), which sets theirs when changed, and Reset, which -/// takes away the angles of their own. +/// they all fold at (empty when they differ), which sets theirs as it is typed, as one undo step +/// that a cancel takes back, and Reset, which takes away the angles of their own. fn show_angle(app: &mut VectorcraftApp, ui: &mut Ui, kept: &Rows) { if !kept.selection || kept.fold_lines == 0 { return; } - let mut call = None; + let mut edit = None; + let mut reset = false; let _ = Line::new().fill_width().show(ui, |ui, _| { Field::new(tl!("Fold Angle")).show(ui, |ui, _| { let field = NumberField::new(tl!("Fold Angle"), Bind::given(kept.angle)) .unit_kind(UnitKind::Degrees) .range(FOLD_ANGLES) .max_decimals(angle_places(kept.angle)); - if let Some(a) = field.id_salt("fold-angle").show(ui).value().copied().flatten() { - call = Some(json!({ "angle": a })); + edit = Some(field.id_salt("fold-angle").show(ui).edit); + }); + reset = clicked(&Button::new(tl!("Reset")).enabled(kept.stored_angles > 0).show(ui)); + }); + let run = |app: &mut VectorcraftApp, p: Value| { + if let Err(e) = app.run(SET_FOLD_ANGLE, p) { + app.status(e); + } + }; + // One undo step per edit of the field; a cancel reverts it. + if let Some(edit) = edit { + apply_edits(app, &edit, EditPath::Scope, |app, a: &Option, _| { + if let Some(a) = a { + run(app, json!({ "angle": a })); } }); - if clicked(&Button::new(tl!("Reset")).enabled(kept.stored_angles > 0).show(ui)) { - call = Some(json!({ "reset": true })); - } - }); - if let Some(p) = call - && let Err(e) = app.run(SET_FOLD_ANGLE, p) - { - app.status(e); + } + if reset { + run(app, json!({ "reset": true })); } } diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 8222b179d5..086ac45e1a 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use egui::{Key, Modifiers}; use serde_json::json; use vectorcraft_engine::Session; @@ -207,3 +208,45 @@ fn the_panel_shows_the_selected_lines_fold_angle_and_what_reset_takes_away() { let text = crate::tests_labels::painted_text(&mut app, show); assert!(!text.contains("Fold Angle"), "{text}"); } + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +#[test] +fn canceling_a_fold_angle_edit_restores_the_angle_and_enter_is_one_undo_step() { + // (the angle the second line folds at first, the text typed, the angle the lines then fold at): one angle, angles + // that differ, and a typed angle the field holds to its range. + for (second, text, typed) in [(None, "135", 135.0), (Some(-45.0), "135", 135.0), (None, "200", 180.0)] { + for cancel in [false, true] { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a, b]})).unwrap(); + if let Some(angle) = second { + app.run(SET_FOLD_ANGLE, json!({"angle": angle, "ids": [b]})).unwrap(); + } + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let mut panel = Panel::new(app, show); + let doc = panel.app().session.active().unwrap().doc.clone(); + let angle = read_rows(&mut panel.app()).angle; + let undo = undo_len(&panel.app()); + // The role list fills the panel's height, so the field below it takes the focus as a screen reader gives it. + panel.focus("Fold Angle"); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text(text); + panel.frame(); + assert_eq!(read_rows(&mut panel.app()).angle, Some(typed), "{second:?} {text}: the lines fold at the angle while it is typed"); + panel.key(if cancel { Key::Escape } else { Key::Enter }, Modifiers::NONE); + panel.frame(); + assert!(panel.shows("Fold Angle"), "{text}: the field stays"); + let mut app = panel.app(); + if cancel { + assert_eq!(app.session.active().unwrap().doc, doc, "{second:?} {text}: Escape restores the lines"); + assert_eq!(read_rows(&mut app).angle, angle, "{second:?} {text}: Escape restores the angle"); + assert_eq!(undo_len(&app), undo, "{second:?} {text}: Escape leaves no undo step"); + } else { + assert_eq!(read_rows(&mut app).angle, Some(typed), "{second:?} {text}: Enter keeps the angle"); + assert_eq!(undo_len(&app), undo + 1, "{second:?} {text}: the edit is one undo step"); + } + } + } +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 2b4ba91076..324f907615 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -5,7 +5,8 @@ //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog //! ([`tangent_circle_radius`]). Everything acts through `addon.pathtools.*` and `tool.setOption`, except that the radius -//! dialog draws its circle with `shape.circleThroughPoints`. +//! dialog draws its circle with `shape.circleThroughPoints`. Canceling an Anchor Inspector field edit restores its +//! opening value: an anchor edit is one undo step that the cancel takes back. pub mod bridge; pub mod corner; @@ -16,7 +17,7 @@ pub mod shared_edge; pub mod tangent_circle; pub mod tangent_circle_radius; -use craft::behavior::ColumnWidth; +use craft::behavior::{ColumnWidth, EditEvents}; use craft::menu::Node; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, clicked}; @@ -35,6 +36,7 @@ use vectorcraft_tools::addons::{anchor_eraser, extend_path, measure_inspect, par use crate::canvas::rulers::general_lengths; use crate::dialogs::host::open_held; +use crate::edits::{EditPath, apply_event}; use crate::menus::{Sep, c, cp}; use crate::panels::empty_state; use crate::{VectorcraftApp, fields}; @@ -73,14 +75,22 @@ const EXTEND_MODES: [(&str, &str); 3] = [("straight", "Straight"), ("bezier", "S pub(crate) struct Inspector { /// How many points Add Points puts on each segment. pub points_per_segment: u32, + /// The In and Out Angle fields' last typed values while their edits run; each field shows its handle's angle in + /// that value's turn, so `200` stays `200` rather than `-160`. + pub angles: [Option; 2], } impl Default for Inspector { fn default() -> Self { - Inspector { points_per_segment: 1 } + Inspector { points_per_segment: 1, angles: [None; 2] } } } +/// `degrees` moved by whole turns to lie nearest `near`; unchanged with no `near`. +fn in_turn_of(degrees: f64, near: Option) -> f64 { + near.map_or(degrees, |near| degrees + 360.0 * ((near - degrees) / 360.0).round()) +} + /// The first selected anchor as the panel shows it: positions less the ruler origin, handles as length and angle. pub(crate) struct AnchorReadout { pub x: f64, @@ -204,36 +214,38 @@ fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { let lengths = general_lengths(app); let origin = app.ruler_origin(); let mut points = app.addon_panels.inspector.points_per_segment; - let mut set: Option = None; + // Each anchor field's edits this pass, as the `addon.pathtools.setAnchor` params they send. + let mut edits: Vec>> = Vec::new(); let mut action: Option<(&str, Value)> = None; match anchor { Some(_) => Text::new(crate::i18n::fmt(tl!("Anchors selected: {count}"), &[("count", &readout.count.to_string())])).show(ui), None => Text::new(tl!("Direct-select anchor points to edit them.")).show(ui), }; let enabled = anchor.is_some(); - let length = |ui: &mut Ui, salt: &'static str, field: NumberField<'static>| typed(field.id_salt(salt).enabled(enabled).show(ui).value()); + // A cleared field sends no params, and its gesture still begins and ends. + let length = |ui: &mut Ui, salt: &'static str, field: NumberField<'static>, to: &dyn Fn(f64) -> Value| { + field.id_salt(salt).enabled(enabled).show(ui).edit.events.map(|v| v.map(to)) + }; + let mut typed_angles = app.addon_panels.inspector.angles; let angle = |ui: &mut Ui, salt: &'static str, v: Option| { let field = NumberField::new(tl!("Angle"), Bind::given(v)).unit_kind(UnitKind::Degrees).fixed_decimals(1); - typed(field.id_salt(salt).enabled(enabled).show(ui).value()) + field.id_salt(salt).enabled(enabled).show(ui).edit.events }; let _ = Grid::new(&COLUMNS).show(ui, |ui, _| { for (label, key, v, o) in [("X", "x", anchor.map(|a| a.x), origin.x), ("Y", "y", anchor.map(|a| a.y), origin.y)] { Text::new(tl!(label)).show(ui); - if let Some(v) = length(ui, key, NumberField::length(tl!(label), Bind::given(v), lengths)) { - set = Some(json!({ key: v + o })); - } + edits.push(length(ui, key, NumberField::length(tl!(label), Bind::given(v), lengths), &|v| json!({ key: v + o }))); } for (label, side, i) in [("In", "in", 0), ("Out", "out", 1)] { Text::new(tl!(label)).show(ui); // A handle's length is a size: `50%` is half of it. let len = fields::size_field(ui, tl!("Length"), anchor.map(|a| a.lengths[i]), lengths); - if let Some(v) = length(ui, if i == 0 { "in-length" } else { "out-length" }, len) { - set = Some(json!({ format!("{side}Length"): v })); - } + edits.push(length(ui, if i == 0 { "in-length" } else { "out-length" }, len, &|v| json!({ format!("{side}Length"): v }))); Text::new("∠").show(ui); - if let Some(v) = angle(ui, if i == 0 { "in-angle" } else { "out-angle" }, anchor.and_then(|a| a.angles[i])) { - set = Some(json!({ format!("{side}Angle"): v })); - } + let shown = anchor.and_then(|a| a.angles[i]).map(|v| in_turn_of(v, typed_angles[i])); + let events = angle(ui, if i == 0 { "in-angle" } else { "out-angle" }, shown); + typed_angles[i] = if events.ended().is_some() { None } else { events.value().copied().flatten().or(typed_angles[i]) }; + edits.push(events.map(|v| v.map(|v| json!({ format!("{side}Angle"): v })))); } }); Divider::horizontal().show(ui); @@ -247,7 +259,8 @@ fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { action = Some(("addon.pathtools.addPoints", json!({ "count": f64::from(points) }))); } let field = NumberField::new(tl!("Points per segment"), Bind::given(Some(f64::from(points)))).range(1.0..=100.0).fixed_decimals(0); - if let Some(v) = typed(field.id_salt("points-per-segment").enabled(selected).show(ui).value()) { + // The value the field holds after its events: a cancel's is the opening value. + if let Some(v) = typed(field.id_salt("points-per-segment").enabled(selected).show(ui).edit.events.landed()) { points = v as u32; } }); @@ -261,8 +274,14 @@ fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { } }); app.addon_panels.inspector.points_per_segment = points; - if let Some(p) = set { - run(app, "addon.pathtools.setAnchor", p); + app.addon_panels.inspector.angles = typed_angles; + // One undo step per gesture; a cancel reverts it. + for event in edits.iter().flatten() { + apply_event(app, event, &EditPath::Scope, &mut |app, p: &Option, _| { + if let Some(p) = p { + run(app, "addon.pathtools.setAnchor", p.clone()); + } + }); } if let Some((id, p)) = action { run(app, id, p); diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index b516412e61..895026b03c 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -1,4 +1,6 @@ +use craft::ui::contract::Role; use craft::ui::patterns::form_dialogs::{FieldValue, HostedParamDialog}; +use egui::{Key, Modifiers}; use serde_json::json; use vectorcraft_engine::Session; use vectorcraft_tools::addons::parametric_shape::ShapeKind; @@ -70,6 +72,81 @@ fn a_short_anchor_inspector_scrolls_to_the_selected_anchors_actions() { assert!(anchor.lengths.iter().all(|length| *length > 0.0)); } +/// The Anchor Inspector's anchor fields with what each test types: the field's name, which of the fields with that name +/// it is (In, then Out) and the text typed. +const ANCHOR_TYPED: [(&str, usize, &str); 6] = + [("X", 0, "40"), ("Y", 0, "60"), ("Length", 0, "30"), ("Angle", 0, "45"), ("Length", 1, "25"), ("Angle", 1, "200")]; + +/// An app whose open path's middle anchor is direct-selected and has both handles, from Make Smooth. +fn app_with_smooth_anchor() -> VectorcraftApp { + let mut app = app(); + let r = app.run("path.create", json!({"anchors": [{"x": 10, "y": 10}, {"x": 110, "y": 10}, {"x": 110, "y": 110}], "closed": false})).unwrap(); + let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + app.run("addon.pathtools.smooth", json!({})).unwrap(); + app +} + +fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +#[test] +fn canceling_an_anchor_field_restores_the_anchor_and_enter_is_one_undo_step() { + for (label, nth, text) in ANCHOR_TYPED { + for cancel in [false, true] { + let mut panel = Panel::new(app_with_smooth_anchor(), super::show); + let doc = panel.app().session.active().unwrap().doc.clone(); + let undo = undo_len(&panel.app()); + panel.click_role_nth(label, Role::SPIN_BUTTON, nth); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text(text); + panel.frame(); + let proposed = panel.app().session.active().unwrap().doc.clone(); + assert_ne!(proposed, doc, "{label} {nth} changes the anchor while typing"); + let shown = readout(&panel.app()).anchor.unwrap(); + panel.key(if cancel { Key::Escape } else { Key::Enter }, Modifiers::NONE); + panel.frame(); + assert!(panel.shows(label), "{label} {nth}: the panel stays open"); + let app = panel.app(); + if cancel { + assert_eq!(app.session.active().unwrap().doc, doc, "{label} {nth} restores the anchor on Escape"); + assert_eq!(undo_len(&app), undo, "{label} {nth}: Escape leaves no undo step"); + } else { + // Enter applies the typed value once more, which can move a handle by a rounding error. + let kept = readout(&app).anchor.unwrap(); + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + let angles = kept.angles.iter().zip(shown.angles).all(|(a, b)| a.zip(b).is_some_and(|(a, b)| near(a, b))); + let lengths = kept.lengths.iter().zip(shown.lengths).all(|(a, b)| near(*a, b)); + assert!(near(kept.x, shown.x) && near(kept.y, shown.y) && lengths && angles, "{label} {nth}: Enter keeps the edit"); + assert_eq!(undo_len(&app), undo + 1, "{label} {nth}: the edit is one undo step"); + } + } + } +} + +#[test] +fn canceling_points_per_segment_restores_its_value_and_enter_keeps_it() { + for cancel in [false, true] { + let mut panel = Panel::new(app_with_smooth_anchor(), super::show); + let undo = undo_len(&panel.app()); + panel.click_role("Points per segment", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("5"); + panel.key(if cancel { Key::Escape } else { Key::Enter }, Modifiers::NONE); + panel.frame(); + assert!(panel.shows("Points per segment"), "the panel stays open"); + let kept = if cancel { 1 } else { 5 }; + assert_eq!(panel.app().addon_panels.inspector.points_per_segment, kept, "canceled: {cancel}"); + assert_eq!(undo_len(&panel.app()), undo, "the field adds no undo step"); + } +} + /// Runs `f` on the held options dialog, `None` when none is open. fn held(app: &VectorcraftApp, f: impl FnOnce(Option<&mut HostedParamDialog>) -> R) -> R { app.dialogs().expect("the window's dialogs").with(|h| f(h.get_mut::())) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index df93dc6bac..2d2f5e9f4c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -140,7 +140,7 @@ impl VectorcraftApp { momentary: None, selection_box: None, selection_bounds: None, - content_bounds: None, + content_bounds: Vec::new(), variable_rows: None, three_d_exportable: None, pixel_aligned: None, diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 1e1de5ae93..a1ab70c788 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -482,16 +482,32 @@ impl VectorcraftApp { /// The art and the artboards together, the span of the canvas's scroll bars: measured once /// per revision, as the canvas reads it every frame. pub fn content_bounds(&mut self) -> Option { - let st = self.session.active()?; + let index = self.session.active_index()?; + self.content_bounds_of(index) + } + + /// The art and the artboards together of the document at `index`, the size each of its windows' canvases fits + /// and scrolls in: measured once per revision of each open document, as every canvas pass reads it. + pub(crate) fn content_bounds_of(&mut self, index: usize) -> Option { + let docs = self.session.documents(); + let st = docs.get(index)?; let key = (st.uid, st.revision); - if let Some((k, b)) = self.canvas.content_bounds - && k == key - { - return b; + if let Some((_, b)) = self.canvas.content_bounds.iter().find(|(k, _)| *k == key) { + return *b; } + #[cfg(test)] + CONTENT_MEASURES.with(|n| n.set(n.get() + 1)); let boards = st.doc.artboards.iter().map(|a| a.rect).reduce(|r, a| r.union(a)); let b = vectorcraft_geom::union_opt(st.doc.art_bounds(), boards); - self.canvas.content_bounds = Some((key, b)); + // An older revision of this document and the documents that have closed leave the cache. + self.canvas.content_bounds.retain(|((uid, _), _)| *uid != key.0 && docs.iter().any(|d| d.uid == *uid)); + self.canvas.content_bounds.push((key, b)); b } } + +#[cfg(test)] +thread_local! { + /// How many times this thread measured a document's content bounds ([`VectorcraftApp::content_bounds_of`]). + pub(crate) static CONTENT_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6907b7ce17..dfac727639 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -82,8 +82,8 @@ pub struct CanvasCache { pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option)>, /// [`VectorcraftApp::selection_bounds`] for (document uid, revision). pub selection_bounds: Option<((u64, u64), Option)>, - /// [`VectorcraftApp::content_bounds`] for (document uid, revision). - pub content_bounds: Option<((u64, u64), Option)>, + /// [`VectorcraftApp::content_bounds_of`] for (document uid, revision), one entry for each open document. + pub content_bounds: Vec<((u64, u64), Option)>, /// Whether the 3D and Materials panel's Export 3D Object button is available (a selected /// object has a 3D effect that `assets.add3D` exports) for (document uid, revision). pub three_d_exportable: Option<((u64, u64), bool)>, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 2efe7e984a..49878cb2d8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -429,13 +429,13 @@ fn scroll_bars(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Op } /// The size of the art and the artboards together, and the artboard Fit Artboard shows (the view's, -/// the first when it has gone). -pub(crate) fn view_target(app: &VectorcraftApp, win: Win) -> ViewTarget { +/// the first when it has gone). The size is measured once per document revision ([`VectorcraftApp::content_bounds_of`]). +pub(crate) fn view_target(app: &mut VectorcraftApp, win: Win) -> ViewTarget { + let all = app.content_bounds_of(win.0); let (Some(st), Some(view)) = (app.session.documents().get(win.0), doc_windows::view(app, win)) else { return ViewTarget::new(Size::new(1.0, 1.0)); }; - let boards = st.doc.artboards.iter().map(|a| a.rect).reduce(|r, a| r.union(a)); - let target = ViewTarget::new(document_size(vectorcraft_geom::union_opt(st.doc.art_bounds(), boards))); + let target = ViewTarget::new(document_size(all)); match st.doc.artboards.get(view.artboard).or(st.doc.artboards.first()) { Some(a) => target.artboard(a.rect), None => target, diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3f1eddb392..3fc37f6433 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6700,3 +6700,42 @@ fn a_move_stops_snapping_to_guides_hidden_during_it() { assert!((centre - xf.to_doc(near).x).abs() < 1e-4 || snaps, "{hide:?}: unsnapped, it follows the pointer: {centre}"); } } + +/// The canvas measures the art and the artboards once per document revision, not in every pass: frames that change +/// nothing measure nothing, an edit measures once, and two open documents keep a measure each. +#[test] +fn the_canvas_measures_the_document_once_per_revision() { + let measures = || crate::app::view::CONTENT_MEASURES.with(std::cell::Cell::get); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..20 { + let x = f64::from(i) * 15.0; + app.session.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 10, "height": 10})).unwrap(); + } + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + let before = measures(); + for _ in 0..10 { + app_step(&mut app, &ctx, vec![]); + } + assert_eq!(measures() - before, 0, "frames that change nothing measure nothing"); + app.session.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 10, "height": 10})).unwrap(); + for _ in 0..5 { + app_step(&mut app, &ctx, vec![]); + } + assert_eq!(measures() - before, 1, "an edit measures once"); + let win = crate::doc_windows::current(&app).unwrap(); + let size = super::view_target(&mut app, win).document; + assert!(size.width >= 510.0 && size.height >= 410.0, "the new rectangle is in the size: {size:?}"); + + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let before = measures(); + for _ in 0..5 { + for index in 0..2 { + let _ = super::view_target(&mut app, (index, 0)); + } + } + assert_eq!(measures() - before, 1, "the new document is measured once, and the first keeps its measure"); +} diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 291177c9e2..d32ec78d67 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -10,7 +10,7 @@ use craft::ui::contract::{Bind, BodyCx, Gap, Props, Show, ShowContainer}; use craft::ui::display::Picture; use craft::ui::layout_components::Row; use craft::ui::primitives::IconSpec; -use craft::ui::runtime::windows::WindowHost; +use craft::ui::runtime::windows::{WindowAction, WindowHost}; use craft::ui::shell::{Frame, Title, TitleBar}; use craft::ui::style::{SurfaceKind, Variant}; use egui::Ui; @@ -142,11 +142,18 @@ pub fn app_bar(ui: &mut Ui, _cx: &mut BodyCx<'_>, app: &mut VectorcraftApp) { let end = |ui: &mut Ui, _: &mut BodyCx<'_>| trailing(ui, &mut app.borrow_mut()); // A nightly's window and Dock entry carry its own name, so they never read as the stable app's. let title = if crate::os_window::stable_services_allowed() { tl!("VectorCraft") } else { crate::os_window::name() }; - let _ = if titled { + let out = if titled { TitleBar::new().surface(SurfaceKind::Background).show_titled(ui, Title::new(title), start, end) } else { TitleBar::new().surface(SurfaceKind::Background).show_fitted(ui, start, end) }; + // The title bar reports a caption Close click in its output and never acts on it. The window host sends the close, + // and a close of the main window goes through the app's close guard, so the unsaved-changes prompt runs as it does + // for an OS close. + if out.close_requested { + let ctx = ui.ctx().clone(); + WindowHost::of(&ctx).act(ctx.viewport_id(), WindowAction::Close); + } } /// The OS window title: the active document's name suffixed with the app name (a `*` prefix diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 9848d86f1a..51834cb232 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -1,9 +1,11 @@ use super::{ROTATE_VIEW_ANGLES, Ui, VectorcraftApp, json}; -use craft::behavior::IconId; use craft::behavior::kurbo::Size; +use craft::behavior::{CanvasView, IconId}; use craft::ui::bars::{Bar, BarKind, StatusMessage, StatusProgress}; use craft::ui::buttons::{Button, IconButton}; -use craft::ui::contract::{Bind, BodyCx, Entry, Gap, LabelKind, Outcome as _, Props as _, Show as _, ShowContainer as _, SideLabel, Trigger}; +use craft::ui::contract::{ + Bind, BodyCx, Entry, Gap, LabelKind, MemoProps, MemoView, Outbox, Outcome as _, Props as _, Show as _, ShowContainer as _, SideLabel, Trigger, +}; use craft::ui::display::{Divider, Elide, Shade, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Row; @@ -12,6 +14,7 @@ use craft::ui::pickers::{Select, SelectLook}; use craft::ui::runtime::env::Env; use craft::ui::style::TypeRole; use craft::ui::text::ZoomField; +use vectorcraft_engine::WindowView; /// Shows the status bar: zoom, rotation, artboard navigator, the info field with its Show menu, the readouts, Stop, /// the background-work progress and last the message, so a narrow bar elides the message before anything else. @@ -22,33 +25,32 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { ui.ctx().request_repaint_after(std::time::Duration::from_secs(secs)); } let print = app.print_ppi(); - let nab = app.session.active().map(|d| d.doc.artboards.len()).unwrap_or(0); + let st = app.session.active(); + let nab = st.map_or(0, |d| d.doc.artboards.len()); let cur = crate::panels::artboards::selected(app, nab); - // PLAN: assumed Artboard::rect has `width()` and `height()`. - let document = - app.session.active().and_then(|d| d.doc.artboards.get(cur)).map_or(Size::new(1.0, 1.0), |a| Size::new(a.rect.width(), a.rect.height())); - let boards: Vec> = app - .session - .active() - .map(|d| d.doc.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect()) - .unwrap_or_default(); - let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); let view = app.view(); let rotation = view.map_or(0.0, |v| v.rotation); + let lang = crate::i18n::current(); + let canvas_view = app.canvas_view(); + // PLAN: assumed Artboard::rect has `width()` and `height()`. + let document = st.and_then(|d| d.doc.artboards.get(cur)).map_or(Size::new(1.0, 1.0), |a| Size::new(a.rect.width(), a.rect.height())); + let scaling = app.ui_scaling(); let turned = ROTATE_VIEW_ANGLES.iter().position(|(_, a)| (rotation - a).abs() < 1e-9).unwrap_or(usize::MAX); // An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0 // turns the -0 of a small negative angle into 0. - let angle = format!("{}°", rotation.round() + 0.0); + let degrees = rotation.round() + 0.0; + let revision = st.map(|d| (d.uid, d.revision)); + let artboards = st.map_or(&[][..], |d| d.doc.artboards.as_slice()); + let mut picks = Vec::new(); let shows: Vec> = StatusBarShow::ALL.into_iter().map(|s| Entry::new(s, s.label()).checked(app.ui.status_bar_show == s)).collect(); let unit = app.session.general_unit(); - let lang = crate::i18n::current(); let render = crate::i18n::tr_ctx(lang, "diagnostics", "render"); let ui_name = crate::i18n::tr_ctx(lang, "diagnostics", "ui"); let busy = busy_labels(app); + let shown_zoom = view.map(|v| crate::state::zoom_display_percent(v.zoom, print)); - let (mut zoom_to, mut rotate_to, mut go, mut show_pick, mut stop) = (None, None, None, None, false); - let mut invalid_zoom = None; + let (mut show_pick, mut stop) = (None, false); let mut snapping = None; // Convenience controls leave first: direct toggles, then the menu. The existing timings and pointer position // retain their priority, and all trailing groups leave before the navigation, info field or message narrows. @@ -90,56 +92,22 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { }; // PLAN: assumed VectorcraftApp::canvas_view() -> Option (cv.S4) and the label msgid "Status Bar". Bar::new(tl!("Status Bar"), BarKind::Status).trailing(readouts).show(ui, |ui, _| { - let zoom = Field::new(tl!("Zoom")) - .side(SideLabel::new().kind(LabelKind::Hidden)) - .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui)); - // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. - if let Some(zoom) = zoom.inner { - if let Some(view) = zoom.view.committed() { - zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, app.ui_scaling()), print)); - } - invalid_zoom = zoom.invalid_zoom.map(|invalid| invalid.message(&Env::of(ui))); - } - Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { - // Entries are keyed by index: an angle is not a hashable value. - rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) - .placeholder(angle.clone()) - .look(SelectLook::Filled) - .enabled(view.is_some()) - .show(ui) - .events - .committed() - .copied(); - }); - Divider::vertical().show(ui); - for (icon, to, tip, enabled) in - [("chevrons_left", "first", tl!("First Artboard"), cur > 0), ("chevron_left", "previous", tl!("Previous Artboard"), cur > 0)] - { - if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { - go = Some(json!(to)); - } - } - Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { - // With no document the navigator shows a dash, as the info readout does. - if let Some(i) = Select::new(tl!("Artboard"), Bind::given(cur), &boards) - .placeholder("\u{2013}") - .look(SelectLook::Filled) - .enabled(nab > 0) - .show(ui) - .events - .committed() - .copied() - { - go = Some(json!(i)); - } - }); - for (icon, to, tip, enabled) in - [("chevron_right", "next", tl!("Next Artboard"), cur + 1 < nab), ("chevrons_right", "last", tl!("Last Artboard"), cur + 1 < nab)] - { - if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { - go = Some(json!(to)); - } - } + let navigation = Navigation { + view: canvas_view, + document, + scaling, + print, + shown_zoom, + has_view: view.is_some(), + turned, + degrees, + cur, + revision, + artboards, + lang, + picked: Outbox::new(&mut picks), + }; + let _ = MemoView::new("status-bar-navigation", navigation, show_navigation).show(ui); Divider::vertical().show(ui); // An empty readout shows a dash. let shown = if info.is_empty() { "\u{2013}" } else { info.as_str() }; @@ -174,10 +142,33 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some((id, params)) = snapping { crate::menus::invoke(app, id, params); } + // The last choice of each kind counts, as the controls report one choice of each in a pass. + let (mut zoom_to, mut invalid_zoom, mut preset_pick, mut rotate_to, mut go) = (None, None, None, None, None); + for pick in picks { + match pick { + NavigationPick::Zoom(zoom) => zoom_to = Some(zoom), + NavigationPick::InvalidZoom(message) => invalid_zoom = Some(message), + NavigationPick::Preset(preset) => preset_pick = Some(preset), + NavigationPick::Rotate(i) => rotate_to = Some(i), + NavigationPick::Artboard(to) => go = Some(to), + } + } // It fails only without a document, when there is no view to turn or zoom. if let Some(zoom) = zoom_to { app.run("view.setZoom", json!({"zoom": zoom})).ok(); } + match preset_pick { + Some(ZoomPreset::Percent(zoom)) => { + app.run("view.setZoom", json!({ "zoom": zoom })).ok(); + } + Some(ZoomPreset::FitOnScreen) => { + app.run("view.fitArtboard", json!({})).ok(); + } + Some(ZoomPreset::FitAll) => { + app.run("view.fitAll", json!({})).ok(); + } + None => {} + } if let Some(&(_, angle)) = rotate_to.and_then(|i| ROTATE_VIEW_ANGLES.get(i)) { app.run("view.rotate", json!({"angle": angle})).ok(); } @@ -196,10 +187,132 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// What the status bar's navigation controls read: the Zoom field, the Rotation menu and the artboard navigator. The +/// bar replays them while these hold still and nothing reaches them (`MemoView`), as most frames only move the +/// readouts. +#[derive(MemoProps)] +struct Navigation<'a> { + /// The canvas view the Zoom field shows and edits. + view: Option, + /// The size of the artboard the navigator shows, which the Zoom field fits. + document: Size, + /// UI Scaling, which divides the canvas view's zoom. + scaling: f32, + /// The density zoom percentages count from ([`VectorcraftApp::print_ppi`]). + print: Option, + /// The view's zoom percentage, which the Zoom Presets menu checks. + shown_zoom: Option, + /// Whether the active document has a view to turn. + has_view: bool, + /// The Rotate View preset the view is turned to, else `usize::MAX`. + turned: usize, + /// The view's angle in whole degrees, shown when it is between the presets. + degrees: f64, + /// The artboard the navigator shows. + cur: usize, + /// The active document's uid and revision. + revision: Option<(u64, u64)>, + #[memo_props(covered_by = "revision", reason = "a document's uid and revision change with every edit of it")] + artboards: &'a [vectorcraft_doc::Artboard], + #[memo_props(hash = "an interface language: an index into the languages offered")] + lang: crate::i18n::Lang, + /// What the controls chose in the pass. + picked: Outbox<'a, NavigationPick>, +} + +/// A choice made in the status bar's navigation controls ([`Navigation`]). +enum NavigationPick { + /// The view's zoom percentage the Zoom field committed (`view.setZoom`). + Zoom(f64), + /// The message of a zoom the Zoom field could not read. + InvalidZoom(String), + /// The entry chosen in the Zoom Presets menu. + Preset(ZoomPreset), + /// The Rotate View preset chosen (an index into [`ROTATE_VIEW_ANGLES`]). + Rotate(usize), + /// The `index` of `view.goToArtboard`: an artboard's index, or first, previous, next or last. + Artboard(serde_json::Value), +} + +/// The Zoom field, the Rotation menu and the artboard navigator of the status bar, from [`Navigation`]. +fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::NAVIGATION_RUNS.with(|n| n.set(n.get() + 1)); + let (view, document) = (p.view, p.document); + let zoom = Field::new(tl!("Zoom")) + .side(SideLabel::new().kind(LabelKind::Hidden)) + .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), view, document).scrub(true).show(ui)); + // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. + if let Some(zoom) = zoom.inner { + if let Some(view) = zoom.view.committed() { + let percent = crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, p.scaling), p.print); + p.picked.send(NavigationPick::Zoom(percent)); + } + if let Some(invalid) = zoom.invalid_zoom { + p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui)))); + } + } + let presets = zoom_presets(p.shown_zoom, p.print); + let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui); + if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked { + p.picked.send(NavigationPick::Preset(preset)); + } + let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); + let (turned, angle, has_view) = (p.turned, format!("{}°", p.degrees), p.has_view); + let mut rotate_to = None; + Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { + // Entries are keyed by index: an angle is not a hashable value. + rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) + .placeholder(angle.clone()) + .look(SelectLook::Filled) + .enabled(has_view) + .show(ui) + .events + .committed() + .copied(); + }); + if let Some(i) = rotate_to { + p.picked.send(NavigationPick::Rotate(i)); + } + Divider::vertical().show(ui); + let (cur, nab) = (p.cur, p.artboards.len()); + for (icon, to, tip, enabled) in + [("chevrons_left", "first", tl!("First Artboard"), cur > 0), ("chevron_left", "previous", tl!("Previous Artboard"), cur > 0)] + { + if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { + p.picked.send(NavigationPick::Artboard(json!(to))); + } + } + let boards: Vec> = p.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect(); + let mut go = None; + Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { + // With no document the navigator shows a dash, as the info readout does. + go = Select::new(tl!("Artboard"), Bind::given(cur), &boards) + .placeholder("\u{2013}") + .look(SelectLook::Filled) + .enabled(nab > 0) + .show(ui) + .events + .committed() + .copied(); + }); + if let Some(i) = go { + p.picked.send(NavigationPick::Artboard(json!(i))); + } + for (icon, to, tip, enabled) in + [("chevron_right", "next", tl!("Next Artboard"), cur + 1 < nab), ("chevrons_right", "last", tl!("Last Artboard"), cur + 1 < nab)] + { + if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { + p.picked.send(NavigationPick::Artboard(json!(to))); + } + } +} + #[cfg(test)] mod tests { use super::*; use crate::tests::panel_harness::Panel; + use craft::ui::canvas::ViewCommands; use craft::ui::contract::Role; #[test] @@ -272,6 +385,121 @@ mod tests { } } + thread_local! { + /// How many times this thread ran the status bar's navigation controls ([`show_navigation`]). + pub(super) static NAVIGATION_RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// Frames that change nothing the navigation controls show replay them instead of laying them out again; a new + /// zoom or a new artboard runs them once, and they show it. + #[test] + fn idle_frames_replay_the_navigation_controls() { + let runs = || NAVIGATION_RUNS.with(std::cell::Cell::get); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let mut panel = Panel::new(app, status_bar); + panel.room(egui::vec2(1200.0, 300.0)); + panel.frame(); + panel.frame(); + let before = runs(); + for _ in 0..10 { + panel.frame(); + } + assert_eq!(runs() - before, 0, "idle frames run the navigation controls no more"); + panel.app().run("view.setZoom", json!({"zoom": 200})).unwrap(); + panel.frame(); + panel.frame(); + assert!(runs() > before, "a new zoom runs them again"); + assert_eq!(panel.value("Zoom").as_deref(), Some("200%"), "and the field shows it"); + panel.app().run("artboard.new", json!({"x": 400, "y": 50, "width": 100, "height": 80, "name": "Back"})).unwrap(); + panel.frame(); + panel.frame(); + let before = runs(); + for _ in 0..10 { + panel.frame(); + } + assert_eq!(runs() - before, 0, "idle frames after an edit run them no more"); + assert!(panel.enabled("Next Artboard") || panel.enabled("Previous Artboard"), "the navigator counts the new artboard"); + } + + #[test] + fn the_zoom_presets_menu_sets_a_stop_and_fits_the_view() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + app.run("view.setZoom", json!({"zoom": 800})).unwrap(); + app.view_mut().unwrap().request = None; + // The canvas applies a fit on its next frame; the status bar alone leaves the request queued. + let requested = |panel: &Panel| panel.app().view().and_then(|v| v.request.map(|(r, _)| r.command())); + let document = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, status_bar); + // Room for the whole menu, so the entries at its foot are on screen. + panel.room(egui::vec2(1200.0, 1600.0)); + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("200%", Role::MENU_ITEM_RADIO); + let print = panel.app().print_ppi(); + assert!((crate::state::zoom_display_percent(panel.app().view().unwrap().zoom, print) - 200.0).abs() < 1e-6, "a stop sets its zoom"); + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("Fit on Screen", Role::MENU_ITEM_RADIO); + assert_eq!(requested(&panel), Some(ViewCommands::FitArtboard), "Fit on Screen runs view.fitArtboard"); + panel.app().view_mut().unwrap().request = None; + + panel.click_role("Zoom Presets", Role::BUTTON); + panel.click_role("Fit All", Role::MENU_ITEM_RADIO); + assert_eq!(requested(&panel), Some(ViewCommands::FitOnScreen), "Fit All runs view.fitAll"); + + let app = panel.app(); + assert_eq!(app.session.active().unwrap().doc, document); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "zooming records no undo step"); + } + + #[test] + fn the_zoom_presets_list_the_stops_from_the_highest_and_check_the_shown_zoom() { + let presets = zoom_presets(Some(200.0), None); + let labels: Vec = presets.iter().filter(|e| e.is_item()).map(|e| e.label().as_str().to_owned()).collect(); + assert_eq!(labels.first().map(String::as_str), Some("64000%")); + assert_eq!(labels.iter().rev().take(3).rev().map(String::as_str).collect::>(), ["3.13%", "Fit on Screen", "Fit All"]); + let checked: Vec<_> = presets.iter().filter(|e| e.is_checked()).filter_map(|e| e.value().copied()).collect(); + assert_eq!(checked, [ZoomPreset::Percent(200.0)]); + assert!(zoom_presets(None, None).iter().all(|e| !e.is_checked()), "without a view no stop is checked"); + } + + /// With Display Print Size on, 100% is more or less than one screen point per document point, so the stops at + /// the ends of the list can fall outside the view's zoom range; the menu lists only the stops a pick sets exactly. + #[test] + fn the_zoom_presets_leave_out_stops_outside_the_zoom_range_at_print_size() { + let percents = |print: Option| -> Vec { + zoom_presets(None, print) + .iter() + .filter_map(|e| match e.value() { + Some(ZoomPreset::Percent(pct)) => Some(*pct), + _ => None, + }) + .collect() + }; + let stops: Vec = crate::state::zoom_stop_percents().collect(); + let n = stops.len(); + assert_eq!(percents(None).len(), n, "at 1:1 every stop is in range"); + let dense = crate::state::print_ppi(true, Some(96.0)); + assert_eq!(percents(dense).first(), Some(&stops[n - 2]), "64000% at 96 PPI is past the highest zoom, 25600% is not"); + assert_eq!(percents(dense).last(), Some(&stops[0]), "3.13% at 96 PPI is in range"); + let sparse = crate::state::print_ppi(true, Some(40.0)); + assert_eq!(percents(sparse).first(), Some(&stops[n - 1]), "64000% at 40 PPI is in range"); + assert_eq!(percents(sparse).last(), Some(&stops[2]), "3.13% and 4.17% at 40 PPI are below the lowest zoom, 6.25% is not"); + let (min, max) = WindowView::ZOOM_RANGE; + for print in [None, dense, sparse] { + for pct in percents(print) { + let zoom = crate::state::zoom_from_display_percent(pct, print); + let set = crate::state::zoom_display_percent(zoom.clamp(min, max), print); + assert!((set - pct).abs() < 1e-6, "{pct}% at {print:?} sets {set}%"); + } + } + } + #[test] fn with_no_document_the_artboard_navigator_shows_a_dash() { let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -295,6 +523,41 @@ fn busy_labels(app: &VectorcraftApp) -> Vec<&str> { .collect() } +/// An entry of the Zoom Presets menu beside the status bar's zoom field. +#[derive(Clone, Copy, Debug, PartialEq)] +enum ZoomPreset { + /// A zoom stop, in the percent `view.setZoom` takes. + Percent(f64), + /// Fit on Screen (`view.fitArtboard`). + FitOnScreen, + /// Fit All (`view.fitAll`). + FitAll, +} + +/// The Zoom Presets menu: the zoom stops from the highest, the one at the `shown` percent checked, then Fit on Screen +/// and Fit All. A stop whose zoom falls outside the view's zoom range ([`WindowView::ZOOM_RANGE`]) at the `print` +/// setting is left out, since `view.setZoom` would set the nearest end of the range instead. +fn zoom_presets(shown: Option, print: Option) -> Vec> { + let (min, max) = WindowView::ZOOM_RANGE; + let reachable = |pct: &f64| { + let zoom = crate::state::zoom_from_display_percent(*pct, print); + zoom >= min * (1.0 - 1e-9) && zoom <= max * (1.0 + 1e-9) + }; + let stops = crate::state::zoom_stop_percents(); + let mut entries: Vec> = stops + .rev() + .filter(reachable) + .map(|pct| { + let label = crate::state::zoom_label(crate::state::zoom_from_display_percent(pct, print), print); + Entry::new(ZoomPreset::Percent(pct), label).checked(shown.is_some_and(|s| (s - pct).abs() < 0.01)) + }) + .collect(); + entries.push(Entry::separator()); + entries.push(Entry::new(ZoomPreset::FitOnScreen, tl!("Fit on Screen"))); + entries.push(Entry::new(ZoomPreset::FitAll, tl!("Fit All"))); + entries +} + /// What the status bar's info field shows, chosen from the Show menu that a click on the field /// opens (`view.statusBarShow`). Kept with the UI state ([`crate::UiState::status_bar_show`]). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index a06ee63300..8fe7f3e43f 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -473,6 +473,59 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() { assert!(widest.zip(narrowest).is_some_and(|(w, n)| n >= w - 0.5), "the search keeps its width until it goes: {search_widths:?}"); } +/// A click on the title bar's Close caption button asks the window to close, and the close reaches the app's close guard +/// as an OS close does: with a modified document the window stays and the Unsaved Changes question shows. +#[test] +fn the_title_bars_close_button_closes_the_window() { + use craft::window::policy::{Backend, Desktop, Frame, Os, Runtime, TitleBarPref, WindowKind, decide}; + crate::i18n::set_current(crate::i18n::Lang::EN); + // The window the desktop host opens on Windows: decorations off, and the title bar draws the caption buttons. + let desktop = Desktop::detect(Backend::X11); + let decision = decide(Os::Windows, Runtime::Native, Backend::X11, &desktop, WindowKind::Main, TitleBarPref::Integrated, None); + assert!(matches!(decision.frame, Frame::Integrated(_)), "{:?}", decision.frame); + let ctx = egui::Context::default(); + craft::ui::shell::embed::install(&ctx, craft::ui::testing::install_spec().frame(decision), &crate::ui_fonts()).expect("the runtime installs"); + craft::ui::testing::windows::set_os(&ctx, Os::Windows); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.session.add_document(vectorcraft_doc::Document::new(612.0, 792.0), None); + app.sync_views(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + let room = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 600.0)); + let frame = |app: &mut crate::VectorcraftApp, events: Vec| { + let out = crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect: Some(room), events, ..Default::default() }); + out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|root| root.commands.contains(&egui::ViewportCommand::Close)) + }; + // The Close button sits at the bar's right end, flush with the window's top right corner. + let at = egui::pos2(room.right() - 4.0, 4.0); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let mut closed = false; + for events in [vec![], vec![], vec![egui::Event::PointerMoved(at)]] { + closed |= frame(&mut app, events); + } + assert!(!closed, "no close before the click"); + for events in [vec![button(true)], vec![button(false)], vec![]] { + closed |= frame(&mut app, events); + } + assert!(closed, "the Close caption button asks the main window to close"); + // The host answers the close with the window's close event, which `embed::logic` takes to the app's close guard. + let mut raw = egui::RawInput { screen_rect: Some(room), ..Default::default() }; + raw.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); + let mut decision = None; + ctx.run_ui(raw, |ui| { + app.ui(ui); + craft::ui::shell::embed::logic(ui.ctx(), || { + let answer = app.close_decision(); + decision = Some(answer); + answer + }); + }) + .textures_delta + .clear(); + assert_eq!(decision, Some(craft::ui::shell::embed::CloseDecision::Hold), "the modified document keeps the window open"); + let asks = app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get::().is_some())); + assert!(asks, "the close asks about the modified document"); +} + /// The app bar's right-hand controls stand at least `space.gap.item` apart, the gap between neighboring controls in a /// bar, so a hovered control's highlight does not touch the one beside it. #[test] diff --git a/crates/ui-egui/src/dialogs/bullets_numbering.rs b/crates/ui-egui/src/dialogs/bullets_numbering.rs index 9bff24d03e..dd09594490 100644 --- a/crates/ui-egui/src/dialogs/bullets_numbering.rs +++ b/crates/ui-egui/src/dialogs/bullets_numbering.rs @@ -404,7 +404,7 @@ impl BulletsDialog { let entries = [Entry::new(0usize, tl!("Left")), Entry::new(1, tl!("Right"))]; let current = self.fields.get("listAlign").and_then(Value::as_str).and_then(|a| ALIGNS.iter().position(|x| *x == a)); let edit = Select::new(tl!("Alignment:"), Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), &entries).show(ui); - if let Some(&i) = edit.value() + if let Some(&i) = edit.events.committed() && let Some(a) = ALIGNS.get(i) { self.fields.insert("listAlign".into(), json!(a)); @@ -924,6 +924,48 @@ mod tests { assert!(app.run("ui.bulletsAndNumbering", json!({})).is_err(), "no type selected"); } + /// Alignment: an entry highlighted with the arrow keys changes no field and leaves the type as it was, Escape + /// closes the list with the dialog open and nothing changed, and Enter applies the entry. + #[test] + fn a_highlighted_alignment_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 10, "text": "One\nTwo", "area": {"width": 200, "height": 100}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + panel.app().run("ui.bulletsAndNumbering", json!({})).unwrap(); + panel.frame(); + panel.frame(); + let state = |panel: &Panel| { + let app = panel.app(); + (fields(&app)["listAlign"].clone(), first(&app, id)) + }; + let before = state(&panel); + assert_eq!(before.0, "left"); + panel.click_role("Alignment:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "a highlighted alignment changes no field and leaves the type as it was"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel.app()), "Escape closes the list, not the dialog"); + assert_eq!(state(&panel), before, "Escape leaves the alignment as it was"); + panel.click_role("Alignment:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel.app()), "Enter in the list keeps the dialog open"); + assert_eq!(state(&panel).0, "right", "Enter applies the alignment"); + } + /// Cancel puts back what the preview changed: the list, its alignment and the indents. #[test] fn cancel_puts_the_type_back_as_it_was() { diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 50e4cb9e31..584964e0c4 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -826,7 +826,7 @@ fn paint_row(key: &'static str, label: &'static str, swatches: Vec<(String, Valu entries.push(Entry::new(selected.clone(), Label::from(shown))); } let out = Select::new(Label::from(label), Bind::given(selected), &entries).show(ui); - if let Some(id) = out.value().cloned() { + if let Some(id) = out.events.committed().cloned() { let paint = match id.as_str() { "" => Some(Value::Null), "none" => Some(json!({"type": "none"})), diff --git a/crates/ui-egui/src/dialogs/char_style_options/tests.rs b/crates/ui-egui/src/dialogs/char_style_options/tests.rs index 4c54feadf6..258d925608 100644 --- a/crates/ui-egui/src/dialogs/char_style_options/tests.rs +++ b/crates/ui-egui/src/dialogs/char_style_options/tests.rs @@ -1007,6 +1007,46 @@ fn color_and_features_preview_cancel_commit_and_new_style() { assert!(t.runs.iter().all(|r| r.style.style_name.as_deref() == Some("Body"))); } +/// Character Color's Fill and Stroke: a paint highlighted with the arrow keys changes no field and leaves the +/// document as it was, Escape closes the list with the dialog open and nothing changed, and Enter sets the paint. +#[test] +fn a_highlighted_character_color_paint_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + for (name, key) in [("Fill", "fill"), ("Stroke", "stroke")] { + let mut app = app(); + styled(&mut app, json!({"size": 24.0}), "Text"); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app(), "Body"); + set::(&panel.app(), "tab", json!("color")); + panel.frame(); + panel.frame(); + let state = |panel: &Panel| { + let app = panel.app(); + (fields::(&app), app.session.doc().unwrap().doc.clone()) + }; + let before = state(&panel); + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "a highlighted {name} paint changes nothing"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert!(is_open::(&panel.app()), "Escape closes the {name} list, not the dialog"); + assert_eq!(state(&panel), before, "Escape leaves {name} as it was"); + panel.click_role(name, Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert!(is_open::(&panel.app()), "Enter in the {name} list keeps the dialog open"); + assert_ne!(state(&panel).0[key], before.0[key], "Enter sets the {name} paint"); + } +} + /// A size or leading below the minimum is refused by OK and runs no preview. #[test] fn size_and_leading_below_minimum_do_not_preview_or_commit() { diff --git a/crates/ui-egui/src/dialogs/composite_fonts.rs b/crates/ui-egui/src/dialogs/composite_fonts.rs index 3ab762bfc5..0465d1e322 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts.rs @@ -604,7 +604,7 @@ impl CompositeFontsDialog { } }) .cell_field(STYLE, style, move |out| { - if let Some(style) = out.value().cloned() { + if let Some(style) = out.events.committed().cloned() { edits.borrow_mut().push((at, PartEdit::Style(style))); } }); diff --git a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs index 3a56a41c23..48070f0b41 100644 --- a/crates/ui-egui/src/dialogs/composite_fonts/tests.rs +++ b/crates/ui-egui/src/dialogs/composite_fonts/tests.rs @@ -612,6 +612,44 @@ fn custom_character_sets_draw_their_characters_and_the_buttons() { } } +/// The parts table's Style: a style highlighted with the arrow keys leaves the font's parts as they were, Escape closes +/// the list with nothing changed, and Enter sets the style. +#[test] +fn a_highlighted_part_style_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + let mut p = Panel::new(app(), crate::tests::picks::dialogs); + p.room(egui::vec2(1280.0, 1100.0)); + open(&mut p.app()).unwrap(); + new_font(&mut p.app()); + dialog(&mut p.app(), |d| { + for class in CharClass::ALL { + d.edit_part(row(class), PartEdit::Font("Source Sans 3".into(), Some("Regular".into()))); + } + }); + p.frame(); + p.frame(); + let parts = |p: &Panel| dialog(&mut p.app(), |d| d.font().map(|f| f.parts.clone())); + let before = parts(&p); + p.click_role("Style", Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + p.frame(); + assert_eq!(parts(&p), before, "a highlighted style changes no part"); + p.key(Key::Escape, Modifiers::NONE); + p.frame(); + assert!(is_open(&p.app()), "Escape closes the list, not the dialog"); + assert_eq!(parts(&p), before, "Escape leaves the parts as they were"); + p.click_role("Style", Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + p.key(Key::Enter, Modifiers::NONE); + p.frame(); + assert!(is_open(&p.app()), "Enter in the list keeps the dialog open"); + assert_ne!(parts(&p), before, "Enter sets the style"); +} + #[test] fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index 78a86553c1..98a8515c16 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -25,8 +25,8 @@ pub(crate) const CMD: &str = "object.vectorHalftone"; pub(crate) struct Open { /// The dialog's id on the host. pub id: DialogId, - /// The drawing whose art the dialog previews and changes. - document: u64, + /// The drawing whose art the dialog previews and changes: its uid and revert count. + document: (u64, u64), /// The temporary dots the dialog shows while it previews. pub preview: LivePreview, } @@ -72,7 +72,7 @@ pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec { /// Opens Object › Vector Halftone, previewing from its first frame. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let document = app.session.active().ok_or("no document")?.uid; + let document = app.session.active().map(|doc| (doc.uid, doc.reverts)).ok_or("no document")?; let defaults = fields(); let rows = screen_params(false, &DialogFields::new()); let initial = fields_of(&rows, defaults.as_object().unwrap_or(&Default::default())); @@ -83,7 +83,12 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ok = |app: &mut VectorcraftApp, result: &ParamResult| { let open = app.effect_dialogs.halftone.as_ref().ok_or("the dialog is closed")?; if !open.in_source(app) { - return Err(tl!("Return to the original drawing to apply Vector Halftone").into()); + let why = if open.reverted(app) { + tl!("The document was reverted. Reopen this dialog to continue.") + } else { + tl!("Return to the original drawing to apply Vector Halftone") + }; + return Err(why.into()); } let params = Value::Object(json_of(&screen_params(false, &result.fields), &result.fields)); let mut open = app.effect_dialogs.halftone.take().ok_or("the dialog is closed")?; @@ -139,10 +144,148 @@ pub(crate) fn previewing(app: &VectorcraftApp) -> bool { impl Open { fn in_source(&self, app: &VectorcraftApp) -> bool { - app.session.active().is_some_and(|doc| doc.uid == self.document) + app.session.active().is_some_and(|doc| (doc.uid, doc.reverts) == self.document) + } + + /// Whether the active drawing is the opening one, reverted since the dialog opened. + fn reverted(&self, app: &VectorcraftApp) -> bool { + let (uid, reverts) = self.document; + app.session.active().is_some_and(|doc| doc.uid == uid && doc.reverts != reverts) } } fn owns_preview(app: &VectorcraftApp) -> bool { app.session.active().and_then(|st| st.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == CMD) } + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_engine::Session; + + use super::*; + use crate::tests::panel_harness::Panel; + + const REVERTED: &str = "The document was reverted. Reopen this dialog to continue."; + + /// A panel over a saved drawing of one black ellipse, with Vector Halftone open on it. The + /// directory holds the saved file. + fn open_on_a_saved_drawing(tag: &str) -> (Panel, vectorcraft_testkit::TempDir) { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.ellipse", json!({"x": 50, "y": 50, "width": 120, "height": 100})).unwrap(); + app.run("paint.setFill", json!({"color": "#000000"})).unwrap(); + let dir = vectorcraft_testkit::TempDir::new(tag); + app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string()))); + app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string()))); + app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + open_dialog(&mut panel); + (panel, dir) + } + + fn open_dialog(panel: &mut Panel) { + crate::menus::invoke(&mut panel.app(), CMD, json!({})); + panel.frame(); + panel.frame(); + assert!(panel.app().effect_dialogs.halftone.is_some(), "Vector Halftone is open"); + } + + fn id(panel: &Panel) -> DialogId { + panel.app().effect_dialogs.halftone.as_ref().map(|o| o.id).expect("Vector Halftone is open") + } + + /// Sets a field as a control client would, then runs two frames. + fn set(panel: &mut Panel, field: &str, value: Value) { + let (id, ctx) = (id(panel), panel.ctx().clone()); + let host = panel.app().dialogs().unwrap(); + host.with(|h| h.set_json_field(&ctx, id, field, value)).unwrap(); + panel.frame(); + panel.frame(); + } + + /// Reverts the drawing to its saved copy and selects the restored ellipse again; returns the + /// restored document and its undo depth. + fn revert_and_reselect(panel: &mut Panel) -> (std::sync::Arc, usize) { + let mut app = panel.app(); + app.run("file.revert", json!({"confirmed": true})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let st = app.session.doc().unwrap(); + (st.doc.clone(), st.history.undo.len()) + } + + fn doc(panel: &Panel) -> std::sync::Arc { + panel.app().session.doc().unwrap().doc.clone() + } + + fn undo_steps(panel: &Panel) -> usize { + panel.app().session.doc().unwrap().history.undo.len() + } + + /// Asserts that the held OK was refused for the revert and the dialog is still open. + fn assert_refused_for_the_revert(panel: &Panel) { + let id = id(panel); + let held = panel.app().dialogs().unwrap().with(|h| h.held_state(id)); + assert!( + matches!(&held, Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str() == REVERTED), + "OK is refused for the revert, the held state is {held:?}" + ); + assert!(panel.app().any_dialog_open(), "the dialog stays open with the refusal"); + } + + /// After File > Revert the draft does not preview on the restored drawing, OK is refused and + /// changes nothing, and Cancel changes nothing; reopened, the dialog applies again. + #[test] + fn vector_halftone_refuses_its_draft_after_file_revert() { + let (mut panel, _dir) = open_on_a_saved_drawing("halftone-revert"); + set(&mut panel, "frequency", json!(25)); + assert!(previewing(&panel.app()), "the draft previews before the revert"); + + let (restored, undo) = revert_and_reselect(&mut panel); + panel.frame(); + panel.frame(); + assert_eq!(doc(&panel), restored, "Preview must leave the restored drawing unchanged"); + set(&mut panel, "frequency", json!(30)); + assert_eq!(doc(&panel), restored, "Preview must leave the restored drawing unchanged after an edit"); + assert!(!panel.app().session.in_interaction(), "no preview runs on the restored drawing"); + + panel.click("OK"); + panel.frame(); + assert_eq!(doc(&panel), restored, "OK must leave the restored drawing unchanged"); + assert_eq!(undo_steps(&panel), undo, "OK must record no undo step"); + assert!(panel.app().effect_dialogs.halftone.is_some(), "the dialog stays open"); + assert_refused_for_the_revert(&panel); + + panel.click("Cancel"); + panel.frame(); + assert!(panel.app().effect_dialogs.halftone.is_none(), "Cancel closes the dialog"); + assert_eq!(doc(&panel), restored, "Cancel must leave the restored drawing unchanged"); + + open_dialog(&mut panel); + assert!(previewing(&panel.app()), "the reopened dialog previews on the restored drawing"); + panel.click("OK"); + panel.frame(); + assert!(panel.app().effect_dialogs.halftone.is_none(), "the reopened dialog applies"); + assert_ne!(doc(&panel), restored, "the reopened dialog changes the restored drawing"); + assert_eq!(undo_steps(&panel), undo + 1, "the reopened dialog's OK is one undo step"); + } + + /// With Preview off, OK after File > Revert is refused and leaves the restored drawing as it is. + #[test] + fn vector_halftone_without_preview_refuses_ok_after_file_revert() { + let (mut panel, _dir) = open_on_a_saved_drawing("halftone-revert-no-preview"); + set(&mut panel, "preview", json!(false)); + set(&mut panel, "frequency", json!(25)); + assert!(!panel.app().session.in_interaction(), "nothing previews with Preview off"); + // With Preview off the drawing has no unsaved change to revert yet. + panel.app().run("object.move", json!({"dx": 5, "dy": 0})).unwrap(); + + let (restored, undo) = revert_and_reselect(&mut panel); + panel.frame(); + panel.click("OK"); + panel.frame(); + assert_eq!(doc(&panel), restored, "OK must leave the restored drawing unchanged"); + assert_eq!(undo_steps(&panel), undo, "OK must record no undo step"); + assert_refused_for_the_revert(&panel); + } +} diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index caefb3bf5c..f3d056a219 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -20,23 +20,23 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::{Background, ColorMode, Unit}; use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, RASTER_PPI}; -use craft::behavior::{ColumnWidth, IconId, Mixed}; +use craft::behavior::{ColumnWidth, IconId}; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, Gap, Props as _, Show as _, ShowContainer as _, clicked}; +use craft::ui::contract::{Bind, Entry, FieldLayout, Gap, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, clicked}; use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; -use craft::ui::layout_components::{Grid, Row}; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::form_dialogs::{ CardCx, CardSource, DetailsCx, DocumentCard, DocumentSettings, HostedNewDocument, NewDocumentDialog, Orientation, PresetCategory, }; use craft::ui::patterns::presets::{GroupPath, NamedPresetEvent, PresetLibrary}; use craft::ui::pickers::Select; use craft::ui::popover::Popover; -use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; +use craft::ui::runtime::env::{Env, Label, LengthUnits, UnitKind}; use craft::ui::sections::Section; use craft::ui::style::TypeRole; -use craft::ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField}; +use craft::ui::text::{LinkMode, LinkedWords, NumberField, follow_equal, link_toggle}; use super::host::open_held; use crate::VectorcraftApp; @@ -288,30 +288,34 @@ impl DocumentSettings for VcNewDocument { let s = &mut values.settings; let units: Vec> = UNITS.iter().map(|u| Entry::new(*u, Label::from(u.label()))).collect(); - Field::new(width.clone()).show(ui, |ui, _| { + // Each label stands above its field, and the fields fill the column, as Name above them does. + Field::new(width.clone()).layout(FieldLayout::Above).id_salt("width").show(ui, |ui, _| { Row::new().show(ui, |ui, _| { size_field(ui, &width, &mut s.width, lengths); - if let Some(u) = Select::new(text(tl!("Units")), Bind::given(unit), &units).show(ui).events.committed().cloned() { + let select = Select::new(text(tl!("Units")), Bind::given(unit), &units).sizing(Sizing::Content); + if let Some(u) = select.show(ui).events.committed().cloned() { s.units = u; memory.units_chosen = true; } }); }); - // The row wraps whenever its fields do not fit the column, so Artboards is never cut off at its right edge. - Row::new().wrap(true).show(ui, |ui, _| { - Field::new(height.clone()).show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths)); - Field::new(orientation.clone()).show(ui, |ui, _| { + // Three shares: the grid stacks the three fields when the column has no room for them side by side, so + // Artboards is never cut off at its right edge. + Grid::new(&THIRDS).fill().show(ui, |ui, _| { + Field::new(height.clone()).layout(FieldLayout::Above).id_salt("height").show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths)); + Field::new(orientation.clone()).layout(FieldLayout::Above).id_salt("orientation").show(ui, |ui, _| { let entries = [ Entry::new(Orientation::Portrait, portrait.clone()).icon(IconId::new("orientation_portrait")), Entry::new(Orientation::Landscape, landscape.clone()).icon(IconId::new("orientation_landscape")), ]; picked = Segmented::new(orientation.clone(), Bind::given(current), &entries).show(ui).events.committed().cloned(); }); - Field::new(artboards.clone()).show(ui, |ui, _| { + Field::new(artboards.clone()).layout(FieldLayout::Above).id_salt("artboards").show(ui, |ui, _| { let field = NumberField::new(artboards.clone(), Bind::given(Some(f64::from(s.artboards)))) .range(1.0..=f64::from(MAX_ARTBOARDS)) .step(1.0) - .commit_decimals(0); + .commit_decimals(0) + .sizing(Sizing::FillWidth); if let Some(n) = field.show(ui).edit.events.committed().copied().flatten().filter(|n| n.is_finite()) { s.artboards = n.round().clamp(1.0, f64::from(MAX_ARTBOARDS)) as u32; } @@ -325,41 +329,23 @@ impl DocumentSettings for VcNewDocument { } let bleed = text(tl!("Bleed")); - Field::new(bleed.clone()).show(ui, |ui, _| { - let mut linked = !memory.bleed_split; - let parts = s.bleed.map(|b| Mixed::Same(Some(b))); - let captions = [text(tl!("Top")), text(tl!("Bottom")), text(tl!("Left")), text(tl!("Right"))]; - let out = LinkedFields::<4>::new(bleed.clone(), Bind::given(parts), Bind::bound(&mut linked)) - .mode(LinkMode::Equal) - .layout(LinkedLayout::Columns) - .captions(captions) - .range(0.0..=vectorcraft_doc::setup::MAX_BLEED) - .lengths(lengths) - .show(ui); - if let Some(edited) = out.edit.events.committed().copied() { - for (side, part) in s.bleed.iter_mut().zip(edited) { - if let Mixed::Same(Some(b)) = part { - *side = b.clamp(0.0, vectorcraft_doc::setup::MAX_BLEED); - } - } - } - memory.bleed_split = !linked; - }); + Field::new(bleed.clone()).layout(FieldLayout::Above).id_salt("bleed").show(ui, |ui, _| bleed_row(ui, s, &mut memory, lengths)); - Field::new(background.clone()).show(ui, |ui, _| { + Field::new(background.clone()).layout(FieldLayout::Above).id_salt("background").show(ui, |ui, _| { let entries: Vec> = BACKGROUNDS.iter().map(|(b, name)| Entry::new(*b, text(tl!(name)))).collect(); - if let Some(b) = Select::new(background.clone(), Bind::given(s.background), &entries).show(ui).events.committed().copied() { + let select = Select::new(background.clone(), Bind::given(s.background), &entries).sizing(Sizing::FillWidth); + if let Some(b) = select.show(ui).events.committed().copied() { s.background = b; } }); Section::new(text(tl!("Advanced Options"))).initially_open(false).show(ui, |ui, _| advanced(ui, s)); - // The two buttons side by side, the item gap apart. + // The two buttons across the column, one above the other. let (mut more, mut manage) = (None, None); - Row::new().gap(Gap::Item).wrap(true).show(ui, |ui, _| { - more = Some(Button::new(text(tl!("More Settings"))).id_salt("more-settings").show(ui)); - manage = Some(Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").show(ui)); + Stack::new().fill_width().gap(Gap::Item).show(ui, |ui, _| { + more = Some(Button::new(text(tl!("More Settings"))).id_salt("more-settings").sizing(Sizing::FillWidth).show(ui)); + manage = Some(Button::new(text(tl!("Manage Profiles"))).id_salt("manage-profiles").sizing(Sizing::FillWidth).show(ui)); }); if let Some(more) = &more { let mut more_open = memory.more_open != clicked(more); @@ -433,9 +419,53 @@ fn pixels_per_inch() -> f64 { 72.0 / Unit::Pixels.to_pt(1.0) } +/// The four Bleed fields in one row, each under its side's name, and the link button at the end; linked, an edit to +/// one side sets all four, and turning the link on sets all four to Top's. Each field is as wide as the widest bleed it +/// takes, and the row wraps when the column has no room for all of them. +fn bleed_row(ui: &mut egui::Ui, s: &mut DocSettings, memory: &mut Memory, lengths: LengthUnits) { + let mut linked = !memory.bleed_split; + let link = LinkMode::Equal.label(&Env::of(ui).words::()); + let sides = [text(tl!("Top")), text(tl!("Bottom")), text(tl!("Left")), text(tl!("Right"))]; + let mut edited = None; + Row::new().wrap(true).show(ui, |ui, _| { + for (i, side) in sides.iter().enumerate() { + // A drag on the side's name scrubs its field. + let field = Field::new(side.clone()).layout(FieldLayout::Above).side(SideLabel::new().scrub(true)).sizing(Sizing::Content); + field.id_salt(("bleed", i)).show(ui, |ui, _| { + let field = NumberField::length(side.clone(), Bind::given(Some(s.bleed[i])), lengths) + .range(0.0..=vectorcraft_doc::setup::MAX_BLEED) + .scrub_by_label() + .sizing(Sizing::Content); + if let Some(v) = field.show(ui).edit.events.committed().copied().flatten().filter(|v| v.is_finite()) { + edited = Some((i, v.clamp(0.0, vectorcraft_doc::setup::MAX_BLEED))); + } + }); + } + // Turning the link on sets every side to Top's bleed. + if let Some(on) = link_toggle(link.clone(), Bind::given(linked)).id_salt("bleed-link").show(ui).value().copied() { + linked = on; + if on { + s.bleed = [s.bleed[0]; 4]; + } + } + }); + if let Some((i, v)) = edited { + if linked { + s.bleed = follow_equal(s.bleed, i, v); + } else { + s.bleed[i] = v; + } + } + memory.bleed_split = !linked; +} + +/// The Height, Orientation and Artboards row. Orientation's share keeps its two buttons side by side in a 900-point +/// window. +const THIRDS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.4), ColumnWidth::fill(1.0)]; + /// A side of the page in points, shown in the chosen units. fn size_field(ui: &mut egui::Ui, name: &Label, points: &mut f64, lengths: LengthUnits) { - let field = NumberField::length(name.clone(), Bind::given(Some(*points)), lengths).range(MIN_SIDE..=MAX_SIDE); + let field = NumberField::length(name.clone(), Bind::given(Some(*points)), lengths).range(MIN_SIDE..=MAX_SIDE).sizing(Sizing::FillWidth); if let Some(v) = field.show(ui).edit.events.committed().copied().flatten().filter(|v| v.is_finite()) { *points = v; } @@ -994,8 +1024,13 @@ mod tests { /// The window's frames with the dialog open, laid out; the last frame's output. fn laid_out(app: &mut VectorcraftApp) -> egui::FullOutput { + laid_out_in(app, egui::vec2(1280.0, 900.0)) + } + + /// [`laid_out`] in a window of `size`. + fn laid_out_in(app: &mut VectorcraftApp, size: egui::Vec2) -> egui::FullOutput { let ctx = ctx(app); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, size); let mut frame = |i: u32| { let input = egui::RawInput { time: Some(0.1 * f64::from(i)), screen_rect: Some(screen), ..Default::default() }; crate::testing::part_frame(app, &ctx, input, |app, ui| app.ui(ui)) @@ -1377,4 +1412,106 @@ mod tests { } crate::i18n::set_current(crate::i18n::Lang::EN); } + + /// The accessibility nodes of New Document opened in a window of `width` by `height`: role, name and bounds. + fn dialog_nodes(width: f32, height: f32) -> Vec<(egui::accesskit::Role, String, egui::accesskit::Rect)> { + let mut app = app(); + open(&mut app); + let out = laid_out_in(&mut app, egui::vec2(width, height)); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, n)| Some((n.role(), n.label()?.to_owned(), n.bounds()?))).collect() + } + + /// The bounds of the node named `name` in `role`. + fn node(nodes: &[(egui::accesskit::Role, String, egui::accesskit::Rect)], name: &str, role: egui::accesskit::Role) -> egui::accesskit::Rect { + nodes.iter().find(|(r, n, _)| *r == role && n == name).map(|(_, _, b)| *b).unwrap_or_else(|| panic!("no {role:?} {name}")) + } + + /// Every Preset Details label stands above its field, at the field's left edge; before, Width, Height, + /// Orientation, Artboards, the Bleed sides and Background Contents sat right-aligned beside their fields. + #[test] + fn new_document_labels_sit_above_their_fields() { + use egui::accesskit::Role; + let nodes = dialog_nodes(1280.0, 900.0); + for (name, role) in [ + ("Width", Role::SpinButton), + ("Height", Role::SpinButton), + ("Orientation", Role::RadioGroup), + ("Artboards", Role::SpinButton), + ("Top", Role::SpinButton), + ("Bottom", Role::SpinButton), + ("Left", Role::SpinButton), + ("Right", Role::SpinButton), + ("Background Contents", Role::ComboBox), + ] { + let (label, field) = (node(&nodes, name, Role::Label), node(&nodes, name, role)); + assert!(label.y1 <= field.y0 + 0.5, "the {name} label {label:?} stands above its field {field:?}"); + assert!((label.x0 - field.x0).abs() <= 1.0, "the {name} label {label:?} starts at its field's left edge {field:?}"); + } + // The four Bleed fields share one row, and the link button follows the last of them. + let sides = ["Top", "Bottom", "Left", "Right"].map(|side| node(&nodes, side, Role::SpinButton)); + assert!(sides.windows(2).all(|w| w[0].y0 == w[1].y0 && w[0].x1 <= w[1].x0), "one row, in order: {sides:?}"); + let link = node(&nodes, "Make all settings the same", Role::Button); + assert!(sides[3].x1 <= link.x0, "the link button {link:?} ends the Bleed row {sides:?}"); + } + + /// Turning the Bleed link on sets every side to Top's bleed; unlinking keeps the four values. + #[test] + fn new_document_bleed_link_turned_on_sets_every_side_to_top() { + let mut panel = actual_preset_dialog(); + set(&panel.app(), "bleed", json!([1, 2, 3, 4])).unwrap(); + panel.frame(); + panel.click("Make all settings the same"); + panel.frame(); + assert_eq!(fields(&panel.app())["bleed"], json!([1.0, 2.0, 3.0, 4.0]), "unlinking keeps the values"); + panel.click("Make all settings the same"); + panel.frame(); + assert_eq!(fields(&panel.app())["bleed"], json!([1.0, 1.0, 1.0, 1.0]), "linking sets every side to Top"); + } + + /// At 1280 by 900 the preset cards stand four to a row, with the details column beside them. + #[test] + fn new_document_presets_show_four_columns_at_the_default_size() { + use egui::accesskit::Role; + let nodes = dialog_nodes(1280.0, 900.0); + let list = node(&nodes, "Blank Document Presets", Role::ListBox); + let inside = |b: &egui::accesskit::Rect| list.x0 <= b.x0 && b.x1 <= list.x1 && list.y0 <= b.y0 && b.y1 <= list.y1; + let cards: Vec<_> = nodes.iter().filter(|(r, _, b)| *r == Role::ListItem && inside(b)).map(|(_, _, b)| *b).collect(); + let first = cards.iter().map(|b| b.y0).fold(f64::INFINITY, f64::min); + let row = cards.iter().filter(|b| (b.y0 - first).abs() < 0.5).count(); + assert_eq!(row, 4, "four cards to the first row: {cards:?}"); + let details = node(&nodes, "Width", Role::SpinButton); + assert!(cards.iter().all(|b| b.x1 < details.x0), "the cards stay left of the details column"); + } + + /// In a 900 by 700 window every Preset Details control ends inside the dialog; before, the Bleed row's Left and + /// Right fields ran past its right edge. + #[test] + fn new_document_details_are_not_clipped_at_the_right_edge() { + use egui::accesskit::Role; + for (width, height) in [(900.0, 700.0), (1280.0, 900.0)] { + let nodes = dialog_nodes(width, height); + let dialog = nodes.iter().find(|(r, _, _)| *r == Role::Dialog).map(|(_, _, b)| *b).expect("the dialog"); + for (name, role) in [ + ("Width", Role::SpinButton), + ("Units", Role::ComboBox), + ("Height", Role::SpinButton), + ("Landscape", Role::RadioButton), + ("Artboards", Role::SpinButton), + ("Top", Role::SpinButton), + ("Bottom", Role::SpinButton), + ("Left", Role::SpinButton), + ("Right", Role::SpinButton), + ("Make all settings the same", Role::Button), + ("Background Contents", Role::ComboBox), + ("More Settings", Role::Button), + ("Manage Profiles", Role::Button), + ] { + let field = node(&nodes, name, role); + assert!(field.x1 <= dialog.x1 - 8.0, "{width}x{height}: {name} {field:?} ends inside the dialog {dialog:?}"); + } + let (portrait, landscape) = (node(&nodes, "Portrait", Role::RadioButton), node(&nodes, "Landscape", Role::RadioButton)); + assert!(portrait.y0 == landscape.y0 && portrait.x1 <= landscape.x0, "{width}x{height}: Portrait and Landscape side by side"); + } + } } diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 839b14a6c1..6b73aed5f9 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -158,6 +158,61 @@ fn map_art_maps_a_symbol_onto_a_surface_of_extrude_and_bevel_classic() { assert!(params.get("__mapArt").is_none() && params.get("__mapSurface").is_none(), "the dialog's own state stays out of the effect"); } +/// Map Art's Symbol: a symbol highlighted with the arrow keys maps nothing and leaves the drawing as it was, Escape +/// closes the list with the dialog open and nothing changed, and Enter maps the symbol. +#[test] +fn a_highlighted_map_art_symbol_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use craft::ui::dialog::StackDialog as _; + + use super::super::three_d; + use crate::tests::panel_harness::Panel; + + fn whole_frame(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + app.tick(ui.ctx()); + app.ui(ui); + } + fn settle(panel: &mut Panel) { + for _ in 0..6 { + panel.frame(); + } + } + + let mut panel = Panel::new(with_symbol("M50 50L150 50L150 150L50 150Z"), whole_frame); + panel.room(vec2(1440.0, 900.0)); + settle(&mut panel); + if let Err(e) = effect::open(&mut panel.app(), &json!({"effect": CLASSIC_EXTRUDE, "item": null})) { + panic!("the dialog did not open: {e}"); + } + settle(&mut panel); + let ctx = panel.ctx().clone(); + let page = three_d::with_fields(&mut panel.app(), |d| d.set_json_field(&ctx, "__page", json!("mapArt"))); + assert!(matches!(page, Some(Ok(()))), "{page:?}"); + settle(&mut panel); + let state = |panel: &Panel| { + let mut app = panel.app(); + let maps = three_d::with_fields(&mut app, |d| d.json_fields()).flatten().and_then(|v| v.get("mapArt").cloned()).unwrap_or(Value::Null); + (maps, app.session.doc().unwrap().doc.clone()) + }; + let before = state(&panel); + assert!(vectorcraft_effects::surface_maps(&json!({"mapArt": before.0})).is_empty(), "no surface has a map yet"); + panel.click_role("Symbol", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + settle(&mut panel); + assert_eq!(state(&panel), before, "a highlighted symbol maps nothing"); + panel.key(Key::Escape, Modifiers::NONE); + settle(&mut panel); + assert!(panel.app().three_d_dialog.is_some(), "Escape closes the list, not the dialog"); + assert_eq!(state(&panel), before, "Escape leaves the maps as they were"); + panel.click_role("Symbol", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + settle(&mut panel); + assert!(panel.app().three_d_dialog.is_some(), "Enter in the list keeps the dialog open"); + let maps = vectorcraft_effects::surface_maps(&json!({"mapArt": state(&panel).0})); + assert_eq!(maps.iter().map(|m| (m.surface, m.symbol.as_str())).collect::>(), [(1, "Mark")], "Enter maps the symbol"); +} + /// The theme's plot size, as a pass of the app's interface resolves it. fn plot_size() -> egui::Vec2 { let mut plot = None; diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 626e5f3d3f..8c9f26bb1e 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -485,7 +485,7 @@ pub(crate) fn map_art_params(data: &Data, fields: &DialogFields, effect: &str) - // A custom row, so a pick and automation both write the map through `set_map_value`. let symbol = Param::custom(MAP_SYMBOL, tl!("Symbol"), move |ui, fields, _| { let picked = Select::new(tl!("Symbol"), Bind::given(shown.clone()), &entries).id_salt(MAP_SYMBOL).show(ui); - if let Some(name) = picked.value().cloned() { + if let Some(name) = picked.events.committed().cloned() { // The select lists only what the map takes: a refusal cannot come from it. let _ = set_map_value(fields, MAP_SYMBOL, json!(name)); } diff --git a/crates/ui-egui/src/dialogs/transform_each.rs b/crates/ui-egui/src/dialogs/transform_each.rs index 735488b500..6bb3b55915 100644 --- a/crates/ui-egui/src/dialogs/transform_each.rs +++ b/crates/ui-egui/src/dialogs/transform_each.rs @@ -6,19 +6,21 @@ //! //! Fields: `scaleH`, `scaleV` (percentages, or with Absolute each object's width and height in pt), //! `relative` (Relative or Absolute scaling), `moveH`, `moveV` (pt), `rotate` (°), `reflectX`, -//! `reflectY`, `random`, `reference` (0..8, the 9-point grid), `copy` (set by the Copy button, which -//! confirms), `objects`, `patterns`, `corners`, `strokes` (the last two default to the preferences, -//! which OK updates) and `preview`; `__constrain` is the link that keeps the two scales in -//! proportion. It opens on the values it was last confirmed with, Copy aside (#1732). +//! `reflectY`, `random`, `reference` (0..8, the 9-point grid), `objects`, `patterns`, `corners`, +//! `strokes` (the last two default to the preferences, which OK updates) and `preview`; +//! `__constrain` is the link that keeps the two scales in proportion. It opens on the values it was +//! last confirmed with. The Copy button confirms as OK does and transforms a copy of each object +//! (#1732); it is not a field. //! -//! The dialog is a held-OK [`HostedParamDialog`]: a refused OK keeps it open. The link and mode +//! The dialog is a held-OK [`HostedParamDialog`]: a refused OK or Copy keeps it open with the reason +//! under the rows. The link and mode //! rules run in its build closure ([`apply_links`]), so a click, a typed value and an automation //! set all follow the same rule. use craft::behavior::Mixed; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; use craft::ui::contract::{Bind, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel}; -use craft::ui::dialog::{DialogHost, DialogId, FieldRefusal}; +use craft::ui::dialog::{DialogHost, DialogId, FieldRefusal, HeldOk}; use craft::ui::display::Text; use craft::ui::form::Field; use craft::ui::layout_components::{Row, Stack}; @@ -40,7 +42,7 @@ use crate::VectorcraftApp; const CMD: &str = "object.transformEach"; const KEY: &str = "transformEach"; -/// The footer action and field of the Copy button. +/// The footer action of the Copy button and the command's `copy` parameter. const COPY: &str = "copy"; /// Where the values OK confirmed last are kept. Not `.remember`: that drops custom rows. @@ -56,6 +58,9 @@ pub(crate) struct Open { document: (u64, u64), /// The tool reset count when the current preview record was created. preview_tool_resets: u64, + /// Whether the OK the dialog holds was filed by the Copy button. Copy is kept here and not in the + /// fields: a change to the fields ends the refusal shown under the rows. + copying: bool, } impl Open { @@ -96,12 +101,11 @@ pub fn fields() -> DialogFields { ("reflectY", FieldValue::Bool(false)), ("random", FieldValue::Bool(false)), ("reference", FieldValue::Int(4)), - (COPY, FieldValue::Bool(false)), (LINK, FieldValue::Bool(false)), ]) } -/// The fields kept from the last OK or Copy: all but Copy, Preview (it opens on), Transform +/// The fields kept from the last OK or Copy: all but Preview (it opens on), Transform /// Patterns (the preference it starts from), the scale options (preferences too) and the Absolute /// targets (`absH`, `absV`), which the dialog sets from the selection every time it opens. const REMEMBERED: [&str; 12] = @@ -144,7 +148,7 @@ fn params(f: &DialogFields) -> Value { "relative": relative(f), "moveH": num(f, "moveH", 0.0), "moveV": num(f, "moveV", 0.0), "rotate": num(f, "rotate", 0.0), "reflectX": flag(f, "reflectX"), "reflectY": flag(f, "reflectY"), "random": flag(f, "random"), - "reference": num(f, "reference", 4.0).clamp(0.0, 8.0) as u64, "copy": flag(f, COPY), + "reference": num(f, "reference", 4.0).clamp(0.0, 8.0) as u64, "copy": false, }); let (h, v) = scale_keys(f); for (key, field) in [("scaleH", h), ("scaleV", v)] { @@ -508,7 +512,8 @@ pub(crate) fn open(app: &mut VectorcraftApp) { let dialog = HostedParamDialog::new(&ctx, KEY, f, move |fields| form(fields, shared, lengths)); let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() }; if let Some(id) = open_held_with(app, dialog, move |app, result| ok(app, &ctx, result), options) { - app.object_dialogs.each = Some(Open { id, preview: LivePreview::default(), document, preview_tool_resets: app.session.tool_resets() }); + app.object_dialogs.each = + Some(Open { id, preview: LivePreview::default(), document, preview_tool_resets: app.session.tool_resets(), copying: false }); } } @@ -522,8 +527,8 @@ fn cancel(app: &mut VectorcraftApp) { } } -/// Applies the confirmed values as one undo step. -fn commit(app: &mut VectorcraftApp, f: &DialogFields) -> Result<(), String> { +/// Applies the confirmed values as one undo step, to a copy of each object with `copy`. +fn commit(app: &mut VectorcraftApp, f: &DialogFields, copy: bool) -> Result<(), String> { let open = app.object_dialogs.each.as_ref().ok_or("the Transform Each dialog is closed")?; let (in_source, reverted, (uid, _), preview_tool_resets) = (open.in_source(app), open.reverted(app), open.document, open.preview_tool_resets); if !in_source { @@ -541,24 +546,19 @@ fn commit(app: &mut VectorcraftApp, f: &DialogFields) -> Result<(), String> { if app.session.tool_resets() != preview_tool_resets && app.session.in_interaction() { return Err("finish the active edit before applying Transform Each".into()); } - let p = with_scale_options(app, f, command_params(app, f))?; + let mut p = command_params(app, f); + p[COPY] = json!(copy); + let p = with_scale_options(app, f, p)?; let preview = app.object_dialogs.each.as_mut().map(|o| std::mem::take(&mut o.preview)).unwrap_or_default(); preview.commit(app, CMD, p).map(|_| ()) } -/// OK: transforms each object and keeps the values for the next open. A refusal turns Copy off, or -/// the next plain OK would copy; a refused plain OK keeps its values, so the dialog shows the reason. +/// OK and Copy: transform each object, or a copy of each with Copy, and keep the values for the +/// next open. A refusal leaves the values as they are, so the dialog shows the reason, and the +/// next OK does not copy. fn ok(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) -> Result<(), String> { - if let Err(reason) = commit(app, &result.fields) { - if let (Some(id), Some(dialogs)) = (app.object_dialogs.each.as_ref().map(|o| o.id), app.dialogs()) { - dialogs.with(|host| { - if let Some(d) = host.get_mut_by_id::(id) { - d.set_field(COPY, FieldValue::Bool(false)); - } - }); - } - return Err(reason); - } + let copy = app.object_dialogs.each.as_mut().is_some_and(|open| std::mem::take(&mut open.copying)); + commit(app, &result.fields, copy)?; let mut kept = DialogFields::new(); for k in REMEMBERED { if let Some(v) = result.fields.get(k) { @@ -571,7 +571,7 @@ fn ok(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) -> Re } /// Each frame: previews the dialog's values while Preview is on, and turns a press of Copy into a -/// confirm with `copy` set. +/// confirm that copies. pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some((id, in_source)) = app.object_dialogs.each.as_ref().map(|o| (o.id, o.in_source(app))) else { return }; let Some(dialogs) = app.dialogs() else { return }; @@ -596,13 +596,18 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { app.object_dialogs.each = Some(open); } if action.as_deref() == Some(COPY) { - dialogs.with(|host: &mut DialogHost| { - if let Some(d) = host.get_mut_by_id::(id) { - d.set_field(COPY, FieldValue::Bool(true)); + // A held confirm returns false; the OK it files shows as waiting. An OK already waiting is not + // turned into a Copy. + let filed = dialogs.with(|host: &mut DialogHost| { + let waiting = |host: &DialogHost| host.held_state(id) == Some(HeldOk::Waiting); + !waiting(host) && { + let _ = host.confirm_by_id(ctx, id); + waiting(host) } - // A refused confirm leaves the dialog as it is: the held OK reports why. - let _ = host.confirm_by_id(ctx, id); }); + if filed && let Some(open) = app.object_dialogs.each.as_mut() { + open.copying = true; + } } } @@ -788,7 +793,7 @@ mod tests { h.get_by_role_and_label(egui::accesskit::Role::Button, "Copy").click(); h.run_steps(4); assert_eq!(h.state().session.doc().unwrap().doc, other, "Copy must leave the other document unchanged"); - assert_ne!(field(&h, COPY), Some(FieldValue::Bool(true)), "a refused Copy clears its flag"); + assert!(!h.state().object_dialogs.each.as_ref().unwrap().copying, "a refused Copy is not kept for the next OK"); h.state_mut().run("document.activate", json!({"index": 0})).unwrap(); h.get_by_role_and_label(egui::accesskit::Role::Button, "Copy").click(); @@ -928,9 +933,96 @@ mod tests { h.run_steps(4); assert_eq!(h.state().session.doc().unwrap().doc, restored, "Copy must leave the restored document unchanged"); assert_eq!(h.state().session.doc().unwrap().history.undo.len(), undo, "Copy must record no undo step"); - assert_ne!(field(&h, COPY), Some(FieldValue::Bool(true)), "a refused Copy clears its flag"); - assert_eq!(h.state().ui.status, REVERTED, "the status line reports the revert"); assert!(h.state().object_dialogs.each.is_some(), "the dialog stays open"); + assert!(!h.state().object_dialogs.each.as_ref().unwrap().copying, "a refused Copy is not kept for the next OK"); + assert_refused_for_the_revert(&h); + } + + /// Every open document with its undo depth. + fn documents(h: &Harness) -> Vec<(std::sync::Arc, usize)> { + h.state().session.documents().iter().map(|doc| (doc.doc.clone(), doc.history.undo.len())).collect() + } + + /// Presses Copy, then checks over several frames that the dialog stays open with `reason` shown + /// under the rows and that no document changed. + fn assert_copy_refused(h: &mut Harness, reason: &str) { + let before = documents(h); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Copy").click(); + // The press, the refusal and the pass that draws it. + h.run_steps(3); + for frame in 0..4 { + h.run_steps(1); + assert!(h.state().object_dialogs.each.is_some(), "the dialog stays open, frame {frame}"); + let id = id(h); + let held = h.state().dialogs().unwrap().with(|host| host.held_state(id)); + assert!( + matches!(&held, Some(craft::ui::dialog::HeldOk::Refused(shown)) if shown.as_str() == reason), + "Copy is refused with {reason:?} on frame {frame}, the held state is {held:?}" + ); + assert!(h.query_by_label_contains(reason).is_some(), "the reason shows under the rows on frame {frame}"); + assert!(documents(h) == before, "a refused Copy changes no document and records no undo step, frame {frame}"); + } + } + + /// Asserts that a press of Copy copies the selection of the active document once, as one undo step. + fn assert_copy_applies(h: &mut Harness) { + let st = h.state().session.doc().unwrap(); + let (count, undo) = (st.doc.layers[0].children().unwrap().len(), st.history.undo.len()); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Copy").click(); + h.run_steps(4); + assert!(h.state().object_dialogs.each.is_none(), "Copy closes the dialog"); + let st = h.state().session.doc().unwrap(); + assert_eq!(st.doc.layers[0].children().unwrap().len(), count + 1, "Copy adds a copy of the square"); + assert_eq!(st.history.undo.len(), undo + 1, "Copy is one undo step"); + } + + /// Copy from another document is refused with its reason, which stays shown; back on the + /// opening document, Copy applies. + #[test] + fn a_refused_copy_keeps_showing_switch_back() { + let (mut h, _) = open_with_two_documents(); + set(&mut h, "preview", json!(false)); + set(&mut h, "moveH", json!(100)); + h.run_steps(2); + h.state_mut().run("document.activate", json!({"index": 1})).unwrap(); + assert_copy_refused(&mut h, "switch back to the document where Transform Each was opened"); + + h.state_mut().run("document.activate", json!({"index": 0})).unwrap(); + h.run_steps(2); + assert_copy_applies(&mut h); + } + + /// Copy after the opening document closed is refused with its reason, which stays shown. + #[test] + fn a_refused_copy_keeps_showing_that_the_document_closed() { + let (mut h, _) = open_with_two_documents(); + set(&mut h, "preview", json!(false)); + set(&mut h, "moveH", json!(100)); + h.run_steps(2); + h.state_mut().session.execute("file.close", &json!({"index": 0})).unwrap(); + h.run_steps(2); + assert_copy_refused(&mut h, "the document where Transform Each was opened has closed"); + } + + /// Copy during an edit that started after the preview is refused with its reason, which stays + /// shown; once the edit ends, Copy applies. + #[test] + fn a_refused_copy_keeps_showing_finish_the_active_edit() { + let (mut h, _) = open_with_two_documents(); + set(&mut h, "moveH", json!(45)); + h.run_steps(2); + let app = h.state_mut(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session.begin_interaction("Another gesture").unwrap(); + app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + h.run_steps(2); + assert_copy_refused(&mut h, "finish the active edit before applying Transform Each"); + assert!(h.state().session.in_interaction(), "the other edit goes on"); + + h.state_mut().session.cancel_interaction().unwrap(); + h.run_steps(2); + assert_copy_applies(&mut h); } #[test] @@ -989,19 +1081,18 @@ mod tests { ] { set(&mut h, k, v); } - // Copy is a footer button, not a row: the fields hold it as the app's Copy action sets it. - let dialog = id(&h); - h.state().dialogs().unwrap().with(|host| host.get_mut_by_id::(dialog).map(|d| d.set_field(COPY, FieldValue::Bool(true)))); - confirm(&mut h); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Copy").click(); + h.run_steps(4); assert!(h.state().object_dialogs.each.is_none()); open(h.state_mut()); h.run_steps(2); for (k, v) in [("scaleH", 150.0), ("scaleV", 100.0), ("moveH", 20.0), ("rotate", 15.0), ("reference", 0.0)] { assert_eq!(number(&h, k), v, "{k}"); } - for (k, v) in [("reflectX", true), ("reflectY", false), ("random", true), ("objects", false), (COPY, false)] { + for (k, v) in [("reflectX", true), ("reflectY", false), ("random", true), ("objects", false)] { assert_eq!(field(&h, k), Some(FieldValue::Bool(v)), "{k}"); } + assert!(!h.state().object_dialogs.each.as_ref().unwrap().copying, "Copy isn't remembered"); // Cancel keeps nothing new. set(&mut h, "scaleH", json!(300)); let (ctx, id) = (h.ctx.clone(), id(&h)); @@ -1041,7 +1132,8 @@ mod tests { assert_eq!(xs(app), vec![20.0, 120.0, 220.0], "Transform Again copies once more"); open(h.state_mut()); h.run_steps(2); - assert_eq!(field(&h, COPY), Some(FieldValue::Bool(false)), "Copy isn't remembered"); + confirm(&mut h); + assert_eq!(h.state().session.doc().unwrap().doc.layers[0].children().unwrap().len(), 3, "a plain OK after Copy does not copy"); h.ctx.forget_all_images(); } } diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index b28d341a57..93218a35b6 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -23,6 +23,7 @@ use craft::behavior::IconId; use craft::behavior::overlay::Side; use craft::ui::buttons::ToggleButton; use craft::ui::contract::{Bind, Outcome as _, Show as _, ShowContainer as _}; +use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::menu::PanelRow; use craft::ui::primitives::IconSpec; @@ -462,14 +463,17 @@ pub(crate) fn drawer(app: &mut VectorcraftApp, ui: &mut Ui, rail_out: &ToolRailO if target.is_some() { return; } - Row::new().show(ui, |ui, _| { - for (name, label, icon) in crate::state::ToolbarShow::CONTROLS { - let on = shown.get(name); - let button = ToggleButton::new(tl!(label), Bind::given(on)).icon(IconSpec::svg(IconId::new(icon))).icon_only(); - if button.show(ui).response().clicked() { - toggled = Some(name); + // The toggles are labeled "Show:", as production's were, so the row says what its icons turn on and off. + Field::new(tl!("Show:")).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + for (name, label, icon) in crate::state::ToolbarShow::CONTROLS { + let on = shown.get(name); + let button = ToggleButton::new(tl!(label), Bind::given(on)).icon(IconSpec::svg(IconId::new(icon))).icon_only(); + if button.show(ui).response().clicked() { + toggled = Some(name); + } } - } + }); }); }); diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index b01ac1a4bb..aefbb09958 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -142,6 +142,23 @@ fn toolbar_show_turns_the_controls_under_the_tools_on_and_off() { assert_eq!(serde_json::from_value::(old).unwrap().toolbar_show, crate::state::ToolbarShow::default()); } +/// The drawer's Show toggles are labeled: they sit in a field named "Show" whose label comes before them. +#[test] +fn the_drawer_labels_its_show_toggles() { + let mut app = app(); + let ctx = ctx(); + settle(&mut app, &ctx, 0.0); + app.run("window.editToolbar", json!({"open": true})).unwrap(); + let nodes = settle(&mut app, &ctx, 1.0); + let open = drawer(&nodes); + let first = inside(&nodes, "Fill and Stroke Controls", open); + let label = named(&nodes, "Show").into_iter().chain(named(&nodes, "Show:")).find(|r| open.contains(r.center())).unwrap_or_else(|| { + panic!("the drawer shows a Show label: {:?}", nodes.iter().filter(|(_, r)| open.contains(r.center())).collect::>()) + }); + assert!(label.expand(0.5).contains_rect(first), "the Show field {label:?} holds the toggles {first:?}"); + assert!(label.left() < first.left(), "the Show label in {label:?} comes before the toggles {first:?}"); +} + /// Every tool is listed once, under a heading; the Basic toolbar's groups come first, in its order. #[test] fn every_tool_is_listed_once_under_a_heading() { diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index b07e126478..e2f384cc95 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -529,7 +529,7 @@ impl StackDialog for FindFontDialog { crate::panels::section(tl!("Replace With Font").to_string()).show(ui, |ui, _| { Field::new(tl!("Replace With Font From").to_string()).show(ui, |ui, _| { let edit = Select::new(tl!("Replace With Font From").to_string(), Bind::given(source), &source_entries).show(ui); - new_source = edit.events.value().copied(); + new_source = edit.events.committed().copied(); }); let edit = TextField::search(tl!("Search").to_string(), Bind::given(self.search.clone())).show(ui); new_search = edit.events.value().cloned(); @@ -544,7 +544,7 @@ impl StackDialog for FindFontDialog { }); Field::new(tl!("Find In").to_string()).show(ui, |ui, _| { let edit = Select::new(tl!("Find In").to_string(), Bind::given(find_in), &find_in_entries).show(ui); - new_find_in = edit.events.value().copied(); + new_find_in = edit.events.committed().copied(); }); }); }); @@ -1013,6 +1013,48 @@ mod tests { // PLAN: files-w11 owns Missing Fonts' hosted type; its test asserts the search there } + /// Replace With Font From and Find In: an entry highlighted with the arrow keys changes no choice, Escape closes + /// the list with the dialog open and nothing changed, and Enter applies the entry. + #[test] + fn a_highlighted_source_or_find_in_applies_only_once_it_is_chosen() { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + use crate::tests::panel_harness::Panel; + + // Replace With Font From opens on System, its last entry, and Find In on Document, its first. + for (name, step) in [("Replace With Font From", Key::ArrowUp), ("Find In", Key::ArrowDown)] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Inter"})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(egui::vec2(1280.0, 1100.0)); + open(&mut panel.app()); + panel.frame(); + panel.frame(); + let state = |panel: &Panel| { + let d = opened(&panel.app()); + (d.replace_from, d.find_in) + }; + let before = state(&panel); + assert_eq!(before, ("system".to_string(), "document".to_string())); + panel.click_role(name, Role::COMBO_BOX); + panel.key(step, Modifiers::NONE); + panel.frame(); + assert_eq!(state(&panel), before, "a highlighted {name} entry changes no choice"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert!(panel.app().dialogs().unwrap().with(|host| host.is_open::()), "Escape closes the {name} list, not the dialog"); + assert_eq!(state(&panel), before, "Escape leaves {name} as it was"); + panel.click_role(name, Role::COMBO_BOX); + panel.key(step, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + assert!(panel.app().dialogs().unwrap().with(|host| host.is_open::()), "Enter in the {name} list keeps the dialog open"); + assert_ne!(state(&panel), before, "Enter applies the {name} entry"); + } + } + /// `f`'s answer, read while the font menu held still: tests running alongside add fonts to /// the shared database and lend it composite fonts. fn while_fonts_hold(mut f: impl FnMut() -> T) -> T { diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 499b782aa9..48af87f872 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -9200,11 +9200,6 @@ file-filter Applications Aplikasi @msg the layer effects of {n} layers weren't drawn efek lapisan dari {n} lapisan tidak digambar @msg the vector masks of 1 layer weren't applied masker vektor dari 1 lapisan tidak diterapkan @msg the vector masks of {n} layers weren't applied masker vektor dari {n} lapisan tidak diterapkan -@msg `opacity` must be a number from 0 to 100 `opacity` harus berupa angka dari 0 sampai 100 -@msg `opacity` must be true or false `opacity` harus true atau false -@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke karakter teks tidak memiliki opasitas sendiri: tambahkan isian atau guratan dengan Tambahkan isian baru atau Tambahkan guratan baru di panel Tampilan -@msg an object selected in a symbol instance has no fill or stroke opacity of its own objek yang dipilih dalam instans simbol tidak memiliki opasitas isian atau guratan sendiri -@msg no target has that fill or stroke to take the opacity tidak ada target yang memiliki isian atau guratan itu untuk menerima opasitas @msg give color, none, swatch, gradient or opacity berikan color, none, swatch, gradient, atau opacity @msg the knockout of 1 layer wasn't applied knockout dari 1 lapisan tidak diterapkan @msg the knockout of {n} layers wasn't applied knockout dari {n} lapisan tidak diterapkan diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 091c5d1ce8..451bb131cc 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -518,6 +518,22 @@ fn flyout_tab(layout: &Layout, panel: &str) -> Option { .map(|front| front.to_string()) } +/// The actions that expand each floating window the pass made from part of a column collapsed to +/// icons, so a group or tab dragged out of an icon column floats as an expanded panel with its tabs +/// in the window. A whole icon column floated stays collapsed. +fn floated_from_icons(before: &Layout, after: &Layout) -> Vec> { + after + .floating + .iter() + .filter(|window| window.column.iconic && !before.floating.iter().any(|old| old.id == window.id)) + .filter_map(|window| { + let first = window.panels().next()?; + let (_, column) = column_of(before, first)?; + (column.iconic && column.panels().count() > window.panels().count()).then(|| Action::set_iconic(first.clone(), false)) + }) + .collect() +} + /// Show `panel` as `window.panel` does, but leave it be when it can be seen already ([`visible`]): /// a command that opens a panel to work in (Edit › Color Settings…) never puts it away. A flyout /// keeps the name of the icon that opened it after another of its tabs is clicked, so a panel whose @@ -1374,13 +1390,20 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo app.dock_rt.rails = rails; // A workspace a command switched to or changed in this pass (`Workspace::replace`) stays; the // pass's edits were to the one it replaced. + let mut expand = Vec::new(); if app.ui.dock_workspace.revision() == revision { - app.ui.dock_workspace = workspace; + let before = std::mem::replace(&mut app.ui.dock_workspace, workspace); + expand = floated_from_icons(before.layout(), layout_of(&app.ui)); } // A command of this pass that opened or closed a flyout wins over the area's own change. if app.ui.open_panel == flyout_before { app.ui.open_panel = flyout; } + if !expand.is_empty() + && let Err(error) = apply(app, None, expand) + { + app.status(error); + } if output.error.is_some() { Arc::make_mut(&mut app.ui.dock_workspace).replace(default_workspace(&[])); app.status(tl!("Invalid panel layout; restored the default dock").to_string()); diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index cd2bfb91c9..e89c22b337 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -17,6 +17,7 @@ struct Harness { ctx: egui::Context, time: f64, nodes: Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>, + shapes: Vec, } impl Harness { @@ -26,7 +27,7 @@ impl Harness { app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = crate::testing::ui_context(); ctx.enable_accesskit(); - let mut h = Self { app, ctx, time: 0.0, nodes: Vec::new() }; + let mut h = Self { app, ctx, time: 0.0, nodes: Vec::new(), shapes: Vec::new() }; h.frames(3); h } @@ -43,10 +44,11 @@ impl Harness { } } - /// Draw one application frame and retain its accessibility output for assertions. + /// Draw one application frame and retain its accessibility output and shapes for assertions. fn run(&mut self, input: egui::RawInput) { let out = crate::testing::app_frame(&mut self.app, &self.ctx, input); self.nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); + self.shapes = out.shapes; } /// The rect of the node of `role` named like `panel` (its title, ignoring case and spaces) in the last frame. @@ -1011,6 +1013,85 @@ fn a_floating_panel_resized_past_the_panel_minimum_stops_at_it() { assert!(after >= PANEL_MIN_WIDTH - 0.5, "dragged in past the minimum: {after}"); } +/// #8307: Swatches with more swatches than fit, floating or docked above Transparency and sized +/// short, keeps its footer buttons inside the panel, and scrolled to its end shows nothing from its +/// list in the strip between those buttons and the panel's bottom edge. +#[test] +fn a_short_swatches_panel_keeps_its_footer_inside_and_its_rows_out_of_the_strip_under_it() { + for (docked, below, height) in + [(false, false, None), (false, true, None), (true, false, None), (true, true, None), (true, true, Some(200.0)), (true, true, Some(150.0))] + { + let case = format!("docked {docked}, above Transparency {below}, height {height:?}"); + let mut h = Harness::new(); + h.app.run("window.panel.float", json!({"panel": "swatches"})).unwrap(); + if below { + h.app.run("window.panel.float", json!({"panel": "transparency", "below": "swatches"})).unwrap(); + } + if docked { + h.app.run("window.panel.dock", json!({"panel": "swatches", "column": 1})).unwrap(); + } + if height.is_some() { + let mut layout = h.layout(); + layout.apply(Action::resize_group("swatches".into(), height)).unwrap(); + h.set_layout(layout); + } + h.frames(3); + footer_strip_shows_no_rows(&mut h, &case); + } +} + +/// Scrolls the Swatches list to its end and checks its footer and the strip under the footer. +fn footer_strip_shows_no_rows(h: &mut Harness, case: &str) { + let rect = |b: egui::accesskit::Rect| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)); + // The wheel turns over the list, or over the panel when it is too short to show any row. + let named = + |h: &Harness, role| h.nodes.iter().find(|(_, n)| n.role() == role && n.label() == Some("Swatches")).and_then(|(_, n)| n.bounds()).map(rect); + let over = named(h, egui::accesskit::Role::ListBox) + .or_else(|| named(h, egui::accesskit::Role::TabPanel)) + .unwrap_or_else(|| panic!("{case}: the panel is drawn")); + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -400.0), + modifiers: Default::default(), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }; + for _ in 0..10 { + h.frame(vec![Event::PointerMoved(over.center()), wheel.clone()]); + } + h.frames(10); + let footer = ["Swatch Libraries Menu", "Show Swatch Kinds", "Swatch Options", "Delete Swatch", "New Swatch", "New Color Group"] + .iter() + .map(|label| { + let found = h.nodes.iter().find(|(_, n)| n.label() == Some(*label)).and_then(|(_, n)| n.bounds()).map(rect); + found.unwrap_or_else(|| panic!("{case}: the footer's {label} button is drawn")) + }) + .reduce(|a, b| a.union(b)) + .unwrap_or(Rect::NOTHING); + let body = named(h, egui::accesskit::Role::TabPanel).unwrap_or_else(|| panic!("{case}: the panel body is drawn")); + assert!(body.contains_rect(footer), "{case}: the footer buttons {footer:?} lie outside the panel {body:?}"); + // A shape of the list starts above the footer; any part of it seen in the strip is a row showing through. + let strip = Rect::from_min_max(pos2(body.left(), footer.bottom()), body.right_bottom()); + let transparent = |shape: &egui::Shape| match shape { + egui::Shape::Noop => true, + egui::Shape::Rect(r) => r.fill.a() == 0, + egui::Shape::Mesh(m) => m.vertices.iter().all(|v| v.color.a() == 0), + _ => false, + }; + let showing: Vec = h + .shapes + .iter() + .filter(|c| !transparent(&c.shape)) + .map(|c| (c.shape.visual_bounding_rect(), c.clip_rect)) + .filter(|(bounds, clip)| { + let seen = clip.intersect(*bounds).intersect(strip); + bounds.height() < 60.0 && bounds.top() < footer.top() && seen.is_positive() && seen.height() > 0.5 + }) + .map(|(bounds, _)| bounds) + .collect(); + assert!(showing.is_empty(), "{case}: list shapes show in the strip {strip:?} under the footer: {showing:?}"); +} + /// A docked column saved narrower than `PANEL_MIN_WIDTH` is drawn at the minimum. #[test] fn a_docked_column_is_never_narrower_than_the_panel_minimum() { @@ -1024,3 +1105,36 @@ fn a_docked_column_is_never_narrower_than_the_panel_minimum() { h.frames(3); assert!(body_width(&h, "Properties") >= PANEL_MIN_WIDTH - 0.5, "saved 100 pt wide: {}", body_width(&h, "Properties")); } + +/// A tab group dragged out of the icon column by its grip floats as an expanded panel: its tabs show +/// in the window, and a click on each tab shows that panel. +#[test] +fn a_group_dragged_out_of_the_icon_column_floats_expanded_and_its_tabs_switch() { + for (icon, tabs) in [("stroke", ["gradient", "transparency", "stroke"]), ("transform", ["align", "pathfinder", "transform"])] { + let mut h = Harness::new(); + h.click(h.icon(icon).expect("the icon column is drawn").center()); + h.frames(2); + let tab = h.tab(icon).expect("the flyout's tabs are drawn"); + let grip = h + .nodes + .iter() + .filter(|(_, node)| node.label() == Some("Move tab group")) + .filter_map(|(_, node)| node.bounds()) + .map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))) + .rfind(|grip| (grip.center().y - tab.center().y).abs() < 20.0) + .expect("the flyout's grip"); + h.drag(grip.center(), h.canvas().center()); + h.frames(2); + let layout = h.layout(); + let window = floating_window(&layout, icon).unwrap_or_else(|| panic!("{icon}: the group floats")); + assert_eq!(window_panels(window).len(), 3, "{icon}: the whole group floats"); + assert!(!window.column.iconic, "{icon}: the window is expanded"); + assert!(in_iconic_column(&layout, "swatches"), "{icon}: the icon column stays collapsed"); + for panel in tabs { + let tab = h.tab(panel).unwrap_or_else(|| panic!("{icon}: the {panel} tab is drawn")); + h.click(tab.center()); + h.frames(1); + assert!(showing(&h.app.ui, panel), "{icon}: a click on the {panel} tab shows it"); + } + } +} diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index b3b4f311d5..890208141d 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -452,12 +452,12 @@ pub(crate) fn footer(tree: &DocLayers, ui: &mut Ui, out: &mut Vec<(String, Value let (nodes, guides) = row_ids(&drag.layers()); own(drag) && !nodes.is_empty() && guides.is_empty() && !root.is_some_and(|r| nodes.contains(&r.0)) }; + let (uid, reverts) = (st.uid, st.reverts); let actions = [ - // PLAN: the framework's `accepts_drops` takes one payload type, so Delete cannot also take - // `PanelDrag` (the appearance drop `footer_drop` maps); it needs a second payload there. FooterAction::new(icon("trash-2"), tl!("Delete Selection").to_string()) .takes_drops_disabled(true) - .accepts_drops(move |d: &LayersDrag| own(d) && !d.layers().is_empty()), + .accepts_drops(move |d: &LayersDrag| own(d) && !d.layers().is_empty()) + .also_accepts_drops(move |d: &PanelDrag| d.appearance_for(uid, reverts).is_some()), FooterAction::new(icon("file-plus"), tl!("Create New Layer").to_string()).enabled(new_layer_ok).accepts_drops(duplicate), FooterAction::new(icon("plus"), tl!("Create New Sublayer").to_string()).enabled(new_sublayer_ok), FooterAction::new(icon("frame"), tl!("Make/Release Clipping Mask").to_string()), diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index d1b8230046..2cd61e7083 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -558,6 +558,99 @@ fn layer_row_footer_drops_after_next_document_leave_the_new_document_alone() { } } +/// Whether object `id` in the active document has a basic appearance. +fn basic(app: &VectorcraftApp, id: NodeId) -> bool { + app.session.active().unwrap().doc.node(id).unwrap().appearance.is_basic() +} + +/// A target circle dropped on Delete Selection reduces its row's appearance to a basic appearance and keeps the row; +/// Create New Layer refuses it. Neither button takes a paint or the selected art dragged from a panel. +#[test] +fn delete_selection_reduces_a_dropped_appearance_to_basic() { + use crate::panel_drag::PanelDrag; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + + let (mut app, _, [a, b]) = two_rects(); + name_row(&mut app, a, "A"); + name_row(&mut app, b, "B"); + app.run("appearance.addFill", json!({"ids": [a.0]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + assert!(!basic(&app, a) && basic(&app, b)); + let rows = rows_of(&app); + let mut panel = Panel::new(app, drag_sources_and_layers); + + for (name, role) in [("Dragged paint", Role::LIST_ITEM), ("Dragged art", Role::LIST_ITEM), ("Target A", Role::BUTTON)] { + for button in ["Delete Selection", "Create New Layer"] { + if name == "Target A" && button == "Delete Selection" { + continue; + } + let from = panel.rect_role(name, role).center(); + let to = panel.rect(button).center(); + panel.drag_hold_role(name, role, to - from); + assert!(drag::active::(panel.ctx()).is_some(), "{name} carries its payload"); + assert!(drag::mark(panel.ctx()).is_none(), "{button} refuses {name}"); + let history = undo_len(&panel.app()); + panel.release(); + let app = panel.app(); + assert_eq!(undo_len(&app), history, "{name} on {button} makes no edit"); + assert!(!basic(&app, a) && rows_of(&app) == rows, "{name} on {button} leaves the rows as they were"); + } + } + + let from = panel.rect_role("Target A", Role::BUTTON).center(); + let to = panel.rect("Delete Selection").center(); + panel.drag_hold_role("Target A", Role::BUTTON, to - from); + assert!(drag::mark(panel.ctx()).is_some(), "Delete Selection takes a target circle's appearance"); + let history = undo_len(&panel.app()); + panel.release(); + let app = panel.app(); + assert!(basic(&app, a) && basic(&app, b), "the dropped appearance is reduced to a basic appearance"); + assert_eq!(undo_len(&app), history + 1); + assert_eq!(rows_of(&app), rows, "the row is not deleted"); + assert!(crate::dialogs::confirm::open_question(&app).is_none()); +} + +/// Delete Selection refuses an appearance carried over from another document: held across Next Document and +/// released on the trash, it leaves the object with the same ID there as it was. +#[test] +fn delete_selection_refuses_an_appearance_from_another_document() { + use crate::panel_drag::PanelDrag; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Key, Modifiers}; + + let (app, [a, _]) = two_documents_with_a_styled(); + let first = app.session.active().unwrap().uid; + let mut panel = Panel::new(app, show); + let from = panel.rect_role("Target A", Role::BUTTON).center(); + let to = panel.rect("Delete Selection").center(); + panel.drag_hold_role("Target A", Role::BUTTON, to - from); + assert!(drag::mark(panel.ctx()).is_some(), "Delete Selection takes an appearance from its own document"); + + panel.key(Key::F6, Modifiers::COMMAND); + let history = { + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_ne!(st.uid, first, "Next Document switches documents during the drag"); + st.history.undo.len() + }; + let carried = drag::active::(panel.ctx()); + assert!(matches!(carried.as_deref(), Some(PanelDrag::Appearance { document, source, .. }) if *document == first && *source == a)); + assert!(drag::mark(panel.ctx()).is_none(), "Delete Selection refuses an appearance from another document"); + panel.release(); + { + let app = panel.app(); + assert!(!basic(&app, a), "the object with the same ID keeps its appearance"); + assert_eq!(undo_len(&app), history, "the foreign drop makes no edit"); + } + + panel.drag("Target A", "Delete Selection", Modifiers::NONE); + assert!(basic(&panel.app(), a), "a drag within the new document still reduces the appearance"); +} + /// The footer's layer count is in the accessibility tree, and it follows the document's layers. #[test] fn the_footer_counts_the_layers() { @@ -987,6 +1080,193 @@ fn row_menus_list_plugin_commands() { assert!(plugins(&app, b).is_empty(), "removed: no Plug-ins submenu"); } +/// Whether `a` and `b` are within float rounding of each other. +fn near(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-6 +} + +/// Object `id`'s opacity in the active document. +fn opacity(app: &VectorcraftApp, id: NodeId) -> f32 { + app.session.active().unwrap().doc.node(id).unwrap().opacity +} + +/// Two documents, each with rows "A" and "B" of the same local IDs in both; A has a second fill and 30% opacity. +/// The first document is active. +fn two_documents_with_a_styled() -> (VectorcraftApp, [NodeId; 2]) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut ids = Vec::new(); + for _ in 0..2 { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let mut add = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + let (a, b) = (add(0), add(60)); + name_row(&mut app, a, "A"); + name_row(&mut app, b, "B"); + app.run("appearance.addFill", json!({"ids": [a.0]})).unwrap(); + app.run("transparency.set", json!({"ids": [a.0], "opacity": 30})).unwrap(); + app.run("select.none", json!({})).unwrap(); + ids.push([a, b]); + } + assert_eq!(ids[0], ids[1], "the documents have different objects with the same local IDs"); + assert!(app.session.set_active(0)); + (app, ids[0]) +} + +/// The Layers panel under three list rows that drag, from the active document, a paint, the bottom object as +/// selected art and the bottom object's appearance. +fn drag_sources_and_layers(app: &mut VectorcraftApp, ui: &mut Ui) { + use crate::panel_drag::PanelDrag; + use craft::ui::contract::ListDrag; + use craft::ui::contract::ShowCollection as _; + use craft::ui::list::{List, ListRow}; + + let st = app.session.active().unwrap(); + let (document, reverts) = (st.uid, st.reverts); + let source = st.doc.layers[0].children().unwrap()[0].id; + let drags = [ + ("Dragged paint", PanelDrag::paint(vectorcraft_color::Paint::None)), + ("Dragged art", PanelDrag::Art { document, reverts, ids: vec![source] }), + ("Dragged appearance", PanelDrag::Appearance { document, reverts, source }), + ]; + egui::Panel::top("drag-sources").exact_size(150.0).show(ui, |ui| { + for (name, drag) in drags { + ui.allocate_ui(egui::vec2(ui.available_width(), 48.0), |ui| { + let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key); + List::::new(name) + .drag_payload(move |_: &ListDrag| Some(drag.clone())) + .show_items(ui, &keys, &mut |_, _| ListRow::new(name)); + }); + } + }); + show(app, ui); +} + +/// A target circle takes an appearance from another row's circle of the same document: a plain drop moves it and an +/// Alt drop copies it. Held back over its own row's circle, the appearance is refused and nothing changes. +#[test] +fn a_target_circle_takes_another_rows_appearance_and_refuses_its_own() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Event, Modifiers}; + + let (mut app, _, [a, b]) = two_rects(); + name_row(&mut app, a, "A"); + name_row(&mut app, b, "B"); + app.run("transparency.set", json!({"ids": [a.0], "opacity": 30})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let mut panel = Panel::new(app, show); + + let own = panel.rect_role("Target A", Role::BUTTON).center(); + let other = panel.rect_role("Target B", Role::BUTTON).center(); + panel.drag_hold_role("Target A", Role::BUTTON, other - own); + assert!(drag::mark(panel.ctx()).is_some(), "another row's circle takes the appearance"); + panel.frame_with(vec![Event::PointerMoved(own)]); + assert!(drag::mark(panel.ctx()).is_none(), "the circle refuses its own row's appearance"); + let history = undo_len(&panel.app()); + panel.release(); + { + let app = panel.app(); + assert_eq!(undo_len(&app), history, "the drop on its own circle makes no edit"); + assert!(near(opacity(&app, a), 0.3) && near(opacity(&app, b), 1.0)); + } + + panel.drag("Target A", "Target B", Modifiers::ALT); + { + let app = panel.app(); + assert!(near(opacity(&app, a), 0.3) && near(opacity(&app, b), 0.3), "an Alt drop copies the appearance"); + } + panel.app().run("transparency.set", json!({"ids": [a.0], "opacity": 50})).unwrap(); + panel.drag("Target A", "Target B", Modifiers::NONE); + let app = panel.app(); + assert!(near(opacity(&app, a), 1.0) && near(opacity(&app, b), 0.5), "a plain drop moves the appearance"); +} + +/// A target circle refuses an appearance carried over from another document: held across Next Document and +/// released on the new document's circle, it leaves the objects with the same IDs there as they were. +#[test] +fn a_target_circle_refuses_an_appearance_from_another_document() { + use crate::panel_drag::PanelDrag; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + use egui::{Event, Key, Modifiers}; + + let (app, [a, b]) = two_documents_with_a_styled(); + let first = app.session.active().unwrap().uid; + let mut panel = Panel::new(app, show); + let from = panel.rect_role("Target A", Role::BUTTON).center(); + let to = panel.rect_role("Target B", Role::BUTTON).center(); + panel.drag_hold_role("Target A", Role::BUTTON, to - from); + assert!(drag::mark(panel.ctx()).is_some(), "the circle takes an appearance from its own document"); + + panel.key(Key::F6, Modifiers::COMMAND); + let history = { + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_ne!(st.uid, first, "Next Document switches documents during the drag"); + st.history.undo.len() + }; + let to = panel.rect_role("Target B", Role::BUTTON).center(); + panel.frame_with(vec![Event::PointerMoved(to)]); + let carried = drag::active::(panel.ctx()); + assert!(matches!(carried.as_deref(), Some(PanelDrag::Appearance { document, source, .. }) if *document == first && *source == a)); + assert!(drag::mark(panel.ctx()).is_none(), "the circle refuses an appearance from another document"); + panel.release(); + { + let app = panel.app(); + assert!(near(opacity(&app, b), 1.0), "the object with the same ID keeps its look"); + assert_eq!(undo_len(&app), history, "the foreign drop makes no edit"); + } + + panel.drag("Target A", "Target B", Modifiers::NONE); + assert!(near(opacity(&panel.app(), b), 0.3), "a drag within the new document still moves the appearance"); +} + +/// A target circle takes only an appearance: a paint or the selected art dragged from a panel is refused and +/// leaves the row as it was. +#[test] +fn a_target_circle_refuses_a_paint_and_dragged_art() { + use crate::panel_drag::PanelDrag; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use craft::ui::runtime::drag; + + let (mut app, _, [a, b]) = two_rects(); + name_row(&mut app, a, "A"); + name_row(&mut app, b, "B"); + app.run("transparency.set", json!({"ids": [a.0], "opacity": 30})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let mut panel = Panel::new(app, drag_sources_and_layers); + let hold = |panel: &mut Panel, name: &str| { + let from = panel.rect_role(name, Role::LIST_ITEM).center(); + let to = panel.rect_role("Target B", Role::BUTTON).center(); + panel.drag_hold_role(name, Role::LIST_ITEM, to - from); + drag::active::(panel.ctx()).map(|carried| (*carried).clone()) + }; + + for name in ["Dragged paint", "Dragged art"] { + let carried = hold(&mut panel, name); + assert!(matches!(carried, Some(PanelDrag::Paint { .. } | PanelDrag::Art { .. })), "{name} carries its payload"); + assert!(drag::mark(panel.ctx()).is_none(), "the circle refuses {name}"); + let history = undo_len(&panel.app()); + panel.release(); + let app = panel.app(); + assert_eq!(undo_len(&app), history, "{name} makes no edit"); + assert!(near(opacity(&app, b), 1.0), "{name} leaves the row's appearance alone"); + } + + let carried = hold(&mut panel, "Dragged appearance"); + let (document, reverts) = { + let app = panel.app(); + let st = app.session.active().unwrap(); + (st.uid, st.reverts) + }; + assert_eq!(carried, Some(PanelDrag::Appearance { document, reverts, source: a })); + assert!(drag::mark(panel.ctx()).is_some(), "the circle takes an appearance from a panel"); + panel.release(); + assert!(near(opacity(&panel.app(), b), 0.3), "the dropped appearance moves to the row"); +} + /// A target circle's appearance held across File › Revert and dropped on another row's circle /// leaves the restored objects with the same IDs as they were; a drag started after the revert /// still moves the appearance. diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 2e34e36dc6..7e3caa1a43 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -25,6 +25,8 @@ pub struct PropertiesUi { /// The cache of `appearance_section::edited_strokes_profiled`, keyed by (document uid, revision, /// active Appearance row). 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)>, } /// The key of [`PropertiesUi::edited_profiled`]: (document uid, revision, active Appearance row). @@ -34,6 +36,7 @@ type ProfiledKey = (u64, u64, Option); const HALVES: [ColumnWidth; 2] = [ColumnWidth::fill(1.0); 2]; /// One Quick Actions button: its label and the command it runs. +#[derive(Clone, Debug)] pub(crate) struct QuickAction { /// The button's label. pub label: &'static str, @@ -169,12 +172,42 @@ fn quick_action_buttons(app: &mut VectorcraftApp, ui: &mut Ui) { } } } - for action in quick_actions(app) { + for action in shown_quick_actions(app) { Button::command(action.command).label(action.label).show(ui); } }); } +/// What the Quick Actions are listed from: the menus' state ([`crate::menus::model::state_key`]), which +/// moves with every command run, the document and its revision, the tool and isolation mode. +fn quick_actions_key(app: &VectorcraftApp) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + crate::menus::model::state_key(app, None).hash(&mut h); + app.session.tool_id().hash(&mut h); + app.session.active().map(|st| (st.uid, st.revision, st.isolation)).hash(&mut h); + h.finish() +} + +#[cfg(test)] +thread_local! { + /// How many times this thread has listed the Quick Actions. + pub(crate) static QUICK_ACTION_LISTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`quick_actions`], listed again only when [`quick_actions_key`] changed. +fn shown_quick_actions(app: &mut VectorcraftApp) -> Vec { + let key = quick_actions_key(app); + if let Some((kept, actions)) = &app.ui.properties_panel.quick_actions + && *kept == key + { + return actions.clone(); + } + let actions = quick_actions(app); + app.ui.properties_panel.quick_actions = Some((key, actions.clone())); + actions +} + /// The ellipsis button that shows the panel `panel` for the section's further options. fn more_options(ui: &mut Ui, panel: &str, tip: &'static str) { IconButton::command(IconId::new("ellipsis"), CommandRef::with_params("window.panel", json!({ "panel": panel }))).label(tip).show(ui); @@ -183,6 +216,8 @@ fn more_options(ui: &mut Ui, panel: &str, tip: &'static str) { /// The Quick Actions the selection offers, in order. Lock and Isolate Group are left out while their commands are /// off (in isolation mode, while an opacity mask is edited). pub(crate) fn quick_actions(app: &mut VectorcraftApp) -> Vec { + #[cfg(test)] + QUICK_ACTION_LISTS.with(|n| n.set(n.get() + 1)); let n_sel = super::selection_len(app); let first = first_selected(app); let kind = first.as_deref().map(|n| &n.kind); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index bb90289aef..4a8158364a 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1084,6 +1084,37 @@ fn quick_actions_follow_the_selection() { } } +/// The panel lists the Quick Actions once per change of what they depend on, not in every frame. +#[test] +fn quick_actions_are_listed_again_only_after_a_change() { + let mut app = new_app(); + rect(&mut app, 10.0, 10.0, 40.0, 40.0); + rect(&mut app, 80.0, 10.0, 40.0, 40.0); + let ctx = crate::testing::ui_context(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); + let mut time = 0.0; + let mut frame = |app: &mut VectorcraftApp| { + time += 0.05; + crate::testing::app_frame(app, &ctx, egui::RawInput { time: Some(time), screen_rect, ..Default::default() }); + }; + for _ in 0..3 { + frame(&mut app); + } + let lists = || QUICK_ACTION_LISTS.with(|n| n.get()); + let shown = |app: &VectorcraftApp| app.ui.properties_panel.quick_actions.as_ref().map(|(_, a)| a.iter().map(|a| a.command).collect::>()); + assert!(shown(&app).is_some_and(|a| !a.contains(&"object.group")), "one object selected: no Group"); + let before = lists(); + frame(&mut app); + frame(&mut app); + assert_eq!(lists() - before, 0, "frames with nothing changed list no Quick Actions"); + app.run("select.all", json!({})).unwrap(); + let before = lists(); + frame(&mut app); + frame(&mut app); + assert_eq!(lists() - before, 1, "a new selection lists them once"); + assert!(shown(&app).is_some_and(|a| a.contains(&"object.group")), "two objects selected: Group"); +} + /// A brushed stroke with a variable width: the Width Profile list lists only Uniform, which removes /// the profile. #[test] diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 4f49283464..e51b4b9072 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -5,7 +5,7 @@ use std::sync::LazyLock; -use craft::behavior::{IconId, Mixed}; +use craft::behavior::{ColumnWidth, IconId, Mixed}; use craft::draw::ui::stroke::{self as draw, StrokeEditor, StrokeField, StrokeSections}; use craft::keymap::CommandRef; use craft::ui::buttons::IconButton; @@ -13,7 +13,8 @@ use craft::ui::choice::Segmented; use craft::ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, TooltipSpec}; use craft::ui::display::Divider; use craft::ui::form::Field; -use craft::ui::layout_components::Row; +use craft::ui::layout_components::{Grid, Row}; +use craft::ui::list::ThumbAspect; use craft::ui::menu::PanelRow; use craft::ui::pickers::Select; use craft::ui::popover::Popover; @@ -34,6 +35,12 @@ use crate::VectorcraftApp; // PLAN: assumed `crate::edits::{apply_edits, EditPath}` (wg.A16). use crate::edits::{EditPath, apply_edits}; +/// The Arrowheads row's columns: the start and end heads share the width, and Swap keeps its own. +const ARROWHEAD_COLUMNS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + +/// The width and height ratio of an arrowhead picture on a closed Arrowheads field, which shows the picture alone. +const ARROWHEAD_ASPECT: (u16, u16) = (2, 1); + /// The key of [`StrokePanel::brushed`]: (document uid, revision, active Appearance row). type BrushedKey = (u64, u64, Option); @@ -409,14 +416,14 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) { (st.and_then(|s| s.end_arrow.clone()), false, tl!("End arrowhead"), "endArrow"), ]; Field::new(tl!("Arrowheads")).show(ui, |ui, _| { - // The two heads share the width the Swap button leaves; a field too narrow for all three puts Swap on a - // new line. - Row::new().fill_width().wrap(true).show(ui, |ui, _| { + // The two heads share the width the Swap button leaves, on one line. + Grid::new(&ARROWHEAD_COLUMNS).sizing(Sizing::FillWidth).show(ui, |ui, _| { for (head, start, label, key) in &heads { let (start, key) = (*start, *key); let out = Select::new(*label, Bind::given(head.clone()), &entries) .picture(move |a, cx, rect| arrow_thumb(cx, rect, a.as_ref(), start)) - .sizing(Sizing::FillWidth) + .picture_only() + .picture_aspect(ThumbAspect::new(ARROWHEAD_ASPECT.0, ARROWHEAD_ASPECT.1)) .show(ui); // A custom head goes with its art, as document.inspect reports it. if let Some(a) = out.events.landed() { @@ -432,20 +439,28 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) { let (arrow_align, has_head) = arrow_align_state(st); let scale = st.map_or((100.0, 100.0), |s| s.arrow_scale); let linked = app.ui.stroke_panel.scale_linked; - let out = LinkedFields::new(tl!("Scale"), Bind::given(Mixed::each([Some(scale.0), Some(scale.1)])), Bind::given(linked)) - .mode(LinkMode::Equal) - .unit_kind(UnitKind::Percent) + let out = Field::new(tl!("Scale")) .enabled(has_head) - .show(ui); - if let Some(on) = out.link.landed() { + .show(ui, |ui, _| { + LinkedFields::new(tl!("Scale"), Bind::given(Mixed::each([Some(scale.0), Some(scale.1)])), Bind::given(linked)) + .mode(LinkMode::Equal) + .unit_kind(UnitKind::Percent) + .enabled(has_head) + .show(ui) + }) + .inner; + if let Some(on) = out.as_ref().and_then(|out| out.link.landed()) { app.ui.stroke_panel.scale_linked = *on; } - if let Some([a, b]) = out.edit.events.landed().map(|p| (*p).map(|m| m.same().copied().flatten())) { + if let Some([a, b]) = out.as_ref().and_then(|out| out.edit.events.landed()).map(|p| (*p).map(|m| m.same().copied().flatten())) { app.run("stroke.setAdvanced", json!({"arrowScale": [a.unwrap_or(scale.0), b.unwrap_or(scale.1)]})).ok(); } let aligns: Vec> = ARROW_ALIGN.iter().map(|(v, _, icon, tip)| Entry::new(*v, *tip).icon(IconId::new(icon))).collect(); - let out = Segmented::new(tl!("Align"), Bind::given(arrow_align), &aligns).enabled(has_head).show(ui); - if let Some(v) = out.events.landed() + let out = Field::new(tl!("Align")) + .enabled(has_head) + .show(ui, |ui, _| Segmented::new(tl!("Align"), Bind::given(arrow_align), &aligns).enabled(has_head).show(ui)) + .inner; + if let Some(v) = out.as_ref().and_then(|out| out.events.landed()) && let Some((_, name, _, _)) = ARROW_ALIGN.iter().find(|(a, ..)| a == v) { set(app, json!({"arrowAlign": name})); diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index c56d2d1737..a179e07a53 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -16,11 +16,12 @@ use craft::theme::Srgba; use craft::ui::choice::SwatchFace; use craft::ui::contract::{Bind, DropPlace, ListDrag, MemoProps, PopupKind, SelectMode}; use craft::ui::contract::{Entry, Props as _, Show as _, ShowContainer as _, Trigger}; +use craft::ui::layout_components::Stack; use craft::ui::menu::{Menu, MenuItem}; use craft::ui::patterns::presets::{PresetEvent, PresetView, ThumbInfo}; use craft::ui::primitives::{ContentPainterCx, Glyph, IconSpec, PaintShape, StrokeWidth}; use craft::ui::runtime::env::Label; -use craft::ui::sections::{FooterAction, FooterBar}; +use craft::ui::sections::{FooterAction, FooterBar, FooterOutput}; use craft::ui::style::{DataColor, UiTokens}; use egui::{Color32, Painter, Rect, Response, Shape, Stroke, StrokeKind, Ui, pos2, vec2}; use serde_json::{Value, json}; @@ -218,8 +219,13 @@ fn name_of(key: &SwatchKey) -> &str { /// The swatches and colour groups selected in the panel, in click order, without names that no longer exist /// (deleted, renamed or undone). pub(crate) fn selected(app: &VectorcraftApp) -> Vec { + selected_in(app, &app.ui.swatches_panel) +} + +/// The swatches and colour groups selected in `model`, as [`selected`] reads them from the app's panel. +fn selected_in(app: &VectorcraftApp, model: &Model) -> Vec { let Some(st) = app.session.active() else { return vec![] }; - let mut names = app.ui.swatches_panel.names(); + let mut names = model.names(); names.retain(|n| n == REGISTRATION || st.doc.swatch_name_taken(n)); names } @@ -401,42 +407,58 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { app.ui.swatches_panel = model; return; }; - let thumbs = Thumbs { - revision: (st.uid, st.revision), - lit: highlighted(&st.doc, &base).into_iter().map(str::to_string).collect(), - doc: Arc::clone(&st.doc), - }; - let dragged_doc = Arc::clone(&thumbs.doc); + let revision = (st.uid, st.revision); + let lit: Vec = highlighted(&st.doc, &base).into_iter().map(str::to_string).collect(); + let doc = Arc::clone(&st.doc); let document = st.uid; let reverts = st.reverts; + let foot = Footer::of(app, &model); let shown_app: &VectorcraftApp = app; - let browser = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0)) - .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag)))) - .thumb(thumbs, thumb) - .row_icons(|key| match key { - SwatchKey::Swatch(name) => row_icons(shown_app, name), - _ => vec![], + let search = model.show_find; + let state = &mut model.state; + // The browser fills the room the footer leaves, so the footer stays in view under the swatches. The body can run + // more than once in a pass, so each run builds its own browser. A list drag is keyed by its browser ID. Each + // document has its own browser. + let mut footed = None; + let out = Stack::new() + .label(tl!("Swatches")) + .fill() + .footer(|ui, _| footed = Some(foot.show(ui))) + .show(ui, |ui, _| { + let dragged_doc = Arc::clone(&doc); + let thumbs = Thumbs { revision, lit: lit.clone(), doc: Arc::clone(&doc) }; + let browser = SwatchesPanel::new(&data, Bind::bound(&mut *state), Srgba::rgb(0.0, 0.0, 0.0)) + .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag)))) + .thumb(thumbs, thumb) + .row_icons(|key| match key { + SwatchKey::Swatch(name) => row_icons(shown_app, name), + _ => vec![], + }) + .row_items(|key| row_items(shown_app, key)) + .takes_drop::(DropPlace::Between, |drag, _| dnd::accepts(drag, document, reverts)) + .takes_drop::(DropPlace::Onto, |drag, _| dnd::accepts(drag, document, reverts)) + .select(SelectMode::Multi) + .search(search) + .reveal(focus.clone().map(SwatchKey::Swatch)) + .footer(None); + ui.push_id(("swatch-rows", document), |ui| browser.show(ui)).inner }) - .row_items(|key| row_items(shown_app, key)) - .takes_drop::(DropPlace::Between, |drag, _| dnd::accepts(drag, document, reverts)) - .takes_drop::(DropPlace::Onto, |drag, _| dnd::accepts(drag, document, reverts)) - .select(SelectMode::Multi) - .search(model.show_find) - .reveal(focus.map(SwatchKey::Swatch)) - .footer(None); - // A list drag is keyed by its browser ID. Each document has its own browser. - let out = ui.push_id(("swatch-rows", document), |ui| browser.show(ui)).inner; + .inner; app.ui.swatches_panel = model; let shown = shown_keys(&data); - if let Some((at, _, alt)) = out.used - && let Some(entry) = data.get(at.group).and_then(|g| g.entries.get(at.index)) - { - apply(app, &entry.name, alt); + if let Some(out) = out { + if let Some((at, _, alt)) = out.used + && let Some(entry) = data.get(at.group).and_then(|g| g.entries.get(at.index)) + { + apply(app, &entry.name, alt); + } + for event in out.events { + on_event(app, &shown, event); + } } - for event in out.events { - on_event(app, &shown, event); + if let Some(out) = footed { + on_footer(app, ui, foot, out); } - footer(app, ui); } /// The rows `drag` moves: the dragged rows of the grabbed row's kind (colour groups or swatches), in panel order. @@ -761,36 +783,64 @@ const NEW_GROUP: usize = 5; /// Swatch and Delete. Alt-click on Delete deletes without asking; Cmd/Ctrl-click on New Swatch makes a spot color, and /// Cmd/Ctrl+Shift-click a global process color. Swatches dragged from the list and dropped on New Swatch are /// duplicated, and rows dropped on Delete are deleted, also with nothing selected. -fn footer(app: &mut VectorcraftApp, ui: &mut Ui) { - let sel = selected(app); - let kind = app.ui.swatches_panel.kind; - let del = actions::deletable(app, &sel); - let opts = actions::editable(app, &sel); - let group = actions::selected_group(app, &sel).filter(|_| opts.is_none()); - let icon = |id: &'static str| IconSpec::svg(IconId::new(id)); - let document = app.session.active().map(|state| state.uid); - let rows_drag = move |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); - let edit = if group.is_some() { - FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group")) - } else { - FooterAction::new(icon("dc-options"), tl!("Swatch Options")).enabled(opts.is_some()) - }; - // Libraries, Show Swatch Kinds and the edit action sit at the start edge; Delete at the end edge, then New Swatch - // and New Color Group before it. - let actions = [ - FooterAction::new(icon("library"), tl!(SwatchLibraries::MENU)) - .popup(PopupKind::Menu) - .pressed(library_panel::any_open::(&app.ui)), - FooterAction::new(icon("dc-swatch-kinds"), tl!("Show Swatch Kinds")).popup(PopupKind::Menu).pressed(kind != Kind::All), - edit, - FooterAction::new(icon("trash-2"), tl!("Delete Swatch")) - .enabled(!del.is_empty()) - .takes_drops_disabled(del.is_empty()) - .accepts_drops::(rows_drag), - FooterAction::new(icon("dc-new-item"), tl!("New Swatch")).accepts_drops::(rows_drag), - FooterAction::new(icon("dc-folder"), tl!("New Color Group")), - ]; - let out = FooterBar::actions(actions).at_start(EDIT + 1).show_footer(ui); +struct Footer { + sel: Vec, + kind: Kind, + del: Vec, + opts: Option, + group: Option, + libraries_open: bool, + document: Option, +} + +impl Footer { + /// The footer's state for the panel `model`, which is out of the app while the swatch browser borrows it. + fn of(app: &VectorcraftApp, model: &Model) -> Self { + let sel = selected_in(app, model); + let del = actions::deletable(app, &sel); + let opts = actions::editable(app, &sel); + let group = actions::selected_group(app, &sel).filter(|_| opts.is_none()); + Footer { + kind: model.kind, + libraries_open: library_panel::any_open::(&app.ui), + document: app.session.active().map(|state| state.uid), + sel, + del, + opts, + group, + } + } + + /// The footer bar, in the room the panel keeps for it under the swatches. + fn show(&self, ui: &mut Ui) -> FooterOutput { + let icon = |id: &'static str| IconSpec::svg(IconId::new(id)); + let document = self.document; + let rows_drag = move |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); + let edit = if self.group.is_some() { + FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group")) + } else { + FooterAction::new(icon("dc-options"), tl!("Swatch Options")).enabled(self.opts.is_some()) + }; + // Libraries, Show Swatch Kinds and the edit action sit at the start edge; Delete at the end edge, then New + // Swatch and New Color Group before it. + let actions = [ + FooterAction::new(icon("library"), tl!(SwatchLibraries::MENU)).popup(PopupKind::Menu).pressed(self.libraries_open), + FooterAction::new(icon("dc-swatch-kinds"), tl!("Show Swatch Kinds")).popup(PopupKind::Menu).pressed(self.kind != Kind::All), + edit, + FooterAction::new(icon("trash-2"), tl!("Delete Swatch")) + .enabled(!self.del.is_empty()) + .takes_drops_disabled(self.del.is_empty()) + .accepts_drops::(rows_drag), + FooterAction::new(icon("dc-new-item"), tl!("New Swatch")).accepts_drops::(rows_drag), + FooterAction::new(icon("dc-folder"), tl!("New Color Group")), + ]; + FooterBar::actions(actions).at_start(EDIT + 1).show_footer(ui) + } +} + +/// Runs what the footer reported: a pressed action, a drop on New Swatch or Delete, or a menu it opened. +fn on_footer(app: &mut VectorcraftApp, ui: &mut Ui, footer: Footer, out: FooterOutput) { + let Footer { sel, kind, del, opts, group, .. } = footer; match out.picked { Some(DELETE) if !del.is_empty() => actions::delete(app, del, out.mods.alt), Some(NEW) => actions::new_swatch(app, &sel, out.mods), diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index e45e0f3132..617fb83a35 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -184,6 +184,22 @@ fn the_footer_menu_buttons_report_that_they_open_a_menu() { } } +/// The footer reads the panel's selection while the browser holds the panel's model: with one swatch selected, Swatch +/// Options and Delete Swatch are enabled. +#[test] +fn the_footer_acts_on_the_panels_selection() { + use crate::tests::panel_harness::Panel; + + let mut app = app(); + select_rows(&mut app, &["Red"]); + let mut panel = Panel::new(app, show); + panel.frame(); + assert_eq!(selected(&panel.app()), vec!["Red".to_string()]); + for name in ["Swatch Options", "Delete Swatch"] { + assert!(panel.enabled(name), "{name}"); + } +} + /// Art `ids` dragged off the canvas. fn art_drag(app: &VectorcraftApp, ids: Vec) -> PanelDrag { let (document, reverts) = app.session.active().map_or((0, 0), |st| (st.uid, st.reverts)); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index 735df1b0fd..e2c5a62b80 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -120,17 +120,32 @@ fn show_hex_field_is_a_setting_of_the_panel() { } /// An explicit null for any `ui.colorWheel` key keeps that key's value, as leaving the key out does, -/// and the other keys of the same call still apply. +/// and the other keys of the same call still apply. `contrastBackground` is the exception: null +/// unpins the background. #[test] fn ui_color_wheel_keeps_a_key_given_as_null() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); let set = json!({ "view": "box", "channel": "red", "opacity": true, "hexField": true, "sliders": "oklch", - "gamut": true, "harmony": true, "harmonyRule": "triad", "vision": true, "documentColors": true + "gamut": true, "harmony": true, "harmonyRule": "triad", "contrast": true, "contrastFor": "largeText", + "contrastBackground": null, "vision": true, "documentColors": true }); let all = app.run("ui.colorWheel", set.clone()).unwrap(); assert_eq!(all, set); - for key in ["view", "channel", "opacity", "hexField", "sliders", "gamut", "harmony", "harmonyRule", "vision", "documentColors"] { + for key in [ + "view", + "channel", + "opacity", + "hexField", + "sliders", + "gamut", + "harmony", + "harmonyRule", + "contrast", + "contrastFor", + "vision", + "documentColors", + ] { assert_eq!(app.run("ui.colorWheel", json!({ key: null })).unwrap(), all, "{key}: null"); } let got = app.run("ui.colorWheel", json!({"view": null, "channel": "blue", "opacity": null, "hexField": false})).unwrap(); @@ -138,7 +153,8 @@ fn ui_color_wheel_keeps_a_key_given_as_null() { got, json!({ "view": "box", "channel": "blue", "opacity": true, "hexField": false, "sliders": "oklch", - "gamut": true, "harmony": true, "harmonyRule": "triad", "vision": true, "documentColors": true + "gamut": true, "harmony": true, "harmonyRule": "triad", "contrast": true, "contrastFor": "largeText", + "contrastBackground": null, "vision": true, "documentColors": true }) ); } diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs index ae639d59be..15554da438 100644 --- a/crates/ui-egui/src/panels/tests_panel_rows.rs +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -150,3 +150,45 @@ fn align_to_shares_the_distribute_spacing_line_inside_the_align_panel() { assert!((field.top()..=field.bottom()).contains(&to.center().y), "Align To at {to:?} is off the spacing field's line {field:?}"); assert!(to.right() <= ROOM.x, "Align To at {to:?} runs past the panel"); } + +#[test] +fn the_swatches_footer_stays_inside_a_short_panel() { + let height = 400.0; + let mut panel = Panel::new(app_with_rect(), swatches::show); + panel.room(egui::vec2(ROOM.x, height)).frame(); + // The swatch browser fills the room the footer leaves, so every footer action is in the panel. + for name in ["Show Swatch Kinds", "New Swatch", "New Color Group", "Delete Swatch"] { + let at = panel.rect(name); + assert!(at.bottom() <= height && at.top() >= 0.0, "{name} at {at:?} is outside the panel's {height} pt"); + } +} + +#[test] +fn the_arrowhead_heads_and_swap_share_one_line_in_the_stroke_panel() { + let names = ["Start arrowhead", "End arrowhead", "Swap start and end arrowheads"]; + let panel = floated(app_with_rect(), "stroke", "en", Place::Floating(340.0), &names); + let middles = panel.middles(&names); + let rects: Vec<&(String, egui::Rect)> = panel.nodes.iter().filter(|(name, _)| names.contains(&name.as_str())).collect(); + assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{middles:?} {rects:?} in {:?}", panel.body); + assert!(panel.past_named(&names).is_empty(), "past the panel: {:?}", panel.past_named(&names)); +} + +#[test] +fn the_arrowhead_scale_and_align_rows_show_their_labels() { + let mut panel = Panel::new(app_with_rect(), stroke::show); + let (shapes, _) = panel.paint_at(1.0); + let texts: Vec<(String, egui::Rect)> = shapes + .iter() + .filter_map(|s| match s { + egui::Shape::Text(t) => Some((t.galley.text().trim_end_matches(':').to_string(), t.visual_bounding_rect())), + _ => None, + }) + .collect(); + // Each label sits at the start of its row, before the row's controls. + for (label, control) in [("Scale", "Scale"), ("Align", "Align")] { + let field = panel.rect(control); + let shown = + texts.iter().find(|(text, at)| text == label && at.right() <= field.right() && (field.top()..=field.bottom()).contains(&at.center().y)); + assert!(shown.is_some(), "no {label:?} label on its row at {field:?}; painted: {:?}", texts.iter().map(|t| &t.0).collect::>()); + } +} diff --git a/crates/ui-egui/src/panels/tests_strokedepth.rs b/crates/ui-egui/src/panels/tests_strokedepth.rs index b05de360e0..b64f2954e1 100644 --- a/crates/ui-egui/src/panels/tests_strokedepth.rs +++ b/crates/ui-egui/src/panels/tests_strokedepth.rs @@ -307,3 +307,16 @@ fn a_long_custom_arrowhead_preview_fits_in_its_box() { assert!(outside.is_empty(), "start {start}: {} pixels outside the box, e.g. {:?}", outside.len(), outside.first()); } } + +/// The End arrowhead select lists the notched arrow under its name, right after Arrow, and +/// picking it gives the stroke that end head. +#[test] +fn arrowhead_select_lists_the_notched_arrow_after_arrow() { + let mut panel = panel(); + panel.frame(); + panel.click("End arrowhead"); + let (arrow, notched, open) = (panel.rect("Arrow"), panel.rect("Notched Arrow"), panel.rect("Arrow (open)")); + assert!(arrow.center().y < notched.center().y && notched.center().y < open.center().y, "{arrow:?} {notched:?} {open:?}"); + panel.click("Notched Arrow"); + assert_eq!(current_stroke(&panel.app()).and_then(|s| s.end_arrow), Some(vectorcraft_doc::Arrowhead::NotchedArrow)); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 4265351f6a..5ac49daeb9 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -230,6 +230,11 @@ fn zoom_stops(print: Option) -> ZoomScheme { ZoomScheme::ILLUSTRATOR.with_hundred(zoom_baseline(print)) } +/// The zoom stops in the percent the status bar shows, lowest first. +pub fn zoom_stop_percents() -> impl DoubleEndedIterator { + zoom_stops(None).rungs.iter().map(|rung| rung * 100.0) +} + /// The zoom `z` as the status bar shows it, in percent of [`zoom_baseline`]. pub fn zoom_display_percent(z: f64, print: Option) -> f64 { zoom_stops(print).percent(z) diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index f1f58c89ad..7a5dff1202 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -140,6 +140,19 @@ impl Panel { self.after(); } + /// [`Panel::click_role`] on the zero-based `index`th control of `role` named `name`, where controls of one role share + /// the name (an In and an Out handle's Length). + pub(crate) fn click_role_nth(&mut self, name: &str, role: craft::ui::contract::Role, index: usize) { + self.frame(); + let target = { + let tree = self.fixture.tree(); + self.fixture.by_role(role).into_iter().filter(|t| tree.name_of(t.node) == Some(name)).nth(index) + }; + let target = target.unwrap_or_else(|| panic!("no {role:?} named {name:?} at {index} in {:?}", self.names())); + self.fixture.click(&target); + self.after(); + } + /// The control of `role` named `name` in the latest frame, where nodes of other roles share the name. fn look_role(&self, name: &str, role: craft::ui::contract::Role) -> Target { let tree = self.fixture.tree(); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index b605447733..e69a40c670 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -876,10 +876,12 @@ fn controls_are_drawn_at_the_size_the_script_gave_them() { .unwrap_or_else(|| panic!("no {role:?} {label:?}")) }; let w = app.session.script_window().unwrap(); + // The field is the text input named for screen readers; the editor inside its padding is a text + // input too, and the update lists the two in no fixed order. let (wide, ok, field) = ( bounds(egui::accesskit::Role::Button, Some("Wide")), bounds(egui::accesskit::Role::Button, Some("OK")), - bounds(egui::accesskit::Role::TextInput, None), + bounds(egui::accesskit::Role::TextInput, Some("Text")), ); assert!(wide.width() > ok.width() && wide.height() > ok.height(), "the wide button is larger than OK: {wide:?} {ok:?}"); assert!((wide.width() - f64::from(w.nodes[1].rect.w)).abs() < 1.0, "the wide button is as wide as its preferred size: {wide:?}"); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index d90dbd96c0..9a3c6c2139 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -184,7 +184,15 @@ pub(crate) fn slots(app: &VectorcraftApp) -> Vec<(Option<&'static str>, Vec<&'st /// The slot a group of tools is in the rail's last-used memory: the index of its first tool in the /// catalog, which stays put while the user edits the toolbar. pub(crate) fn slot_id(first: &str) -> SlotId { - vectorcraft_tools::catalog::all_tools().position(|t| t.id == first).and_then(|i| SlotId::try_from(i).ok()).unwrap_or(SlotId::MAX) + static IDS: std::sync::OnceLock> = std::sync::OnceLock::new(); + let ids = IDS.get_or_init(|| { + let mut ids = std::collections::HashMap::new(); + for (i, tool) in vectorcraft_tools::catalog::all_tools().enumerate() { + ids.entry(tool.id).or_insert_with(|| SlotId::try_from(i).unwrap_or(SlotId::MAX)); + } + ids + }); + ids.get(first).copied().unwrap_or(SlotId::MAX) } /// A rail tool that selects `id`: the tool's command in the catalog, which gives the button its name, its icon and @@ -196,6 +204,8 @@ pub(crate) fn rail_tool(id: &str) -> RailTool { /// The rail's slots for `slots`: a category's first slot carries its caption, and its last ends the /// group. pub(crate) fn rail_slots(slots: &[(Option<&'static str>, Vec<&'static str>)]) -> Vec> { + #[cfg(test)] + SLOT_BUILDS.with(|n| n.set(n.get() + slots.len())); slots .iter() .enumerate() @@ -344,19 +354,54 @@ pub(crate) fn rail_view(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: height } +/// The tool groups a rail's slots are built from, with the language their captions are in. +#[derive(Clone, Debug, PartialEq, Eq)] +struct SlotSource { + /// A strip's slots hold one tool each. + strip: bool, + /// The UI language. + lang: crate::i18n::Lang, + /// Each slot's caption and tools. + groups: Vec<(Option<&'static str>, Vec<&'static str>)>, +} + +impl SlotSource { + /// The rail's slots for these groups. + fn slots(&self) -> Vec> { + if !self.strip { + return rail_slots(&self.groups); + } + #[cfg(test)] + SLOT_BUILDS.with(|n| n.set(n.get() + self.groups.len())); + self.groups.iter().flat_map(|(_, tools)| tools).map(|tool| ToolSlot::new(slot_id(tool), vec![rail_tool(tool)])).collect() + } +} + +#[cfg(test)] +thread_local! { + /// How many rail slots this thread has built. + pub(crate) static SLOT_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// What a rail reads across passes: its slots and the tools they showed last, each edited only when -/// it changed, so a pass where neither changed reads neither. +/// it changed, so a pass where neither changed reads neither. The slots are built again only when +/// the groups they come from change. #[derive(Default)] pub(crate) struct RailModel { + source: Option, slots: Tracked>>, last_used: Tracked>, } impl RailModel { - /// Brings the model up to `slots` and `last_used`. - fn refresh(&mut self, slots: Vec>, last_used: LastUsed) { - if *self.slots != slots { - self.slots.edit(|kept| *kept = slots); + /// Brings the model up to `source` and `last_used`. + fn refresh(&mut self, source: SlotSource, last_used: LastUsed) { + if self.source.as_ref() != Some(&source) { + let slots = source.slots(); + if *self.slots != slots { + self.slots.edit(|kept| *kept = slots); + } + self.source = Some(source); } if *self.last_used != last_used { self.last_used.edit(|kept| *kept = last_used); @@ -366,21 +411,22 @@ impl RailModel { /// [`rail_view`] over `model`, the rail's own. fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, model: &mut RailModel) -> f32 { - let (slots, last_used) = match &owner { - Owner::Tools => (rail_slots(&slots(app)), app.ui.tools_last_used.clone()), + let lang = crate::i18n::current(); + let (source, last_used) = match &owner { + Owner::Tools => (SlotSource { strip: false, lang, groups: slots(app) }, app.ui.tools_last_used.clone()), Owner::Toolbar(id) => { let Some(bar) = bar_of(&app.ui, *id) else { return 0.0 }; - let groups: Vec<_> = groups_of(app, &owner).into_iter().map(|g| (None, g)).collect(); - (rail_slots(&groups), bar.last_used.clone()) + let groups = groups_of(app, &owner).into_iter().map(|g| (None, g)).collect(); + (SlotSource { strip: false, lang, groups }, bar.last_used.clone()) } // One slot per tool, so a strip has no flyouts. A group no longer in the toolbar draws // nothing; `keep_strips` closes its panel. Owner::Strip(parent, first) => { - let tools = strip_tools(app, parent, first); - (tools.iter().map(|tool| ToolSlot::new(slot_id(tool), vec![rail_tool(tool)])).collect(), Default::default()) + let groups = vec![(None, strip_tools(app, parent, first))]; + (SlotSource { strip: true, lang, groups }, Default::default()) } }; - model.refresh(slots, last_used); + model.refresh(source, last_used); let current = app.session.tool_id().to_string(); // PLAN: the sheet's `Cards<'a> { app }` cannot be held beside the footer's `&mut app`; Cards copies the two prefs. let cards = card::Cards::new(app); @@ -718,10 +764,11 @@ fn quad_bounds(quad: &[Point; 4]) -> vectorcraft_geom::Rect { /// The Fill/Stroke proxy, Color/Gradient/None, the drawing modes and screen mode under the rail's /// tools: in two columns the three drawing modes show, in one only the current one, which cycles /// them. A row the rail is too narrow for goes on in the next line. The All Tools drawer's Show -/// section hides any of them. +/// section hides any of them. A rule above them parts them from the tools, which scroll above it in a short rail. fn bottom_controls(app: &mut VectorcraftApp, ui: &mut Ui, footer: RailFooter) { let two = footer.columns > 1; let show = app.ui.toolbar_show; + Divider::horizontal().show(ui); if show.fill_stroke { crate::panels::proxy(app, ui); } @@ -734,7 +781,8 @@ fn bottom_controls(app: &mut VectorcraftApp, ui: &mut Ui, footer: RailFooter) { ]; let fallback = crate::panels::srgba(&app.session.last_solid); let mut clicked = None; - Row::new().wrap(true).show(ui, |ui, _| { + // A tight gap apart, as the drawing modes, so the three share one line in a one-column rail. + Row::new().gap(Gap::Tight).wrap(true).show(ui, |ui, _| { for (label, cmd, paint) in &chips { let shown = Mixed::Same(well_paint(paint, &|_| None)); let out = diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 6e2eeea570..243cde1c7f 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -306,6 +306,40 @@ fn the_paint_and_drawing_mode_buttons_fit_the_toolbar_width() { assert_eq!(app.session.draw_mode, vectorcraft_engine::DrawMode::Behind); } +/// In one column the Color, Gradient and None chips share one line, and a rule across the rail parts the controls under +/// the tools from the tools, which scroll above them in a short rail: it lies between the last tool and Fill and +/// Stroke. +#[test] +fn the_controls_under_the_tools_share_a_line_under_a_rule() { + let mut app = app_with(200, 200); + let ctx = reader(); + app.run("window.toolbarColumns", json!({ "double": false })).unwrap(); + let nodes = settled(&mut app, &ctx, 0.0, 2000.0); + let chips = ["Color (, or Shift+,)", "Gradient (. or Shift+.)", "None (/)"].map(|label| named_rect(&nodes, label)); + assert!(chips.iter().all(|r| (r.top() - chips[0].top()).abs() < 0.5), "one line: {chips:?}"); + let last = cells(&app, &nodes).into_iter().max_by(|a, b| a.bottom().total_cmp(&b.bottom())).expect("the rail shows tools"); + let proxy = named_rect(&nodes, "Fill and Stroke"); + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 2000.0))); + let out = crate::testing::app_frame(&mut app, &ctx, egui::RawInput { time: Some(1.0), screen_rect, ..Default::default() }); + let mut flat = Vec::new(); + let mut stack: Vec = out.shapes.into_iter().map(|clipped| clipped.shape).collect(); + while let Some(shape) = stack.pop() { + match shape { + egui::Shape::Vec(inner) => stack.extend(inner), + shape => flat.push(shape), + } + } + // A rule is a thin horizontal line or bar across most of the rail's width, between the tools and the controls. + let between = |y: f32| y > last.bottom() && y < proxy.top(); + let across = |left: f32, right: f32| right - left >= last.width() * 0.75 && left < last.right() && right > last.left(); + let ruled = flat.iter().any(|shape| match shape { + egui::Shape::LineSegment { points: [a, b], .. } => (a.y - b.y).abs() < 0.5 && between(a.y) && across(a.x.min(b.x), a.x.max(b.x)), + egui::Shape::Rect(r) => r.rect.height() <= 2.0 && between(r.rect.center().y) && across(r.rect.left(), r.rect.right()), + _ => false, + }); + assert!(ruled, "a rule lies between the last tool {last:?} and Fill and Stroke {proxy:?}"); +} + /// A screen reader reads the drawing-mode buttons' state as the rail shows it, in every mode: in two columns the /// current mode's button reads pressed and the other two not pressed; in one column the single button is named for the /// current mode and cycles the modes, so it reads as a plain button with no pressed state. @@ -473,3 +507,24 @@ fn a_tool_card_shows_what_the_tool_does_and_what_its_keys_do() { app.run("prefs.set", json!({"key": "showToolTips", "value": false})).unwrap(); assert!(!card::Cards::new(&app).has(&"selection".to_string()), "tool tips off: no card"); } + +#[test] +fn the_rail_builds_its_slots_only_when_its_tool_groups_change() { + let mut app = app_with(300, 300); + let ctx = reader(); + settled(&mut app, &ctx, 0.0, 800.0); + let built = || SLOT_BUILDS.with(|n| n.get()); + let before = built(); + frame(&mut app, &ctx, 0.2, vec![], 800.0); + frame(&mut app, &ctx, 0.25, vec![], 800.0); + assert_eq!(built() - before, 0, "frames with the same tool groups build no slots"); + let basic = rail_slots(&slots(&app)).len(); + app.run("window.toolbarAdvanced", json!({"advanced": true})).unwrap(); + let before = built(); + frame(&mut app, &ctx, 0.3, vec![], 800.0); + let advanced = slots(&app).len(); + assert_ne!(advanced, basic); + assert_eq!(built() - before, advanced, "the Advanced toolbar's slots are built once"); + let kept = app.dock_rt.rail_models.get(&Owner::Tools.panel()).map(|model| model.slots.len()); + assert_eq!(kept, Some(advanced), "the rail shows the Advanced toolbar's slots"); +} diff --git a/docs/mcp.md b/docs/mcp.md index b118517bb9..8c817c55c9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7548,13 +7548,14 @@ and `stroke.widthProfile.reset` removes every saved one. `stroke.set {profile}` ## Arrowheads -`stroke.set {startArrow, endArrow}` takes any of 41 generated heads by name (the params doc lists them; `null` for -none): arrows (`Arrow`, `LineArrow`, `Barbed`, `Concave`, `DoubleArrow`, `HalfArrowLeft`/`Right`, `Chevron`, `Feather`, -`Swallowtail`…), filled and open shapes (`Triangle`, `Circle`, `Oval`, `Target`, `Tag`, `Diamond`, `Hexagon`, `Star`, -the `…Open` rings…) and marks (`Bar`, `DoubleBar`, `DotOnBar`, `Slash`, `DoubleSlash`, `Bracket`, `Fork`, `Cross`, -`Plus`). Each head fits a box about four times its weight long and wide. A head's weight is the stroke weight scaled by -`arrowScale`, at least 0.25 pt. `LineArrow` has two arms of the head's weight (the line's weight at 100 % for lines of -0.25 pt or more) at right angles and spreads twice as wide. +`stroke.set {startArrow, endArrow}` takes any of 42 generated heads by name (the params doc lists them; `null` for +none): arrows (`Arrow`, `NotchedArrow`, `LineArrow`, `Barbed`, `Concave`, `DoubleArrow`, `HalfArrowLeft`, `HalfArrowRight`, +`Chevron`, `Feather`, `Swallowtail`…), filled and open shapes (`Triangle`, `Circle`, `Oval`, `Target`, `Tag`, +`Diamond`, `Hexagon`, `Star`, the `…Open` rings…) and marks (`Bar`, `DoubleBar`, `DotOnBar`, `Slash`, `DoubleSlash`, +`Bracket`, `Fork`, `Cross`, `Plus`). Each head fits a box about four times its weight long and wide. A head's weight +is the stroke weight scaled by `arrowScale`, at least 0.25 pt. `LineArrow` has two arms of the head's weight (the +line's weight at 100 % for lines of 0.25 pt or more) at right angles and spreads twice as wide. `NotchedArrow` is +slender (2.4 weights across at its barbs), its sides bend in halfway back, and it has a V-shaped notch in its back. Custom arrowheads come from the arrowheads file, `Arrowheads.vectorcraft` next to the preferences (none on the web or in runs with `VECTORCRAFT_NO_PREFS`). `stroke.arrowheads.edit` (Stroke panel menu › Edit Arrowheads…) opens it, and @@ -7902,7 +7903,9 @@ Selected End Points) joins the ends again; `path.join {ids: [a, b], ends: ["last (Average & Join, Cmd+Alt+Shift+J) moves two ends to their midpoint and joins them there, the joined anchor a corner or a smooth point, in one undo step: the two direct-selected anchors when they are open path ends, else the nearest ends of the two open paths in `ids` or the selection (both ends of one, closing it); anything else is refused. `path.convertAnchor {id, subpath?, anchor, to, x?, y?}` and -`path.split {id, subpath?, anchor}` do the same to one anchor (the Anchor Point and Scissors tools); `path.split`, +`path.split {id, subpath?, anchor}` do the same to one anchor (the Anchor Point and Scissors tools). With the Anchor Point +tool, a `pointer_gesture` that sets `mods.shift` on `down` moves the anchor; one that leaves Shift off on `down` and sets +`mods.shift` on later `drag` events pulls out handles at 45° steps round the anchor (General › Constrain Angle). `path.split`, at an anchor or at `segment` and `t`, leaves the first anchor of the piece after the cut selected alone, and a Direct Selection press on two anchors on top of each other takes the selected one. The paths that `path.cutAtAnchors` and `path.split` make keep the source path's fill and stroke settings (weight, paint, caps, joins, dashes, width profile, @@ -16305,6 +16308,10 @@ Commands: at right angles to the bisector of the angle its neighbours make at it, each `ratio` (0.1 to 0.5, 0.3905 by default: the ratio that makes a square's corners a circle) × the nearer neighbour's distance long; an open end aims its handle at its neighbour's. Equalize gives both handles their average length and makes a missing one opposite the other. + In the panel, an edit of X, Y or a handle's Length or Angle runs `addon.pathtools.setAnchor` as it is typed and is + one undo step; canceling it restores the anchor and leaves no undo step. While an Angle edit runs, the field shows + the handle's angle in the typed value's turn (`200` stays `200` rather than `-160`). Canceling a Points per segment + edit restores the count Add Points uses. - `addon.pathtools.removeKeepShape {}` removes the direct-selected anchors, refitting the handles beside each. - `addon.pathtools.addPoints {count?}` splits each selected segment (between two selected anchors, or every segment of a path selected whole) into `count + 1` (1 to 100) pieces of equal length. @@ -17282,7 +17289,7 @@ the range or one that is not a number. One undo step, none when nothing changes. Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, kind `command`) on the angle that the selected lines it can change fold at (90° when they differ), shown with every decimal place it has. While the selection holds no such line, `ui.menuDialog` fails with the reason the command gives. While the selection -holds such lines, the Fold Lines panel shows a Fold Angle field with that angle, empty when they differ. Typing an angle there sets it, and the Reset button beside it takes their own angles away. +holds such lines, the Fold Lines panel shows a Fold Angle field with that angle, empty when they differ. Typing an angle there sets it as it is typed, as one undo step; canceling the edit restores the lines' angles and leaves no undo step. The Reset button beside it takes their own angles away. ```json {"name":"run_command","arguments":{"command":"addon.packaging.setFoldAngle","params":{"angle":135}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c8dfff097..e16cc2a719 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1619,7 +1619,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Group Selection (#2441):** a click picks one path of a compound path (its outline within the pick tolerance, else the innermost path whose area holds the click: the outer shape or a hole), Shift-click adds another, and a click on a selected path adds the compound path, as a click on a group member climbs to its group. A path selected this way moves, rotates and scales on its own; paint still goes to the compound path. With Direct Selection, an Alt-click on a path selected whole adds its group, and each further Alt-click adds the next group up, as Group Selection's clicks do; the climb stops below the layer and its sublayers and at the isolated object. An Alt-drag still copies the selection, and Alt+Shift-click on a segment or the fill still adds or removes the path. Public references: [Select objects](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copies). With Alt held at the press, a Direct Selection marquee is Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), not the anchors inside it, and the Group Selection pointer stays until the release (#4890; test `an_alt_marquee_selects_the_paths_it_touches_whole`). - With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). + With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). Shift pressed once a drag from an anchor (or a spine point) is under way keeps the handles it pulls out at 45° steps round the anchor from the Constrain Angle, as the Pen does when it pulls out handles ([Pen, Curvature and Pencil help page](https://helpx.adobe.com/illustrator/using/drawing-pen-curvature-or-pencil.html)), and releasing Shift frees them. A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it with Direct Selection for the Corners dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)) or with the Selection tool for the Transform panel (a double-click on a selected live shape's corner widget shows the Transform panel, [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html); which tool gives which is VectorCraft's own rule), and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. With the pointer on a Direct Selection corner widget or close to it, the canvas marks the cut of that widget's corner with a thicker line (#1232). The help page describes this marking of a widget's corner while the pointer is on the widget or close to it ([Live Corners help page, archived](https://web.archive.org/web/2016id_/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, the mark also shows with the Selection tool and the shape tools on the widgets they show, it is a 2 px line of the layer color within 5 px of the widget, a square corner gets none, and none is drawn while a mouse button is down. Tests: `corners::tests::a_widget_under_the_pointer_gives_its_corners_cut`, `corners::tests::a_square_corner_gives_no_cut_and_a_plain_paths_corner_gives_its_own`, `corners::tests::a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none`, `canvas::widgets::tests::hovering_a_corner_widget_highlights_its_corner`. @@ -2207,7 +2207,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Gradient panel's Presets menu applies the chosen preset to the fill or stroke behind the proxy in front, as the panel's other controls do. The help page describes a Fill or Stroke control on the Gradient panel that toggles whether the fill or the stroke is being edited ([Gradient panel options](https://web.archive.org/web/20251006210616/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/gradient-tool-and-panel.html)). As VectorCraft's own rule, an active Appearance panel row takes the preset only when it is a fill row and the Fill proxy is in front, or a stroke row and the Stroke proxy is in front (`panels::gradient` tests `the_presets_menu_applies_to_the_stroke_in_front_over_an_active_fill_row`, `the_presets_menu_applies_to_the_fill_in_front_over_an_active_stroke_row` and `the_presets_menu_applies_to_the_active_row_of_the_kind_in_front`). In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with each end's own span slope and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined until the line between samples stays within the outline tolerance, and reusing a segment's own flattened points only where they already follow the curve) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt) rather than one cubic per flatten step, so a profiled outline draws the same shape as a uniform one and exports stay close to its path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. + - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-two more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421; and Notched Arrow: slender and filled, its sides bending in halfway back, with a V-shaped notch in its back, #8142), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with each end's own span slope and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined until the line between samples stays within the outline tolerance, and reusing a segment's own flattened points only where they already follow the curve) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt) rather than one cubic per flatten step, so a profiled outline draws the same shape as a uniform one and exports stay close to its path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: a check of pen pressure on a Mac with a tablet, and tilt, bearing and rotation on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). @@ -2253,7 +2253,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Fill and stroke paint (Fill, Stroke, None, Apply Last Color and Apply Last Gradient, also on characters selected with the Type tool), the Stroke panel's options, gradient and freeform point edits, Swap Fill and Stroke, Default Fill and Stroke, the Eyedropper, and the Appearance panel's item edits, Clear Appearance, Reduce to Basic Appearance, Remove Item, item reordering and Move Appearance record no undo step when they change nothing. The Appearance panel's row edits (`appearance.setItem`), Duplicate Item (`appearance.duplicateItem`) and fill and stroke edits aimed at a row (`item`) look up which objects had their shown row written in a set, so that step takes time in step with the number of objects. With 20,000 squares, each with one fill and one stroke row and each command given every square's id, that step takes 0.4 ms of thread CPU time on Linux instead of 57 to 63 ms, and the whole `appearance.setItem` command takes 96 ms instead of 158 ms; at 2,000 objects the difference is about 2 ms (`crates/engine/examples/appearance_rows_bench.rs`; `cmd::graph::tests::row_edits_on_several_labels_keep_the_last_written_shown_row`). A Stroke panel edit (`stroke.set` with no `item`) checks each object it collects against a set of the objects already listed, so collecting its targets takes time in step with the number of objects, and the list and its order are the same as before. With 20,000 paths in one group, collecting the targets takes 0.66 ms of thread CPU time on Linux, against 55 ms when each object is looked up in the list, and the whole command takes 60 ms (`crates/engine/examples/stroke_targets_bench.rs`; `cmd::stroke::tests::stroke_targets_match_the_listed_merge`). - A Layers panel target circle dropped on the panel's Delete Selection button reduces that layer, group or object to basic appearance (`appearance.reduceToBasic`) in one undo step and deletes nothing, as the [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) help page describes for that drag. Which fill and stroke stay (the topmost visible ones), that a layer or group keeps only the rows it had, and that the object's opacity and blend mode stay are VectorCraft's own rules (`panels::layers` test `dropping_a_target_circle_on_the_trash_reduces_it_to_basic_appearance`). + A Layers panel target circle dropped on the panel's Delete Selection button reduces that layer, group or object to basic appearance (`appearance.reduceToBasic`) in one undo step and deletes nothing, as the [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) help page describes for that drag. Which fill and stroke stay (the topmost visible ones), that a layer or group keeps only the rows it had, and that the object's opacity and blend mode stay are VectorCraft's own rules (`panels::layers` tests `delete_selection_reduces_a_dropped_appearance_to_basic` and `delete_selection_refuses_an_appearance_from_another_document`). The Add New Effect popup (Appearance panel, Properties), the Appearance panel's swatch picker, the Gradient panel's gradient swatches menu and the Image Trace button's list of presets stop at the bottom of a short window, and the mouse wheel or the scroll bar reaches their last rows. A list that fits does not scroll (`a_long_swatch_picker_scrolls_inside_a_short_window`). An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box, or the outline of the image's opaque area or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds then measures an image by its frame. Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index feee137ed9..4c0eaa6d5a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -231,7 +231,7 @@ tools, never checked side by side) isn't captured row by row. | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | | Blend Replace Spine, move and Undo redraw (#5179) | CPU regression-tested | Renderer damage bounds include keys and steps rotated along a curved spine. Both original straight and curved CPU regressions pass, checking full-frame agreement and that every changed pixel lies inside the advertised redraw area. | | Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away | -| Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles; Alt held while dragging a handle links it with the opposite handle and makes the anchor smooth, on a blend's spine too | +| Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles; Shift pressed once a drag from an anchor is under way keeps the handles it pulls out at 45° steps round the anchor, on a blend's spine too; Alt held while dragging a handle links it with the opposite handle and makes the anchor smooth, on a blend's spine too | | Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor (a short level line) while Shift or Alt is held before the press, and a path-continuation cursor (a short rising line) over an end of a selected open path, where the stroke continues the path, freehand or straight, and while a continuing stroke ends near an open end of another selected path it connects to; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the way round a closed path that leaves the bigger shape, so a stroke across a shape carves off its smaller part and an arch over a thin shape's side keeps the shape; on an open path the way the stroke runs along it at each end decides: where it starts it replaces the part it runs along, where it lands it joins the part it runs into, so it replaces the part between, closes the path round it without the closing cursor, or ends where the pen is lifted; #2850), the stroke's ends bent smoothly onto the path; a stroke lifted farther than the distance takes the path with it (a closed path opens where the stroke starts, an open one is cut there and drops the part the stroke heads along), one back to its starting point adds a loop, and a selected compound path's member paths are redrawn too (#3793); while such a stroke is drawn the preview shows the stroke as drawn and the path changes at the release; with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, or a stroke continuing a selected path (a straight line too) to within it of that path's other end, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path | | Drop Shadow, Outer Glow and Inner Glow: Opacity, the offsets, Blur and Darkness have spinner arrows that step by one (a unit for distances), repeat when held and stop at the fields' ends (#5367, #5368) | done | dialogs::effect test drop_shadow_and_outer_glow_fields_have_spinner_arrows; other effect dialogs' number fields still have none | | Effect dialogs' colour fields: a swatch beside the hex follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills it and Cancel comes back unchanged (#5365) | done | dialogs::effect tests outer_glow_colour_swatch_opens_the_color_picker and drop_shadow_colour_swatch_opens_the_color_picker (Drop Shadow's Color, #5364); the picker previews nothing itself, the effect dialog previews the returned colour | @@ -572,8 +572,10 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Smart Pen add-on (VectorCraft addition): Object › Plug-ins › Smart Pen selects the Smart Pen Tool (also in the Pen tool's group in both shipped toolbars, after the Quick Pen; the All Tools drawer lists it under Draw; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut), and opens the Smart Pen panel (next segment straight or curved; Remove Points Keep Shape, Make Smooth, Make Corner, Retract Handles, Close or Join). The tool draws (click: straight or curved segment, a curve after a straight one tangent; drag: smooth anchor, Alt breaks the handle, Shift 45°, Space moves it; Tab switches a segment; rubber band; close, join, continue) and edits without switching tools (click selects a point, drag moves it, Alt-click removes it keeping the shape, Shift+Alt-click deletes it, double-click toggles smooth/corner; handle drags with Shift and Alt; segment drags reshape, Alt-click adds a point) | done | `addon.pen.*`, `crates/tools/src/addons/smart_pen.rs`, `crates/ui-egui/src/addons/pen.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its nine tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path, Shared Edge Merge Tool, Tangent Circle Tool, Trim at Crossings Tool), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped (except Trim at Crossings, which both shipped toolbars and the drawer show in the Scissors tool's group), opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; the Shared Edge Merge Tool shows, over two paths touching at two coincident anchors, the two stretches and the edge merging them, a click merges them (half way; Shift the upper path, Alt the lower), and near anchors meet or an anchor one path lacks is added to match (Shift+Alt asks for this inside a stretch), with a Shared Edges section in the Anchor Inspector (brush diameter, coincidence 0 to 3 pt, Keep Shared Points Together, which takes coincident anchors along with the add-on's own anchor moves); a double-click on the brush, Extend Path or Tangent Circle tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | +| Anchor Inspector fields restore canceled edits | done | Canceling an X, Y, handle Length or Angle edit restores the anchor, with no undo step, and canceling a Points per segment edit restores its count. An accepted anchor edit is one undo step. | | Corner and Shared Edge Merge options restore canceled edits | done | Canceling a control gesture restores its opening draft values. Confirmed changes remain available to the tool. | | Parametric Shape panel restores canceled edits | done | Canceling a field edit or Shape menu choice restores the selected shape, with no undo step, or the tool's next shape. An accepted edit of a selected shape is one undo step. With no shape selected, a highlighted Shape entry applies only once chosen. | +| Fold Lines panel restores a canceled Fold Angle edit | done | Canceling a Fold Angle edit restores the selected lines' angles, with no undo step. An accepted edit is one undo step. | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index d6edc4c1ce..d8c86d36a2 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -192,7 +192,7 @@ def reviewed_manual_actors(caller_source, policy): def caller_pin(name): - return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", + return re.findall(r"(?m)^ tooling-revision: (\S+)$", (ROOT / ".github/workflows" / name).read_text())[0] @@ -359,7 +359,7 @@ class NightlyTrustAnchors(unittest.TestCase): self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") pins.update(uses) self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") - self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main") class NightlyEnabledCallers(unittest.TestCase): @@ -777,7 +777,7 @@ def trust_closure_problems(workflows): if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"): if name == "nightly-sign.yml": signer_calls += 1 - if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref): + if name != "nightly-sign.yml" or ref != "main": problems.append(name + " calls nightly-release.yml@" + ref) if workflow.lower() in ("release.yml", "release.yaml"): stable_callers.add(name) @@ -827,7 +827,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase): "a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, "uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"}, "another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, - "a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])}, + "a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")}, "a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"}, "a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")}, }