#8068: sample Image Trace ignore color from the source

This commit is contained in:
yoriswind committed 2026-11-16 17:07:34 -08:00
1 parent 9a01d266b0
commit fb333e757d
9 files changed
+736 -5

No files matched your search

+113 -1
View File
@@ -16,6 +16,9 @@
//!
//! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into
//! the open dialog (`brushKeyColor` UI request) and switches back.
//!
//! Image Trace's Ignore Color eyedropper passes its bound document point to the panel, which
//! samples the original image pixels; this tool changes neither paint nor selection.
use std::collections::HashSet;
@@ -28,7 +31,7 @@ use vectorcraft_geom::{Affine, Point, Rect};
use super::paint_owner;
use crate::params::color_json;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
#[derive(Default)]
pub struct EyedropperTool {
@@ -38,6 +41,8 @@ pub struct EyedropperTool {
text_selection: crate::text::TypeTool,
/// Brush Options › Key Color (Hue Shift): sample into the dialog, then [`Self::stop`].
brush_key_color: bool,
/// Image Trace > Ignore Color: the panel's opaque document/object/revision binding.
image_trace_ignore_color: Option<Value>,
}
/// The colour of `paint` at `p` (gradients are sampled along their vector, radial ones honouring
@@ -462,6 +467,13 @@ impl Tool for EyedropperTool {
if ev.kind != PointerKind::Down {
return vec![];
}
if let Some(binding) = self.image_trace_ignore_color.take() {
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
return vec![
Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] })),
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![] };
@@ -496,6 +508,23 @@ impl Tool for EyedropperTool {
out
}
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key != ToolKey::Escape {
return vec![];
}
let Some(binding) = self.image_trace_ignore_color.take() else { return vec![] };
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "cancel": true })), Action::SwitchTool(back)]
}
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
self.image_trace_ignore_color.is_some() && key == ToolKey::Escape
}
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
self.image_trace_ignore_color.is_some()
}
/// Expose a transient text range alongside gradient-stop and brush-key sampling state.
fn options(&self) -> Value {
let selected = self.text_selection.options();
@@ -503,6 +532,9 @@ impl Tool for EyedropperTool {
if let Some(o) = options.as_object_mut() {
o.insert("stop".into(), json!(self.stop));
o.insert("brushKeyColor".into(), json!(self.brush_key_color));
if let Some(binding) = &self.image_trace_ignore_color {
o.insert("imageTraceIgnoreColor".into(), binding.clone());
}
}
options
}
@@ -512,6 +544,7 @@ impl Tool for EyedropperTool {
match key {
"stop" => self.stop = value.as_str().map(str::to_string),
"brushKeyColor" => self.brush_key_color = value.as_bool().unwrap_or(false),
"imageTraceIgnoreColor" => self.image_trace_ignore_color = (!value.is_null()).then(|| value.clone()),
"textSelection" => self.text_selection.set_option(key, value),
_ => {}
}
@@ -636,6 +669,85 @@ mod tests {
assert_eq!(t.options(), json!({ "stop": null, "brushKeyColor": false }));
}
/// The panel samples the bound original raster, even on empty canvas or with modifiers held.
#[test]
fn image_trace_sampling_forwards_its_binding_and_document_point_once() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let binding = json!({"doc": 7, "target": id.0, "revision": 11});
for mods in [Mods::default(), Mods { alt: true, ..Default::default() }, Mods { alt: true, shift: true, ..Default::default() }] {
let mut t = EyedropperTool::default();
t.set_option("stop", &json!("gradient"));
t.set_option("imageTraceIgnoreColor", &binding);
assert_eq!(t.options()["imageTraceIgnoreColor"], binding);
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Move, -25.5, 400.25)).is_empty());
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, -25.5, 400.25)).is_empty());
assert_eq!(
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, -25.5, 400.25).with_mods(mods)),
vec![
Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "point": [-25.5, 400.25]})),
Action::SwitchTool("gradient".into()),
]
);
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
assert!(!t.claims_key(&cx, ToolKey::Escape));
assert!(!t.ends_on_escape(&cx));
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
}
}
/// Escape's UI request is claimed only while this one-shot target is armed.
#[test]
fn image_trace_escape_cancels_its_binding_and_restores_the_tool_once() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let binding = json!({"doc": 7, "target": id.0, "revision": 11});
let mut t = EyedropperTool::default();
assert!(!t.claims_key(&cx, ToolKey::Escape));
assert!(!t.ends_on_escape(&cx));
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
t.set_option("stop", &json!("selection"));
t.set_option("imageTraceIgnoreColor", &binding);
assert!(t.claims_key(&cx, ToolKey::Escape));
assert!(t.ends_on_escape(&cx));
assert!(!t.claims_key(&cx, ToolKey::Enter));
assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty());
assert_eq!(t.options()["imageTraceIgnoreColor"], binding);
assert_eq!(
t.key(&cx, ToolKey::Escape, Mods::default()),
vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "cancel": true})), Action::SwitchTool("selection".into())]
);
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
assert!(!t.claims_key(&cx, ToolKey::Escape));
assert!(!t.ends_on_escape(&cx));
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
}
/// A cleared Image Trace request leaves the existing brush/stop options and keys alone.
#[test]
fn clearing_image_trace_sampling_preserves_existing_brush_and_stop_options() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut t = EyedropperTool::default();
t.set_option("brushKeyColor", &json!(true));
t.set_option("stop", &json!("selection"));
let original = t.options();
t.set_option("imageTraceIgnoreColor", &json!({"doc": 7, "target": 8, "revision": 11}));
t.set_option("imageTraceIgnoreColor", &Value::Null);
assert_eq!(t.options(), original);
assert!(!t.claims_key(&cx, ToolKey::Escape));
assert!(!t.ends_on_escape(&cx));
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
assert_eq!(t.options(), original);
assert_eq!(
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)),
vec![Action::Dialog("brushKeyColor".into(), json!({"color": color_json(&Color::WHITE)})), Action::SwitchTool("selection".into())]
);
}
/// The hex of the colour a `paint.sampleColor` action samples.
fn sampled_hex(a: &[Action]) -> String {
let [Action::Exec(c, p)] = a else { panic!("one action: {a:?}") };
+1
View File
@@ -467,6 +467,7 @@ impl VectorcraftApp {
}
self.ui.flyout = None;
switched?;
crate::panels::image_trace::cancel_ignore_sampler(self, false);
if let Some(g) = vectorcraft_tools::catalog::group_of(id)
&& let Some(slot) = self.ui.group_tool.get_mut(g)
{
+11 -3
View File
@@ -248,6 +248,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// The meshes of the tools' shared paths. Likewise, a frame that does not draw the tools'
// overlays drops them.
let mut shared_paths = std::mem::take(&mut app.canvas.shared_paths);
let sampler_cancelled = crate::panels::image_trace::refresh_ignore_sampler(app);
// A release ends the Image Trace panel's eye-button hold, also when the panel is no longer
// drawn, so a later press elsewhere does not show the source image.
if app.ui.trace_hold_source.is_some() && !ui.input(|i| i.pointer.any_down()) {
@@ -295,7 +296,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
scroll_bars(app, ui, rect, outer, &t);
}
let resp = ui.interact(rect, egui::Id::unique("canvas"), Sense::click_and_drag());
canvas_input(app, ui, &resp, rect);
input_after_sampler_refresh(app, ui, &resp, rect, sampler_cancelled);
let v = *app.view().unwrap_or(&View::default());
let xf = Xf::at(rect, &v, app.canvas_ui_zoom);
// While the view pans, zooms or turns under the pointer, the art under it isn't hit-tested.
@@ -461,6 +462,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
/// A press arriving with an invalidated sampler is consumed, not given to its restored tool.
fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) {
if !cancelled || !ui.input(|i| i.pointer.any_pressed()) {
canvas_input(app, ui, resp, rect);
}
}
/// The pointer on the canvas: the tool's input, unless the context menu or the 3D gizmo has the press.
pub(crate) fn canvas_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) {
if app.ui.dialog.as_ref().is_some_and(crate::dialogs::revolve_gizmo::active) {
@@ -634,8 +642,8 @@ fn cache_key(
rich_black: app.session.prefs.black_on_screen == "rich",
// A tool's drag on the canvas, during an interaction (not a dialog's preview).
dragging: app.session.in_interaction() && ui.data(|d| d.get_temp::<Drag>(drag_id())) == Some(Drag::Tool),
// The Image Trace panel's eye button, while it is held.
trace_source: app.ui.trace_hold_source.clone(),
// The sampler keeps its bound original visible between clicks, independently of the eye.
trace_source: crate::panels::image_trace::ignore_sampler_source(app, st.uid).or_else(|| app.ui.trace_hold_source.clone()),
// Preferences › Performance › Use Monitor Profile for Canvas.
display: app.display_profile.key(app.session.prefs.monitor_profile_display),
backdrop: backdrop(app, st, app.outline_view()),
+3
View File
@@ -378,6 +378,9 @@ pub(crate) fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) {
/// Send a pointer event to the active tool and act on UI requests (dialogs, tool switches).
pub fn dispatch(app: &mut VectorcraftApp, ev: &PointerEvent, view: vectorcraft_engine::ViewInfo) {
if ev.kind == PointerKind::Down && crate::panels::image_trace::discard_stale_ignore_click(app) {
return;
}
// A press lent to a selection tool (Cmd/Ctrl held) does not use the tool of a held key.
if ev.kind == PointerKind::Down && app.session.lent_tool_id(&ev.mods).is_none() {
crate::shortcuts::note_tool_use(app);
+5
View File
@@ -124,6 +124,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) {
}
// Double-clicking a stop on the gradient annotator: its popover, next to the stop's chip.
"gradientStop" => Dialog::new(kind, json!({"index": p.get("index").cloned().unwrap_or(json!(0)), "x": x, "y": y, "tab": "color"})),
// Image Trace's Ignore Color eyedropper updates the panel, not the document's paint.
"imageTraceIgnoreColor" => {
crate::panels::image_trace::apply_ignore_color_sample(app, &p);
return;
}
// Brush Options › Key Color eyedropper: update the open dialog, do not replace it.
"brushKeyColor" => {
if let Some(c) = p.get("color") {
+169 -1
View File
@@ -232,6 +232,155 @@ fn hold_source(app: &mut VectorcraftApp, ctx: &egui::Context, down: bool) {
}
}
/// The retained original image of a live trace, or the selected placed image itself.
fn source_image(n: &Node) -> Option<&vectorcraft_doc::ImageObject> {
let source = if is_trace(n) { n.children()?.first()?.as_ref() } else { n };
match &source.kind {
NodeKind::Image(image) => Some(image),
_ => None,
}
}
fn sampler_binding(s: &crate::state::TraceIgnoreSampler) -> Value {
json!({ "doc": s.doc, "target": s.target.0, "revision": s.revision })
}
fn sampler_valid(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler) -> bool {
let Some(doc) = app.session.active() else { return false };
doc.uid == s.doc
&& doc.revision == s.revision
&& target_key(app) == Some((s.doc, s.target))
&& doc.doc.node(s.target).and_then(source_image).is_some_and(|image| doc.doc.images.contains_key(&image.key))
}
fn sampler_tool_active(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler) -> bool {
app.session.tool_id() == "eyedropper" && app.session.tool_options()["imageTraceIgnoreColor"] == sampler_binding(s)
}
/// Clear only this temporary mode. An explicit tool choice keeps the tool the user chose.
pub(crate) fn cancel_ignore_sampler(app: &mut VectorcraftApp, restore: bool) {
let Some(s) = app.ui.trace_ignore_sampler.take() else { return };
if sampler_tool_active(app, &s) {
app.session.set_tool_option("imageTraceIgnoreColor", &Value::Null);
app.session.set_tool_option("stop", &Value::Null);
}
if restore && app.session.tool_id() == "eyedropper" {
app.return_to_tool(&s.back);
}
if let Some(ctx) = &app.ui_ctx {
ctx.request_repaint();
}
}
/// Also runs when the panel is closed: document changes and tool changes end the source preview.
pub(crate) fn refresh_ignore_sampler(app: &mut VectorcraftApp) -> bool {
let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false };
if !sampler_valid(app, s) {
cancel_ignore_sampler(app, true);
} else if !sampler_tool_active(app, s) {
cancel_ignore_sampler(app, false);
} else {
return false;
}
true
}
/// A stale sampler's click must not become a paint/selection click in the restored tool.
pub(crate) fn discard_stale_ignore_click(app: &mut VectorcraftApp) -> bool {
let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false };
if sampler_valid(app, s) && sampler_tool_active(app, s) {
return false;
}
let restore = app.session.tool_id() == "eyedropper";
cancel_ignore_sampler(app, restore);
true
}
/// Render the bound live trace's original without changing its stored View or the eye's hold.
pub(crate) fn ignore_sampler_source(app: &VectorcraftApp, doc: u64) -> Option<Arc<Vec<NodeId>>> {
let s = app.ui.trace_ignore_sampler.as_ref()?;
(s.doc == doc && sampler_valid(app, s) && sampler_tool_active(app, s) && target(app).0).then(|| Arc::new(vec![s.target]))
}
fn start_ignore_sampler(app: &mut VectorcraftApp, ctx: &egui::Context) {
if app.ui.trace_ignore_sampler.is_some() {
cancel_ignore_sampler(app, true);
return;
}
let Some((doc, target)) = target_key(app) else { return };
let Some(revision) = app.session.active().map(|d| d.revision) else { return };
let s = crate::state::TraceIgnoreSampler { doc, target, revision, back: app.session.tool_id().to_string() };
if !sampler_valid(app, &s) {
return;
}
if let Err(e) = app.try_select_tool("eyedropper") {
app.status(e);
return;
}
if !sampler_valid(app, &s) {
app.return_to_tool(&s.back);
return;
}
app.session.set_tool_option("imageTraceIgnoreColor", &sampler_binding(&s));
app.session.set_tool_option("stop", &json!(s.back.as_str()));
// Bind the reply to this panel's state, also when it is drawn without the full app frame.
app.ui_ctx = Some(ctx.clone());
app.ui.trace_ignore_sampler = Some(s);
if let Some(ctx) = &app.ui_ctx {
ctx.request_repaint();
}
}
/// Match Image Trace's input bytes, not the current canvas result or the working-space colour.
fn sampled_ignore_color(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler, p: &Value) -> Option<String> {
let point = vectorcraft_geom::Point::new(p["point"][0].as_f64()?, p["point"][1].as_f64()?);
if !point.x.is_finite() || !point.y.is_finite() {
return None;
}
let doc = &app.session.active()?.doc;
let image = source_image(doc.node(s.target)?)?;
if image.xf.determinant().abs() < 1e-12 {
return None;
}
let pixel = image.xf.inverse() * point;
let [r, g, b, alpha] = doc.images.get(&image.key)?.sample_object(pixel.x, pixel.y, (image.width, image.height), 1)?;
(alpha != 0).then(|| format!("#{r:02x}{g:02x}{b:02x}"))
}
/// Handle the one-shot tool's reply after it has consumed its transient binding.
pub(crate) fn apply_ignore_color_sample(app: &mut VectorcraftApp, p: &Value) {
let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return };
if p["binding"] != sampler_binding(s) {
return;
}
let valid = sampler_valid(app, s);
let s = s.clone();
cancel_ignore_sampler(app, false);
if !valid || p["cancel"] == true {
return;
}
let Some(color) = sampled_ignore_color(app, &s, p) else { return };
// The canvas UI establishes this context before a real panel click can arm the sampler.
let Some(ctx) = app.ui_ctx.clone() else { return };
let all = presets(app, &ctx);
let mut st: TraceUi = pstate(&ctx, "image-trace");
let (is_trace, _, stored) = target(app);
follow_preset_changes(app, &mut st, &all);
let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect();
sync_with_object(&mut st, stored, Some((s.doc, s.target)), &all, &changes);
st.params["ignoreColor"] = json!(color);
st.preset = "Custom".into();
let preview = app.ui.image_trace_preview;
if is_trace || !preview {
st.preview_off = !preview;
}
if is_trace && preview {
trace(app, &ctx, &mut st);
}
set_pstate(&ctx, "image-trace", st);
ctx.request_repaint();
}
/// The selected Image Trace object's View row (Control bar, Properties).
pub(crate) fn view_row(app: &mut VectorcraftApp, ui: &mut Ui, current: TraceView, width: f32) {
widgets::dim_label(ui, tl!("View:"));
@@ -807,17 +956,36 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.horizontal(|ui| {
let on = st.params["ignoreWhite"].as_bool().unwrap_or(false);
if widgets::check(ui, tl!("Ignore Color"), on, true) {
if on {
cancel_ignore_sampler(app, true);
}
st.params["ignoreWhite"] = json!(!on);
st.preset = "Custom".into();
retrace = true;
}
if on {
let mut rgb = ignore_color(&st.params);
if ui.color_edit_button_srgb(&mut rgb).changed() {
let picker = ui.color_edit_button_srgb(&mut rgb);
if picker.clicked() {
cancel_ignore_sampler(app, true);
}
if picker.changed() {
st.params["ignoreColor"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]));
st.preset = "Custom".into();
retrace = true;
}
if widgets::icon_button_enabled(
ui,
"pipette",
tl!("Eyedropper: click the source image to sample the ignored color"),
app.ui.trace_ignore_sampler.is_some(),
is_trace || is_image,
22.0,
)
.clicked()
{
start_ignore_sampler(app, ui.ctx());
}
}
});
}
+13
View File
@@ -6,6 +6,15 @@ use vectorcraft_geom::Point;
use crate::theme::Brightness;
/// A one-shot Image Trace Ignore Color sampler, bound to the unchanged selected source.
#[derive(Clone, Debug)]
pub struct TraceIgnoreSampler {
pub doc: u64,
pub target: vectorcraft_doc::NodeId,
pub revision: u64,
pub back: String,
}
/// Per-document view (camera).
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct View {
@@ -847,6 +856,9 @@ pub struct UiState {
/// panel's eye button is held down ([`vectorcraft_render::RenderOptions::trace_source`]).
#[serde(skip)]
pub trace_hold_source: Option<std::sync::Arc<Vec<vectorcraft_doc::NodeId>>>,
/// Ignore Color's one-shot canvas sampler; independent of the eye button's press lifetime.
#[serde(skip)]
pub trace_ignore_sampler: Option<TraceIgnoreSampler>,
/// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only, Locate Selected Objects).
#[serde(default)]
pub layers_panel: crate::panels::layers::PanelOptions,
@@ -1271,6 +1283,7 @@ impl Default for UiState {
psd_import: Value::Null,
home: None,
trace_hold_source: None,
trace_ignore_sampler: None,
layers_panel: Default::default(),
navigator_panel: Default::default(),
layers_filter: Default::default(),
@@ -0,0 +1,419 @@
//! Image Trace Ignore Color's real panel button, tool callback and canvas presentation.
//! All APIs used here exist on the pre-fix base; the first regression fails on the missing button.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::time::{Duration, Instant};
use egui::{Event, PointerButton, Pos2, RawInput, Rect, vec2};
use serde_json::{Value, json};
use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView};
use vectorcraft_engine::Session;
use vectorcraft_geom::Point;
use vectorcraft_tools::{PointerEvent, PointerKind};
use vectorcraft_ui_egui::{CacheKey, VectorcraftApp, canvas, trace_runs};
const SAMPLE_TIP: &str = "Eyedropper: click the source image to sample the ignored color";
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<Event>) -> egui::FullOutput {
let mut raw = RawInput { events, focused: true, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1400.0))), ..Default::default() };
// raw_input_hook already begins the host iteration; do not begin a second one.
app.raw_input_hook(ctx, &mut raw);
ctx.run_ui(raw, |ui| {
app.tick(ui.ctx());
app.ui(ui);
})
}
fn settle(app: &mut VectorcraftApp, ctx: &egui::Context) {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
trace_runs::poll(app);
frame(app, ctx, vec![]).textures_delta.clear();
if !trace_runs::any_running(app) {
break;
}
assert!(Instant::now() < deadline, "the tiny fixture's background trace did not finish");
std::thread::sleep(Duration::from_millis(5));
}
for _ in 0..2 {
frame(app, ctx, vec![]).textures_delta.clear();
}
}
fn click_control(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) {
let mut found = None;
for _ in 0..3 {
let mut out = frame(app, ctx, vec![]);
if let Some(update) = &out.platform_output.accesskit_update {
found = update.nodes.iter().find(|(_, node)| node.label() == Some(label)).and_then(|(_, node)| node.bounds());
}
out.textures_delta.clear();
if found.is_some() {
break;
}
}
let bounds = found.unwrap_or_else(|| panic!("missing accessible Image Trace control: {label}"));
let at = egui::pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32);
let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
frame(app, ctx, vec![Event::PointerMoved(at)]).textures_delta.clear();
frame(app, ctx, vec![press(true)]).textures_delta.clear();
frame(app, ctx, vec![press(false)]).textures_delta.clear();
settle(app, ctx);
}
fn fixture(live_trace: bool, rgb: [u8; 3], preview: bool) -> (VectorcraftApp, egui::Context) {
vectorcraft_ui_egui::i18n::set_current(vectorcraft_ui_egui::i18n::Lang::EN);
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let pixels: Vec<u8> = (0..400).flat_map(|i| if i % 20 < 10 { [rgb[0], rgb[1], rgb[2], 255] } else { [255; 4] }).collect();
let image =
craft_image_codecs::Image::from_raw(20, 20, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels).unwrap();
let png = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
app.run(
"file.place",
json!({"name": "sampler-original.png", "dataBase64": vectorcraft_format::base64_encode(&png), "link": false, "at": [200, 150]}),
)
.unwrap();
if live_trace {
app.run(
"imageTrace.make",
json!({"preset": "Default", "params": {"mode": "blackAndWhite", "threshold": 127, "noise": 1, "ignoreWhite": false}}),
)
.unwrap();
}
app.select_tool("selection");
app.ui.image_trace_preview = preview;
app.ui.image_trace_advanced = true;
app.ui.task_bar = false;
app.ui.view.rulers = false;
app.session.prefs.monitor_profile_display = false;
app.canvas.worker_started = true; // the existing same-thread CPU canvas route
// An ordinary dock column gives Advanced the full window height without an auxiliary OS viewport.
app.run("window.panel.dock", json!({"panel": "imageTrace", "side": "End", "collapsed": false})).unwrap();
app.run("window.panel.activate", json!({"panel": "imageTrace"})).unwrap();
let ctx = egui::Context::default();
ctx.enable_accesskit();
for _ in 0..8 {
frame(&mut app, &ctx, vec![]).textures_delta.clear();
}
click_control(&mut app, &ctx, "Ignore Color");
(app, ctx)
}
fn selected(app: &VectorcraftApp) -> Node {
let state = app.session.active().unwrap();
state.doc.node(state.selection.objects[0]).unwrap().clone()
}
fn settings(app: &VectorcraftApp) -> Value {
selected(app).extras().trace.as_deref().unwrap().clone()
}
fn source_point(app: &VectorcraftApp, x: f64) -> Point {
let selected = selected(app);
let original = selected.children().and_then(|children| children.first()).map_or(&selected, |child| child.as_ref());
let NodeKind::Image(image) = &original.kind else { panic!("selected source image") };
image.xf * Point::new(f64::from(image.width) * x, f64::from(image.height) * 0.5)
}
fn sample(app: &mut VectorcraftApp, ctx: &egui::Context, point: Point) {
click_control(app, ctx, SAMPLE_TIP);
assert_eq!(app.session.tool_id(), "eyedropper", "the actual panel button arms sampling");
let view = app.view_info();
canvas::dispatch(app, &PointerEvent::new(PointerKind::Down, point.x, point.y), view);
settle(app, ctx);
}
#[test]
fn samples_original_trace_pixels_without_painting() {
let (mut app, ctx) = fixture(true, [37; 3], false);
let point = source_point(&app, 0.25);
let state = app.session.active().unwrap();
let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision);
let history = (state.history.undo.len(), state.history.redo.len());
let paint = app.session.paint.clone();
click_control(&mut app, &ctx, SAMPLE_TIP);
assert_eq!(app.session.tool_id(), "eyedropper");
let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point);
assert!(app.canvas_rect.unwrap().contains(at));
let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear();
frame(&mut app, &ctx, vec![press(false)]).textures_delta.clear();
settle(&mut app, &ctx);
assert_eq!(app.session.tool_id(), "selection");
assert_eq!(app.session.paint, paint);
let state = app.session.active().unwrap();
assert_eq!(state.doc, document, "Preview off leaves the document unchanged");
assert_eq!(state.selection, selection);
assert_eq!(state.revision, revision);
assert_eq!((state.history.undo.len(), state.history.redo.len()), history);
click_control(&mut app, &ctx, "Trace");
assert_eq!(settings(&app)["params"]["ignoreColor"], "#252525", "persist the original gray, not the black tracing result");
}
#[test]
fn colored_placed_image_and_live_trace_keep_preview_off_drafts_until_trace() {
for live_trace in [false, true] {
let (mut app, ctx) = fixture(live_trace, [37, 83, 149], false);
let point = source_point(&app, 0.25);
let id = selected(&app).id;
let state = app.session.active().unwrap();
let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision);
let history = (state.history.undo.len(), state.history.redo.len());
let paint = app.session.paint.clone();
sample(&mut app, &ctx, point);
let state = app.session.active().unwrap();
assert_eq!(state.doc, document, "placed/live={live_trace}: sample only the panel draft");
assert_eq!(state.selection, selection);
assert_eq!(state.revision, revision);
assert_eq!((state.history.undo.len(), state.history.redo.len()), history);
assert_eq!(app.session.paint, paint);
app.run("select.none", json!({})).unwrap();
settle(&mut app, &ctx);
app.run("select.set", json!({"ids": [id.0]})).unwrap();
settle(&mut app, &ctx);
click_control(&mut app, &ctx, "Trace");
assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395", "the raw non-gray draft survives the selection round trip");
assert_eq!(settings(&app)["preset"], "Custom");
assert_eq!(app.session.active().unwrap().history.undo.len(), history.0 + 1, "Trace creates the only edit");
}
}
#[test]
fn preview_traces_once_and_undo_redo_restore_the_results() {
let (mut app, ctx) = fixture(true, [37, 83, 149], true);
let point = source_point(&app, 0.25);
let state = app.session.active().unwrap();
let (before, selection, steps) = (state.doc.clone(), state.selection.clone(), state.history.undo.len());
let paint = app.session.paint.clone();
let view = selected(&app).trace_view();
sample(&mut app, &ctx, point);
let after = app.session.active().unwrap().doc.clone();
assert_ne!(after, before);
assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395");
assert_eq!(settings(&app)["preset"], "Custom");
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1);
// The existing imageTrace.make replaces the trace group and selects its new ID.
// Keep the logical trace selected, rather than requiring the removed group's ID.
let mut traced_selection = selection.clone();
traced_selection.set([selected(&app).id]);
assert_eq!(app.session.active().unwrap().selection, traced_selection);
assert!(after.node(selection.objects[0]).is_none());
assert_eq!(app.session.paint, paint);
assert_eq!(selected(&app).trace_view(), view);
assert_eq!(app.session.tool_id(), "selection");
settle(&mut app, &ctx);
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "later frames do not retrace");
app.run("edit.undo", json!({})).unwrap();
settle(&mut app, &ctx);
assert_eq!(app.session.active().unwrap().doc, before);
assert_eq!(app.session.active().unwrap().selection, selection);
assert_eq!(app.session.active().unwrap().history.undo.len(), steps);
app.run("edit.redo", json!({})).unwrap();
settle(&mut app, &ctx);
assert_eq!(app.session.active().unwrap().doc, after);
assert_eq!(app.session.active().unwrap().selection, traced_selection);
assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1);
}
#[test]
fn miss_escape_and_explicit_tool_choice_do_not_sample_or_paint() {
for exit in ["outside", "escape", "rectangle", "eyedropper"] {
let (mut app, ctx) = fixture(true, [37, 83, 149], false);
let old_color = settings(&app)["params"]["ignoreColor"].clone();
let state = app.session.active().unwrap();
let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision);
let history = (state.history.undo.len(), state.history.redo.len());
let paint = app.session.paint.clone();
click_control(&mut app, &ctx, SAMPLE_TIP);
assert_eq!(app.session.tool_id(), "eyedropper");
match exit {
"outside" => {
let view = app.view_info();
canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Down, -100.0, -100.0), view);
}
"escape" => {
let key = |pressed| Event::Key {
key: egui::Key::Escape,
physical_key: Some(egui::Key::Escape),
pressed,
repeat: false,
modifiers: egui::Modifiers::NONE,
};
// Full public input path: claims/ends are observed before tool_key, and
// Escape's requests are applied only if the tool claims the key.
frame(&mut app, &ctx, vec![key(true)]).textures_delta.clear();
frame(&mut app, &ctx, vec![key(false)]).textures_delta.clear();
}
chosen => app.select_tool(chosen),
}
let expected = if exit == "outside" || exit == "escape" { "selection" } else { exit };
assert_eq!(app.session.tool_id(), expected, "{exit}: restore or respect the explicit choice");
assert!(app.session.tool_options_of("eyedropper")["imageTraceIgnoreColor"].is_null());
settle(&mut app, &ctx);
assert!(app.canvas.key.as_ref().unwrap().trace_source.is_none());
assert_eq!(app.session.paint, paint);
let state = app.session.active().unwrap();
assert_eq!(state.doc, document);
assert_eq!(state.selection, selection, "{exit}: Escape does not fall through to deselect");
assert_eq!(state.revision, revision);
assert_eq!((state.history.undo.len(), state.history.redo.len()), history);
click_control(&mut app, &ctx, "Trace");
assert_eq!(settings(&app)["params"]["ignoreColor"], old_color, "{exit}: no hidden draft color was sampled");
}
}
#[test]
fn stale_target_click_is_consumed_before_the_restored_tool_can_select_or_paint() {
for invalidation in ["selection", "document", "revision_round_trip"] {
let (mut app, ctx) = fixture(true, [37, 83, 149], false);
let point = source_point(&app, 0.25);
let old_document = app.session.active().unwrap().doc.clone();
let old_uid = app.session.active().unwrap().uid;
let armed_revision = app.session.active().unwrap().revision;
click_control(&mut app, &ctx, SAMPLE_TIP);
match invalidation {
"selection" => {
app.run("select.none", json!({})).unwrap();
}
"document" => {
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
}
_ => {
app.run("imageTrace.setView", json!({"view": TraceView::Outlines.id()})).unwrap();
app.run("edit.undo", json!({})).unwrap();
assert_eq!(app.session.active().unwrap().doc, old_document);
assert_ne!(app.session.active().unwrap().revision, armed_revision);
}
}
let state = app.session.active().unwrap();
let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision);
let history = (state.history.undo.len(), state.history.redo.len());
let paint = app.session.paint.clone();
// No UI refresh intervenes: this must exercise the real dispatch stale-Down guard.
let view = app.view_info();
canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Down, point.x, point.y), view);
assert_eq!(app.session.tool_id(), "selection", "{invalidation}: restore prior tool");
let state = app.session.active().unwrap();
assert_eq!(state.doc, document);
assert_eq!(state.selection, selection, "the stale click cannot reselect the source");
assert_eq!(state.revision, revision);
assert_eq!((state.history.undo.len(), state.history.redo.len()), history);
assert_eq!(app.session.paint, paint);
assert_eq!(app.session.documents().iter().find(|d| d.uid == old_uid).unwrap().doc, old_document);
settle(&mut app, &ctx);
assert!(app.canvas.key.as_ref().unwrap().trace_source.is_none());
}
}
#[test]
fn a_stale_sampler_and_canvas_press_in_one_frame_do_not_reselect_the_source() {
let (mut app, ctx) = fixture(true, [37, 83, 149], false);
let point = source_point(&app, 0.25);
let target = selected(&app).id;
click_control(&mut app, &ctx, SAMPLE_TIP);
app.run("select.none", json!({})).unwrap();
// The last real layout supplies the canvas rect and view. Canvas itself records this
// context's zoom_factor as its UI-coordinate scale before routing input.
let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point);
assert!(app.canvas_rect.unwrap().contains(at));
let state = app.session.active().unwrap();
let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision);
let history = (state.history.undo.len(), state.history.redo.len());
let paint = app.session.paint.clone();
let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear();
assert_eq!(app.session.tool_id(), "selection");
let state = app.session.active().unwrap();
assert_eq!(state.doc, document);
assert_eq!(state.selection, selection, "the press in the cancellation frame is consumed");
assert_eq!(state.revision, revision);
assert_eq!((state.history.undo.len(), state.history.redo.len()), history);
assert_eq!(app.session.paint, paint);
frame(&mut app, &ctx, vec![press(false)]).textures_delta.clear();
assert!(app.session.active().unwrap().selection.objects.is_empty());
// Positive control: the same ordinary, unarmed click really hits and selects this trace.
frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear();
frame(&mut app, &ctx, vec![press(false)]).textures_delta.clear();
assert_eq!(app.session.active().unwrap().selection.objects, vec![target]);
}
fn capture_canvas(app: &mut VectorcraftApp, ctx: &egui::Context) -> (vectorcraft_render::Rendered, CacheKey) {
app.canvas.key = None; // force a complete upload, not a partial delta requiring reconstruction
let mut out = frame(app, ctx, vec![]);
let id = app.canvas.texture.as_ref().expect("real canvas texture").id();
let upload =
out.textures_delta.set.iter().find(|(texture, _)| **texture == id).and_then(|(_, updates)| updates.last()).expect("CPU canvas upload");
assert!(upload.pos.is_none());
let egui::ImageData::Color(image) = &upload.image;
let rendered = vectorcraft_render::Rendered {
width: image.width() as u32,
height: image.height() as u32,
pixels: image.pixels.iter().flat_map(|c| c.to_array()).collect(),
};
let key = app.canvas.key.as_ref().unwrap().clone();
out.textures_delta.clear();
(rendered, key)
}
fn pixel_at(image: &vectorcraft_render::Rendered, key: &CacheKey, point: Point) -> [u8; 4] {
assert!(key.pixel.is_none() && key.rot == 0.0, "fixture uses the ordinary unrotated canvas");
let x = (f64::from(image.width) * 0.5 + (point.x - key.cx) * key.zoom * f64::from(key.ppp)).floor();
let y = (f64::from(image.height) * 0.5 + (point.y - key.cy) * key.zoom * f64::from(key.ppp)).floor();
assert!(x >= 0.0 && x < f64::from(image.width) && y >= 0.0 && y < f64::from(image.height));
let at = ((y as usize * image.width as usize) + x as usize) * 4;
image.pixels[at..at + 4].try_into().unwrap()
}
#[test]
fn actual_canvas_shows_original_while_armed_then_restores_the_stored_view() {
let (mut app, ctx) = fixture(true, [37, 83, 149], false);
let point = source_point(&app, 0.25);
let control = source_point(&app, 0.75);
let target: NodeId = selected(&app).id;
let state = app.session.active().unwrap();
let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision);
let history = (state.history.undo.len(), state.history.redo.len());
let uid = state.uid;
let original = state.doc.node(target).unwrap().children().unwrap()[0].clone();
assert!(!original.visible, "the live trace retains its hidden original");
let NodeKind::Image(image) = &original.kind else { panic!("original image") };
let blob = state.doc.images.get(&image.key).unwrap();
assert_eq!(
blob.sample_object(f64::from(image.width) * 0.25, f64::from(image.height) * 0.5, (image.width, image.height), 1),
Some([37, 83, 149, 255])
);
let source_hash = blob.content_key();
let stored = settings(&app);
let (before, before_key) = capture_canvas(&mut app, &ctx);
assert_eq!(pixel_at(&before, &before_key, point), [0, 0, 0, 255]);
assert_eq!(pixel_at(&before, &before_key, control), [255; 4]);
click_control(&mut app, &ctx, SAMPLE_TIP);
let (armed, armed_key) = capture_canvas(&mut app, &ctx);
assert!(!ctx.input(|i| i.pointer.any_down()), "the source remains visible after releasing the button");
assert_eq!(armed_key.trace_source.as_deref().map(Vec::as_slice), Some([target].as_slice()));
assert_eq!(pixel_at(&armed, &armed_key, point), [37, 83, 149, 255]);
assert_eq!(pixel_at(&armed, &armed_key, control), [255; 4]);
app.select_tool("selection");
let (restored, restored_key) = capture_canvas(&mut app, &ctx);
assert!(restored_key.trace_source.is_none());
assert_eq!(restored.pixels, before.pixels, "the exact stored result returns");
let state = app.session.active().unwrap();
assert_eq!((state.uid, state.revision), (uid, revision));
assert_eq!(state.doc, document);
assert_eq!(state.selection, selection);
assert_eq!((state.history.undo.len(), state.history.redo.len()), history);
if let Some(dir) = std::env::var_os("VECTORCRAFT_TRACE_SAMPLER_EVIDENCE") {
let dir = std::path::PathBuf::from(dir);
std::fs::create_dir_all(&dir).unwrap();
for (name, image) in [("before.png", &before), ("armed.png", &armed), ("restored.png", &restored)] {
std::fs::write(dir.join(name), image.to_png().unwrap()).unwrap();
}
let binding = json!({"doc": uid, "target": target.0, "revision": revision, "storedTrace": stored, "sourceContentKey": source_hash,
"point": [point.x,point.y], "controlPoint": [control.x,control.y], "width": before.width, "height": before.height,
"before": pixel_at(&before,&before_key,point), "armed": pixel_at(&armed,&armed_key,point), "restored": pixel_at(&restored,&restored_key,point),
"sourceIdsWhileArmed": [target.0], "undoRedoLengths": [history.0,history.1], "documentUnchanged": true,
"view": {"zoom":before_key.zoom,"center":[before_key.cx,before_key.cy],"rotation":before_key.rot,"pixelsPerPoint":before_key.ppp}});
std::fs::write(dir.join("binding.json"), serde_json::to_vec_pretty(&binding).unwrap()).unwrap();
}
}
+2
View File
@@ -416,6 +416,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
| Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` |
| Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (<https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html>). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. |
| Image Trace panel: holding the eye button next to View down shows the selected Image Trace objects' source image on the canvas | done | Per the public documentation, the control next to View is pressed and held to compare the trace result with the source image (<https://web.archive.org/web/20250831090623/https://helpx.adobe.com/illustrator/using/image-trace.html>). On release the objects show their View again; the document, its View and the undo history are unchanged. `RenderOptions::trace_source`; `panels/image_trace.rs` headless test `holding_the_eye_button_shows_the_source_image_until_released`, render test `trace_source_draws_the_source_image_of_the_listed_objects`. The Control bar and Properties have no such button |
| Image Trace panel: Ignore Color has a canvas eyedropper beside its color picker | done | #8068. Samples original pixels of the selected placed image or the retained source of a live trace. A live trace shows its source temporarily without changing View. The existing color picker remains available. Preview off keeps a draft; Preview on retraces a live trace as one undo step. A sample, Escape or a miss restores the previous tool; changing the target cancels. Paint defaults and selection are retained. `tests/image_trace_ignore_sampler.rs`; no algorithm parity claim. |
| Live trace result bounds and selection highlights exclude the retained bitmap; source-image views retain it | done | All TraceView modes and rotated result bounds regression-covered; ordinary hidden group behavior retained |
| Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (<https://web.archive.org/web/20250831090623/https://helpx.adobe.com/illustrator/using/image-trace.html>). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) |
| Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls |
@@ -560,6 +561,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra
| Date | Change | Summary |
|---|---|---|
| 2026-11-16 | minor | Image Trace: Ignore Color samples original image pixels with a canvas eyedropper, retaining the manual picker, Preview drafts, source View and Undo behavior (#8068). Scores and estimates unchanged. |
| 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. |
| 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). Scores and estimates unchanged. |
| 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. |