diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index ebd4811959..784c8d981f 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -1582,7 +1582,7 @@ pub fn blend_expand(keys: &[Arc], spec: &BlendSpec) -> Vec { // Even position of the step, then where the easing puts its shape and its colours. let u = j as f64 / (n + 1) as f64; // Easing needs a spine: a blend made without one keeps its steps evenly spaced. - let eased = rail.is_some() && !spec.no_spine; + let eased = rail.is_some() && spec.eases_along_spine(); let (t, tc) = (if eased { spec.ease.apply(u) } else { u }, spec.color_position(u)); let mut s = lerp.at_eased(t, tc); if let Some(r) = &rail { diff --git a/crates/doc/src/live/blend_spec.rs b/crates/doc/src/live/blend_spec.rs index 56405e0d18..047e1ad7b5 100644 --- a/crates/doc/src/live/blend_spec.rs +++ b/crates/doc/src/live/blend_spec.rs @@ -119,6 +119,12 @@ impl BlendSpec { pub fn start(&self, i: usize) -> Option { self.starts.get(i).copied().flatten().map(|a| a as usize) } + + /// Whether [`Self::ease`] moves the steps: the blend has a spine ([`Self::no_spine`] is off) + /// and a replaced spine or Align to Path, the cases where the steps are placed along it. + pub fn eases_along_spine(&self) -> bool { + !self.no_spine && (self.spine.is_some() || self.orientation == BlendOrientation::AlignToPath) + } } /// The Blend panel's Create Spine setting: whether a new blend gets a spine. diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index d47e81befd..a208d527fa 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -389,6 +389,39 @@ pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result { }) } +pub(super) fn blend_set_easing(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.blend.setEasing"; + let id = match crate::cmd::object_param(p, "id", C)? { + Some(id) => id, + None => *selected_of(s, is_blend).first().ok_or_else(|| bad(C, "select a blend or give `id`"))?, + }; + let doc = &s.doc()?.doc; + let Some(NodeKind::Blend { children, spec }) = doc.node(id).map(|n| &n.kind) else { return Err(bad(C, "not a blend")) }; + if !doc.is_editable(id) { + return Err(bad(C, "the object is hidden or locked")); + } + let ease = ease_param(p, C, spec.ease)?; + let color_shift = percent_param(p, C, "colorShift", spec.color_shift, -100.0)?; + // Easing moves the steps along a spine, so it needs one with a length to run along. + let easing = ["easingType", "ramp"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null())); + let spined = spec.eases_along_spine() + && live::blend_spine(children, spec).and_then(|(path, _)| Spine::new(&path)).is_some_and(|sp| sp.length().is_finite() && sp.length() > 0.0); + if easing && !spined { + return Err(bad(C, "the blend has no spine")); + } + let changed = ease != spec.ease || color_shift != spec.color_shift; + if changed { + s.edit("Blend Options", |d, _| { + if let Some(NodeKind::Blend { spec, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + spec.ease = ease; + spec.color_shift = color_shift; + } + Ok(()) + })?; + } + Ok(json!({ "id": id.0, "easingType": ease.kind.id(), "ramp": ease.ramp * 100.0, "colorShift": color_shift, "changed": changed })) +} + /// Spacing and orientation as `object.blend.options` takes them; the step count and distance /// not in use show their defaults. fn blend_options_json(spacing: BlendSpacing, orientation: BlendOrientation) -> Value { diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 1013c606c5..8e325c69be 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -1,6 +1,6 @@ use super::blend::{ blend_create_spine, blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine, - blend_reverse_stack, spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment, + blend_reverse_stack, blend_set_easing, spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment, }; use super::common::{has_blend, has_envelope, has_mesh}; use super::envelope::{ @@ -49,6 +49,15 @@ pub fn specs() -> Vec { always, blend_create_spine ), + cmd!( + "object.blend.setEasing", + "Blend Easing", + [], + None, + "{id? (default: the first selected blend), easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100)} set one blend's easing and color shift, as the blend widgets on the canvas do; omitted ones keep their value. easingType and ramp need a blend whose steps follow a spine (a replaced or edited spine, or Align to Path); a blend made without a spine takes them once Replace Spine has given it one; out of range, a hidden or locked blend and a blend with no spine are errors. A value that changes nothing records no undo step → {id, easingType, ramp, colorShift, changed}", + has_doc, + blend_set_easing + ), cmd!( "object.blend.expand", "Expand", diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 94f865e224..b411820971 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -242,6 +242,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.blend.replaceSpine", "object.blend.reverseFrontToBack", "object.blend.reverseSpine", + "object.blend.setEasing", "object.blend.spine.addAnchor", "object.blend.spine.convertAnchor", "object.blend.spine.moveAnchor", diff --git a/crates/engine/src/tests/blendopts.rs b/crates/engine/src/tests/blendopts.rs index 4b391c5714..93f531d1e8 100644 --- a/crates/engine/src/tests/blendopts.rs +++ b/crates/engine/src/tests/blendopts.rs @@ -405,6 +405,143 @@ fn a_document_with_bad_blend_easing_numbers_opens_clamped_while_commands_refuse( } } +/// `object.blend.setEasing` sets one blend's easing and color shift, records no undo step when +/// nothing changes, and refuses bad values, a blend whose steps follow no spine (easing only), a +/// hidden or locked blend and a target that is not a blend, leaving the blend and the history alone. +#[test] +fn set_easing_edits_one_blend_and_refuses_what_it_cannot_set() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0)); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.blend.make", &json!({"steps": 3})).unwrap()); + let depth = |s: &Session| s.doc().unwrap().history.undo.len(); + let d0 = depth(&s); + // Align to Page along the straight lines between the keys: the steps follow no spine. + for bad in [json!({"ramp": 30}), json!({"easingType": "easeOut"})] { + let e = s.execute("object.blend.setEasing", &bad).unwrap_err().to_string(); + assert!(e.contains("the blend has no spine"), "{e}"); + } + assert_eq!(depth(&s), d0); + let r = s.execute("object.blend.setEasing", &json!({"colorShift": 25})).unwrap(); + assert_eq!(r, json!({"id": g.0, "easingType": "easeIn", "ramp": 0.0, "colorShift": 25.0, "changed": true})); + assert_eq!((spec(&s, g).1.color_shift, depth(&s)), (25.0, d0 + 1)); + let r = s.execute("object.blend.setEasing", &json!({"colorShift": 25})).unwrap(); + assert_eq!((&r["changed"], depth(&s)), (&json!(false), d0 + 1), "an unchanged value records no undo step"); + // Along the spine each of the four types keeps its kind through a ramp change and its undo. + s.execute("object.blend.options", &json!({"orientation": "path"})).unwrap(); + for kind in ["easeIn", "easeOut", "easeInOut", "easeOutIn"] { + s.execute("object.blend.setEasing", &json!({"easingType": kind, "ramp": 60})).unwrap(); + let r = s.execute("object.blend.setEasing", &json!({"ramp": 20})).unwrap(); + assert_eq!((&r["easingType"], &r["ramp"], &r["colorShift"]), (&json!(kind), &json!(20.0), &json!(25.0))); + s.execute("edit.undo", &json!({})).unwrap(); + let sp = spec(&s, g).1; + assert_eq!((sp.ease.kind.id(), sp.ease.ramp, sp.color_shift), (kind, 0.6, 25.0)); + } + let before = spec(&s, g).1; + let d1 = depth(&s); + for bad in [ + json!({"ramp": 101}), + json!({"ramp": -1}), + json!({"ramp": "x"}), + json!({"colorShift": 1e308}), + json!({"colorShift": -101}), + json!({"easingType": "sideways"}), + json!({"id": "abc", "ramp": 10}), + json!({"id": a.0, "ramp": 10}), + ] { + assert!(s.execute("object.blend.setEasing", &bad).is_err(), "{bad}"); + assert_eq!((spec(&s, g).1, depth(&s)), (before.clone(), d1), "{bad}"); + } + // An explicit id works with nothing selected; nothing selected and no id is an error. + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("object.blend.setEasing", &json!({"ramp": 10})).is_err()); + s.execute("object.blend.setEasing", &json!({"id": g.0, "ramp": 10})).unwrap(); + assert_eq!(spec(&s, g).1.ease.ramp, 0.1); + // A hidden or locked blend is refused. + for hide in [true, false] { + s.edit("state", |d, _| { + let n = d.node_mut(g).unwrap(); + (n.visible, n.locked) = (!hide, !hide); + Ok(()) + }) + .unwrap(); + let (before, d2) = (spec(&s, g).1, depth(&s)); + let e = s.execute("object.blend.setEasing", &json!({"id": g.0, "colorShift": 5})).unwrap_err().to_string(); + assert!(e.contains("the object is hidden or locked"), "{e}"); + assert_eq!((spec(&s, g).1, depth(&s)), (before, d2)); + } + // A blend made without a spine takes no easing, Align to Path included; its color shift still + // changes. + let (c, d) = (rect(&mut s, 0.0, 300.0, 40.0), rect(&mut s, 200.0, 300.0, 40.0)); + sel(&mut s, &[c, d]); + let n = id_of(&s.execute("object.blend.make", &json!({"createSpine": "never", "orientation": "path"})).unwrap()); + let d3 = depth(&s); + let e = s.execute("object.blend.setEasing", &json!({"id": n.0, "ramp": 30})).unwrap_err().to_string(); + assert!(e.contains("the blend has no spine"), "{e}"); + assert_eq!(depth(&s), d3); + s.execute("object.blend.setEasing", &json!({"id": n.0, "colorShift": 10})).unwrap(); + assert_eq!(spec(&s, n).1.color_shift, 10.0); + // Replace Spine gives it a spine, and it takes easing from then on. + let path = id_of(&s.execute("path.create", &json!({"d": "M0 320 L200 320"})).unwrap()); + sel(&mut s, &[n, path]); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + let r = s.execute("object.blend.setEasing", &json!({"id": n.0, "easingType": "easeOut", "ramp": 30})).unwrap(); + assert_eq!((&r["easingType"], &r["ramp"], &r["changed"]), (&json!("easeOut"), &json!(30.0), &json!(true))); +} + +/// Dragging a blend widget with the Selection tool or the Blend tool is one undo step; a click, a +/// drag that ends at its starting value and a drag canceled with Escape record none, and Escape +/// puts the value back. +#[test] +fn dragging_a_blend_widget_is_one_undo_step_and_a_click_or_escape_none() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0)); + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.blend.make", &json!({"steps": 3, "orientation": "path", "easingType": "easeOut"})).unwrap()); + let v = ViewInfo::default(); + let depth = |s: &Session| s.doc().unwrap().history.undo.len(); + let ptr = |s: &mut Session, kind: PointerKind, x: f64, y: f64| { + s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap(); + }; + s.select_tool("selection", v).unwrap(); + sel(&mut s, &[g]); + let d0 = depth(&s); + // The Easing widget sits 16 px below the spine's halfway point (120, 20). + ptr(&mut s, PointerKind::Down, 120.0, 36.0); + ptr(&mut s, PointerKind::Drag, 135.0, 36.0); + ptr(&mut s, PointerKind::Drag, 150.0, 36.0); + ptr(&mut s, PointerKind::Up, 150.0, 36.0); + let sp = spec(&s, g).1; + assert_eq!((sp.ease.kind.id(), sp.ease.ramp, sp.color_shift, depth(&s)), ("easeOut", 0.3, 0.0, d0 + 1)); + assert_eq!(s.doc().unwrap().selection.objects, vec![g], "the blend stays selected"); + // A click, and a drag back to where it started. + ptr(&mut s, PointerKind::Down, 120.0, 36.0); + ptr(&mut s, PointerKind::Up, 120.0, 36.0); + ptr(&mut s, PointerKind::Down, 120.0, 36.0); + ptr(&mut s, PointerKind::Drag, 160.0, 36.0); + ptr(&mut s, PointerKind::Drag, 120.0, 36.0); + ptr(&mut s, PointerKind::Up, 120.0, 36.0); + assert_eq!((spec(&s, g).1.ease.ramp, depth(&s)), (0.3, d0 + 1)); + // Escape during a drag puts the value back. + ptr(&mut s, PointerKind::Down, 120.0, 36.0); + ptr(&mut s, PointerKind::Drag, 170.0, 36.0); + assert_eq!(spec(&s, g).1.ease.ramp, 0.8, "the drag previews"); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + ptr(&mut s, PointerKind::Up, 170.0, 36.0); + assert_eq!((spec(&s, g).1.ease.ramp, depth(&s)), (0.3, d0 + 1)); + // The Blend tool drags the Appearance widget, 16 px above: the color shift alone. + s.select_tool("blend", v).unwrap(); + sel(&mut s, &[g]); + ptr(&mut s, PointerKind::Down, 120.0, 4.0); + ptr(&mut s, PointerKind::Drag, 100.0, 4.0); + ptr(&mut s, PointerKind::Up, 100.0, 4.0); + let sp = spec(&s, g).1; + assert_eq!((sp.ease.kind.id(), sp.ease.ramp, sp.color_shift, depth(&s)), ("easeOut", 0.3, -20.0, d0 + 2)); + assert_eq!(s.doc().unwrap().selection.objects, vec![g]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(spec(&s, g).1.color_shift, 0.0); +} + #[test] fn native_blend_easing_values_clamp_and_non_finite_become_default() { for (bad, ramp, shift) in [ diff --git a/crates/tools/src/blendwidget.rs b/crates/tools/src/blendwidget.rs new file mode 100644 index 0000000000..af1194d78b --- /dev/null +++ b/crates/tools/src/blendwidget.rs @@ -0,0 +1,568 @@ +//! Blend widgets: two handles beside the spine of one selected blend, at the point halfway along +//! the spine, one 16 screen pixels above it and one 16 pixels below it. Where other artwork crowds +//! that spot (the boxes of three or more other visible objects hold it), a widget moves further +//! out in 16-pixel steps, up to 144 pixels, to the first spot that is not crowded, and the line +//! the canvas draws from the halfway point to the widget grows with it. The upper one sets the +//! blend's color shift (`colorShift`, -100 to 100) and the lower one its easing strength (`ramp`, +//! 0 to 100). The lower one shows only when the steps follow a spine (a replaced or edited spine, +//! or Align to Path), where easing moves them; a blend made without a spine shows neither. A drag along the spine's direction at the press +//! changes the value by one per screen pixel, starting from the value at the press, and the arrow +//! keys during the drag change it by one (Shift: by ten); Escape or a switch to another tool +//! cancels the drag and puts the value back. Each drag previews +//! `object.blend.setEasing` and is one undo step, or none when the value ends where it started; a +//! click changes nothing. The Selection and Blend tools hit the widgets and the canvas draws them +//! from the same geometry. + +use serde_json::json; +use vectorcraft_doc::live::{Spine, blend_spine}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection}; +use vectorcraft_geom::{Point, Rect, Vec2}; + +use crate::{Action, Overlay, PointerEvent, ToolContext}; + +/// How far (screen px) a widget's center sits above or below the spine's halfway point. +pub const OFFSET_PX: f64 = 16.0; +/// The widget's radius (screen px), as the canvas draws it. +pub const RADIUS_PX: f32 = 4.0; +/// How near (screen px) the pointer must be to hit a widget. +const HIT_PX: f64 = 5.0; +/// Points of value per screen pixel of drag along the spine. +const PER_PX: f64 = 1.0; +/// The undo step a drag records, as the Blend panel's changes do. +const LABEL: &str = "Blend Options"; +/// How many [`OFFSET_PX`] steps further out a widget may move from a crowded spot. +const CLEAR_STEPS: usize = 8; +/// A spot is crowded when the boxes of this many other visible objects hold it. +const CROWDED: usize = 3; +/// The most nodes looked at to find what crowds the widgets, topmost first. +const LOOK: usize = 1024; + +/// What a blend widget sets. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BlendControl { + /// The upper widget: the color shift. + Appearance, + /// The lower widget: the easing strength. + Easing, +} + +impl BlendControl { + /// The `object.blend.setEasing` param this widget sets. + fn key(self) -> &'static str { + match self { + Self::Appearance => "colorShift", + Self::Easing => "ramp", + } + } + + /// The values the param takes. + fn range(self) -> (f64, f64) { + match self { + Self::Appearance => (-100.0, 100.0), + Self::Easing => (0.0, 100.0), + } + } +} + +/// One widget of the selected blend. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BlendWidget { + pub id: NodeId, + pub control: BlendControl, + /// The spine's halfway point, in the document. + pub on: Point, + /// The widget's center in the document: [`OFFSET_PX`] from `on`, or further out where other + /// artwork crowds that spot. + pub at: Point, + /// The spine's direction at `on` (unit length, in the document). + pub along: Vec2, + /// The value the widget sets, as it is now. + pub value: f64, +} + +impl BlendWidget { + /// The widgets of the selection at `zoom` (screen px per document point), with `up` the + /// document direction of the screen's up: the Appearance widget, then the Easing widget. Empty + /// unless the selection is one whole blend, visible and unlocked, with two or more keys and a + /// spine of some length, and no anchors are selected. Each widget sits at the first spot out + /// from the spine, in [`OFFSET_PX`] steps, that the boxes of fewer than three other visible + /// objects hold, at most nine steps out; where every spot is crowded it stays at the first. + pub fn of(doc: &Document, selection: &Selection, zoom: f64, up: Vec2) -> Vec { + let up_len = up.hypot(); + let usable = |v: f64| v.is_finite() && v > 0.0; + if !selection.anchors.is_empty() || selection.symbol_part.is_some() || !usable(zoom) || !usable(up_len) { + return vec![]; + } + let [id] = selection.objects.as_slice() else { return vec![] }; + let Some(NodeKind::Blend { children, spec }) = doc.node(*id).map(|n| &n.kind) else { return vec![] }; + if children.len() < 2 || !doc.is_editable(*id) { + return vec![]; + } + let Some(spine) = blend_spine(children, spec).and_then(|(path, _)| Spine::new(&path)) else { return vec![] }; + if !usable(spine.length()) { + return vec![]; + } + let (on, angle) = spine.at(0.5); + let along = Vec2::new(angle.cos(), angle.sin()); + if !(on.x.is_finite() && on.y.is_finite() && along.x.is_finite() && along.y.is_finite()) { + return vec![]; + } + let lift = up * (OFFSET_PX / zoom / up_len); + let reach = lift.hypot() * (CLEAR_STEPS + 1) as f64 + f64::from(RADIUS_PX) / zoom; + let boxes = boxes_near(doc, *id, Rect::new(on.x - reach, on.y - reach, on.x + reach, on.y + reach)); + let clear = |side: Vec2| { + let crowded = |p: Point| boxes.iter().filter(|b| b.x0 <= p.x && p.x <= b.x1 && b.y0 <= p.y && p.y <= b.y1).count() >= CROWDED; + (1..=CLEAR_STEPS + 1).map(|k| on + side * k as f64).find(|p| !crowded(*p)).unwrap_or(on + side) + }; + let value = |v: f64, control: BlendControl| { + let (lo, hi) = control.range(); + if v.is_finite() { v.clamp(lo, hi) } else { 0.0 } + }; + let shift = value(spec.color_shift, BlendControl::Appearance); + let mut out = vec![Self { id: *id, control: BlendControl::Appearance, on, at: clear(lift), along, value: shift }]; + if spec.eases_along_spine() { + let ramp = value(spec.ease.ramp * 100.0, BlendControl::Easing); + out.push(Self { id: *id, control: BlendControl::Easing, on, at: clear(-lift), along, value: ramp }); + } + out + } + + /// The widgets the tool in `cx` can drag. + pub fn for_tool(cx: &ToolContext) -> Vec { + Self::of(cx.doc, cx.selection, cx.zoom, screen_up(cx)) + } + + /// The widget of `cx` nearest `p` within reach. + fn at_point(cx: &ToolContext, p: Point) -> Option { + let d = |w: &Self| w.at.distance(p); + Self::for_tool(cx).into_iter().filter(|w| d(w) <= cx.tol(HIT_PX)).min_by(|a, b| d(a).total_cmp(&d(b))) + } +} + +/// The document direction of the screen's up (the page's up without a window). +fn screen_up(cx: &ToolContext) -> Vec2 { + cx.screen.map(|s| -s.down).filter(|v| v.x.is_finite() && v.y.is_finite() && v.hypot() > 0.0).unwrap_or(Vec2::new(0.0, -1.0)) +} + +/// The geometric boxes of the visible objects other than blend `skip` that reach into `region`. +/// The walk goes into visible layers and groups without a clipping path, topmost first, and looks +/// at no more than [`LOOK`] nodes; any other object counts by its own box. +fn boxes_near(doc: &Document, skip: NodeId, region: Rect) -> Vec { + let reaches = |b: &Rect| b.x0 <= region.x1 && region.x0 <= b.x1 && b.y0 <= region.y1 && region.y0 <= b.y1; + // Each node is queued at most once, so `room` bounds both the queue and the walk; a container + // with more members than there is room for queues its topmost ones. + fn queue<'a>(nodes: &'a [std::sync::Arc], skip: NodeId, room: &mut usize) -> impl Iterator { + let take = nodes.len().min(*room); + *room -= take; + nodes.iter().skip(nodes.len() - take).filter(move |c| c.visible && c.id != skip).map(|c| &**c) + } + let mut room = LOOK; + let mut stack: Vec<&Node> = queue(&doc.layers, skip, &mut room).collect(); + let mut out = vec![]; + while let Some(n) = stack.pop() { + match &n.kind { + NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { + stack.extend(queue(children, skip, &mut room)); + } + _ => out.extend(n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()) && reaches(b))), + } + } + out +} + +/// Is `p` over a blend widget? +pub fn over_widget(cx: &ToolContext, p: Point) -> bool { + BlendWidget::at_point(cx, p).is_some() +} + +/// Dragging a blend widget: its value follows the pointer along the spine's direction at the +/// press. +#[derive(Clone, Debug)] +pub struct BlendWidgetDrag { + widget: BlendWidget, + start: Point, + /// The pointer's last position. + at: Point, + /// What the arrow keys added. + keys: f64, + began: bool, + value: f64, +} + +impl BlendWidgetDrag { + /// The drag has left the click: the value is changing. + pub fn adjusting(&self) -> bool { + self.began + } + + /// Start a drag when the press `ev` is on a blend widget of the selection. + pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { + let widget = BlendWidget::at_point(cx, ev.pos)?; + Some(Self { widget, start: ev.pos, at: ev.pos, keys: 0.0, began: false, value: widget.value }) + } + + /// The value at the press plus the pointer's move along the spine, before the keys' steps + /// and the range. + fn dragged(&self, cx: &ToolContext) -> f64 { + let moved = (self.at - self.start).dot(self.widget.along) * cx.zoom; + self.widget.value + if moved.is_finite() { (moved * PER_PX).round() } else { 0.0 } + } + + /// The value for the pointer at `self.at` and the keys pressed, within the range. + fn value_now(&self, cx: &ToolContext) -> f64 { + let (lo, hi) = self.widget.control.range(); + (self.dragged(cx) + self.keys).clamp(lo, hi) + } + + /// The actions that show the value now: the drag's start when it begins, then a preview. + fn preview(&mut self, cx: &ToolContext) -> Vec { + let mut out = vec![]; + if !self.began { + self.began = true; + out.push(Action::Begin(LABEL.into())); + } + self.value = self.value_now(cx); + let mut params = json!({ "id": self.widget.id.0 }); + params[self.widget.control.key()] = json!(self.value); + out.push(Action::Preview("object.blend.setEasing".into(), params)); + out + } + + pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + self.at = p; + if !self.began && p.distance(self.start) < cx.tol(3.0) { + return vec![]; + } + self.preview(cx) + } + + /// An arrow key during the drag: one point more (`more`) or less, ten with Shift. + pub fn step(&mut self, cx: &ToolContext, more: bool, big: bool) -> Vec { + let by = if big { 10.0 } else { 1.0 }; + // The step goes from the value shown, so past either end (by keys or by the drag) the way + // back starts at once. + let (lo, hi) = self.widget.control.range(); + let stepped = (self.value_now(cx) + if more { by } else { -by }).clamp(lo, hi); + self.keys = stepped - self.dragged(cx); + self.preview(cx) + } + + pub fn finish(self) -> Vec { + if self.began { vec![Action::Commit] } else { vec![] } + } + + /// The value next to the pointer. + pub fn overlays(&self, cx: &ToolContext) -> Vec { + if !self.began || !cx.measurement_labels { + return vec![]; + } + vec![Overlay::Measure { p: self.at, text: format!("{:.0}%", self.value) }] + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::select::SelectionTool; + use crate::testutil::*; + use crate::{Mods, PointerKind, Tool, ToolKey}; + use std::sync::Arc; + use vectorcraft_doc::live::{BlendEase, BlendEaseType, BlendOrientation, BlendSpec}; + use vectorcraft_doc::{Appearance, Node}; + use vectorcraft_geom::{PathData, Rect, SubPath, shapes}; + + const UP: Vec2 = Vec2::new(0.0, -1.0); + + fn square(d: &mut Document, x: f64, y: f64) -> Arc { + let id = d.alloc_id(); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), Appearance::default_art())) + } + + /// A blend of squares centered at `centers`, with `spec`, selected. + fn blend_doc(centers: &[(f64, f64)], spec: BlendSpec) -> (Document, NodeId, Selection) { + let mut d = Document::new(800.0, 800.0); + let l = d.layers[0].id; + let children = centers.iter().map(|(x, y)| square(&mut d, x - 10.0, y - 10.0)).collect(); + let id = d.alloc_id(); + d.insert(Some(l), 0, Node::new(id, NodeKind::Blend { children, spec: Box::new(spec) })).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, id, s) + } + + /// Steps along a spine (Align to Path), eased In Out at 40%, color shift -20. + fn eased() -> BlendSpec { + BlendSpec { + orientation: BlendOrientation::AlignToPath, + ease: BlendEase { kind: BlendEaseType::InOut, ramp: 0.4 }, + color_shift: -20.0, + ..Default::default() + } + } + + fn ev(kind: PointerKind, p: Point) -> PointerEvent { + PointerEvent::new(kind, p.x, p.y) + } + + fn near(a: Point, b: Point) -> bool { + a.distance(b) < 1e-9 + } + + #[test] + fn the_widgets_sit_above_and_below_the_spines_halfway_point() { + let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + let w = BlendWidget::of(&d, &s, 1.0, UP); + assert_eq!(w.iter().map(|w| w.control).collect::>(), [BlendControl::Appearance, BlendControl::Easing]); + assert!(w.iter().all(|w| w.id == id && near(w.on, Point::new(200.0, 200.0))), "{w:?}"); + assert!(near(w[0].at, Point::new(200.0, 184.0)) && near(w[1].at, Point::new(200.0, 216.0)), "{w:?}"); + assert_eq!((w[0].value, w[1].value), (-20.0, 40.0)); + // 16 screen pixels at any zoom, and above on the screen in a turned view. + assert!(near(BlendWidget::of(&d, &s, 4.0, UP)[0].at, Point::new(200.0, 196.0))); + let turned = BlendWidget::of(&d, &s, 1.0, Vec2::new(1.0, 0.0)); + assert!(near(turned[0].at, Point::new(216.0, 200.0)) && near(turned[1].at, Point::new(184.0, 200.0)), "{turned:?}"); + // Halfway along by length: three keys spaced unevenly. + let (d, _, s) = blend_doc(&[(0.0, 0.0), (100.0, 0.0), (100.0, 300.0)], eased()); + assert!(near(BlendWidget::of(&d, &s, 1.0, UP)[0].on, Point::new(100.0, 100.0))); + } + + /// Adds a filled rectangle from `(x0, y0)` to `(x1, y1)` on top of the first layer. + fn cover(d: &mut Document, x0: f64, y0: f64, x1: f64, y1: f64) -> NodeId { + let l = d.layers[0].id; + let id = d.alloc_id(); + let at = d.layers[0].children().map_or(0, |c| c.len()); + d.insert(Some(l), at, Node::path(id, shapes::rectangle(Rect::new(x0, y0, x1, y1)), Appearance::default_art())).unwrap(); + id + } + + #[test] + fn a_widget_moves_out_from_crowded_artwork_and_its_line_follows() { + let (mut d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + // Two objects under the Appearance widget's spot do not crowd it. + for _ in 0..2 { + cover(&mut d, 190.0, 175.0, 210.0, 195.0); + } + assert!(near(BlendWidget::of(&d, &s, 1.0, UP)[0].at, Point::new(200.0, 184.0))); + // A third does: the widget moves 16 px further out, past them, and the Easing widget below + // stays where it is. The halfway point it joins stays the same. + let third = cover(&mut d, 190.0, 175.0, 210.0, 195.0); + let w = BlendWidget::of(&d, &s, 1.0, UP); + assert!(near(w[0].at, Point::new(200.0, 168.0)) && near(w[0].on, Point::new(200.0, 200.0)), "{w:?}"); + assert!(near(w[1].at, Point::new(200.0, 216.0)), "{w:?}"); + // A hidden object does not count. + d.node_mut(third).unwrap().visible = false; + assert!(near(BlendWidget::of(&d, &s, 1.0, UP)[0].at, Point::new(200.0, 184.0))); + // The walk looks at the topmost 1024 nodes only: with more objects above them, the covers + // below are not looked at. + d.node_mut(third).unwrap().visible = true; + let mut many = d.clone(); + for i in 0..LOOK { + let x = (i % 30) as f64 * 25.0; + cover(&mut many, x, 500.0, x + 10.0, 510.0); + } + assert!(near(BlendWidget::of(&many, &s, 1.0, UP)[0].at, Point::new(200.0, 184.0))); + assert!(near(BlendWidget::of(&d, &s, 1.0, UP)[0].at, Point::new(200.0, 168.0))); + // Crowded all the way out (past 144 px): the widget stays at the first spot. + let (mut d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + for _ in 0..3 { + cover(&mut d, 150.0, 0.0, 250.0, 199.0); + } + assert!(near(BlendWidget::of(&d, &s, 1.0, UP)[0].at, Point::new(200.0, 184.0))); + // The blend's own keys never crowd it: three 100 pt keys that all hold both spots. + let mut d = Document::new(800.0, 800.0); + let l = d.layers[0].id; + let big = |d: &mut Document, x: f64| { + let id = d.alloc_id(); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(x - 50.0, 150.0, x + 50.0, 250.0)), Appearance::default_art())) + }; + let children = vec![big(&mut d, 150.0), big(&mut d, 200.0), big(&mut d, 250.0)]; + let id = d.alloc_id(); + d.insert(Some(l), 0, Node::new(id, NodeKind::Blend { children, spec: Box::new(eased()) })).unwrap(); + let mut s = Selection::default(); + s.add(id); + let w = BlendWidget::of(&d, &s, 1.0, UP); + assert!(near(w[0].at, Point::new(200.0, 184.0)) && near(w[1].at, Point::new(200.0, 216.0)), "{w:?}"); + } + + #[test] + fn the_easing_widget_needs_steps_that_follow_a_spine() { + // The straight lines between the keys with Align to Page: the steps do not follow a spine. + let (d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], BlendSpec::default()); + assert_eq!(BlendWidget::of(&d, &s, 1.0, UP).iter().map(|w| w.control).collect::>(), [BlendControl::Appearance]); + // A replaced spine, closed, with the keys spread along it. + let spine = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(200.0, 200.0)], true)); + let (d, _, s) = blend_doc(&[(0.0, 0.0), (200.0, 0.0)], BlendSpec { spine: Some(spine), ..Default::default() }); + let w = BlendWidget::of(&d, &s, 1.0, UP); + assert_eq!(w.len(), 2, "{w:?}"); + assert!(w[0].on.x.is_finite() && w[0].on.y.is_finite()); + } + + #[test] + fn no_widgets_for_a_selection_they_cannot_edit() { + let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + assert!(BlendWidget::of(&d, &Selection::default(), 1.0, UP).is_empty(), "nothing selected"); + assert!(BlendWidget::of(&d, &s, 0.0, UP).is_empty() && BlendWidget::of(&d, &s, f64::NAN, UP).is_empty(), "no zoom"); + assert!(BlendWidget::of(&d, &s, 1.0, Vec2::ZERO).is_empty(), "no up"); + // Two blends, or a blend and another object. + let (mut two, a, _) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + let l = two.layers[0].id; + let keys = vec![square(&mut two, 0.0, 400.0), square(&mut two, 200.0, 400.0)]; + let b = two.alloc_id(); + two.insert(Some(l), 0, Node::new(b, NodeKind::Blend { children: keys, spec: Box::new(eased()) })).unwrap(); + let mut both = Selection::default(); + both.add(a); + both.add(b); + assert!(BlendWidget::of(&two, &both, 1.0, UP).is_empty(), "two blends"); + // Locked or hidden. + for hide in [false, true] { + let mut d = d.clone(); + let n = d.node_mut(id).unwrap(); + (n.visible, n.locked) = (!hide, !hide); + assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "hidden: {hide}"); + } + // A key object selected on its own is not the whole blend. + let NodeKind::Blend { children, .. } = &d.node(id).unwrap().kind else { panic!("not a blend") }; + let mut key = Selection::default(); + key.add(children[0].id); + assert!(BlendWidget::of(&d, &key, 1.0, UP).is_empty(), "a key"); + // Keys on one spot: the spine has no length. + let (d, _, s) = blend_doc(&[(100.0, 200.0), (100.0, 200.0)], eased()); + assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "no length"); + // One key. + let (d, _, s) = blend_doc(&[(100.0, 200.0)], eased()); + assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "one key"); + // A blend made without a spine (Create Spine › Never), Align to Path included. + let (d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], BlendSpec { no_spine: true, ..eased() }); + assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "no spine"); + } + + /// A drag of the Easing widget along the spine changes the ramp by one per pixel from its + /// value at the press, in one undo step, without changing the type or the color shift. + #[test] + fn dragging_the_easing_widget_sets_the_ramp_from_its_value() { + let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + let p = paint(); + let c = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + let at = Point::new(200.0, 216.0); + assert!(t.pointer(&c, &ev(PointerKind::Down, at)).is_empty()); + // A small move first: no jump, the value stays at the press's 40. + assert!(t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(1.0, 1.0))).is_empty()); + let a = t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(3.0, 30.0))); + assert_eq!(a[0], Action::Begin(LABEL.into())); + assert_eq!(a[1], Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 43.0})), "across the spine counts for nothing"); + assert!(t.transforming()); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "43%"))); + let a = t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(-70.0, 0.0))); + assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 0.0}))], "clamped at 0"); + let a = t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(500.0, 0.0))); + assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 100.0}))], "clamped at 100"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at)), vec![Action::Commit]); + // A click that doesn't move sends nothing. + assert!(t.pointer(&c, &ev(PointerKind::Down, at)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, at)).is_empty()); + } + + /// The Appearance widget sets the color shift alone, and at 4× zoom a pixel is a quarter point. + #[test] + fn dragging_the_appearance_widget_sets_the_color_shift() { + let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + let p = paint(); + let c = ToolContext { zoom: 4.0, ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + let at = Point::new(200.0, 196.0); + t.pointer(&c, &ev(PointerKind::Down, at)); + let a = t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(-5.0, 0.0))); + assert_eq!(a[1], Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "colorShift": -40.0}))); + let a = t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(-50.0, 0.0))); + assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "colorShift": -100.0}))]); + } + + /// The drag follows the spine's direction at the press: along a vertical spine, down adds. + #[test] + fn the_drag_follows_the_spines_direction() { + let (d, id, s) = blend_doc(&[(200.0, 100.0), (200.0, 300.0)], eased()); + let p = paint(); + let c = cx(&d, &s, &p); + let w = BlendWidget::of(&d, &s, 1.0, UP); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w[1].at)); + let a = t.pointer(&c, &ev(PointerKind::Drag, w[1].at + Vec2::new(40.0, 10.0))); + assert_eq!(a[1], Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 50.0}))); + } + + /// Switching away from the Selection or Blend tool during a drag cancels it, and after a press + /// that has not moved there is nothing to put back. + #[test] + fn a_tool_switch_cancels_the_drag() { + let (d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(200.0, 216.0); + let tools: [Box; 2] = [Box::new(SelectionTool::default()), Box::new(crate::meshblend::BlendTool::default())]; + for mut t in tools { + t.pointer(&c, &ev(PointerKind::Down, at)); + assert_eq!(t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(20.0, 0.0))).len(), 2); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + t.pointer(&c, &ev(PointerKind::Down, at)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } + } + + /// The arrow keys during a drag change the value by one, ten with Shift, and Escape cancels. + #[test] + fn arrow_keys_step_and_escape_cancels() { + let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + let p = paint(); + let c = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + let at = Point::new(200.0, 216.0); + t.pointer(&c, &ev(PointerKind::Down, at)); + let a = t.key(&c, ToolKey::Up, Mods::default()); + assert_eq!(a, vec![Action::Begin(LABEL.into()), Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 41.0}))]); + let a = t.key(&c, ToolKey::Left, Mods { shift: true, ..Default::default() }); + assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 31.0}))]); + for _ in 0..10 { + t.key(&c, ToolKey::Down, Mods { shift: true, ..Default::default() }); + } + let a = t.key(&c, ToolKey::Right, Mods::default()); + assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 1.0}))], "steps past 0 are not kept"); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + assert!(t.pointer(&c, &ev(PointerKind::Up, at)).is_empty(), "the release commits nothing"); + } + + /// A double-click on a widget with the Selection tool does nothing to the artwork under it. + #[test] + fn a_double_click_on_a_widget_leaves_the_artwork_under_it_alone() { + let (mut d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + cover(&mut d, 190.0, 206.0, 210.0, 226.0); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(200.0, 216.0); + assert!(over_widget(&c, at)); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::DoubleClick, at)).is_empty()); + // Beside the widget, the double-click reaches the artwork. + assert!(!t.pointer(&c, &ev(PointerKind::DoubleClick, Point::new(192.0, 224.0))).is_empty()); + } + + /// After a drag past either end, the first arrow key steps back from the value shown. + #[test] + fn an_arrow_key_after_a_drag_past_an_end_steps_from_the_value_shown() { + let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(200.0, 216.0); + let ramp = |v: f64| vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": v}))]; + for (moved, back, shown) in [(200.0, ToolKey::Left, 99.0), (-200.0, ToolKey::Right, 1.0)] { + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, at)); + t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(moved, 0.0))); + assert_eq!(t.key(&c, back, Mods::default()), ramp(shown), "{moved}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at + Vec2::new(moved, 0.0))), vec![Action::Commit]); + } + } +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 54a4d131bd..d73cd2297f 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -9,6 +9,7 @@ pub mod addons; pub mod bbox; +pub mod blendwidget; pub mod builder; pub mod catalog; pub mod corners; diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index d64b4b162b..d61eb95f5f 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -4,6 +4,7 @@ //! point of a path blends from that point (`starts`). Each further click adds the object as one //! more key of the new blend (as does clicking a blend first). Double-click or Alt-click opens //! Blend Options (dialog `blendOptions`). Clicking empty canvas or pressing Escape starts over. +//! A press on a widget of the selected blend drags it ([`crate::blendwidget`]). //! - Mesh: click inside a filled path → `object.mesh.create {ids, at}` (1×1 mesh plus lines through //! the click); click inside a mesh or a mesh envelope → `object.mesh.addLine` (a gradient mesh's //! new point takes the current fill color in its own model, unless Shift); drag a mesh point, @@ -19,6 +20,7 @@ use vectorcraft_color::Paint; use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::Point; +use crate::blendwidget::{self, BlendWidgetDrag}; use crate::meshedit::{MeshEdit, grid_of}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -51,6 +53,8 @@ pub struct BlendTool { /// `first` and `chained` when the button went down: a dropped press puts them back, unless /// the press picked an object or made a blend. before_press: Option<(Option, bool)>, + /// A press on a widget of the selected blend, and its drag. + widget: Option, } /// The anchor of the first subpath of path or compound path `id` (its first member's) nearest @@ -98,6 +102,19 @@ impl Tool for BlendTool { if self.first.is_some_and(|(a, _)| cx.doc.node(a).is_none()) { (self.first, self.chained) = (None, false); } + // The selected blend's widgets take a press before the picks, and its drag. + match (ev.kind, &mut self.widget) { + (PointerKind::Drag, Some(d)) => return d.drag(cx, ev.pos), + (PointerKind::Up, Some(_)) => return self.widget.take().map(BlendWidgetDrag::finish).unwrap_or_default(), + (PointerKind::DoubleClick, _) if blendwidget::over_widget(cx, ev.pos) => return vec![], + (PointerKind::Down, _) if !ev.mods.alt => { + if let Some(d) = BlendWidgetDrag::hit(cx, ev) { + self.widget = Some(d); + return vec![]; + } + } + _ => {} + } match ev.kind { PointerKind::DoubleClick => options(self), PointerKind::Down if ev.mods.alt => options(self), @@ -131,6 +148,9 @@ impl Tool for BlendTool { } } fn overlays(&self, cx: &ToolContext) -> Vec { + if let Some(d) = &self.widget { + return d.overlays(cx); + } let Some((id, start)) = self.first(cx) else { return vec![] }; let Some(n) = cx.doc.node(id) else { return vec![] }; let at = match (start, &n.kind) { @@ -144,6 +164,9 @@ impl Tool for BlendTool { vec![Overlay::Anchor { p, color: FEEDBACK, filled: true, size: 6.0 }] } fn cursor(&self, cx: &ToolContext, p: Point, _mods: Mods) -> Cursor { + if self.widget.is_some() || blendwidget::over_widget(cx, p) { + return Cursor::ArrowHollow; + } match pick(cx, p) { Some((_, Some(_))) => Cursor::BlendAnchor, Some(_) => Cursor::BlendObject, @@ -151,15 +174,34 @@ impl Tool for BlendTool { } } fn busy(&self) -> bool { - self.first.is_some() + self.first.is_some() || self.widget.is_some() + } + fn transforming(&self) -> bool { + self.widget.as_ref().is_some_and(BlendWidgetDrag::adjusting) + } + /// The arrows while a blend widget is pressed: its value. + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + self.widget.is_some() && matches!(key, ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right) } /// A first pick, or adding to the blend just made: Escape ends either. fn ends_on_escape(&self, cx: &ToolContext) -> bool { self.first(cx).is_some() } /// Escape drops the object picked first and stops adding to the blend just made, so the next - /// click picks a new first object. The document and the selection stay as they are. - fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec { + /// click picks a new first object. The document and the selection stay as they are. While a + /// blend widget is pressed, the arrows change its value and Escape cancels its drag instead. + fn key(&mut self, cx: &ToolContext, key: crate::ToolKey, mods: Mods) -> Vec { + if let Some(d) = &mut self.widget { + return match key { + ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right => d.step(cx, matches!(key, ToolKey::Up | ToolKey::Right), mods.shift), + ToolKey::Escape => { + let began = d.adjusting(); + self.widget = None; + if began { vec![Action::Cancel] } else { vec![] } + } + _ => vec![], + }; + } if key == crate::ToolKey::Escape { (self.first, self.chained, self.before_press) = (None, false, None); } @@ -172,11 +214,18 @@ impl Tool for BlendTool { if let Some((first, chained)) = self.before_press.take() { (self.first, self.chained) = (first, chained); } - vec![] + // A dropped widget drag puts its value back. + match self.widget.take() { + Some(d) if d.adjusting() => vec![Action::Cancel], + _ => vec![], + } } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { (self.first, self.chained, self.before_press) = (None, false, None); - vec![] + match self.widget.take() { + Some(d) if d.adjusting() => vec![Action::Cancel], + _ => vec![], + } } /// Choosing the Blend tool again finishes the blend: it drops the object picked first and /// stops adding to the blend just made, so the next click picks a new first object. The diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 2f177d5847..17bf7eeaef 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -45,6 +45,7 @@ use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag}; +use crate::blendwidget::{self, BlendWidgetDrag}; use crate::corners::{self, CornerDrag, over_widget}; use crate::guides::{PointSnap, Targets, distance_guides, hold_on_path}; use crate::objects_on_path::{ @@ -131,6 +132,8 @@ enum State { Corner(CornerDrag), /// Dragging a live ellipse's pie widget. Pie(PieDrag), + /// Dragging a selected blend's Appearance or Easing widget. + BlendWidget(BlendWidgetDrag), /// Dragging an Objects on Path group's Rotate All widget. RotateAll(RotateAllDrag), /// Dragging an Objects on Path group's Space widget. @@ -757,15 +760,19 @@ impl Tool for SelectionTool { /// E during a marquee drag switches the marquee between the objects it touches and only the /// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or - /// rotation, a marquee, a corner widget, a pie widget, the Rotate All, Space, Move All or Select/Move widget, the brackets of type on a path, a mirror + /// rotation, a marquee, a corner widget, a pie widget, a blend widget, the Rotate All, Space, Move All or Select/Move widget, the brackets of type on a path, a mirror /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy /// is left, and the tool waits for the next press. With the pointer loaded with text, Escape /// drops the text. - fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { // Up and Down while a corner widget is pressed: the corners' kind (#2898). if let (ToolKey::Up | ToolKey::Down, State::Corner(c)) = (key, &mut self.state) { return c.step_kind(key == ToolKey::Up); } + // The arrows while a blend widget is pressed: its value, by one (Shift: ten). + if let (ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right, State::BlendWidget(d)) = (key, &mut self.state) { + return d.step(cx, matches!(key, ToolKey::Up | ToolKey::Right), mods.shift); + } if key == ToolKey::Letter('e') && let State::Marquee { enclosed, .. } = &mut self.state { @@ -816,10 +823,23 @@ impl Tool for SelectionTool { out } + /// Switching tools during a blend widget's drag cancels it, as Escape does: its value goes back. + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + match std::mem::take(&mut self.state) { + State::BlendWidget(d) if d.adjusting() => vec![Action::Cancel], + State::BlendWidget(_) => vec![], + other => { + self.state = other; + vec![] + } + } + } + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { match self.state { State::Marquee { .. } => key == ToolKey::Letter('e'), State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down), + State::BlendWidget(_) => matches!(key, ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right), State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape, _ => false, } @@ -850,6 +870,7 @@ impl Tool for SelectionTool { State::Moving { began: true, .. } | State::Scaling { .. } | State::Rotating { .. } => true, State::Corner(c) => c.adjusting(), State::Pie(d) => d.adjusting(), + State::BlendWidget(d) => d.adjusting(), State::RotateAll(d) => d.adjusting(), State::Space(d) => d.adjusting(), State::MoveAll(d) => d.adjusting(), @@ -1024,6 +1045,15 @@ impl Tool for SelectionTool { self.state = State::Idle; d.finish() } + (PointerKind::Drag, State::BlendWidget(mut d)) => { + let out = d.drag(cx, p); + self.state = State::BlendWidget(d); + out + } + (PointerKind::Up, State::BlendWidget(d)) => { + self.state = State::Idle; + d.finish() + } (PointerKind::Drag, State::RotateAll(mut d)) => { let out = d.drag(cx, p, m.shift); self.state = State::RotateAll(d); @@ -1122,6 +1152,7 @@ impl Tool for SelectionTool { }), State::Corner(c) => o.extend(c.overlays(cx)), State::Pie(d) => o.extend(d.overlays(cx)), + State::BlendWidget(d) => o.extend(d.overlays(cx)), State::RotateAll(d) => o.extend(d.overlays(cx)), State::Space(d) => o.extend(d.overlays(cx)), State::MoveAll(d) => o.extend(d.overlays(cx)), @@ -1176,7 +1207,7 @@ impl Tool for SelectionTool { State::Moving { began: true, .. } if m.alt => return Cursor::SelectionCopy, State::Moving { began: true, .. } => return if self.snapped { Cursor::ArrowHollow } else { Cursor::Arrow }, State::Corner(_) => return Cursor::CornerRadius, - State::Pie(_) => return Cursor::ArrowHollow, + State::Pie(_) | State::BlendWidget(_) => return Cursor::ArrowHollow, State::RotateAll(_) => return Cursor::Rotate, State::Space(_) => return Cursor::ArrowHollow, State::MoveAll(_) | State::Member(_) => return Cursor::Move, @@ -1199,6 +1230,9 @@ impl Tool for SelectionTool { if near_selected && pie::over_widget(cx, p) { return Cursor::ArrowHollow; } + if blendwidget::over_widget(cx, p) { + return Cursor::ArrowHollow; + } if over_rotate_all(cx, p) { return Cursor::Rotate; } @@ -1518,6 +1552,11 @@ impl SelectionTool { if let Some(a) = release_guide_at(cx, p, m) { return vec![a]; } + // A selected blend's widget takes a plain double-click: the artwork under it is neither + // edited nor isolated. + if blendwidget::over_widget(cx, p) { + return vec![]; + } if crate::rulerguide::guide_at(cx, p).is_some() { return vec![]; } @@ -1557,7 +1596,7 @@ impl SelectionTool { self.state = State::Loaded { from, before: port == crate::text::Port::In, press: None }; return Some(vec![]); } - // 1. Live Corners widgets, pie widgets, the Rotate All, Space, Move All and Select/Move widgets and type on a path's brackets, then the + // 1. Live Corners widgets, pie widgets, blend widgets, the Rotate All, Space, Move All and Select/Move widgets and type on a path's brackets, then the // bounding-box handles of the current selection. if let Some(c) = CornerDrag::hit(cx, ev, false) { self.state = State::Corner(c); @@ -1567,6 +1606,10 @@ impl SelectionTool { self.state = State::Pie(d); return Some(vec![]); } + if let Some(d) = BlendWidgetDrag::hit(cx, ev) { + self.state = State::BlendWidget(d); + return Some(vec![]); + } if let Some(d) = RotateAllDrag::hit(cx, ev) { self.state = State::RotateAll(d); return Some(vec![]); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 202a0542a8..781ca2c2f6 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -61,7 +61,7 @@ use outline::KEY_OUTLINE; use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; #[cfg(test)] use overlays::selected_anchor; -use overlays::{HandleLook, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; +use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; pub use panes::Panes; pub(crate) use panes::{consolidate, pane, tile, tiled_area}; use raster::{changed_pixels, pixel_region, upload}; @@ -1207,6 +1207,9 @@ fn selection_visuals( hidden_chars_overlay(app, painter, xf); } } + if !revolve_edit { + blend_widgets_overlay(app, painter, xf); + } // Edit › Spelling › Auto Spell Check: shown with the edges hidden too, as it marks the type // rather than the selection. if app.ui.view.auto_spell_check && !revolve_edit { diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 9551c45954..7eb31f7d01 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -250,6 +250,26 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: rotate_all_widget(p, xf, tool, &st.doc, &st.selection); } +/// The Appearance and Easing widgets of one selected blend (Selection and Blend tools), each joined +/// by a line to the spine's halfway point: the Appearance widget hollow above it, the Easing widget +/// filled below it. Drawn with the edges hidden too, as they are controls. +pub(super) fn blend_widgets_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { + use vectorcraft_tools::blendwidget::{BlendControl, BlendWidget, RADIUS_PX}; + if !matches!(app.session.tool_id(), "selection" | "blend") { + return; + } + let Some(st) = app.session.active() else { return }; + // The screen's up in the document, with the view turned by `xf.rot`. + let up = vectorcraft_geom::Vec2::new(-xf.rot.sin(), -xf.rot.cos()); + for w in BlendWidget::of(&st.doc, &st.selection, xf.zoom, up) { + let (on, c, color) = (xf.to_screen(w.on), xf.to_screen(w.at), c32(st.doc.layer_color(w.id))); + p.line_segment([on, c], Stroke::new(1.0, color)); + let fill = if w.control == BlendControl::Easing { color } else { Color32::WHITE }; + p.circle_filled(c, RADIUS_PX, fill); + p.circle_stroke(c, RADIUS_PX, Stroke::new(1.0, color)); + } +} + /// The Select/Move, Rotate All, Space and Move All widgets (Selection and Objects on Path tools, one /// Objects on Path group selected). The Rotate All widget is joined by a line to the first object's /// attachment point. It stays while dragged. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index abf371b274..281cd9dd3b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2004,6 +2004,7 @@ font-technology Variable Променливи Move Slices Преместване на резени Move Spine Point Преместване на точка от оста Reshape Spine Segment Промяна на формата на сегмент от оста + Blend Easing Плавност на преливането Move Brush Преместване на четка Move Swatch Преместване на образец Move Up Преместване нагоре diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index e11d2c21e4..5f6cd0dea7 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3556,6 +3556,7 @@ theme Appearance Izgled Move Mesh Points Pomjeri tačke mreže Move Spine Point Pomjeri tačku kičme Reshape Spine Segment Preoblikuj segment kičme + Blend Easing Ublažavanje stapanja Reset with Mesh Vrati mrežom Reset with Warp Vrati iskrivljenjem Set Mesh Point Color Postavi boju tačke mreže diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 91812ded4e..c05e0a4a7b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3609,6 +3609,7 @@ digits Malayalam Malaiàlam Reshape Segment Remodela el segment Reshape Spine Remodela l’espina Reshape Spine Segment Remodela el segment de l’espina + Blend Easing Suavitzat de la fusió Reshape Tool Eina de remodelació Reshape Type Area Remodela l’àrea de text Resize Redimensiona diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ddc33a08ae..acc5d40c0b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3610,6 +3610,7 @@ theme Appearance Motiv Move Mesh Points Přesunout body sítě Move Spine Point Přesunout bod páteře Reshape Spine Segment Přetvarovat segment páteře + Blend Easing Náběh prolnutí Reset with Mesh Obnovit sítí Reset with Warp Obnovit pokřivením Set Mesh Point Color Nastavit barvu bodu sítě diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 5478fb4f98..9b365488f7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3343,6 +3343,7 @@ theme Appearance Udseende Move Mesh Points Flyt meshpunkter Move Spine Point Flyt rygradpunkt Reshape Spine Segment Omform rygradsegment + Blend Easing Blandingens acceleration Reset with Mesh Nulstil med mesh Reset with Warp Nulstil med forvrængning Set Mesh Point Color Angiv farve for meshpunkt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7621e4c4c0..990ea4b57f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2080,6 +2080,7 @@ file-filter Templates Vorlagen Move Slices Slices verschieben Move Spine Point Achsenpunkt verschieben Reshape Spine Segment Achsensegment umformen + Blend Easing Beschleunigung der Angleichung Move Brush Pinsel verschieben Move Swatch Farbfeld verschieben Move Up Nach oben verschieben diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 557be7dce9..8434a793a6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2916,6 +2916,7 @@ theme Appearance Εμφάνιση Move Slices Μετακίνηση τομών Move Spine Point Μετακίνηση σημείου κεντρικής καμπύλης Reshape Spine Segment Αναδιαμόρφωση τμήματος κεντρικής καμπύλης + Blend Easing Επιτάχυνση ανάμειξης Move Brush Μετακίνηση πινέλου Move Swatch Μετακίνηση δείγματος χρώματος Move Up Μετακίνηση επάνω diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4a35ed82c6..2ee16434ed 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2074,6 +2074,7 @@ font-technology Variable Variables Move Slices Mover sectores Move Spine Point Mover punto del eje Reshape Spine Segment Remodelar segmento del eje + Blend Easing Suavizado de fusión Move Brush Mover pincel Move Swatch Mover muestra Move Up Subir diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2b1a420e90..715a09f51a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3548,6 +3548,7 @@ theme Appearance Ulkoasu Move Mesh Points Siirrä verkkopisteitä Move Spine Point Siirrä selkärangan pistettä Reshape Spine Segment Muotoile selkärangan segmentti uudelleen + Blend Easing Sulautuksen pehmennys Reset with Mesh Palauta verkolla Reset with Warp Palauta vääristyksellä Set Mesh Point Color Aseta verkkopisteen väri diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 892d576345..3c39dd825b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2068,6 +2068,7 @@ font-technology Variable Variables Move Slices Déplacer les tranches Move Spine Point Déplacer le point de la dorsale Reshape Spine Segment Modeler le segment de la dorsale + Blend Easing Lissage du dégradé de formes Move Brush Déplacer la forme Move Swatch Déplacer la nuance Move Up Monter diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index a73be6f0df..66f60e0d2e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3941,6 +3941,7 @@ antiAlias Sharp शार्प Reshape Segment सेगमेंट को आकार देना Reshape Spine स्पाइन का आकार बदलें Reshape Spine Segment स्पिन सेगमेंट को फिर से आकार दें + Blend Easing ब्लेंड ईज़िंग Reshape Tool रीशेप टूल Reshape Type Area रीशैप टाइप एरिया Reshape Type Path टाइप पाथ रीशेप करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 8ca8717178..6cbbfba3ea 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3458,6 +3458,7 @@ mark-style Japanese Japán Reshape Átformálás Reshape Segment Szakasz átformálása Reshape Spine Segment Gerincszakasz átformálása + Blend Easing Összemosás gyorsítása Reshape Tool Átformálás Reshape Type Area Szövegterület átformálása Resize Átméretezés diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c233d02ec9..8da428bd43 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3343,6 +3343,7 @@ theme Appearance Tampilan Move Mesh Points Pindahkan titik-titik mesh Move Spine Point Pindahkan titik spine Reshape Spine Segment Bentuk ulang segmen spine + Blend Easing Easing blend Reset with Mesh Atur ulang dengan mesh Reset with Warp Atur ulang dengan warp Set Mesh Point Color Tetapkan warna titik mesh diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6e4179989f..b480ba2b5e 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2112,6 +2112,7 @@ file-filter Templates Modelli Move Slices Sposta sezioni Move Spine Point Sposta punto dorsale Reshape Spine Segment Rimodella segmento della dorsale + Blend Easing Andamento fusione Move Brush Sposta pennello Move Swatch Sposta campione Move Up Sposta su diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ff5e05f97a..c2456ab918 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2328,6 +2328,7 @@ antiAlias Sharp シャープ Move Slices スライスを移動 Move Spine Point スパインポイントを移動 Reshape Spine Segment スパインセグメントをシェイプ変形 + Blend Easing ブレンドのイージング Move Brush ブラシを移動 Move Swatch スウォッチを移動 Move Up 上へ移動 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 4694025797..bb9fe6b9ee 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3189,6 +3189,7 @@ theme Appearance იერსახე Move Mesh Points ბადის წერტილების გადაადგილება Move Spine Point ხერხემლის წერტილის გადაადგილება Reshape Spine Segment ხერხემლის სეგმენტის ფორმის შეცვლა + Blend Easing გადასვლის შერბილება Reset with Mesh ბადით ჩამოყრა Reset with Warp გაღუნვით ხელახლა დაყენება Set Mesh Point Color ბადის წერტილის ფერის დაყენება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 48d92bd719..635c36b576 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2318,6 +2318,7 @@ antiAlias Sharp 날카롭게 Move Slices 슬라이스 이동 Move Spine Point 스파인 포인트 이동 Reshape Spine Segment 스파인 세그먼트 모양 변경 + Blend Easing 블렌드 이징 Move Brush 브러시 이동 Move Swatch 견본 이동 Move Up 위로 이동 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index fa9aca3df9..6922b67cd6 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3357,6 +3357,7 @@ theme Appearance Vormgeving Move Mesh Points Maaspunten verplaatsen Move Spine Point Aspunt verplaatsen Reshape Spine Segment Segment van de as opnieuw vormgeven + Blend Easing Blend-easing Reset with Mesh Opnieuw instellen met maas Reset with Warp Opnieuw instellen met vervorming Set Mesh Point Color Kleur van maaspunt instellen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0e6e2e82a2..c0adac32fb 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3489,6 +3489,7 @@ theme Appearance Wygląd Move Mesh Points Przesuń punkty siatki Move Spine Point Przesuń punkt grzbietu Reshape Spine Segment Zmień kształt segmentu grzbietu + Blend Easing Wygładzanie przejścia Reset with Mesh Resetuj z siatką Reset with Warp Resetuj z wypaczeniem Set Mesh Point Color Ustaw kolor punktu siatki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4b0a3cd7da..7c840b8ffd 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1758,6 +1758,7 @@ antiAlias Sharp Nítido Move Slices Mover Fatias Move Spine Point Mover Ponto de Coluna Reshape Spine Segment Remodelar Segmento da Coluna + Blend Easing Suavização da Mesclagem Move Brush Mover Pincel Move Swatch Mover Amostra Move Up Mover para Cima diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 06875888cf..fc07d37d01 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2101,6 +2101,7 @@ file-filter Templates Шаблоны Move Slices Переместить фрагменты Move Spine Point Переместить точку остова Reshape Spine Segment Изменить форму сегмента остова + Blend Easing Сглаживание перехода Move Brush Переместить кисть Move Swatch Переместить образец Move Up Переместить вверх diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index b3e3062143..3be29b4afe 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2015,6 +2015,7 @@ font-technology Variable Variabla Move Slices Flytta skivor Move Spine Point Flytta ryggradspunkt Reshape Spine Segment Omforma ryggradssegment + Blend Easing Blandningens acceleration Move Brush Flytta pensel Move Swatch Flytta färgruta Move Up Flytta upp diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 799ebb6b40..1cb15a3232 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1904,6 +1904,7 @@ font-technology Variable Değişken Move Slices Dilimleri Taşı Move Spine Point Omurga Noktasını Taşı Reshape Spine Segment Omurga Segmentini Yeniden Şekillendirin + Blend Easing Karışım Yumuşatma Move Swatch Renk Örneğini Taşı Move Up Yukarı Taşı Move… Taşı… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index c7e77a3f17..feeb65975a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2106,6 +2106,7 @@ file-filter Templates Шаблони Move Slices Перемістити фрагменти Move Spine Point Перемістити точку осі Reshape Spine Segment Змінити форму сегмента осі + Blend Easing Згладжування переходу Move Brush Перемістити пензель Move Swatch Перемістити зразок Move Up Перемістити вгору diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 13669ca858..72b7247119 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3227,6 +3227,7 @@ mark-style Japanese Kiểu Nhật Reshape Định hình lại Reshape Segment Định hình lại đoạn Reshape Spine Segment Định hình lại đoạn trục + Blend Easing Gia tốc hòa trộn Reshape Tool Công cụ Định hình lại Reshape Type Area Định hình lại vùng chữ Resize Thay đổi kích thước diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ae00ce8a34..a5393d9757 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1968,6 +1968,7 @@ file-filter Templates 模板 Move Slices 移动切片 Move Spine Point 移动脊线点 Reshape Spine Segment 整形脊线线段 + Blend Easing 渐变缓动 @msg select a blend or give `id` 请选择一个混合对象,或给出 `id` @msg not a blend 不是混合对象 @msg the blend has no spine 混合对象没有脊线 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4970f1d88f..726aa84eec 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3060,6 +3060,7 @@ file-filter Templates 範本 Move Slices 移動切片 Move Spine Point 移動脊線點 Reshape Spine Segment 改變脊線線段外框 + Blend Easing 漸變緩動 @msg select a blend or give `id` 請選取漸變物件,或提供 `id` @msg not a blend 不是漸變物件 @msg the blend has no spine 漸變物件沒有脊線 diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index f0ff34ef64..db262870ab 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -787,8 +787,20 @@ fn busy_tool_keys(app: &mut VectorcraftApp, ctx: &egui::Context, view: ViewInfo) // The arrows while dragging: a polygon's sides, a grid's rows (↑/↓) and columns (←/→)… let arrows = [(Key::ArrowUp, ToolKey::Up), (Key::ArrowDown, ToolKey::Down), (Key::ArrowLeft, ToolKey::Left), (Key::ArrowRight, ToolKey::Right)]; for (k, tk) in arrows { + // The press's Shift and Alt (the consume below takes those presses too) go to a tool that + // claims the arrow (Shift steps a blend widget by ten); other tools get the plain arrow. + let pressed = ctx.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::Key { key, pressed: true, modifiers, .. } if *key == k && !(modifiers.command || modifiers.ctrl) => Some(*modifiers), + _ => None, + }) + }); if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)) { - let _ = app.session.tool_key(tk, Mods::default(), view); + let mods = match pressed { + Some(m) if app.session.tool_claims_key(tk, view) => crate::canvas::mods(m, false), + _ => Mods::default(), + }; + let _ = app.session.tool_key(tk, mods, view); } } // Digits (5 while dragging with the Perspective Selection tool), once per press. diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index e002d07adf..932dd9e0f3 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -3032,6 +3032,38 @@ fn a_plain_up_nudges_unless_a_corner_widget_is_pressed() { assert_eq!(kind2, CornerKind::InvertedRound, "Up stepped the kind"); } +/// While a blend widget is pressed, an arrow steps its value by one and Shift with an arrow by ten. +#[test] +fn shift_arrows_step_a_pressed_blend_widget_by_ten() { + use vectorcraft_doc::{NodeId, NodeKind}; + use vectorcraft_tools::blendwidget::BlendWidget; + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.session.execute("shape.rectangle", &json!({"x": x, "y": 190, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 90.0), rect(&mut app, 290.0)); + app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let id = NodeId(app.session.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let shift = |app: &VectorcraftApp| { + let NodeKind::Blend { spec, .. } = &app.session.active().unwrap().doc.node(id).unwrap().kind else { panic!("not a blend") }; + spec.color_shift + }; + let view = app.view_info(); + let st = app.session.active().unwrap(); + let at = BlendWidget::of(&st.doc, &st.selection, view.zoom, vectorcraft_geom::Vec2::new(0.0, -1.0))[0].at; + app.session.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y), view).unwrap(); + frame(&mut app, press(Key::ArrowUp, Modifiers::SHIFT)); + assert_eq!(shift(&app), 10.0, "Shift+Up steps by ten"); + frame(&mut app, press(Key::ArrowUp, Modifiers::NONE)); + assert_eq!(shift(&app), 11.0, "Up steps by one"); + app.session.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y), view).unwrap(); + assert_eq!(shift(&app), 11.0); +} + /// #5218: the status bar navigator's four buttons are commands of their own, listed in Edit › /// Keyboard Shortcuts without a default key, so a user can give them one (Page Up and Page Down /// here) and step through the artboards from the keyboard. diff --git a/docs/gaps.md b/docs/gaps.md index 21272bee97..2030cc96bb 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -538,8 +538,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi (#1676). A linked image is refused, as the public documentation has it. - **Partial:** blend easing (#1124, 30.7): Window › Blend has Type (Ease In, Ease Out, Ease In Out, Ease Out In), Ramp 0–100% and independent color Shift; easing is disabled without a spine. - The original polynomial distributions approximate the public description. On-canvas easing handles - and their synchronization remain missing. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html). + The original polynomial distributions approximate the public description. With the Selection or + Blend tool, on-canvas widgets on a blend with a spine set the color Shift and, when the steps follow + that spine, the Ramp; a blend made without a spine shows neither widget. The Blend panel shows the + values they set. [Public source](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html). - **Done:** gradient Dither (30.0): the Gradient panel's Dither box (`paint.editGradient` `dither`, also in `paint.setFill`'s `gradient`, swatches and the native file) draws a linear or radial gradient fill as pixels with seeded noise of up to a diff --git a/docs/mcp.md b/docs/mcp.md index fbe40fab40..a5f798b81b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9083,6 +9083,24 @@ so its point at `t` moves by (dx, dy), turning a straight spine into a curve (`p {"name":"run_command","arguments":{"command":"object.blend.spine.moveAnchor","params":{"id":40,"anchor":1,"x":150,"y":20}}} ``` +`object.blend.setEasing {id?, easingType?, ramp?, colorShift?}` sets one blend's easing and color shift (the +first selected blend without `id`) and returns `{id, easingType, ramp, colorShift, changed}`; omitted values are kept. +`easingType` is `easeIn`, `easeOut`, `easeInOut` or `easeOutIn`, `ramp` is 0 to 100 and `colorShift` -100 to 100. +`easingType` and `ramp` need a blend whose steps follow a spine (a replaced or edited spine, or +`orientation: "path"`), as the Blend panel's Type and Ramp do. A blend made without a spine +(`createSpine: "never"`) takes them once Replace Spine has given it one. A value out of range, a hidden or locked blend and a target that is not a blend are errors, +and a call that changes nothing records no undo step (`changed: false`). With one blend selected that has a spine, +the Selection and Blend tools show the same values as widgets +16 px above and below the spine's halfway point (where the boxes of three or more other visible objects hold that +spot, a widget moves out in 16 px steps, up to 144 px, joined to the halfway point by a line): the upper one sets +`colorShift` and the lower one, shown only when the steps follow the spine as `ramp` needs, sets `ramp`, by one per screen pixel dragged along the spine and by one per arrow key +during the drag (ten with Shift). Each drag is one undo step, and `press_key` Escape or a switch to another tool +during it puts the value back: + +```json +{"name":"run_command","arguments":{"command":"object.blend.setEasing","params":{"id":40,"ramp":35}}} +``` + How blends interpolate: closed shapes start where they twist least unless `starts` picks the anchors; strokes interpolate weight, dashes (a solid stroke counts as the dashed one with its gaps closed), miter limit, arrowhead scale, width profiles and the pen pressure, tilt, bearing and rotation recorded with the Paintbrush (a stroke without a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4ae0fc2d32..71434dfb7f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1720,6 +1720,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Blend, mesh and envelope points by number:** `object.blend.spine.moveAnchor`, `reshapeSegment` and `removeAnchor`, `object.mesh.setPointColor`, `movePoint` and `deletePoint`, and `object.envelope.setMeshPoint` refuse an `anchor`, `segment` or `index` that is not a whole number, and `object.envelope.setMeshPoint` refuses a negative `index`. Specified Steps (`object.blend.make`, `object.blend.options`) and the rows and columns of `object.mesh.create`, `object.envelope.makeWithMesh` and `resetWithMesh` must be whole numbers too. +- **Blend widgets on the canvas:** with one blend selected that has a spine, the Selection and Blend tools show two widgets 16 px above and below the spine's halfway point (further out, joined to that point by a line, where the boxes of three or more other objects crowd the spot), as the [Blend panel help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html) describes an upper widget for Appearance and a lower one for Easing. The upper one sets Shift and the lower one Ramp, keeping the Type, and the lower one shows only when the steps follow that spine; a blend made without a spine shows neither. A drag along the spine changes the value by one per screen pixel from its value at the press, the arrow keys during the drag by one (Shift: ten), and Escape or a tool switch cancels it. A drag is one undo step, or none when the value ends where it started. The placement, the drag and the keys are VectorCraft's own rules. `object.blend.setEasing` sets the same values for agents. Evidence: `blendwidget::tests`, `tests::blendopts::{set_easing_edits_one_blend_and_refuses_what_it_cannot_set, dragging_a_blend_widget_is_one_undo_step_and_a_click_or_escape_none}`, `shortcuts::tests::shift_arrows_step_a_pressed_blend_widget_by_ten`. + - **Blend, mesh and envelope numbers given as text:** `object.blend.make` and `object.blend.options` (`steps`, `distance`, `value`), `object.envelope.makeWithWarp`, `resetWithWarp` and `options` (`bend`, `h`, `v`, `horizontalDistortion`, `verticalDistortion`), `object.envelope.makeWithMesh` and `resetWithMesh` (`rows`, `cols`, `columns`), `object.envelope.options` (`fidelity`), `object.mesh.create` (`rows`, `cols`, `columns`, `highlight`) and `object.mesh.setPointColor` (`opacity`) refuse a value other than a number or null, such as `"8"`, and change nothing. `object.mesh.create` refuses an `at` that is not `[x, y]`. - **Blend and envelope options given as text:** `object.blend.make` and `object.blend.options` (`smooth`), `object.blend.spine.moveAnchor` (`independent`) and `reshapeSegment` (`perpendicular`), `object.envelope.makeWithWarp`, `resetWithWarp` and `options` (`horizontal`), `object.envelope.resetWithMesh` (`maintainShape`), `object.envelope.options` (`antiAlias`, `distortAppearance`, `distortLinearGradients`, `distortPatternFills`) and `object.envelope.editContents` (`editing`) refuse a value other than true, false or null, such as `"false"`, and leave the document and its undo history as they were.