diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f70e1c39f47..e2915300296 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -28,7 +28,7 @@ pub use color_panel::ColorPanelState; pub use panel_state::{CurvesEditorState, PointCurveDrag, PointCurveState}; pub use text_edit::{TextEdit, TypeInsertionStyle, TypeTransform}; pub use tool::Tool; -pub use tool_options::{SampleAllLayers, ToolOptions}; +pub use tool_options::{ObjectFinderMode, SampleAllLayers, ToolOptions}; use tool_options::{default_brush_tool, yes}; pub use transform::{CamTransform, ContentAwareOptions, Extras, FreeTransform, MadeLayer, SessionWarp}; diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 6475f9c4b0e..d3a211e64ac 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -6,6 +6,16 @@ use craft::imaging::ui::select::MagneticSettings; use super::tool::Tool; use super::{Deserialize, Serialize}; +/// Object Selection › gear › Object Finder Mode (#12857). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ObjectFinderMode { + /// Auto Refresh: the finder re-analyses the document after every edit. + #[default] + Auto, + /// Manual Refresh: the finder re-analyses only when Refresh is clicked. + Manual, +} + /// Options-bar state for tools (Photoshop keeps these per tool). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -18,6 +28,10 @@ pub struct ToolOptions { pub sample_all: SampleAllLayers, /// Object Selection › Object Finder: hovering highlights the object a click selects (#4087). pub object_finder: bool, + /// Object Selection › gear › Object Subtract; stored only, today's subtract behaviour is unchanged (#12857). + pub object_subtract: bool, + /// Object Selection › gear › Object Finder Mode: when the finder re-analyses (#12857). + pub object_finder_mode: ObjectFinderMode, /// Object Selection › Hard Edge (#12855): off, the result gets a softer, slightly wider rim. pub object_hard_edge: bool, /// Remove tool: the fill goes to a new layer above the target (Photoshop's Create a new layer). @@ -412,6 +426,8 @@ impl Default for ToolOptions { anti_alias: true, sample_all: SampleAllLayers::default(), object_finder: true, + object_subtract: true, + object_finder_mode: ObjectFinderMode::Auto, object_hard_edge: true, remove_new_layer: false, remove_after_each_stroke: true, diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index c66d112cf20..a1789e53051 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -69,6 +69,8 @@ mod gradient_options_bar_mode_tests; #[cfg(test)] mod line_tool_defaults_tests; #[cfg(test)] +mod object_selection_gear_tests; +#[cfg(test)] mod object_selection_mode_tests; #[cfg(test)] mod path_selection_ctrl_direct_tests; diff --git a/crates/ui-egui/src/tools/object_finder.rs b/crates/ui-egui/src/tools/object_finder.rs index 9ae769824b3..cd5790aa4f6 100644 --- a/crates/ui-egui/src/tools/object_finder.rs +++ b/crates/ui-egui/src/tools/object_finder.rs @@ -11,6 +11,12 @@ //! pixels, so an edit drops it. The preview itself is keyed by document revision, sampled layer and //! Sample All Layers, and clears when the pointer leaves the canvas, the tool changes, a button //! goes down or the option is off. Quality of the object found is out of scope here (#2788). +//! +//! The options bar has a Refresh button and a gear menu (#12857): Object Finder on/off, Object +//! Subtract (stored only) and Object Finder Mode. Auto Refresh re-analyses after every edit, as +//! above. Manual Refresh keeps the analysed pixels (`Finder::basis`) across the pointer leaving, +//! a tool switch and selection-only changes; it analyses nothing until Refresh is clicked +//! ([`refresh`]): not on the first hover, on another document, or after a pixel edit. use std::sync::Arc; @@ -23,7 +29,7 @@ use photocraft_engine::smartselect_cmds::{empty_sampled_area, find_object, sampl use crate::PhotocraftApp; use crate::canvas::tools::in_gesture; -use crate::state::Tool; +use crate::state::{ObjectFinderMode, Tool}; /// Seconds the pointer must rest before an object is looked up. pub const DEBOUNCE: f64 = 0.12; @@ -53,6 +59,8 @@ pub(crate) struct Finder { shown: Option>, /// The hover mask of `shown`, with the object it was made from. mask: Option<(Arc, HoverMask)>, + /// The document whose pixels were last analysed (Manual Refresh compares against it). + basis: Arc, } /// What [`update`] decided. @@ -95,7 +103,7 @@ fn mask_of(r: &Region) -> HoverMask { pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: bool, now: f64, ctx: &egui::Context) -> Update { let at = at.filter(|p| p[0].is_finite() && p[1].is_finite()); let (Some(at), true) = (at, active(app, pressed)) else { - app.object_finder = None; + idle(app); return Update::default(); }; let Some(st) = app.session.active() else { return Update::default() }; @@ -104,10 +112,24 @@ pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: boo let (doc, revision, layer) = (st.doc.id, st.revision, st.active_layer); let px = [at[0].floor() as i32, at[1].floor() as i32]; let fresh = app.object_finder.as_ref().is_some_and(|f| f.doc == doc && f.revision == revision && f.target == target && f.all_layers == all_layers); - if !fresh { - app.object_finder = Some(Finder { doc, revision, target, all_layers, at: px, since: now, job: None, misses: Vec::new(), shown: None, mask: None }); - } let doc_arc = Arc::clone(&st.doc); + if !fresh { + let manual = app.ui.tool_options.object_finder_mode == ObjectFinderMode::Manual; + match app.object_finder.as_mut() { + // Manual Refresh: a selection-only change keeps the analysis, a pixel edit makes it stale. + Some(f) if manual && f.doc == doc => { + if f.target == target && f.all_layers == all_layers && photocraft_engine::layer_multi_cmds::same_pixels(&f.basis, &doc_arc) { + f.revision = revision; + } else { + return Update::default(); + } + } + // Manual Refresh analyses nothing until Refresh is clicked: no finder yet, or one kept + // for another document, waits for [`refresh`] (#12857). + _ if manual => return Update::default(), + _ => app.object_finder = start(app), + } + } // The click reports an empty sampled layer; the hover says so too instead of showing nothing. let here = photocraft_geom::Rect::from_xywh(px[0], px[1], 1, 1); if doc_arc.bounds().contains(px[0], px[1]) && empty_sampled_area(&doc_arc, layer, all_layers, here).is_some() { @@ -197,9 +219,50 @@ fn spawn(doc: Arc, layer: Option, all_layers: bool, px: [i32; Job { at: px, doc, rx } } +/// Drops the preview. Auto Refresh forgets the finder; Manual Refresh keeps the analysed +/// pixels so the pointer leaving or a tool switch doesn't lose them. +fn idle(app: &mut PhotocraftApp) { + if app.ui.tool_options.object_finder_mode == ObjectFinderMode::Manual + && let Some(f) = app.object_finder.as_mut() + { + f.shown = None; + f.job = None; + f.mask = None; + f.misses.clear(); + } else { + app.object_finder = None; + } +} + /// Clears the preview (a tool switch or an edit made elsewhere is caught by [`update`] too). pub(crate) fn clear(app: &mut PhotocraftApp) { - app.object_finder = None; + idle(app); +} + +/// The options bar's Refresh button: the next [`update`] analyses the current pixels. Under +/// Manual Refresh this is the only way a finder starts. +pub(crate) fn refresh(app: &mut PhotocraftApp) { + app.object_finder = start(app); +} + +/// A new finder for the active document's current pixels, sampled layer and Sample All Layers. +/// Its pointer position is unset, so the first hover starts the debounce. +fn start(app: &PhotocraftApp) -> Option { + let st = app.session.active()?; + let all_layers = app.ui.tool_options.sample_all.object_selection; + Some(Finder { + doc: st.doc.id, + revision: st.revision, + target: sampled_target(&st.doc, st.active_layer, all_layers), + all_layers, + at: [i32::MIN, i32::MIN], + since: 0.0, + job: None, + misses: Vec::new(), + shown: None, + mask: None, + basis: Arc::clone(&st.doc), + }) } /// Updates the preview for this frame and shows the highlight. `at` is the pointer in document diff --git a/crates/ui-egui/src/tools/object_selection_gear_tests.rs b/crates/ui-egui/src/tools/object_selection_gear_tests.rs new file mode 100644 index 00000000000..72cf230ecf7 --- /dev/null +++ b/crates/ui-egui/src/tools/object_selection_gear_tests.rs @@ -0,0 +1,146 @@ +//! Object Selection's Refresh button and gear menu (#12857): Object Finder, Object Subtract and +//! Object Finder Mode are options that Reset Tool restores; Manual Refresh keeps the analysed +//! pixels until Refresh is clicked, Auto Refresh re-analyses after every edit. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::object_finder::{Update, refresh, update}; +use crate::state::{ObjectFinderMode, Tool, ToolOptions}; + +const DISC: [f64; 2] = [100.0, 80.0]; + +/// A 200 x 160 document: a red disc (centre 100,80, radius 45) on blue, nothing selected. +fn app(mode: ObjectFinderMode) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 160})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 160})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#3366cc"})).unwrap(); + app.run("select.rect", json!({"x": 55, "y": 35, "width": 90, "height": 90, "ellipse": true})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#e63319"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::ObjectSelection; + app.ui.tool_options.object_finder = true; + app.ui.tool_options.object_finder_mode = mode; + app +} + +/// Hovers at `at` until the lookup settles (time advances past the debounce). +fn hover(app: &mut PhotocraftApp, at: [f64; 2]) -> Update { + let ctx = app.ctx().clone(); + let mut t = 100.0; + loop { + let u = update(app, Some(at), false, t, &ctx); + if !u.busy || t > 130.0 { + return u; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + t += 0.05; + } +} + +/// A pixel edit away from the disc. +fn edit_pixels(app: &mut PhotocraftApp) { + app.run("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); +} + +#[test] +fn defaults_and_old_settings() { + let d = ToolOptions::default(); + assert!(d.object_finder && d.object_subtract); + assert_eq!(d.object_finder_mode, ObjectFinderMode::Auto); + let o: ToolOptions = serde_json::from_value(json!({})).unwrap(); + assert!(o.object_finder && o.object_subtract); + assert_eq!(o.object_finder_mode, ObjectFinderMode::Auto); + let mut v = serde_json::to_value(&d).unwrap(); + let m = v.as_object_mut().unwrap(); + m.remove("object_subtract"); + m.remove("object_finder_mode"); + let o: ToolOptions = serde_json::from_value(v).unwrap(); + assert_eq!(o, d); +} + +#[test] +fn options_round_trip() { + let o = ToolOptions { object_subtract: false, object_finder_mode: ObjectFinderMode::Manual, ..ToolOptions::default() }; + let back: ToolOptions = serde_json::from_value(serde_json::to_value(&o).unwrap()).unwrap(); + assert!(!back.object_subtract); + assert_eq!(back.object_finder_mode, ObjectFinderMode::Manual); +} + +#[test] +fn reset_tool_restores_them() { + let mut o = ToolOptions { object_finder: false, object_subtract: false, object_finder_mode: ObjectFinderMode::Manual, ..ToolOptions::default() }; + crate::tools::tool_reset::reset_options(&mut o, Tool::Lasso); + assert!(!o.object_finder && !o.object_subtract && o.object_finder_mode == ObjectFinderMode::Manual); + crate::tools::tool_reset::reset_options(&mut o, Tool::ObjectSelection); + assert_eq!(o, ToolOptions::default()); +} + +/// Hovers long past the debounce and checks nothing was shown or started. +fn assert_idle(app: &mut PhotocraftApp) { + let u = hover(app, DISC); + assert!(u.shown.is_none() && !u.busy); + let ctx = app.ctx().clone(); + let u = update(app, Some(DISC), false, 500.0, &ctx); + assert!(u.shown.is_none() && !u.busy); +} + +#[test] +fn manual_refresh_analyses_nothing_before_refresh() { + let mut app = app(ObjectFinderMode::Manual); + assert_idle(&mut app); + refresh(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); +} + +#[test] +fn manual_refresh_needs_refresh_on_another_document() { + let mut app = app(ObjectFinderMode::Manual); + refresh(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); + app.run("file.new", json!({"width": 200, "height": 160})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 55, "y": 35, "width": 90, "height": 90, "ellipse": true})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#e63319"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + assert_idle(&mut app); + refresh(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); +} + +#[test] +fn manual_refresh_waits_for_refresh_after_a_pixel_edit() { + let mut app = app(ObjectFinderMode::Manual); + refresh(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); + edit_pixels(&mut app); + assert_idle(&mut app); + refresh(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); +} + +#[test] +fn manual_refresh_survives_selection_changes_and_leaving() { + let mut app = app(ObjectFinderMode::Manual); + refresh(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); + let ctx = app.ctx().clone(); + assert!(update(&mut app, None, false, 200.0, &ctx).shown.is_none()); + app.run("select.all", json!({})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + assert!(hover(&mut app, DISC).shown.is_some()); +} + +#[test] +fn auto_refresh_reanalyses_after_a_pixel_edit() { + let mut app = app(ObjectFinderMode::Auto); + assert!(hover(&mut app, DISC).shown.is_some()); + edit_pixels(&mut app); + assert!(hover(&mut app, DISC).shown.is_some()); +} diff --git a/crates/ui-egui/src/tools/retouch_ui/bar/select.rs b/crates/ui-egui/src/tools/retouch_ui/bar/select.rs index be9ad1aeb21..a53e7aa9e5a 100644 --- a/crates/ui-egui/src/tools/retouch_ui/bar/select.rs +++ b/crates/ui-egui/src/tools/retouch_ui/bar/select.rs @@ -1,14 +1,18 @@ //! The Retouch options bar's selection family: Quick Selection and Object Selection. -use craft::ui::buttons::Button; -use craft::ui::contract::{Show as _, clicked}; +use craft::behavior::IconId; +use craft::ui::buttons::{Button, IconButton}; +use craft::ui::contract::{Entry, Props as _, Show as _, Trigger, clicked}; use craft::ui::display::Divider; +use craft::ui::menu::Menu; +use craft::ui::runtime::access::PopupKind; use craft::ui::text::RangeAlert; use serde_json::json; use super::heal::check; use crate::PhotocraftApp; use crate::option_cells::hint; +use crate::state::ObjectFinderMode; /// The Select Subject button both selection tools carry; `empty` is the message when nothing is found. fn select_subject(ui: &mut egui::Ui, app: &mut PhotocraftApp, empty: &str) { @@ -29,16 +33,52 @@ pub(super) fn quick_selection(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Opt None } -/// Object Selection's options: the selection operation (#12853), Object Finder, Sample All Layers -/// and Hard Edge. +/// A row of the Object Selection gear menu. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum GearOption { + Finder, + Subtract, + Auto, + Manual, +} + +/// The Refresh button and the gear menu after the operation segments (#12857): Object Finder, +/// Object Subtract (stored only) and Object Finder Mode (Auto or Manual Refresh). +fn finder_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let refresh = IconButton::new(IconId::new("rotate_cw")).label(tl!("Refresh").to_string()).tooltip(tl!("Click to refresh object finder.")).show(ui); + let label = tl!("Set additional options").to_string(); + let button = IconButton::new(IconId::new("settings")).label(label.clone()).tooltip(tl!("Set additional options")).popup(PopupKind::Menu).show(ui); + let o = &app.ui.tool_options; + let auto = o.object_finder_mode == ObjectFinderMode::Auto; + let entries = [ + Entry::new(GearOption::Finder, tl!("Object Finder").to_string()).checked(o.object_finder), + Entry::new(GearOption::Subtract, tl!("Object Subtract").to_string()).checked(o.object_subtract), + Entry::new(GearOption::Auto, tl!("Auto Refresh").to_string()).checked(auto), + Entry::new(GearOption::Manual, tl!("Manual Refresh").to_string()).checked(!auto), + ]; + let picked = Menu::new(label).opened_by(&button, Trigger::Press).pick(ui, &entries).picked; + let o = &mut app.ui.tool_options; + match picked { + Some(GearOption::Finder) => o.object_finder = !o.object_finder, + Some(GearOption::Subtract) => o.object_subtract = !o.object_subtract, + Some(GearOption::Auto) => o.object_finder_mode = ObjectFinderMode::Auto, + Some(GearOption::Manual) => o.object_finder_mode = ObjectFinderMode::Manual, + None => {} + } + if clicked(&refresh) { + crate::object_finder::refresh(app); + } +} + +/// Object Selection's options: the selection operation (#12853), Refresh and the gear menu, +/// Sample All Layers and Hard Edge. pub(super) fn object_selection(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Option { crate::panels::options_bar::selection::operation_segments(app, ui, true); Divider::vertical().show(ui); + finder_buttons(app, ui); let o = &mut app.ui.tool_options; - check(ui, tl!("Object Finder"), &mut o.object_finder, true, None); check(ui, tl!("Sample All Layers"), &mut o.sample_all.object_selection, true, None); check(ui, tl!("Hard Edge"), &mut o.object_hard_edge, true, None); - hint(ui, tl!("Drag a rectangle around the object")); Divider::vertical().show(ui); select_subject(ui, app, tl!("No subject found — try a rectangle around the object")); None diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 0399ab0ba57..9ae6996347b 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -205,7 +205,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::MagneticLasso => reset!(feather, anti_alias, magnetic), Tool::MagicWand => reset!(tolerance, anti_alias, contiguous), Tool::QuickSelection => reset!(enhance_edge), - Tool::ObjectSelection => reset!(enhance_edge, object_finder, object_hard_edge), + Tool::ObjectSelection => reset!(enhance_edge, object_finder, object_subtract, object_finder_mode, object_hard_edge), Tool::Crop => reset!(crop), Tool::PerspectiveCrop => reset!(perspective_crop, perspective_crop_grid), Tool::Eyedropper => reset!(eyedropper),