mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 11:05:03 +00:00
Merge pull request #8276 from yoriswind/codex/8068-trace-ignore-sampler
#8068: sample Image Trace Ignore Color from the source image
This commit is contained in:
@@ -907,7 +907,7 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry};
|
||||
pub use buildcmds::{TracePreset, TracePresetChange};
|
||||
|
||||
/// An Image Trace made off the UI thread, and what it traced (#3098).
|
||||
pub use buildcmds::{TraceRun, Traced};
|
||||
pub use buildcmds::{TraceRun, Traced, image_trace_target};
|
||||
|
||||
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
|
||||
pub(crate) use buildcmds::TracePresetChanges;
|
||||
|
||||
@@ -42,7 +42,7 @@ pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, iso
|
||||
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
|
||||
use shape_builder::{sb_merge, sb_regions};
|
||||
pub(crate) use trace::TracePresetChanges;
|
||||
pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced};
|
||||
pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target};
|
||||
use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view};
|
||||
|
||||
/// Name of an Image Trace group.
|
||||
|
||||
@@ -606,6 +606,30 @@ struct Prepared {
|
||||
library: Vec<([u8; 3], Paint)>,
|
||||
}
|
||||
|
||||
/// The object `imageTrace.make` would trace, without preparing settings or reading image bytes.
|
||||
pub fn image_trace_target(s: &Session, p: &Value) -> Result<NodeId> {
|
||||
target_image(s, "imageTrace.make", p).map(|(target, _)| target)
|
||||
}
|
||||
|
||||
fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box<ImageObject>)> {
|
||||
let roots = root_ids(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
roots
|
||||
.iter()
|
||||
.find_map(|r| {
|
||||
let n = d.node(*r)?;
|
||||
match &n.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ if is_trace_group(n) => match &n.children()?.first()?.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))
|
||||
}
|
||||
|
||||
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
|
||||
fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
let mut params = trace_params(s, c, p)?;
|
||||
@@ -625,25 +649,7 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
|
||||
None if is(tr::preset(named)) || is(tr::enhanced_preset(named)) => named.to_string(),
|
||||
None => "Custom".to_string(),
|
||||
};
|
||||
let roots = root_ids(s, p)?;
|
||||
// The image (inside a trace group, or selected directly).
|
||||
let (target, image) = {
|
||||
let d = &s.doc()?.doc;
|
||||
roots
|
||||
.iter()
|
||||
.find_map(|r| {
|
||||
let n = d.node(*r)?;
|
||||
match &n.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ if is_trace_group(n) => match &n.children()?.first()?.kind {
|
||||
NodeKind::Image(i) => Some((*r, i.clone())),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))?
|
||||
};
|
||||
let (target, image) = target_image(s, c, p)?;
|
||||
if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) {
|
||||
return Err(bad(c, LIVE_PATHFINDER_BY_COLOR));
|
||||
}
|
||||
|
||||
@@ -1003,7 +1003,7 @@ impl PasteProfile {
|
||||
if o.keys().any(|k| k != "rgb" && k != "cmyk") {
|
||||
return Err(refuse());
|
||||
}
|
||||
let model = |m: &str| o.get(m).map(&one).transpose();
|
||||
let model = |m: &str| o.get(m).map(one).transpose();
|
||||
Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? }))
|
||||
}
|
||||
Some(v) => {
|
||||
|
||||
@@ -27,8 +27,12 @@
|
||||
//! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into
|
||||
//! the open dialog (`brushKeyColor` UI request) and switches back.
|
||||
//!
|
||||
//! Escape ends either pick without sampling and switches back to that tool. With neither pick
|
||||
//! Escape ends an armed pick without sampling and switches back to that tool. With no pick
|
||||
//! armed, Escape is left to the application.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -51,6 +55,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 gradient mesh points the tool switched from had picked, each a mesh and a point index.
|
||||
mesh_points: Vec<(NodeId, usize)>,
|
||||
}
|
||||
@@ -512,6 +518,11 @@ 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 opts = sample_options(cx);
|
||||
if self.brush_key_color {
|
||||
let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] };
|
||||
@@ -573,6 +584,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());
|
||||
}
|
||||
if !self.mesh_points.is_empty() {
|
||||
let points: Vec<Value> = self.mesh_points.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect();
|
||||
o.insert("meshPoints".into(), Value::Array(points));
|
||||
@@ -587,6 +601,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()),
|
||||
"meshPoints" => self.mesh_points = crate::meshedit::points_of(value),
|
||||
"textSelection" => self.text_selection.set_option(key, value),
|
||||
_ => {}
|
||||
@@ -621,12 +636,15 @@ impl Tool for EyedropperTool {
|
||||
Cursor::Eyedropper
|
||||
}
|
||||
|
||||
/// Escape ends a gradient stop's or Key Color's pick without sampling and switches back to the
|
||||
/// tool that armed it.
|
||||
/// Escape ends the armed pick without sampling; Image Trace receives its cancellation reply.
|
||||
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
|
||||
if key != ToolKey::Escape || !self.picking() {
|
||||
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, "cancel": true })), Action::SwitchTool(back)];
|
||||
}
|
||||
let back = self.stop.take().unwrap_or_else(|| "selection".to_string());
|
||||
self.brush_key_color = false;
|
||||
vec![Action::SwitchTool(back)]
|
||||
@@ -648,9 +666,9 @@ impl Tool for EyedropperTool {
|
||||
}
|
||||
|
||||
impl EyedropperTool {
|
||||
/// Is a one-shot pick armed (a gradient stop's or Brush Options' Key Color)?
|
||||
/// 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.stop.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -869,6 +887,96 @@ mod tests {
|
||||
assert_eq!(t.options(), json!({ "stop": null, "brushKeyColor": false }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_sampling_keeps_forwarding_its_binding_until_the_panel_accepts_a_color() {
|
||||
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]}))]
|
||||
);
|
||||
assert_eq!(t.options()["imageTraceIgnoreColor"], binding, "a point is only a request until the panel accepts its source color");
|
||||
assert_eq!(t.options()["stop"], "gradient");
|
||||
assert!(t.claims_key(&cx, ToolKey::Escape));
|
||||
assert!(t.ends_on_escape(&cx));
|
||||
let next = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 20.0));
|
||||
assert_eq!(next, vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "point": [10.0, 20.0]}))]);
|
||||
t.set_option("imageTraceIgnoreColor", &Value::Null);
|
||||
t.set_option("stop", &Value::Null);
|
||||
assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}));
|
||||
assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[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!(t.drop_press(&cx).is_empty(), "a dropped press leaves this pick waiting too");
|
||||
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 binding without a saved tool still claims its one Escape and returns to Selection.
|
||||
t.set_option("imageTraceIgnoreColor", &binding);
|
||||
assert!(t.claims_key(&cx, ToolKey::Escape) && t.ends_on_escape(&cx));
|
||||
assert_eq!(
|
||||
t.key(&cx, ToolKey::Escape, Mods::default()),
|
||||
vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "cancel": true})), Action::SwitchTool("selection".into())]
|
||||
);
|
||||
assert!(!t.claims_key(&cx, ToolKey::Escape) && !t.ends_on_escape(&cx));
|
||||
}
|
||||
|
||||
#[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);
|
||||
// Clearing Trace leaves the ordinary Brush pick armed, including its upstream Escape.
|
||||
assert!(t.claims_key(&cx, ToolKey::Escape));
|
||||
assert!(t.ends_on_escape(&cx));
|
||||
assert!(t.key(&cx, ToolKey::Enter, 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:?}") };
|
||||
|
||||
@@ -519,6 +519,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)
|
||||
{
|
||||
|
||||
@@ -181,6 +181,7 @@ impl VectorcraftApp {
|
||||
/// injected until the batch was actually applied, so a burst of hidden ticks cannot queue
|
||||
/// several steps of a drag or replay them together later.
|
||||
pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
crate::canvas::capture_pointer_before_input(ctx, raw.viewport_id);
|
||||
self.fill_raw_input(ctx, raw);
|
||||
crate::font_menu::sync_wheel_target(self, ctx, raw.viewport_id);
|
||||
crate::font_menu::take_raw_wheel(ctx, raw);
|
||||
|
||||
@@ -251,6 +251,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()) {
|
||||
@@ -263,7 +264,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if app.ui.home.is_some_and(|k| k != crate::menus::home_key(app)) {
|
||||
app.ui.home = None;
|
||||
}
|
||||
if crate::menus::home_showing(app) {
|
||||
let home_showing = crate::menus::home_showing(app);
|
||||
observe_hidden_ignore_sampler_pointer(app, ui, home_showing);
|
||||
if home_showing {
|
||||
// No IME owner this pass (`ime_caret_rect` stays None): the end-of-pass observation marks
|
||||
// the context absent and keeps any marked text as typed.
|
||||
home(app, ui, full);
|
||||
@@ -298,7 +301,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.
|
||||
@@ -470,6 +473,272 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct CanvasClick {
|
||||
count: u8,
|
||||
at: Option<Pos2>,
|
||||
}
|
||||
|
||||
fn pointer_before_input_id(viewport: egui::ViewportId) -> egui::Id {
|
||||
egui::Id::unique("canvas-pointer-before-input").with(viewport)
|
||||
}
|
||||
|
||||
/// The existing host hook calls this before egui updates the pointer for this batch.
|
||||
pub(crate) fn capture_pointer_before_input(ctx: &egui::Context, viewport: egui::ViewportId) {
|
||||
let pointer = ctx.input_for(viewport, |i| i.pointer.clone());
|
||||
ctx.data_mut(|data| data.insert_temp(pointer_before_input_id(viewport), pointer));
|
||||
}
|
||||
|
||||
/// Each release keeps egui's own qualification, including earlier releases in this batch.
|
||||
fn canvas_pointer_releases(ui: &Ui) -> Vec<IgnoreSamplerRelease> {
|
||||
let previous = ui.data(|data| data.get_temp::<egui::PointerState>(pointer_before_input_id(ui.ctx().viewport_id()))).unwrap_or_default();
|
||||
let options = ui.ctx().options(|o| o.input_options);
|
||||
let pixels_per_point = ui.ctx().pixels_per_point();
|
||||
ui.input(|i| {
|
||||
let mut counts = [0usize; egui::NUM_POINTER_BUTTONS];
|
||||
for event in &i.events {
|
||||
if let egui::Event::PointerButton { button, pressed: false, .. } = event {
|
||||
counts[*button as usize] += 1;
|
||||
}
|
||||
}
|
||||
i.events
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, event)| {
|
||||
let egui::Event::PointerButton { pos, button, pressed: false, .. } = event else { return None };
|
||||
let clicked = if counts[*button as usize] == 1 {
|
||||
i.pointer.button_clicked(*button)
|
||||
} else {
|
||||
// Aggregated flags cannot identify a later non-click release. Replay only
|
||||
// an ambiguous button's prefix, before its Up, through egui's public API.
|
||||
let mut before = i.clone();
|
||||
before.pointer = previous.clone();
|
||||
let raw = egui::RawInput { time: Some(i.time), events: i.events[..index].to_vec(), ..i.raw.clone() };
|
||||
before.begin_pass(raw, false, pixels_per_point, options).pointer.could_any_button_be_click()
|
||||
};
|
||||
Some(IgnoreSamplerRelease { button: *button, at: *pos, clicked })
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// Two non-sampler clicks replace egui's last two click times after a consumed pick.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct IgnoreSamplerClicks {
|
||||
last: Option<(f64, Pos2)>,
|
||||
remaining: u8,
|
||||
}
|
||||
|
||||
fn ignore_sampler_primary_id(id: egui::Id) -> egui::Id {
|
||||
id.with("image-trace-consumed-primary")
|
||||
}
|
||||
|
||||
fn ignore_sampler_owns_primary(ui: &Ui, id: egui::Id) -> bool {
|
||||
ui.data(|data| data.get_temp::<bool>(ignore_sampler_primary_id(id)).unwrap_or(false))
|
||||
}
|
||||
|
||||
fn reset_ignore_sampler_clicks(ui: &Ui, id: egui::Id) {
|
||||
ui.data_mut(|data| data.insert_temp(id.with("image-trace-clicks"), IgnoreSamplerClicks { last: None, remaining: 2 }));
|
||||
}
|
||||
|
||||
/// Reclassify only the two clicks whose raw history can still contain a consumed pick.
|
||||
/// Other widgets' clicks count too, as they do in egui; its pointer state stays untouched.
|
||||
fn ignore_sampler_clicks(ui: &Ui, id: egui::Id, consumed: bool, releases: &[IgnoreSamplerRelease]) {
|
||||
ui.data_mut(|data| data.remove::<CanvasClick>(id.with("image-trace-click-count")));
|
||||
if !releases.iter().any(|release| release.clicked) {
|
||||
return;
|
||||
}
|
||||
if consumed {
|
||||
reset_ignore_sampler_clicks(ui, id);
|
||||
return;
|
||||
}
|
||||
let time = ui.input(|i| i.time);
|
||||
for release in releases.iter().filter(|release| release.clicked) {
|
||||
record_ignore_sampler_click(ui, id, release.at, time, release.button == egui::PointerButton::Primary);
|
||||
}
|
||||
}
|
||||
|
||||
fn record_ignore_sampler_click(ui: &Ui, id: egui::Id, at: Pos2, time: f64, primary: bool) {
|
||||
let (delay, distance) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist));
|
||||
ui.data_mut(|data| {
|
||||
let history_id = id.with("image-trace-clicks");
|
||||
let Some(mut clicks) = data.remove_temp::<IgnoreSamplerClicks>(history_id) else {
|
||||
if primary {
|
||||
data.remove::<CanvasClick>(id.with("image-trace-click-count"));
|
||||
}
|
||||
return;
|
||||
};
|
||||
let double = clicks.last.is_some_and(|(last, pos)| time - last < delay && pos.distance_sq(at) < distance * distance);
|
||||
if primary {
|
||||
data.insert_temp(id.with("image-trace-click-count"), CanvasClick { count: if double { 2 } else { 1 }, at: Some(at) });
|
||||
}
|
||||
clicks.last = Some((time, at));
|
||||
clicks.remaining -= 1;
|
||||
if clicks.remaining != 0 {
|
||||
data.insert_temp(history_id, clicks);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn primary_click(ui: &Ui, resp: &egui::Response) -> CanvasClick {
|
||||
if !resp.clicked_by(egui::PointerButton::Primary) {
|
||||
return CanvasClick::default();
|
||||
}
|
||||
ui.data(|data| data.get_temp::<CanvasClick>(resp.id.with("image-trace-click-count"))).unwrap_or_else(|| {
|
||||
let count = if resp.triple_clicked() {
|
||||
3
|
||||
} else if resp.double_clicked() {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let at = ui.data(|data| data.get_temp::<Pos2>(resp.id.with("canvas-qualified-primary-release")));
|
||||
CanvasClick { count, at }
|
||||
})
|
||||
}
|
||||
|
||||
fn primary_click_count(ui: &Ui, resp: &egui::Response) -> u8 {
|
||||
primary_click(ui, resp).count
|
||||
}
|
||||
|
||||
/// Remove only the pointer sequence acquired by this sampler, never a view or tool drag.
|
||||
fn clear_ignore_sampler_gesture(ui: &Ui, id: egui::Id) {
|
||||
ui.data_mut(|data| {
|
||||
data.remove::<bool>(ignore_sampler_primary_id(id));
|
||||
if matches!(data.get_temp::<Drag>(drag::drag_id()), Some(Drag::Gesture)) {
|
||||
data.remove::<Drag>(drag::drag_id());
|
||||
data.remove::<Pos2>(drag::drag_pos_id());
|
||||
data.remove::<Point>(drag::tool_drag_doc_id());
|
||||
data.remove::<Point>(drag::tool_press_doc_id());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct IgnoreSamplerRelease {
|
||||
button: egui::PointerButton,
|
||||
at: Pos2,
|
||||
clicked: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct IgnoreSamplerPointer {
|
||||
owned: bool,
|
||||
replaced: bool,
|
||||
ordinary_pressed: bool,
|
||||
consumed_release: bool,
|
||||
releases: Vec<IgnoreSamplerRelease>,
|
||||
}
|
||||
|
||||
/// Attribute a fresh press after an owned release before egui's per-frame flags lose their order.
|
||||
fn ignore_sampler_pointer_frame(ui: &Ui, id: egui::Id, cancelled: bool, releases: &[IgnoreSamplerRelease]) -> IgnoreSamplerPointer {
|
||||
let owned = ignore_sampler_owns_primary(ui, id);
|
||||
if !owned && !cancelled {
|
||||
return IgnoreSamplerPointer::default();
|
||||
}
|
||||
ui.input(|i| {
|
||||
let mut frame = IgnoreSamplerPointer { owned, ..Default::default() };
|
||||
let mut first_press_owned = cancelled;
|
||||
let mut releases = releases.iter();
|
||||
for event in &i.events {
|
||||
if let egui::Event::PointerButton { pos, button, pressed, .. } = event {
|
||||
if *pressed {
|
||||
if *button == egui::PointerButton::Primary {
|
||||
frame.replaced |= frame.owned;
|
||||
// An observed old Up ends that cancelled sequence; without it,
|
||||
// a fresh invalid press keeps the existing cancellation gate.
|
||||
frame.owned = first_press_owned && !frame.consumed_release;
|
||||
first_press_owned = false;
|
||||
frame.ordinary_pressed |= !frame.owned;
|
||||
}
|
||||
} else {
|
||||
let clicked = releases.next().is_some_and(|release| release.clicked);
|
||||
ignore_sampler_release(&mut frame, *button, *pos, clicked);
|
||||
}
|
||||
}
|
||||
}
|
||||
frame
|
||||
})
|
||||
}
|
||||
|
||||
fn ignore_sampler_release(frame: &mut IgnoreSamplerPointer, button: egui::PointerButton, at: Pos2, clicked: bool) {
|
||||
if button == egui::PointerButton::Primary && frame.owned {
|
||||
frame.consumed_release = true;
|
||||
frame.releases.clear();
|
||||
} else if frame.consumed_release {
|
||||
frame.releases.push(IgnoreSamplerRelease { button, at, clicked });
|
||||
}
|
||||
}
|
||||
|
||||
fn ignore_sampler_frame_clicks(ui: &Ui, id: egui::Id, frame: &IgnoreSamplerPointer, consumed: bool, releases: &[IgnoreSamplerRelease]) {
|
||||
if !frame.consumed_release || !frame.ordinary_pressed {
|
||||
ignore_sampler_clicks(ui, id, consumed, releases);
|
||||
return;
|
||||
}
|
||||
// Consume the old sequence, then classify only subsequent ordinary releases. A new Down
|
||||
// still reaches the tool when the last release belongs to the consumed sequence.
|
||||
reset_ignore_sampler_clicks(ui, id);
|
||||
ui.data_mut(|data| data.insert_temp(id.with("image-trace-click-count"), CanvasClick::default()));
|
||||
let time = ui.input(|i| i.time);
|
||||
for release in &frame.releases {
|
||||
let primary = release.button == egui::PointerButton::Primary;
|
||||
if release.clicked {
|
||||
record_ignore_sampler_click(ui, id, release.at, time, primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn begin_ignore_sampler_pointer(ui: &Ui, id: egui::Id, cancelled: bool) -> (bool, bool) {
|
||||
let releases = canvas_pointer_releases(ui);
|
||||
ui.data_mut(|data| {
|
||||
let position_id = id.with("canvas-qualified-primary-release");
|
||||
data.remove::<Pos2>(position_id);
|
||||
if let Some(release) = releases.iter().rev().find(|release| release.clicked && release.button == egui::PointerButton::Primary) {
|
||||
data.insert_temp(position_id, release.at);
|
||||
}
|
||||
});
|
||||
let frame = ignore_sampler_pointer_frame(ui, id, cancelled, &releases);
|
||||
if frame.replaced {
|
||||
// This also replaces an abandoned sampler Down whose release was not observed.
|
||||
clear_ignore_sampler_gesture(ui, id);
|
||||
}
|
||||
if frame.owned {
|
||||
ui.data_mut(|data| data.insert_temp(ignore_sampler_primary_id(id), true));
|
||||
}
|
||||
let consumed = frame.owned && ui.input(|i| i.pointer.primary_pressed() || i.pointer.primary_released() || i.pointer.primary_down());
|
||||
ignore_sampler_frame_clicks(ui, id, &frame, consumed, &releases);
|
||||
(consumed, frame.ordinary_pressed)
|
||||
}
|
||||
|
||||
fn end_ignore_sampler_pointer(ui: &Ui, id: egui::Id) {
|
||||
// A valid Down can acquire ownership and complete in the same frame.
|
||||
if ignore_sampler_owns_primary(ui, id) && !ui.input(|i| i.pointer.primary_down()) {
|
||||
if ui.input(|i| i.pointer.button_clicked(egui::PointerButton::Primary)) {
|
||||
reset_ignore_sampler_clicks(ui, id);
|
||||
}
|
||||
clear_ignore_sampler_gesture(ui, id);
|
||||
}
|
||||
}
|
||||
|
||||
fn observe_hidden_ignore_sampler_pointer(app: &VectorcraftApp, ui: &Ui, home_showing: bool) {
|
||||
if home_showing || app.session.active().is_none() {
|
||||
// Home and the empty window still advance egui's click history. Observe the same
|
||||
// correction there so it retires after the two ordinary clicks that replace a pick.
|
||||
let id = egui::Id::unique("canvas");
|
||||
begin_ignore_sampler_pointer(ui, id, false);
|
||||
end_ignore_sampler_pointer(ui, id);
|
||||
}
|
||||
}
|
||||
|
||||
/// A sampler press keeps its release, even if its Down completes or its binding expires held.
|
||||
fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) {
|
||||
let (consumed, ordinary_pressed) = begin_ignore_sampler_pointer(ui, resp.id, cancelled);
|
||||
if !consumed && (ordinary_pressed || !cancelled || !ui.input(|i| i.pointer.any_pressed())) {
|
||||
canvas_input(app, ui, resp, rect);
|
||||
}
|
||||
end_ignore_sampler_pointer(ui, resp.id);
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
@@ -643,7 +912,6 @@ 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(),
|
||||
// Preferences › Performance › Use Monitor Profile for Canvas.
|
||||
display: app.display_profile.key(app.session.prefs.monitor_profile_display),
|
||||
|
||||
@@ -380,6 +380,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);
|
||||
@@ -422,11 +425,27 @@ fn pressed_with(app: &mut VectorcraftApp, index: Option<usize>, pos: Point, tool
|
||||
pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result<Vec<vectorcraft_engine::UiRequest>>) {
|
||||
match r {
|
||||
Ok(reqs) => {
|
||||
let mut sampler_return = None;
|
||||
for r in reqs {
|
||||
match r {
|
||||
vectorcraft_engine::UiRequest::Dialog(kind, p) => crate::dialogs::open_tool_dialog(app, &kind, p),
|
||||
vectorcraft_engine::UiRequest::Dialog(kind, p) => {
|
||||
let back = if kind == "imageTraceIgnoreColor" && p["cancel"] == true {
|
||||
app.ui.trace_ignore_sampler.as_ref().map(|sampler| sampler.back.clone())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
crate::dialogs::open_tool_dialog(app, &kind, p);
|
||||
// A matching callback must actually consume the active sampler.
|
||||
sampler_return = back.filter(|_| app.ui.trace_ignore_sampler.is_none());
|
||||
}
|
||||
vectorcraft_engine::UiRequest::Panel(panel) => activate_panel(app, &panel),
|
||||
vectorcraft_engine::UiRequest::SwitchTool(t) => app.select_tool(&t),
|
||||
vectorcraft_engine::UiRequest::SwitchTool(t) => {
|
||||
if sampler_return.take().is_some_and(|back| back == t) {
|
||||
app.return_to_tool(&t);
|
||||
} else {
|
||||
app.select_tool(&t);
|
||||
}
|
||||
}
|
||||
vectorcraft_engine::UiRequest::Status(msg) => app.status(msg),
|
||||
vectorcraft_engine::UiRequest::Place(p) => crate::place::place_from_cursor(app, &p),
|
||||
// In the document the press was made in, which may no longer be the active one.
|
||||
|
||||
@@ -140,7 +140,7 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo
|
||||
drag_held(app, ui, &f, d, p);
|
||||
} else {
|
||||
// The drag ends where its button went up: the moves after the release in this frame are hover.
|
||||
drag_released(app, ui, &f, d, release_pos(ui, button).unwrap_or(p));
|
||||
drag_released(app, ui, &f, d, release_pos(ui, button, false).unwrap_or(p));
|
||||
}
|
||||
} else if let Some(p) = hover_tool
|
||||
// A press on an artboard's name starts no drag: the moves while it is held are not hover.
|
||||
@@ -190,15 +190,18 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo
|
||||
.unwrap_or(m.shift);
|
||||
select_named_artboard(app, i, shift || release_shift);
|
||||
}
|
||||
if resp.double_clicked()
|
||||
let click = super::primary_click(ui, resp);
|
||||
if !super::ignore_sampler_owns_primary(ui, resp.id)
|
||||
&& click.count == 2
|
||||
&& !f.modal
|
||||
&& let Some(p) = at
|
||||
&& let Some(p) = click.at.or(at)
|
||||
{
|
||||
double_click(app, ui, &f, p);
|
||||
}
|
||||
if resp.triple_clicked()
|
||||
if !super::ignore_sampler_owns_primary(ui, resp.id)
|
||||
&& click.count == 3
|
||||
&& !f.modal
|
||||
&& let Some(p) = at
|
||||
&& let Some(p) = click.at.or(at)
|
||||
{
|
||||
triple_click(app, ui, &f, p);
|
||||
}
|
||||
@@ -339,7 +342,7 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) {
|
||||
Drag::RotateView { start_angle: (p.y - c.y).atan2(p.x - c.x) as f64, start_rot: v.rotation, snaps: !space }
|
||||
} else {
|
||||
// Cmd with another tool drags with the selection tool used last (the session lends it).
|
||||
let ev = PointerEvent {
|
||||
let mut ev = PointerEvent {
|
||||
kind: PointerKind::Down,
|
||||
pos: xf.to_doc(p),
|
||||
mods: mods(m, space),
|
||||
@@ -347,9 +350,25 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) {
|
||||
pressure: pen_pressure(ui, app, true),
|
||||
pen: pen_pose(app, &xf),
|
||||
};
|
||||
// Only a Down actually sent to this sampler owns the gesture. Cmd/Ctrl's borrowed
|
||||
// selection press keeps the ordinary tool path.
|
||||
let sampler = app.ui.trace_ignore_sampler.is_some() && tool == "eyedropper" && app.session.lent_tool_id(&ev.mods).is_none();
|
||||
if sampler {
|
||||
// A later hover move is not the source pixel that was pressed.
|
||||
let pressed = ui.input(|i| {
|
||||
i.events.iter().find_map(|event| match event {
|
||||
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos),
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
if let Some(pressed) = pressed {
|
||||
ev.pos = xf.to_doc(pressed);
|
||||
}
|
||||
ui.data_mut(|data| data.insert_temp(super::ignore_sampler_primary_id(resp.id), true));
|
||||
}
|
||||
dispatch(app, &ev, view);
|
||||
crate::document_drag::begin(app, ui.ctx(), ev.pos);
|
||||
Drag::Tool
|
||||
if sampler { Drag::Gesture } else { Drag::Tool }
|
||||
};
|
||||
// A drag of the Zoom, Hand or Rotate View tool uses the tool of a held shortcut; held Space's
|
||||
// view tools are not that tool.
|
||||
@@ -611,7 +630,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po
|
||||
// The second click of a double-click: don't fit another artboard on this release.
|
||||
// A double-click on an object does not open Artboard Options. Empty artboard
|
||||
// space still does.
|
||||
if resp.double_clicked() && app.session.tool_id() == "artboard" {
|
||||
if super::primary_click_count(ui, resp) == 2 && app.session.tool_id() == "artboard" {
|
||||
app.session.set_tool_option("suppressFitClick", &json!(true));
|
||||
}
|
||||
// A move that came in the release's own frame shapes the preview first: the
|
||||
@@ -714,13 +733,14 @@ fn triple_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) {
|
||||
dispatch(app, &ev, view);
|
||||
}
|
||||
|
||||
/// Where `button` went up in this frame, if it did.
|
||||
fn release_pos(ui: &Ui, button: egui::PointerButton) -> Option<Pos2> {
|
||||
/// Where `button` went up: the first release ends a drag, the last classifies this frame's click.
|
||||
fn release_pos(ui: &Ui, button: egui::PointerButton, last: bool) -> Option<Pos2> {
|
||||
ui.input(|i| {
|
||||
i.events.iter().find_map(|e| match e {
|
||||
let mut releases = i.events.iter().filter_map(|e| match e {
|
||||
egui::Event::PointerButton { pos, button: b, pressed: false, .. } if *b == button => Some(*pos),
|
||||
_ => None,
|
||||
})
|
||||
});
|
||||
if last { releases.next_back() } else { releases.next() }
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -171,28 +171,17 @@ thread_local! {
|
||||
static TARGET_LOOKUPS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The object Trace acts on: the first selected image or Image Trace object in paint order, as
|
||||
/// `imageTrace.make` takes it, else the first selected object. Only the selected images and Image
|
||||
/// Trace objects are put in paint order.
|
||||
/// The image or Image Trace object `imageTrace.make` takes from the selected roots, else the
|
||||
/// first selected non-traceable object's metadata. Release and Expand keep their own selection scope.
|
||||
fn find_target(app: &VectorcraftApp) -> Target {
|
||||
let Some(st) = app.session.active() else { return Target::default() };
|
||||
#[cfg(test)]
|
||||
TARGET_LOOKUPS.with(|n| n.set(n.get() + 1));
|
||||
let mut any_trace = false;
|
||||
let traceable: Vec<NodeId> = st
|
||||
.selection
|
||||
.objects
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| {
|
||||
st.doc.node(*id).is_some_and(|n| {
|
||||
let trace = is_trace(n);
|
||||
any_trace |= trace;
|
||||
trace || matches!(n.kind, NodeKind::Image(_))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let node = st.doc.paint_order(traceable).into_iter().find_map(|id| st.doc.node(id)).or_else(|| first_node(app));
|
||||
let any_trace = st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(is_trace));
|
||||
let node = vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null)
|
||||
.ok()
|
||||
.and_then(|id| st.doc.node(id))
|
||||
.or_else(|| first_node(app).filter(|n| !is_trace(n) && !matches!(n.kind, NodeKind::Image(_))));
|
||||
let Some(n) = node else { return Target { any_trace, ..Target::default() } };
|
||||
Target {
|
||||
object: Some((st.uid, n.id)),
|
||||
@@ -319,6 +308,175 @@ 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
|
||||
&& find_target(app).object == 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 };
|
||||
// This UI session owns these transient fields even while Cmd/Ctrl parks the eyedropper
|
||||
// behind a borrowed selection tool. The named setter also updates that stored lender.
|
||||
let options = serde_json::Map::from_iter([("imageTraceIgnoreColor".into(), Value::Null), ("stop".into(), Value::Null)]);
|
||||
app.session.set_tool_options(Some("eyedropper"), &options);
|
||||
if restore && app.session.tool_id() == "eyedropper" {
|
||||
app.return_to_tool(&s.back);
|
||||
}
|
||||
if let Some(ctx) = &app.ui_ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Presets and restored panel settings can turn Ignore Color off without its checkbox.
|
||||
fn cancel_disabled_ignore_sampler(app: &mut VectorcraftApp, params: &Value) {
|
||||
if params["ignoreWhite"] != true {
|
||||
cancel_ignore_sampler(app, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Also runs when the panel is closed: document changes and tool changes end the pick.
|
||||
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
|
||||
}
|
||||
|
||||
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(app, ctx).object 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;
|
||||
if !pixel.x.is_finite()
|
||||
|| !pixel.y.is_finite()
|
||||
|| pixel.x < 0.0
|
||||
|| pixel.y < 0.0
|
||||
|| pixel.x >= f64::from(image.width.max(1))
|
||||
|| pixel.y >= f64::from(image.height.max(1))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
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}"))
|
||||
}
|
||||
|
||||
/// A miss keeps the pick armed; only a valid source color, Escape or invalid binding ends it.
|
||||
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;
|
||||
}
|
||||
if p["cancel"] == true {
|
||||
// Escape already carries its one deferred SwitchTool request.
|
||||
cancel_ignore_sampler(app, false);
|
||||
return;
|
||||
}
|
||||
if !sampler_valid(app, s) {
|
||||
cancel_ignore_sampler(app, true);
|
||||
return;
|
||||
}
|
||||
// Outside the source or over a transparent pixel there is no color to accept. Keep the
|
||||
// binding and previous tool so the next canvas click can still complete this pick.
|
||||
let Some(color) = sampled_ignore_color(app, s, p) else { return };
|
||||
let s = s.clone();
|
||||
// The canvas UI establishes this context before a real panel click can arm the sampler.
|
||||
let Some(ctx) = app.ui_ctx.clone() else { return };
|
||||
cancel_ignore_sampler(app, false);
|
||||
let all = presets(app, &ctx);
|
||||
let mut st: TraceUi = pstate(&ctx, "image-trace");
|
||||
let Target { is_trace, stored, .. } = target(app, &ctx);
|
||||
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();
|
||||
// Complete the temporary tool without treating its return as a fresh explicit tool choice.
|
||||
// A miss above has no switch request and remains armed.
|
||||
app.return_to_tool(&s.back);
|
||||
}
|
||||
|
||||
/// 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:"));
|
||||
@@ -894,17 +1052,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());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -942,6 +1119,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if is_trace || !preview {
|
||||
st.preview_off = !preview;
|
||||
}
|
||||
cancel_disabled_ignore_sampler(app, &st.params);
|
||||
if retrace && is_trace && preview {
|
||||
trace(app, ui.ctx(), &mut st);
|
||||
}
|
||||
|
||||
@@ -1763,7 +1763,8 @@ fn lookup_fixture() -> (VectorcraftApp, std::collections::HashMap<&'static str,
|
||||
/// The panel's lookup gives what putting the whole selection in paint order gave, field for field,
|
||||
/// for every kind of selection: images in either selection order, an Image Trace object with its
|
||||
/// own image, a clipping group named Image Trace, nested groups, hidden and locked images, two
|
||||
/// layers, repeated ids, ids the document lacks, and nothing selected. The result kept for a
|
||||
/// layers, repeated ids, ids the document lacks, and nothing selected. Selected ancestors with
|
||||
/// their descendants have separate canonical-root expectations below. The result kept for a
|
||||
/// revision follows each change of the selection, an edit, Undo and a switch of document.
|
||||
#[test]
|
||||
fn the_target_lookup_matches_sorting_the_whole_selection() {
|
||||
@@ -1779,10 +1780,8 @@ fn the_target_lookup_matches_sorting_the_whole_selection() {
|
||||
&["trace image", "trace"],
|
||||
&["rect", "trace image"],
|
||||
&["clip"],
|
||||
&["clip", "clipped"],
|
||||
&["rect", "clipped"],
|
||||
&["outer"],
|
||||
&["outer", "deep"],
|
||||
&["inner", "rect"],
|
||||
&["deep", "back"],
|
||||
&["hidden", "locked"],
|
||||
@@ -1838,6 +1837,37 @@ fn the_target_lookup_matches_sorting_the_whole_selection() {
|
||||
assert_eq!(target(&none, &ctx), Target::default());
|
||||
}
|
||||
|
||||
/// Trace only accepts selected roots: a selected parent blocks its image descendant.
|
||||
/// Missing implicit-selection ids are dropped, while explicit ids are validated.
|
||||
#[test]
|
||||
fn the_target_lookup_obeys_canonical_roots_and_explicit_id_validation() {
|
||||
let (mut app, ids) = lookup_fixture();
|
||||
let ctx = egui::Context::default();
|
||||
for (parent, child) in [("clip", "clipped"), ("outer", "deep")] {
|
||||
select_as_is(&mut app, &[ids[parent], ids[child]]);
|
||||
let uid = app.session.active().unwrap().uid;
|
||||
let expected = Target { object: Some((uid, ids[parent])), ..Default::default() };
|
||||
assert_eq!(find_target(&app), expected, "the selected {parent} supplies metadata, not its pruned image");
|
||||
assert_eq!(target(&app, &ctx), expected);
|
||||
assert_eq!(target(&app, &ctx), expected, "the canonical result is also cached");
|
||||
assert!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).is_err());
|
||||
let document = app.session.active().unwrap().doc.clone();
|
||||
assert!(app.run("imageTrace.make", json!({})).is_err(), "Trace rejects that non-image root");
|
||||
assert_eq!(app.session.active().unwrap().doc, document);
|
||||
select_as_is(&mut app, &[ids[child]]);
|
||||
assert_eq!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).unwrap(), ids[child], "the image alone remains eligible");
|
||||
}
|
||||
let stale = NodeId(u64::MAX);
|
||||
select_as_is(&mut app, &[stale, ids["front"]]);
|
||||
assert_eq!(target(&app, &ctx).object.map(|(_, id)| id), Some(ids["front"]), "implicit stale entries do not hide a valid image");
|
||||
assert_eq!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).unwrap(), ids["front"]);
|
||||
let explicit = json!({"ids": [stale.0, ids["front"].0]});
|
||||
let document = app.session.active().unwrap().doc.clone();
|
||||
assert!(vectorcraft_engine::cmd::image_trace_target(&app.session, &explicit).is_err(), "explicit missing ids are invalid");
|
||||
assert!(app.run("imageTrace.make", explicit).is_err());
|
||||
assert_eq!(app.session.active().unwrap().doc, document);
|
||||
}
|
||||
|
||||
/// The panel and its menu look the object Trace acts on up once for each revision of the document,
|
||||
/// however many frames show it, and again once the revision moves.
|
||||
#[test]
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
/// A Brush Options Key Color click, owned by its dialog and document until release or cancel.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BrushKeyColorPick {
|
||||
@@ -928,6 +937,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,
|
||||
@@ -1372,6 +1384,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(),
|
||||
attributes_panel: Default::default(),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+3
-2
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+4
-1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user