diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 0418477194..2770471f70 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2192,6 +2192,13 @@ pub fn blend_steps(keys: &[Arc], spec: &BlendSpec) -> Vec { StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0 } +/// Most steps the blends in `n` and its subtree make in all when drawn: a step that copies a +/// blend counts that blend's steps again, and each instance of a repeat counts its source's +/// steps again. Objects that are not blend steps count 0. +pub fn blend_steps_made(n: &Node) -> usize { + StepCount::default().node(n, false) +} + /// Does each pair of `keys` blended with `spec` ask for the same number of steps /// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and, /// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)? diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 653ed92752..446d441fc4 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1463,6 +1463,16 @@ impl Session { } } + /// The object a click of the active tool at `p` with `mods` would act on + /// ([`vectorcraft_tools::Tool::hover_object`]), for Smart Guides › Object Highlighting. None + /// while Cmd lends a selection tool to the press ([`Self::lent_tool_at`]). + pub fn hover_object(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Option { + if mods.cmd && self.lender.is_none() && !self.tool_editing() && self.lent_tool_at(p, &mods, view).is_some() { + return None; + } + self.with_tool_cx(view, |t, cx| t.hover_object(cx, p, mods)) + } + pub fn tool_options(&self) -> Value { self.tool.options() } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index ca01993a6e..486de86876 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -267,6 +267,12 @@ pub trait Tool: Send { fn wants_rehover(&self) -> bool { false } + /// The object a click at `p` with `mods` would act on, which Smart Guides › Object + /// Highlighting outlines while the pointer rests there (the Eyedropper's source). None when a + /// click there acts on no object, or the tool does not name one. + fn hover_object(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Option { + None + } /// What the Info panel shows for the tool as it is now: the drag in progress (a move of the /// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear /// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show. diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index ea677ec654..cb02554785 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -1675,15 +1675,22 @@ fn object_behind(cx: &ToolContext, p: Point) -> Option { /// member with only some anchors or segments selected does not count: the press selects `top`. /// A member with every anchor selected (as `select.anchors` and `select.key` leave a path) counts. fn selected_under(cx: &ToolContext, h: &Hit, top: NodeId) -> Option { - if cx.selection.contains(top) { + selected_under_in(cx.doc, cx.selection, h, top) +} + +/// [`selected_under`] in `doc` with `selection`: the selected object a Selection tool press on +/// `h` lands on, where `top` is the object the press would select. The canvas's hover outline +/// outlines nothing where this finds an object. +pub fn selected_under_in(doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection, h: &Hit, top: NodeId) -> Option { + if selection.contains(top) { return Some(top); } let every_anchor = |id: NodeId| { - cx.selection + selection .partial(id) - .is_none_or(|picked| cx.doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.anchors().all(|(s, i, _)| picked.contains(&(s, i))))) + .is_none_or(|picked| doc.node(id).and_then(|n| n.path_data()).is_some_and(|p| p.anchors().all(|(s, i, _)| picked.contains(&(s, i))))) }; - let whole = |id: NodeId| cx.selection.contains(id) && every_anchor(id) && !cx.selection.segments.contains_key(&id); + let whole = |id: NodeId| selection.contains(id) && every_anchor(id) && !selection.segments.contains_key(&id); let below = h.ancestry.iter().position(|id| *id == top).map_or(&[][..], |i| h.ancestry.get(i..).unwrap_or_default()); below.iter().copied().chain(std::iter::once(h.leaf)).find(|id| whole(*id)) } diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index d45dff84ed..0c63f2f21c 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -34,6 +34,9 @@ //! Image Trace's Ignore Color eyedropper passes its bound document point to the panel, which //! samples the original image pixels and ends the pick only when a color is accepted. A miss //! stays armed; this tool changes neither paint nor selection. +//! +//! The object a click at the pointer would act on, with the keys held, is the tool's hover object +//! ([`Tool::hover_object`]), which Smart Guides › Object Highlighting outlines. use std::collections::HashSet; @@ -165,6 +168,12 @@ pub(crate) fn sample_source(cx: &ToolContext, p: Point) -> Option<(vectorcraft_d /// The visible color under `p`, including image pixels, pattern tiles, mesh colors, intermediate /// gradient colors, the steps a blend draws and an envelope's distorted contents. pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option { + sample_at(cx, p).map(|(c, _)| c) +} + +/// [`sample_color_at`] with the object of the document that gives the color: the object hit, the +/// blend or envelope whose art is sampled, or an object below them that was passed over to. +fn sample_at(cx: &ToolContext, p: Point) -> Option<(Color, NodeId)> { let (doc, opts, raster_sample) = (cx.doc, sample_options(cx), cx.raster_sample); vectorcraft_doc::depth::with_deep_stack(|| { let symbol_nodes = doc.symbols.iter().map(|s| s.art.count()).sum(); @@ -175,13 +184,13 @@ pub(crate) fn sample_color_at(cx: &ToolContext, p: Point) -> Option { }) } -/// The color the front-most object of `doc` hit at `p` with `opts` shows there. Where a stroke +/// The color the front-most object of `doc` hit at `p` with `opts` shows there, and that object. Where a stroke /// gives no color at `p` (a gap between its pattern's tiles), the object's own fill there does; /// an object that gives none at all is passed over for the ones below it. A hit on a blend or an /// envelope, or on an object it holds, samples the art it draws ([`live_color_at`]), and where /// that art leaves `p` empty the whole blend or envelope is passed over. `levels` holds the /// scratch documents for art inside art, one for each level deeper. -fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], p: Point, opts: HitOptions) -> Option { +fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], p: Point, opts: HitOptions) -> Option<(Color, NodeId)> { let mut passed: HashSet = HashSet::new(); let mut size = None; loop { @@ -197,7 +206,7 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], let h = hit_test_visible_skipping(doc, p, opts, &|id| passed.contains(&id))?; if let Some(live) = drawn_live(doc, &h.ancestry) { if let Some(c) = live_color_at(s, levels, live, p) { - return Some(c); + return Some((c, live.id)); } if !passed.insert(live.id) { return None; @@ -208,13 +217,13 @@ fn color_under(s: &mut Sampler, doc: &Document, levels: &mut [Option], let n = doc.node(id)?; let on_stroke = h.kind == HitKind::Stroke; if let Some(c) = node_color_at(s, levels, n, on_stroke, p) { - return Some(c); + return Some((c, id)); } if on_stroke && fill_covers(n, p) && let Some(c) = node_color_at(s, levels, n, false, p) { - return Some(c); + return Some((c, id)); } if !passed.insert(id) { return None; @@ -240,14 +249,28 @@ fn drawn_live<'d>(doc: &'d Document, ancestry: &[NodeId]) -> Option<&'d Node> { /// The color the art blend or envelope `n` draws shows at `p`, sampled as [`art_color_at`] samples /// art: a blend's keys and steps, an envelope's distorted contents, symbol instances in them by /// their symbols' art. Evaluating it counts the objects it holds, and the art made counts its -/// objects. +/// objects. When less work is left than the steps of its blends make in all, the steps that copy +/// a nested blend included ([`vectorcraft_doc::blend::blend_steps_made`]), it is not evaluated. fn live_color_at(s: &mut Sampler, levels: &mut [Option], n: &Node, p: Point) -> Option { + let steps = vectorcraft_doc::blend::blend_steps_made(n); + if s.work < steps { + // Too little work is left for the steps the blends make. + s.spend(steps)?; + } s.spend(n.count())?; + #[cfg(test)] + EXPANSIONS.with(|e| e.set(e.get() + 1)); let art = vectorcraft_effects::expand_live_deep(Some(s.doc), n); s.spend(art.count())?; art_color_at(s, levels, [art], p) } +#[cfg(test)] +thread_local! { + /// The blends and envelopes [`live_color_at`] has evaluated on this thread. + static EXPANSIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The color `n` shows at `p`: an image's pixels, a mesh's interpolated patch color, a symbol /// instance's art, or the color of its fill (or its stroke, when the stroke was hit or there is no /// fill) there. Images, symbols and patterns are looked up in the sampled document. @@ -464,7 +487,7 @@ fn art_color_at(s: &mut Sampler, levels: &mut [Option], art: impl Into scratch.insert(Some(layer), usize::MAX, n).ok()?; } let opts = HitOptions { scope: None, tol: 0.0, outline: false, ..s.opts }; - color_under(s, scratch, deeper, p, opts) + color_under(s, scratch, deeper, p, opts).map(|(c, _)| c) } /// Gives `n` and everything in it new ids from `doc` (pattern instances all have id 0). @@ -524,72 +547,50 @@ impl Tool for EyedropperTool { if ev.kind != PointerKind::Down { return vec![]; } - if let Some(binding) = &self.image_trace_ignore_color { - // The panel knows whether this hits an opaque source pixel. It clears the binding - // and restores the previous tool only after accepting a color, not on a miss. - return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] }))]; + let Some(click) = self.click(cx, ev.pos, ev.mods) else { return vec![] }; + match click { + Click::ImageTrace(binding) => { + // The panel knows whether this hits an opaque source pixel. It clears the binding + // and restores the previous tool only after accepting a color, not on a miss. + vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] }))] + } + Click::BrushKeyColor(c, _) => { + let back = self.stop.take().unwrap_or_else(|| "selection".to_string()); + self.brush_key_color = false; + vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)] + } + Click::BackToBucket => { + self.stop = None; + vec![Action::SwitchTool("livePaintBucket".into())] + } + Click::MeshPoints(id, points, color) => { + let params = json!({ "id": id.0, "points": points, "color": color_json(&color), "keepModel": true }); + vec![Action::Exec("object.mesh.setPointColor".into(), params)] + } + Click::CopyFrom(src, how) => { + let params = match how { + Some(how) => json!({ "source": src.0, how: true }), + None => json!({ "source": src.0 }), + }; + vec![Action::Exec("appearance.copyFrom".into(), params)] + } + Click::Sample { color, meshes, stop, .. } => { + let color = color_json(&color); + if !meshes.is_empty() { + let ids: Vec = meshes.iter().map(|id| id.0).collect(); + return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stroke": false, "ids": ids }))]; + } + let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] }; + self.stop = None; + vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back)] + } } - let opts = sample_options(cx); - if self.brush_key_color { - let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; - let back = self.stop.clone().unwrap_or_else(|| "selection".to_string()); - self.brush_key_color = false; - self.stop = None; - return vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)]; - } - // A pick for a stop of the Live Paint Bucket's gradient (the default paint's) ends without - // sampling once that stop is no longer selected (a Cmd-click selected another object) or no - // longer there (another paint was chosen): the click switches back. - let bucket_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; - let bucket_stop = cx.gradient_stop.filter(|i| matches!(bucket_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); - if self.stop.as_deref() == Some("livePaintBucket") && bucket_stop.is_none() { - self.stop = None; - return vec![Action::SwitchTool("livePaintBucket".into())]; - } - let stop = self.stop.as_ref().zip(cx.gradient_stop); - // A plain click on a selected gradient mesh gives the fill color to the point there, else - // to the four points of the patch there. - if stop.is_none() - && !ev.mods.alt - && !ev.mods.shift - && let Paint::Solid { color, .. } = &cx.paint.fill - && let Some((id, points)) = selected_mesh_points(cx, ev.pos) - { - let params = json!({ "id": id.0, "points": points, "color": color_json(color), "keepModel": true }); - return vec![Action::Exec("object.mesh.setPointColor".into(), params)]; - } - // Reading a source is independent of its editability. Only Alt's reverse operation - // writes to the clicked object; Shift+Alt appends its appearance to the selection. - let source = if ev.mods.alt && !ev.mods.shift && stop.is_none() { - hit_test(cx.doc, ev.pos, opts).map(|h| (paint_owner(cx.doc, h.leaf), h.kind)) - } else { - sample_source(cx, ev.pos) - }; - let Some((src, _)) = source else { return vec![] }; - let Some(n) = cx.doc.node(src) else { return vec![] }; - if ev.mods.alt && stop.is_none() { - let how = if ev.mods.shift { "append" } else { "reverse" }; - return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0, how: true }))]; - } - let image = matches!(n.kind, NodeKind::Image(_)); - // Picked mesh points take only a color sampled from other art or an image: the sample goes - // to them as a fill, and to nothing else that is selected. A click on a mesh with picked - // points is handled as before. - let meshes = if stop.is_none() { picked_meshes(cx, &self.mesh_points) } else { vec![] }; - let meshes = if meshes.contains(&src) { vec![] } else { meshes }; - if !(ev.mods.shift || stop.is_some() || image || !meshes.is_empty()) { - return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0 }))]; - } - let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; - let color = color_json(&c); - if !meshes.is_empty() { - let ids: Vec = meshes.iter().map(|id| id.0).collect(); - return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stroke": false, "ids": ids }))]; - } - let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] }; - let out = vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back.clone())]; - self.stop = None; - out + } + + /// The object a click there samples, recolors or copies attributes to, as [`Self::click`] + /// finds it. + fn hover_object(&self, cx: &ToolContext, p: Point, mods: Mods) -> Option { + self.click(cx, p, mods)?.object() } /// Expose a transient text range alongside gradient-stop and brush-key sampling state. @@ -684,11 +685,92 @@ impl Tool for EyedropperTool { } } +/// What a click with the Eyedropper does, which [`EyedropperTool::pointer`] carries out. +enum Click { + /// Image Trace's Ignore Color pick: the panel samples the image with this binding. + ImageTrace(Value), + /// Brush Options › Key Color: this color, sampled from this object. + BrushKeyColor(Color, NodeId), + /// A pick for a Live Paint Bucket stop that is no longer selected switches back unsampled. + BackToBucket, + /// The fill color goes to these points of this selected gradient mesh. + MeshPoints(NodeId, Vec, Color), + /// `appearance.copyFrom` this source, with `reverse` or `append` or neither. + CopyFrom(NodeId, Option<&'static str>), + /// This color, sampled from `source`, goes to the picked points of `meshes`, else to the + /// gradient stop of `stop` (the tool to switch back to and the stop), else to the active fill + /// or stroke. + Sample { color: Color, source: NodeId, meshes: Vec, stop: Option<(String, usize)> }, +} + +impl Click { + /// The object of the document the click reads from or writes to. + fn object(&self) -> Option { + match self { + Click::ImageTrace(_) | Click::BackToBucket => None, + Click::BrushKeyColor(_, id) | Click::MeshPoints(id, ..) | Click::CopyFrom(id, _) | Click::Sample { source: id, .. } => Some(*id), + } + } +} + impl EyedropperTool { /// Is a gradient stop, Brush Key Color or Image Trace Ignore Color pick armed? fn picking(&self) -> bool { self.stop.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some() } + + /// What a click at `p` with `mods` does, or None when it does nothing. + fn click(&self, cx: &ToolContext, p: Point, mods: Mods) -> Option { + if let Some(binding) = &self.image_trace_ignore_color { + return Some(Click::ImageTrace(binding.clone())); + } + if self.brush_key_color { + let (c, source) = sample_at(cx, p)?; + return Some(Click::BrushKeyColor(c, source)); + } + // A pick for a stop of the Live Paint Bucket's gradient (the default paint's) ends without + // sampling once that stop is no longer selected (a Cmd-click selected another object) or no + // longer there (another paint was chosen): the click switches back. + let bucket_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; + let bucket_stop = cx.gradient_stop.filter(|i| matches!(bucket_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); + if self.stop.as_deref() == Some("livePaintBucket") && bucket_stop.is_none() { + return Some(Click::BackToBucket); + } + let stop = self.stop.clone().zip(cx.gradient_stop); + // A plain click on a selected gradient mesh gives the fill color to the point there, else + // to the four points of the patch there. + if stop.is_none() + && !mods.alt + && !mods.shift + && let Paint::Solid { color, .. } = &cx.paint.fill + && let Some((id, points)) = selected_mesh_points(cx, p) + { + return Some(Click::MeshPoints(id, points, *color)); + } + // Reading a source is independent of its editability. Only Alt's reverse operation + // writes to the clicked object; Shift+Alt appends its appearance to the selection. + let source = if mods.alt && !mods.shift && stop.is_none() { + hit_test(cx.doc, p, sample_options(cx)).map(|h| (paint_owner(cx.doc, h.leaf), h.kind)) + } else { + sample_source(cx, p) + }; + let (src, _) = source?; + let n = cx.doc.node(src)?; + if mods.alt && stop.is_none() { + return Some(Click::CopyFrom(src, Some(if mods.shift { "append" } else { "reverse" }))); + } + let image = matches!(n.kind, NodeKind::Image(_)); + // Picked mesh points take only a color sampled from other art or an image: the sample goes + // to them as a fill, and to nothing else that is selected. A click on a mesh with picked + // points is handled as before. + let meshes = if stop.is_none() { picked_meshes(cx, &self.mesh_points) } else { vec![] }; + let meshes = if meshes.contains(&src) { vec![] } else { meshes }; + if !(mods.shift || stop.is_some() || image || !meshes.is_empty()) { + return Some(Click::CopyFrom(src, None)); + } + let (color, source) = sample_at(cx, p)?; + Some(Click::Sample { color, source, meshes, stop }) + } } #[cfg(test)] @@ -1824,7 +1906,7 @@ mod tests { let opts = sample_options(&cx); let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 1_000, exhausted: false, patterns: 0 }; let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); - assert_eq!(color_under(&mut s, &d, &mut levels, Point::new(150.0, 150.0), opts).map(|c| c.to_hex()), None); + assert_eq!(color_under(&mut s, &d, &mut levels, Point::new(150.0, 150.0), opts).map(|(c, _)| c.to_hex()), None); assert!(s.exhausted); } @@ -1917,6 +1999,157 @@ mod tests { assert_eq!(sampled_hex(&below), "#00ff00"); } + /// The object the hover names for a Shift-click is the one whose color the click samples: the + /// blend where a step is drawn, and the rectangle below it in a gap between the steps. Away + /// from all art it names none. + #[test] + fn shift_hover_names_the_object_the_sample_comes_from() { + use vectorcraft_doc::live::{BlendSpacing, BlendSpec}; + use vectorcraft_geom::Rect; + let d = doc_with_live_over_green(|d| { + let red = solid_rect(d, Rect::new(300.0, 300.0, 320.0, 320.0), Color::rgb(1.0, 0.0, 0.0)); + let blue = solid_rect(d, Rect::new(400.0, 300.0, 420.0, 320.0), Color::rgb(0.0, 0.0, 1.0)); + let spec = BlendSpec { spacing: BlendSpacing::Steps(1), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Blend { children: vec![std::sync::Arc::new(red), std::sync::Arc::new(blue)], spec: Box::new(spec) }) + }); + let ids: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + let [.., green, blend] = ids[..] else { panic!("two objects over the rectangle expected") }; + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let t = EyedropperTool::default(); + let names = |x: f64, y: f64| t.hover_object(&cx(&d, &s, &p), Point::new(x, y), shift); + assert_eq!(names(360.0, 310.0), Some(blend), "a blend step"); + assert_eq!(names(335.0, 310.0), Some(green), "a gap between the steps"); + assert_eq!(names(480.0, 480.0), None, "no art"); + } + + /// A blend's steps count as work before it is evaluated: the steps of every blend it holds + /// are counted, and with less work left than that the sample gives no color and the blend is + /// not evaluated. + #[test] + fn blend_steps_count_before_the_blend_is_evaluated() { + use vectorcraft_doc::Document; + use vectorcraft_doc::blend::blend_steps_made; + use vectorcraft_doc::live::{BlendSpacing, BlendSpec}; + use vectorcraft_geom::Rect; + let blend = |d: &mut Document, steps: u32| { + let red = solid_rect(d, Rect::new(300.0, 300.0, 320.0, 320.0), Color::rgb(1.0, 0.0, 0.0)); + let blue = solid_rect(d, Rect::new(400.0, 300.0, 420.0, 320.0), Color::rgb(0.0, 0.0, 1.0)); + let spec = BlendSpec { spacing: BlendSpacing::Steps(steps), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Blend { children: vec![std::sync::Arc::new(red), std::sync::Arc::new(blue)], spec: Box::new(spec) }) + }; + let mut scratch = Document::new(500.0, 500.0); + let (big, small) = (blend(&mut scratch, 1000), blend(&mut scratch, 3)); + let rect = solid_rect(&mut scratch, Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb(0.0, 1.0, 0.0)); + assert_eq!(blend_steps_made(&big), 1000); + assert_eq!(blend_steps_made(&rect), 0); + let group = + Node::new(scratch.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(big), std::sync::Arc::new(small)], clip: false }); + assert_eq!(blend_steps_made(&group), 1003, "every blend in the group"); + + let d = doc_with_live_over_green(|d| blend(d, 1000)); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let opts = sample_options(&cx); + let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); + let at = Point::new(360.0, 310.0); + let evaluated = || EXPANSIONS.with(std::cell::Cell::get); + let before = evaluated(); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 900, exhausted: false, patterns: 0 }; + assert_eq!(color_under(&mut s, &d, &mut levels, at, opts).map(|(c, _)| c.to_hex()), None); + assert!(s.exhausted, "less work left than the blend's 1,000 steps"); + assert_eq!(evaluated(), before, "the blend is not evaluated"); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: MAX_WORK, exhausted: false, patterns: 0 }; + assert!(color_under(&mut s, &d, &mut levels, at, opts).is_some(), "a step is drawn at the point"); + assert!(evaluated() > before, "with enough work the blend is evaluated"); + } + + /// Each step of a blend whose keys are blends is a copy of one of them, so the steps it makes + /// in all count before it is evaluated: an outer blend of 20 steps between two blends of 100 + /// steps makes more than 2,000, though its blends have 220 steps between their own keys. + #[test] + fn steps_that_copy_a_nested_blend_count_before_it_is_evaluated() { + use vectorcraft_doc::Document; + use vectorcraft_doc::live::{BlendSpacing, BlendSpec}; + use vectorcraft_geom::Rect; + let blend = |d: &mut Document, keys: Vec, steps: u32| { + let spec = BlendSpec { spacing: BlendSpacing::Steps(steps), ..Default::default() }; + Node::new(d.alloc_id(), NodeKind::Blend { children: keys.into_iter().map(std::sync::Arc::new).collect(), spec: Box::new(spec) }) + }; + let inner = |d: &mut Document, y: f64| { + let red = solid_rect(d, Rect::new(300.0, y, 320.0, y + 10.0), Color::rgb(1.0, 0.0, 0.0)); + let blue = solid_rect(d, Rect::new(400.0, y, 420.0, y + 10.0), Color::rgb(0.0, 0.0, 1.0)); + blend(d, vec![red, blue], 100) + }; + let d = doc_with_live_over_green(|d| { + let (a, b) = (inner(d, 300.0), inner(d, 330.0)); + blend(d, vec![a, b], 20) + }); + let outer = d.layers[0].children().unwrap().last().unwrap(); + assert!(vectorcraft_doc::blend::blend_steps_made(outer) > 2_000, "the copies' steps count"); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let opts = sample_options(&cx); + let mut levels: Vec> = (0..MAX_NESTING).map(|_| None).collect(); + let at = Point::new(310.0, 305.0); + let evaluated = || EXPANSIONS.with(std::cell::Cell::get); + let before = evaluated(); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: 1_000, exhausted: false, patterns: 0 }; + assert_eq!(color_under(&mut s, &d, &mut levels, at, opts).map(|(c, _)| c.to_hex()), None); + assert!(s.exhausted, "less work left than the steps the outer blend makes"); + assert_eq!(evaluated(), before, "the outer blend is not evaluated"); + let mut s = Sampler { doc: &d, opts, raster_sample: cx.raster_sample, symbol_nodes: 0, work: MAX_WORK, exhausted: false, patterns: 0 }; + assert!(color_under(&mut s, &d, &mut levels, at, opts).is_some(), "a key is drawn at the point"); + assert!(evaluated() > before, "with enough work the outer blend is evaluated"); + } + + /// For a Shift-click on an envelope, the hover names the envelope where its distorted contents + /// are drawn, and the rectangle below where they leave the point empty. + #[test] + fn shift_hover_names_the_envelope_where_its_art_is_drawn() { + use vectorcraft_geom::{Affine, Rect}; + let d = doc_with_live_over_green(|d| { + let red = solid_rect(d, Rect::new(300.0, 300.0, 420.0, 320.0), Color::rgb(1.0, 0.0, 0.0)); + let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + let content = vec![std::sync::Arc::new(red)]; + let options = Default::default(); + Node::new( + d.alloc_id(), + NodeKind::Envelope { content, kind: Box::new(kind), fidelity: 50.0, editing: false, options, frame: Box::new(Affine::IDENTITY) }, + ) + }); + let ids: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + let [.., green, envelope] = ids[..] else { panic!("two objects over the rectangle expected") }; + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let t = EyedropperTool::default(); + let names = |x: f64, y: f64| t.hover_object(&cx(&d, &s, &p), Point::new(x, y), shift); + assert_eq!(names(360.0, 310.0), Some(envelope), "the distorted contents"); + assert_eq!(names(360.0, 332.0), Some(green), "a point the contents leave empty"); + } + + /// A plain click on a selected gradient mesh recolors its points, and the hover names that + /// mesh; Image Trace's Ignore Color pick, which the panel samples, names nothing. + #[test] + fn hover_names_the_selected_mesh_a_click_recolors() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mesh = d.alloc_id(); + let grid = GradientMesh::from_surface(1, 1, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(mesh, NodeKind::Mesh(grid))).unwrap(); + let p = paint(); + let mut s = Selection::default(); + s.set([mesh]); + let mut t = EyedropperTool::default(); + let at = Point::new(150.0, 150.0); + let a = t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(matches!(a.first(), Some(Action::Exec(id, _)) if id == "object.mesh.setPointColor"), "{a:?}"); + assert_eq!(t.hover_object(&cx(&d, &s, &p), at, Mods::default()), Some(mesh)); + t.set_option("imageTraceIgnoreColor", &json!({"binding": 1})); + assert_eq!(t.hover_object(&cx(&d, &s, &p), at, Mods::default()), None); + } + /// A blend of two instances of one symbol draws its steps as instances too: Shift-click on a /// step samples the symbol's art there, and where that art leaves the point empty, what lies /// below. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index dab6a5e8e4..299f4c22d5 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -145,6 +145,7 @@ impl VectorcraftApp { plugin_keys: Default::default(), placed_keys: Default::default(), view_moved: None, + hover_object: None, grab: None, carry_target: None, last_drag: None, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index c563d511d3..90875851d4 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -91,6 +91,10 @@ pub struct CanvasCache { /// The view the canvas last drew and when it last changed (egui's input time): while it moves, /// the canvas doesn't hit-test the art under the pointer ([`canvas::hover_wait`], #2452). pub view_moved: Option<(canvas::ViewKey, f64)>, + /// The object the Eyedropper's click at the pointer would act on, which Object Highlighting + /// outlines, with what it was found for: finding it again, which can sample a color, waits + /// until one of those changes. + pub hover_object: Option<(canvas::HoverObjectKey, Option)>, /// Where the press of the gesture running on the canvas landed, in document points: a move carried out of the /// canvas drops its art there relative to the pointer (`canvas::drops`). pub grab: Option, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b097971511..596cb119f0 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -50,6 +50,7 @@ pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, pane, tile, tiled_area}; pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; pub(crate) use rulers::{general_lengths, stroke_lengths}; +pub use selection::HoverObjectKey; pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, has_colors, is_task_bar_action, read_hidden_task_bar_actions}; pub use tool_adapter::{apply_requests, dispatch, mods}; pub(crate) use tool_adapter::{busy_tool, in_gesture, pose_on_page, tool_enter}; diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 33d17fc6fd..2018e50323 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -18,8 +18,9 @@ use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintU use craft::ui::style::{ComponentStyle, DataColor, StyleCx}; use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2}; use vectorcraft_doc::{NodeId, NodeKind}; -use vectorcraft_engine::{DocState, Prefs}; +use vectorcraft_engine::{DocState, Prefs, ViewInfo}; use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point}; +use vectorcraft_tools::Mods; use super::cursor::ViewKey; use super::outline::{c32, node_outline, selection_hit_at, too_many_anchors, walk_drawn}; @@ -323,7 +324,8 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin } /// The outline of the object under the pointer at document point `at`, at view `zoom`, for Smart Guides › Object -/// Highlighting: the object a click of the selection tools would pick, unless it is selected or has too many points. +/// Highlighting: the object a click of the selection tools would pick, unless the click keeps the selection (the +/// object, or with the Selection tool selected art inside it, is selected) or the object has too many points. /// None while the view moves (`still` false), under Snap to Grid or Pixel Preview, with a tool that is busy or is not /// a selection tool, and with the preference off. `tool` is the tool whose marks show ([`super::shown_tool`]): while /// Cmd is held, the selection tool a press borrows. @@ -337,13 +339,139 @@ pub(super) fn hover(app: &VectorcraftApp, st: &DocState, tool: &str, at: Point, } let hit = selection_hit_at(app, at, zoom)?; let id = if tool == "selection" { hit.top_object(st.isolation) } else { hit.leaf }; - if st.selection.contains(id) { + // A Selection tool press on selected art inside `id`, such as a group member picked with Group Selection, keeps + // the selection and selects nothing new. + let kept = if tool == "selection" { + vectorcraft_tools::select::selected_under_in(&st.doc, &st.selection, &hit, id).is_some() + } else { + st.selection.contains(id) + }; + if kept { return None; } + outline_of(st, id) +} + +/// The hover outline of `id` in its layer colour, unless it has too many points. +fn outline_of(st: &DocState, id: NodeId) -> Option { let node = st.doc.node(id).filter(|n| !too_many_anchors([*n]))?; Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes()), color: c32(st.doc.layer_color(id)) }) } +/// The hover outline the canvas shows at document point `at` with the keys `held`: none while Space lends the view +/// tools, since a press then pans the view; with the Eyedropper, the object its click there acts on +/// ([`eyedropper_hover`]); else the selection tools' outline ([`hover`]). `tool`, `zoom` and `still` are as [`hover`] +/// takes them. +pub(super) fn hover_target(app: &mut VectorcraftApp, tool: &str, at: Point, held: Mods, zoom: f64, still: bool) -> Option { + if held.space && (held.cmd || !app.session.tool_wants_text()) { + return None; + } + if tool == "eyedropper" { + return eyedropper_hover(app, at, held, still); + } + let st = app.session.active()?; + hover(app, st, tool, at, zoom, still) +} + +/// The outline of the object the Eyedropper's click at `at` with `mods` would act on +/// ([`vectorcraft_engine::Session::hover_object`]), for Smart Guides › Object Highlighting: the source of a plain +/// click (locked and template art included), the selected mesh it recolors, with Alt the object that gets the +/// selection's attributes, and with Shift the object the color comes from. A selected object is outlined too, since a +/// click on it still acts on it. None under the conditions [`hover`] names. +pub(super) fn eyedropper_hover(app: &mut VectorcraftApp, at: Point, mods: Mods, still: bool) -> Option { + let (view, prefs) = (&app.ui.view, &app.session.prefs); + if !still || !view.smart_guides || !prefs.object_highlighting || view.snap_to_grid || view.pixel_preview || app.session.tool_busy() { + return None; + } + let info = app.view_info(); + let id = eyedropper_hover_object(app, at, mods, info)?; + outline_of(app.session.active()?, id) +} + +/// What the Eyedropper's hover object depends on: the point, the keys held, the document as it is, the selection and +/// isolation, the tool's options (an armed pick), the paint defaults and the selected gradient stop, the selection +/// tolerance, Eyedropper Options (the raster sample size), whether guides show and are locked, and the view's zoom and +/// Outline mode: everything the tool's context gives a click that can change what it acts on. +#[derive(Clone, Debug, PartialEq)] +pub struct HoverObjectKey { + at: Point, + mods: Mods, + doc: (u64, u64), + selection: vectorcraft_doc::Selection, + isolation: Option, + options: serde_json::Value, + paint: vectorcraft_tools::PaintDefaults, + fill_active: bool, + stop: Option, + tolerance: f64, + eyedropper: vectorcraft_engine::EyedropperOptions, + guides: (bool, bool), + zoom: f64, + outline: bool, +} + +/// [`vectorcraft_engine::Session::hover_object`] at `at`, found again only when its [`HoverObjectKey`] changes: over +/// an image, or with Shift held, finding it samples a color. The cached key is compared field by field, the cheap +/// fields first, and the key is copied only when it changed. +fn eyedropper_hover_object(app: &mut VectorcraftApp, at: Point, mods: Mods, view: ViewInfo) -> Option { + let st = app.session.active()?; + let s = &app.session; + let cached = app.canvas.hover_object.as_ref().filter(|(k, _)| { + let HoverObjectKey { + at: k_at, + mods: k_mods, + doc, + selection, + isolation, + options, + paint, + fill_active, + stop, + tolerance, + eyedropper, + guides, + zoom, + outline, + } = k; + *k_at == at + && *k_mods == mods + && *doc == (st.uid, st.revision) + && *isolation == st.isolation + && *fill_active == s.fill_active + && *stop == s.selected_stop() + && *tolerance == s.prefs.selection_tolerance + && *eyedropper == s.prefs.eyedropper + && *guides == (view.guides, s.guides_locked()) + && *zoom == view.zoom + && *outline == view.outline + && *selection == st.selection + && *paint == s.paint + && *options == s.tool_options() + }); + if let Some((_, id)) = cached { + return *id; + } + let key = HoverObjectKey { + at, + mods, + doc: (st.uid, st.revision), + selection: st.selection.clone(), + isolation: st.isolation, + options: app.session.tool_options(), + paint: app.session.paint.clone(), + fill_active: app.session.fill_active, + stop: app.session.selected_stop(), + tolerance: app.session.prefs.selection_tolerance, + eyedropper: app.session.prefs.eyedropper, + guides: (view.guides, app.session.guides_locked()), + zoom: view.zoom, + outline: view.outline, + }; + let id = app.session.hover_object(at, mods, view); + app.canvas.hover_object = Some((key, id)); + id +} + /// The dots of the selection: point type's origin, the centre of each object that shows it, and the key anchor. pub(super) fn dots(app: &VectorcraftApp, st: &DocState) -> Dots { let mut out = Dots { grow: grow(&app.session.prefs), ..Dots::default() }; @@ -468,11 +596,11 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp }; // While Cmd is held, the marks of the selection tool a press borrows. let tool = super::shown_tool(app, ui.ctx()); - let Some(st) = app.session.active() else { return }; let hovered = match (kind, app.hover_doc) { (BodyKind::Pane, _) | (_, None) => None, - (_, Some(at)) => hover(app, st, tool, at, space.view.zoom, still), + (_, Some(at)) => hover_target(app, tool, at, super::held_mods(ui.ctx()), space.view.zoom, still), }; + let Some(st) = app.session.active() else { return }; if let Some(h) = hovered { HoverOutline::new("Object highlight", Some(HoverShape::Path(h.path))).color(DataColor::new(h.color)).show_at(ui, rect); } diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index ed590c2df6..fdca4b2a9e 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -331,6 +331,163 @@ fn hover_outlines_the_object_under_the_pointer_unless_something_hides_it() { assert!(!hovered(&app, true), "a tool that is not a selection tool"); } +fn held(shift: bool, alt: bool, cmd: bool, space: bool) -> Mods { + Mods { shift, alt, cmd, space, ..Mods::default() } +} + +const NO_KEYS: Mods = Mods { shift: false, alt: false, cmd: false, ctrl: false, space: false }; + +/// The box of the hover outline at `at` with `held` keys down, as the canvas finds it: the tool whose marks show +/// (with Cmd, the selection tool a press there borrows), then that tool's outline. +fn outline_box(app: &mut VectorcraftApp, at: Point, held: Mods) -> Option { + let view = app.view_info(); + let tool = app.session.hover_tool_at(Some(at), &held, view); + hover_target(app, tool, at, held, 1.0, true).map(|h| h.path.bounding_box()) +} + +/// Whether two boxes agree to within a point. +fn same_box(a: Option, b: vectorcraft_geom::Rect) -> bool { + a.is_some_and(|a| (a.x0 - b.x0).abs() < 1.0 && (a.y0 - b.y0).abs() < 1.0 && (a.x1 - b.x1).abs() < 1.0 && (a.y1 - b.y1).abs() < 1.0) +} + +fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> vectorcraft_geom::Rect { + vectorcraft_geom::Rect::new(x0, y0, x1, y1) +} + +/// A rectangle filled with `color`, its id. +fn filled(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64, color: &str) -> NodeId { + let id = id_of(&app.run("shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h})).unwrap()); + app.run("paint.setFill", json!({"ids": [id.0], "color": color})).unwrap(); + id +} + +/// With the Eyedropper, Smart Guides › Object Highlighting outlines the object under the pointer as the selection +/// tools do, and nothing over empty canvas. While Space is held a press pans the view, so no tool outlines anything. +#[test] +fn eyedropper_hover_outlines_the_object_under_the_pointer() { + let mut app = hover_scene(); + app.select_tool("eyedropper"); + let over = Point::new(150.0, 150.0); + assert!(same_box(outline_box(&mut app, over, NO_KEYS), rect(100.0, 100.0, 200.0, 200.0)), "the rectangle under the pointer"); + assert!(outline_box(&mut app, Point::new(300.0, 50.0), NO_KEYS).is_none(), "nothing over empty canvas"); + for tool in ["eyedropper", "selection"] { + app.select_tool(tool); + assert!(outline_box(&mut app, over, NO_KEYS).is_some(), "{tool}: outlined"); + assert!(outline_box(&mut app, over, held(false, false, false, true)).is_none(), "{tool}: Space held"); + assert!(outline_box(&mut app, over, NO_KEYS).is_some(), "{tool}: Space let go"); + } +} + +/// The Eyedropper outlines a selected object too, since its click still acts on it. With Cmd held, a click selects +/// with the selection tool lent to it, so the outline is that tool's: none on a selected object, and the object under +/// the pointer otherwise. Hiding the object under the pointer, or arming Image Trace's Ignore Color pick (which acts on +/// no object), removes the outline without the pointer moving. +#[test] +fn eyedropper_hover_outline_follows_the_selection_cmd_and_the_document() { + let mut app = blank(); + let id = id_of(&app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()); + app.select_tool("eyedropper"); + let (over, square) = (Point::new(150.0, 150.0), rect(100.0, 100.0, 200.0, 200.0)); + assert!(app.session.active().unwrap().selection.contains(id)); + assert!(same_box(outline_box(&mut app, over, NO_KEYS), square), "a selected object"); + let cmd = held(false, false, true, false); + assert!(outline_box(&mut app, over, cmd).is_none(), "Cmd over a selected object"); + app.run("select.none", json!({})).unwrap(); + assert!(same_box(outline_box(&mut app, over, cmd), square), "Cmd over an unselected object"); + assert!(outline_box(&mut app, over, NO_KEYS).is_some(), "Cmd let go"); + app.session.set_tool_option("imageTraceIgnoreColor", &json!({"binding": 1})); + assert!(outline_box(&mut app, over, NO_KEYS).is_none(), "an armed Ignore Color pick"); + app.session.set_tool_option("imageTraceIgnoreColor", &serde_json::Value::Null); + assert!(outline_box(&mut app, over, NO_KEYS).is_some(), "the pick disarmed"); + app.run("object.hide", json!({"ids": [id.0]})).unwrap(); + assert!(outline_box(&mut app, over, NO_KEYS).is_none(), "hidden art"); +} + +/// With a group member selected (as Group Selection leaves it), the Selection tool outlines nothing over that member, +/// where a press keeps the selection, and the group over its other member, where a press selects the group. +#[test] +fn selection_hover_outline_skips_a_selected_group_member() { + let mut app = blank(); + let a = id_of(&app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()); + let b = id_of(&app.run("shape.rectangle", json!({"x": 200, "y": 100, "width": 50, "height": 50})).unwrap()); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + app.select_tool("selection"); + assert!(outline_box(&mut app, Point::new(125.0, 125.0), NO_KEYS).is_none(), "the selected member"); + let other = outline_box(&mut app, Point::new(225.0, 125.0), NO_KEYS); + assert!(same_box(other, rect(100.0, 100.0, 250.0, 150.0)), "the other member: {other:?}"); +} + +/// For a Shift-click the Eyedropper outlines the object whose color the click samples: the blend where one of its +/// steps is drawn, and the rectangle below it in a gap between the steps. +#[test] +fn eyedropper_shift_hover_outlines_the_object_sampled() { + let mut app = blank(); + filled(&mut app, 20.0, 50.0, 360.0, 150.0, "#00ff00"); + let a = filled(&mut app, 100.0, 100.0, 20.0, 20.0, "#ff0000"); + let b = filled(&mut app, 200.0, 100.0, 20.0, 20.0, "#0000ff"); + app.run("object.blend.make", json!({"ids": [a.0, b.0], "steps": 1})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.select_tool("eyedropper"); + let shift = held(true, false, false, false); + // One step, halfway: (150, 100) to (170, 120). + let step = outline_box(&mut app, Point::new(160.0, 110.0), shift); + assert!(same_box(step, rect(100.0, 100.0, 220.0, 120.0)), "a blend step: {step:?}"); + let gap = outline_box(&mut app, Point::new(135.0, 110.0), shift); + assert!(same_box(gap, rect(20.0, 50.0, 380.0, 200.0)), "a gap between the steps: {gap:?}"); +} + +/// The Eyedropper's hover outline follows Smart Guides › Object Highlighting. +#[test] +fn eyedropper_hover_outline_follows_object_highlighting() { + let mut app = hover_scene(); + app.select_tool("eyedropper"); + let over = Point::new(150.0, 150.0); + app.run("prefs.set", json!({"key": "objectHighlighting", "value": false})).unwrap(); + assert!(outline_box(&mut app, over, NO_KEYS).is_none(), "the option off"); + app.run("prefs.set", json!({"key": "objectHighlighting", "value": true})).unwrap(); + assert!(outline_box(&mut app, over, NO_KEYS).is_some(), "the option on"); +} + +/// The Eyedropper outlines the object its click there then acts on: the front object a plain click copies attributes +/// from, a locked one included (the Eyedropper reads locked art), and with Alt the unlocked object below it that an +/// Alt-click gives the selection's attributes to. +#[test] +fn eyedropper_hover_outline_is_the_object_the_click_acts_on() { + let mut app = blank(); + let back = filled(&mut app, 100.0, 100.0, 100.0, 100.0, "#0000ff"); + let front = filled(&mut app, 150.0, 150.0, 100.0, 100.0, "#ff0000"); + let target = filled(&mut app, 20.0, 20.0, 40.0, 40.0, "#00ff00"); + app.run("select.set", json!({"ids": [target.0]})).unwrap(); + app.select_tool("eyedropper"); + let fill = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().appearance.fill_paint(); + let click = |app: &mut VectorcraftApp, at: Point, mods: Mods| { + let view = app.view_info(); + for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] { + let ev = vectorcraft_tools::PointerEvent { mods, ..vectorcraft_tools::PointerEvent::new(kind, at.x, at.y) }; + crate::canvas::dispatch(app, &ev, view); + } + }; + let over = Point::new(175.0, 175.0); + let alt = held(false, true, false, false); + let shown = outline_box(&mut app, over, NO_KEYS); + assert!(same_box(shown, rect(150.0, 150.0, 250.0, 250.0)), "the front rectangle: {shown:?}"); + click(&mut app, over, NO_KEYS); + assert_eq!(fill(&app, target), fill(&app, front), "the click copied the outlined rectangle's fill"); + + app.run("object.lock", json!({"ids": [front.0]})).unwrap(); + app.run("select.set", json!({"ids": [target.0]})).unwrap(); + app.run("paint.setFill", json!({"ids": [target.0], "color": "#00ff00"})).unwrap(); + let shown = outline_box(&mut app, over, NO_KEYS); + assert!(same_box(shown, rect(150.0, 150.0, 250.0, 250.0)), "the locked front rectangle is still the source: {shown:?}"); + let shown = outline_box(&mut app, over, alt); + assert!(same_box(shown, rect(100.0, 100.0, 200.0, 200.0)), "with Alt, the unlocked rectangle below: {shown:?}"); + click(&mut app, over, alt); + assert_eq!(fill(&app, back), fill(&app, target), "the Alt-click gave the outlined rectangle the selection's fill"); + assert_ne!(fill(&app, front), fill(&app, target)); +} + #[test] fn a_group_of_too_many_paths_has_no_hover_outline_and_a_key_outline_of_its_bounds() { let mut app = blank(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3d8a4b58ba..06f07ff7b5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2072,6 +2072,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pasting into hex color fields:** in the hex fields of the Color Picker, Swatch Options, Recolor Artwork, the Color panel, Document Setup, Duotone, Color Themes and Perspective Grid, a click or keyboard focus selects the digits. A pasted code of six digits, with or without `#`, replaces them wherever the caret is. A pasted code of three digits also replaces them, unless the paste holds only those digits and exactly three digits stay; those digits then edit the text in place. A press on another field commits the text as Tab and Enter do. As VectorCraft's own rule, a paste that is not a color leaves the field as it was. Tests: `a_hex_code_pasted_into_the_hex_field_replaces_its_digits` in `crates/ui-egui/src/dialogs/tests.rs`, `define_grid_takes_a_three_digit_color` in `crates/ui-egui/src/dialogs/tests_perspective.rs` and `a_paste_into_a_hex_field_replaces_or_edits_its_digits` in `crates/ui-egui/src/tests/numfields.rs`. - **Color Picker layout (#2008):** a centered draggable header, equal-width actions above aligned HSB/RGB/Hex and Lab/CMYK fields, compact field and slider, and warnings below the preview. No horizontal scrolling; narrow windows stack the sections with vertical scrolling. Tests in `dialogs/color_picker.rs` cover actual pointer/key input, typed values before OK/Enter, Cancel/Escape rollback, one Undo step, mode-size stability, warnings and layout at two UI scales. The screen sampler sits above the field and the upstream two-grid Tab order is retained. AccessKit regressions check the action names and each channel slider's displayed value, units and range. German and enlarged English UI renders were reviewed locally; no reference images are shipped. This is a layout improvement, with no change to scores or remaining-hour estimates. - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. + - **Eyedropper hover outline:** as VectorCraft's own behavior, with Smart Guides › Object Highlighting on, the Eyedropper outlines the object a click at the pointer would act on, in the selection tools' 1.5 px layer-color outline: the source a click copies from (locked and template art included), the selected gradient mesh a click recolors, the front editable object an Alt-click gives the selection's attributes to (the one below when locked art covers it), and for a Shift-click the object whose color is sampled (a blend or envelope where its art is drawn, the art below where it leaves a gap). A selected object is outlined too. With Cmd held, a click selects with the selection tool lent to the Eyedropper, and the outline is that tool's. The Selection tool's outline, lent or not, leaves out a group whose selected member is under the pointer, where a press keeps the selection. Finding a Shift-click's sample counts a blend's steps before the blend is evaluated. Empty canvas and hidden art show no outline, and with the Eyedropper or a selection tool, Space held for the view tools hides the outline. Tests: `eyedropper_hover_outlines_the_object_under_the_pointer`, `eyedropper_hover_outline_follows_object_highlighting`, `eyedropper_hover_outline_is_the_object_the_click_acts_on`, `eyedropper_hover_outline_follows_the_selection_cmd_and_the_document`, `selection_hover_outline_skips_a_selected_group_member` and `eyedropper_shift_hover_outlines_the_object_sampled` in `crates/ui-egui/src/canvas/tests.rs`, and `shift_hover_names_the_object_the_sample_comes_from`, `shift_hover_names_the_envelope_where_its_art_is_drawn`, `hover_names_the_selected_mesh_a_click_recolors` and `blend_steps_count_before_the_blend_is_evaluated` in `crates/tools/src/xform/eyedropper.rs`. - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C62 M19 Y0 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). The ICC profile written for it (embedded in exports) gives the paper as its media white point, and its colorimetric Lab → CMYK table is the inverse of its CMYK → Lab table, without black-point compensation; the perceptual and saturation tables keep compensation.