diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/adjust_dialog.rs index ff6ace25753..cdd4cac083d 100644 --- a/crates/ui-egui/src/adjust_dialog.rs +++ b/crates/ui-egui/src/adjust_dialog.rs @@ -126,6 +126,29 @@ pub fn owns(fields: &Map) -> bool { fields.contains_key("__adjust") } +/// Root of the dialog editor's view state in egui memory. +fn dialog_mem(kind: &str) -> egui::Id { + egui::Id::new(("adjust-dialog", kind)) +} + +/// Whether holding Alt turns the dialog's Cancel into Reset. Measured in Photoshop 25.4 for Color +/// Balance; other kinds keep Cancel until checked against Photoshop. +pub fn resets(fields: &Map) -> bool { + fields.get("__adjust").and_then(Value::as_str) == Some("colorBalance") +} + +/// Alt+Cancel (Reset): back to the defaults Photoshop's Reset restores, dialog stays open. +pub fn reset(ctx: &egui::Context, fields: &mut Map) { + if !resets(fields) { + return; + } + let mut values = crate::filter_dialog::params_of(fields); + adjust_editors::reset_color_balance(ctx, dialog_mem("colorBalance"), &mut values); + if let Value::Object(v) = values { + fields.extend(v); + } +} + /// Opens the dialog for `command` with the kind's neutral settings. pub fn open(app: &mut PhotocraftApp, command: &str) -> Option { let kind = command.strip_prefix(PREFIX).filter(|k| adjust_editors::has_editor(k))?; @@ -159,7 +182,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map Some(tone::histograms(app, HistSource::Layer(id), adjust_editors::space_of(&values))), _ => None, }; - let cx = EditorCx { mem: egui::Id::new(("adjust-dialog", kind.as_str())), hist, gray, swatches: adjust_editors::swatches(app) }; + let cx = EditorCx { mem: dialog_mem(&kind), hist, gray, swatches: adjust_editors::swatches(app), dialog: true }; let e = adjust_editors::editor(ui, &kind, &mut values, &cx); if e.changed && let Value::Object(v) = values @@ -275,6 +298,99 @@ mod tests { } } + fn color_balance_dialog() -> (Harness<'static, PhotocraftApp>, u64) { + // Real frame times: a double-click's two clicks must land within the double-click time. + let mut h = Harness::builder() + .with_size(egui::vec2(1200.0, 900.0)) + .with_step_dt(1.0 / 60.0) + .build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut(), "image.adjustments.colorBalance").unwrap(); + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + for (k, v) in + [("shadows", json!([10, 0, 0])), ("midtones", json!([40, -30, 20])), ("highlights", json!([0, 0, -15])), ("preserveLuminosity", json!(false))] + { + d.fields.insert(k.into(), v); + } + h.run_steps(3); + (h, id) + } + + fn field(h: &Harness<'static, PhotocraftApp>, id: u64, key: &str) -> Value { + h.state().ui.dialogs.iter().find(|d| d.id == id).map(|d| d.fields.get(key).cloned().unwrap_or(Value::Null)).unwrap_or(Value::Null) + } + + fn input(h: &mut Harness<'static, PhotocraftApp>, mods: egui::Modifiers, events: &[egui::Event]) { + h.event(egui::Event::ModifiersChanged(mods)); + h.run_steps(1); + for e in events { + h.event(e.clone()); + h.run_steps(1); + } + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(3); + } + + /// Photoshop 25.4's Color Balance dialog (measured with the real application): a double-click + /// on a slider zeroes it whatever the modifiers; the wheel over a slider steps it by 1, with + /// Shift by 10 (Ctrl/Alt: 1); holding Alt turns Cancel into Reset, which zeroes every tone, + /// shows Midtones, keeps Preserve Luminosity and leaves the dialog open. + #[test] + fn color_balance_dialog_gestures_match_photoshop() { + use egui_kittest::kittest::Queryable; + let (mut h, id) = color_balance_dialog(); + let label = h.query_all_by_label("Cyan · Red").last().map(|n| n.rect()).expect("Cyan · Red row"); + let at = egui::pos2(label.left() + 60.0, label.bottom() + 14.0); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(at), press(true), press(false), press(true), press(false)]); + assert_eq!(field(&h, id, "midtones"), json!([0.0, -30.0, 20.0]), "Alt+double-click zeroes the slider"); + assert_eq!(field(&h, id, "shadows"), json!([10, 0, 0]), "other tones untouched"); + let wheel = + |n: f32, m| egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: egui::vec2(0.0, n), phase: egui::TouchPhase::Move, modifiers: m }; + input(&mut h, egui::Modifiers::NONE, &[egui::Event::PointerMoved(at), wheel(3.0, egui::Modifiers::NONE)]); + assert_eq!(field(&h, id, "midtones")[0], json!(3.0), "3 notches up"); + input(&mut h, egui::Modifiers::SHIFT, &[egui::Event::PointerMoved(at), wheel(2.0, egui::Modifiers::SHIFT)]); + assert_eq!(field(&h, id, "midtones")[0], json!(23.0), "Shift: 10 per notch"); + input(&mut h, egui::Modifiers::CTRL, &[egui::Event::PointerMoved(at), wheel(-1.0, egui::Modifiers::CTRL)]); + assert_eq!(field(&h, id, "midtones")[0], json!(22.0), "Ctrl: 1 per notch, down"); + // Alt turns Cancel into Reset. + assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Reset").is_none()); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("highlights".into(), json!([5, 5, 5])); + let tone = egui::Id::new(("adjust-dialog", "colorBalance")).with("cb-tone"); + h.ctx.data_mut(|d| d.insert_temp(tone, 2usize)); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + h.run_steps(2); + let reset = h.get_by_label("Reset").rect(); + assert!(h.query_by_label("Cancel").is_none()); + let click = + |pressed| egui::Event::PointerButton { pos: reset.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + input(&mut h, egui::Modifiers::ALT, &[egui::Event::PointerMoved(reset.center()), click(true), click(false)]); + assert!(h.state().ui.dialogs.iter().any(|d| d.id == id), "Reset keeps the dialog open"); + for k in ["shadows", "midtones", "highlights"] { + assert_eq!(field(&h, id, k), json!([0.0, 0.0, 0.0]), "{k}"); + } + assert_eq!(field(&h, id, "preserveLuminosity"), json!(false), "Reset keeps Preserve Luminosity"); + assert_eq!(h.ctx.data(|d| d.get_temp::(tone)), Some(1), "Reset shows Midtones"); + // Without Alt it is Cancel again, and it closes. + let cancel = h.get_by_label("Cancel").rect(); + let click = + |pressed| egui::Event::PointerButton { pos: cancel.center(), button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + input(&mut h, egui::Modifiers::NONE, &[egui::Event::PointerMoved(cancel.center()), click(true), click(false)]); + assert!(h.state().ui.dialogs.is_empty(), "Cancel closes"); + } + + /// Alt+Cancel is Reset only where it was checked against Photoshop. + #[test] + fn other_adjustment_dialogs_keep_cancel_under_alt() { + use egui_kittest::kittest::Queryable; + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app_with_image()); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + open(h.state_mut(), "image.adjustments.levels").unwrap(); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + h.run_steps(3); + assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Reset").is_none()); + } + fn sample_params(kind: &str) -> Value { match kind { "brightnessContrast" => json!({"brightness": 40}), diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rs index 10297cca3bb..d83783a1bbf 100644 --- a/crates/ui-egui/src/adjust_editors.rs +++ b/crates/ui-egui/src/adjust_editors.rs @@ -79,6 +79,9 @@ pub struct EditorCx { pub gray: bool, /// Current foreground and background colours (Gradient Map preset). pub swatches: [[f32; 3]; 2], + /// Hosted by an Image › Adjustments dialog (false: the Properties panel). Photoshop's dialog + /// sliders follow the mouse wheel; the panel's don't. + pub dialog: bool, } /// The Levels/Curves channel space the values address. @@ -863,8 +866,23 @@ fn hue_saturation(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { // --------------------------------------------------------------------------------------------- // Color Balance +/// Where the Color Balance editor rooted at `mem` keeps its Tone choice. +fn color_balance_tone_id(mem: egui::Id) -> egui::Id { + mem.with("cb-tone") +} + +/// Photoshop's Color Balance reset to defaults (Alt+Cancel in the dialog; the Properties panel's +/// Reset once the layer is as the panel found it): every tone back to 0 and the Tone choice back +/// to Midtones; Preserve Luminosity stays as it is. +pub fn reset_color_balance(ctx: &egui::Context, mem: egui::Id, v: &mut Value) { + for key in ["shadows", "midtones", "highlights"] { + v[key] = json!([0.0, 0.0, 0.0]); + } + ctx.data_mut(|d| d.insert_temp(color_balance_tone_id(mem), 1usize)); +} + fn color_balance(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { - let tone_id = cx.mem.with("cb-tone"); + let tone_id = color_balance_tone_id(cx.mem); let mut tone_ix: usize = ui.data(|d| d.get_temp(tone_id)).unwrap_or(1); ui.horizontal(|ui| { label(ui, tl!("Tone:")); @@ -883,9 +901,12 @@ fn color_balance(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit { (tl!("Magenta · Green"), Color32::from_rgb(210, 40, 190), Color32::from_rgb(40, 190, 60)), (tl!("Yellow · Blue"), Color32::from_rgb(230, 210, 30), Color32::from_rgb(40, 80, 230)), ]; + // Photoshop: a double-click on a slider zeroes it (this tone only); the dialog's sliders step + // with the wheel; Up/Down step the fields; Shift makes those steps 10. + let gestures = widgets::RowGestures { reset: Some(0.0), wheel_step: cx.dialog.then_some(1.0) }; let mut changed = false; for (i, (text, a, b)) in rows.iter().enumerate() { - let r = gradient_slider(ui, text, &mut vals[i], -100.0..=100.0, "", *a, *b); + let r = Edit::of(&widgets::slider_row_with(ui, text, &mut vals[i], -100.0..=100.0, "", Some(&[*a, *b]), gestures)); changed |= r.changed; e.add(r); } @@ -1186,6 +1207,83 @@ pub fn swatches(app: &PhotocraftApp) -> [[f32; 3]; 2] { [c(app.session.tools.foreground), c(app.session.tools.background)] } +/// Root of an adjustment layer's Properties editor view state in egui memory. +pub fn layer_mem(id: LayerId) -> egui::Id { + egui::Id::new(("adjust-layer", id.0)) +} + +/// Kinds whose Properties edits follow Photoshop's history and Reset (measured for Color Balance, +/// Photoshop 25.4): consecutive edits of the layer make one history step, and Reset first returns +/// to the settings the layer had when the panel started showing it. +fn photoshop_session(kind: &str) -> bool { + kind == "colorBalance" +} + +/// The `coalesce` key of a layer's Properties edits (one history step while they follow each +/// other, like Photoshop's "Modify … Layer"). +pub fn properties_coalesce(id: LayerId) -> String { + format!("properties-adjustment:{}", id.0) +} + +/// A layer's Properties session: document, last pass drawn, the settings the panel found, and +/// whether the panel edited them since (or since the last Reset). +type Session = (u64, u64, Value, bool); + +fn session_key(id: LayerId) -> egui::Id { + layer_mem(id).with("session") +} + +/// Remember the settings `id` (in document `doc`) had when the panel started showing it: kept +/// while it is drawn pass after pass, taken anew after a pass without it (another layer, +/// document or panel state shown). +fn track_session(ctx: &egui::Context, doc: u64, id: LayerId, committed: &Value) { + let pass = ctx.cumulative_pass_nr(); + let kept: Option = ctx.data(|d| d.get_temp(session_key(id))); + let (start, edited) = match kept { + Some((d, last, v, e)) if d == doc && last.saturating_add(1) >= pass => (v, e), + _ => (committed.clone(), false), + }; + ctx.data_mut(|d| d.insert_temp(session_key(id), (doc, pass, start, edited))); +} + +fn set_edited(ctx: &egui::Context, id: LayerId, edited: bool) { + let kept: Option = ctx.data(|d| d.get_temp(session_key(id))); + if let Some((doc, pass, start, _)) = kept { + ctx.data_mut(|d| d.insert_temp(session_key(id), (doc, pass, start, edited))); + } +} + +/// The settings layer `id` of document `doc` had when the Properties panel started showing it, +/// if the panel has edited them since (or since the last Reset). +pub fn session_start(ctx: &egui::Context, doc: u64, id: LayerId) -> Option { + let kept: Option = ctx.data(|d| d.get_temp(session_key(id))); + kept.filter(|k| k.0 == doc && k.3).map(|k| k.2) +} + +/// The Properties panel's Reset for an adjustment layer whose kind follows Photoshop's session +/// ([`photoshop_session`]): the `layer.setAdjustment` params, or None for other kinds. Edited in +/// the panel since it started showing the layer (or since the last Reset): back to the settings it +/// found (Tone choice kept); otherwise the defaults (Color Balance: [`reset_color_balance`]). +/// Either way part of the layer's edit step. +pub fn properties_reset(ctx: &egui::Context, doc: u64, id: LayerId, adj: &Adjustment) -> Option { + let kind = photocraft_engine::commands::adjustment_kind(adj); + if !photoshop_session(kind) { + return None; + } + let mut v = match session_start(ctx, doc, id) { + Some(start) => start, + None => { + let mut v = adjust_params::to_params(adj); + reset_color_balance(ctx, layer_mem(id), &mut v); + v + } + }; + set_edited(ctx, id, false); + v["layer"] = json!(id.0); + v["coalesce"] = json!(properties_coalesce(id)); + Some(v) +} + /// The Properties-panel editor of an adjustment layer: previews live (`app.live_adjust`) while a /// control moves and commits one `layer.setAdjustment` per gesture. pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj: &Adjustment) { @@ -1205,13 +1303,17 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj _ => {} } let committed = adjust_params::to_params(adj); + let session = photoshop_session(kind); + if session && let Some(doc) = app.session.active().map(|s| s.doc.id.0) { + track_session(ui.ctx(), doc, id, &committed); + } let mut values = match &app.live_adjust { Some((l, v)) if *l == id => v.clone(), _ => committed.clone(), }; let gray = app.session.active().is_some_and(|s| is_gray(s.doc.mode)); let hist = needs_histogram(kind).then(|| tone::histograms(app, HistSource::BelowLayer(id), space_of(&values))); - let cx = EditorCx { mem: egui::Id::new(("adjust-layer", id.0)), hist, gray, swatches: swatches(app) }; + let cx = EditorCx { mem: layer_mem(id), hist, gray, swatches: swatches(app), dialog: false }; let e = editor(ui, kind, &mut values, &cx); if e.changed { app.live_adjust = Some((id, values.clone())); @@ -1221,6 +1323,10 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj let rev = app.session.active().map(|s| s.revision); let mut p = values; p["layer"] = json!(id.0); + if session { + p["coalesce"] = json!(properties_coalesce(id)); + set_edited(ui.ctx(), id, true); + } if let Err(err) = app.run("layer.setAdjustment", p) { app.ui.status = err; } diff --git a/crates/ui-egui/src/adjust_editors_tests.rs b/crates/ui-egui/src/adjust_editors_tests.rs index aaefe7e6c6d..33aa5aec67f 100644 --- a/crates/ui-egui/src/adjust_editors_tests.rs +++ b/crates/ui-egui/src/adjust_editors_tests.rs @@ -31,8 +31,13 @@ const ALL_KINDS: [&str; 16] = [ ]; fn app_harness(kind: &str, mode: &str, depth: u32) -> Harness<'static, PhotocraftApp> { + app_harness_stepped(kind, mode, depth, 0.25) +} + +/// [`app_harness`] advancing `step_dt` seconds per frame (double-clicks need real frame times). +fn app_harness_stepped(kind: &str, mode: &str, depth: u32, step_dt: f32) -> Harness<'static, PhotocraftApp> { let (kind, mode) = (kind.to_string(), mode.to_string()); - let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).with_step_dt(step_dt).build_eframe(move |cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut s = photocraft_engine::Session::new(); s.execute("file.new", json!({"width": 96, "height": 64, "mode": mode, "depth": depth})).unwrap(); @@ -235,3 +240,159 @@ fn curves_fast_release_commits_one_edit_and_undo_restores_the_curve() { h.state_mut().run("edit.undo", json!({})).unwrap(); assert_eq!(layer(&h).1, before); } + +/// Real pointer input: `n` clicks at `at` with `mods` held (2 = a double-click). +fn clicks_with(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, n: usize, mods: egui::Modifiers) { + // Well past the double-click time since the last gesture. + h.run_steps(40); + h.event(egui::Event::ModifiersChanged(mods)); + h.hover_at(at); + h.run_steps(1); + for _ in 0..n { + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: mods }); + h.run_steps(1); + } + } + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(3); +} + +fn wheel_at(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, notches: f32, mods: egui::Modifiers) { + h.event(egui::Event::ModifiersChanged(mods)); + h.hover_at(at); + h.run_steps(1); + h.event(egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, notches), phase: egui::TouchPhase::Move, modifiers: mods }); + h.run_steps(1); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(3); +} + +fn key_with(h: &mut Harness<'_, PhotocraftApp>, key: egui::Key, mods: egui::Modifiers) { + h.event(egui::Event::ModifiersChanged(mods)); + for pressed in [true, false] { + h.event(egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: mods }); + } + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(3); +} + +fn color_balance_of(a: &Adjustment) -> ([f32; 3], [f32; 3], [f32; 3], bool) { + match a { + Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => (*shadows, *midtones, *highlights, *preserve_luminosity), + other => panic!("{other:?}"), + } +} + +/// Photoshop 25.4, Color Balance in the Properties panel (measured on the real application by +/// scripted clicks and reading the layer back): a double-click on a slider's knob or track sets that +/// slider of the shown tone to 0, whatever modifier is held; the label doesn't; a click jumps; the +/// wheel does nothing; Up/Down in a field step 1, with Shift 10. +#[test] +fn color_balance_sliders_reset_and_step_like_photoshop() { + let mut h = app_harness_stepped("colorBalance", "rgb", 8, 1.0 / 60.0); + let (id, _) = layer(&h); + let start = json!({"layer": id.0, "shadows": [10, 0, 0], "midtones": [40, -30, 20], "highlights": [0, 0, -15], "preserveLuminosity": false}); + h.state_mut().run("layer.setAdjustment", start.clone()).unwrap(); + h.run_steps(4); + let label = label_rect(&h, "Cyan · Red").expect("Cyan · Red row"); + let on_track = Pos2::new(label.left() + 60.0, label.bottom() + 14.0); + let cb = |h: &Harness<'_, PhotocraftApp>| color_balance_of(&layer(h).1); + + // A click jumps to the pointer, with or without modifiers. + clicks_with(&mut h, on_track, 1, egui::Modifiers::NONE); + let jumped = cb(&h).1[0]; + assert!(jumped < 0.0 && jumped > -100.0, "click jumps to the pointer: {jumped}"); + for mods in [egui::Modifiers::SHIFT, egui::Modifiers::CTRL, egui::Modifiers::ALT] { + h.state_mut().run("layer.setAdjustment", start.clone()).unwrap(); + h.run_steps(3); + clicks_with(&mut h, on_track, 1, mods); + assert_eq!(cb(&h).1[0], jumped, "{mods:?}-click is a plain click"); + } + // A double-click anywhere on the slider zeroes it, with any modifier; nothing else changes. + for mods in [egui::Modifiers::NONE, egui::Modifiers::SHIFT, egui::Modifiers::CTRL, egui::Modifiers::ALT] { + h.state_mut().run("layer.setAdjustment", start.clone()).unwrap(); + h.run_steps(3); + clicks_with(&mut h, on_track, 2, mods); + assert_eq!(cb(&h), ([10.0, 0.0, 0.0], [0.0, -30.0, 20.0], [0.0, 0.0, -15.0], false), "{mods:?} double-click"); + } + // The label is not a reset target. + h.state_mut().run("layer.setAdjustment", start.clone()).unwrap(); + h.run_steps(3); + clicks_with(&mut h, label.center(), 2, egui::Modifiers::NONE); + assert_eq!(cb(&h).1, [40.0, -30.0, 20.0], "double-click on the label"); + // The panel's sliders ignore the wheel. + wheel_at(&mut h, on_track, 3.0, egui::Modifiers::NONE); + wheel_at(&mut h, on_track, 3.0, egui::Modifiers::SHIFT); + assert_eq!(cb(&h).1, [40.0, -30.0, 20.0], "wheel over a Properties slider"); + // Up/Down in the field: 1, Shift: 10 (also below zero, where a half step used to round away). + let field = h + .query_all_by_role(egui::accesskit::Role::SpinButton) + .map(|n| n.rect()) + .find(|r| (r.center().y - label.center().y).abs() < 8.0) + .expect("Cyan · Red field"); + clicks_with(&mut h, field.center(), 1, egui::Modifiers::NONE); + key_with(&mut h, egui::Key::ArrowUp, egui::Modifiers::NONE); + assert_eq!(cb(&h).1[0], 41.0, "Up"); + key_with(&mut h, egui::Key::ArrowUp, egui::Modifiers::SHIFT); + assert_eq!(cb(&h).1[0], 51.0, "Shift+Up"); + for _ in 0..8 { + key_with(&mut h, egui::Key::ArrowDown, egui::Modifiers::SHIFT); + } + key_with(&mut h, egui::Key::ArrowDown, egui::Modifiers::NONE); + assert_eq!(cb(&h).1[0], -30.0, "Shift+Down ×8, Down"); + key_with(&mut h, egui::Key::ArrowUp, egui::Modifiers::NONE); + assert_eq!(cb(&h).1[0], -29.0, "Up below zero"); +} + +/// Photoshop 25.4, Color Balance in the Properties panel: edits that follow each other make one +/// history step (a double-click, whose first click moved the knob, undoes in one go); Reset first +/// returns to the settings the layer had when the panel started showing it (Tone choice kept), +/// then to the defaults (every tone 0, Midtones, Preserve Luminosity kept), within that step. +#[test] +fn color_balance_properties_history_and_reset_like_photoshop() { + let mut h = app_harness_stepped("colorBalance", "rgb", 8, 1.0 / 60.0); + let (id, _) = layer(&h); + let start = ([10.0, 0.0, 0.0], [40.0, -30.0, 20.0], [0.0, 0.0, -15.0], false); + h.state_mut() + .run( + "layer.setAdjustment", + json!({"layer": id.0, "shadows": [10, 0, 0], "midtones": [40, -30, 20], "highlights": [0, 0, -15], "preserveLuminosity": false}), + ) + .unwrap(); + // Show another layer, then this one again: the panel starts showing it with these settings. + let bg = h.state().session.active().unwrap().doc.layers[0].id; + h.state_mut().session.select_layer(bg).unwrap(); + h.run_steps(4); + h.state_mut().session.select_layer(id).unwrap(); + h.run_steps(4); + let cb = |h: &Harness<'_, PhotocraftApp>| color_balance_of(&layer(h).1); + let steps = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.past_len(); + let label = label_rect(&h, "Cyan · Red").expect("Cyan · Red row"); + let on_track = Pos2::new(label.left() + 60.0, label.bottom() + 14.0); + let before = steps(&h); + clicks_with(&mut h, on_track, 1, egui::Modifiers::NONE); + clicks_with(&mut h, Pos2::new(label.left() + 90.0, on_track.y), 2, egui::Modifiers::NONE); + assert_eq!(cb(&h).1, [0.0, -30.0, 20.0]); + assert_eq!(steps(&h), before + 1, "a click and a double-click: one history step"); + assert!(h.state_mut().session.undo()); + h.run_steps(3); + assert_eq!(cb(&h), start, "one Undo returns to the settings before them"); + // Edit with Highlights shown; Reset returns to the settings the panel started with. + let hl = label_rect(&h, "Highlights").expect("Highlights radio"); + clicks_with(&mut h, hl.center(), 1, egui::Modifiers::NONE); + clicks_with(&mut h, on_track, 1, egui::Modifiers::NONE); + assert_ne!(cb(&h), start); + let tone = crate::adjust_editors::layer_mem(id).with("cb-tone"); + let reset = h.get_by_label("Reset to defaults").rect(); + let before = steps(&h); + clicks_with(&mut h, reset.center(), 1, egui::Modifiers::NONE); + assert_eq!(cb(&h), start, "first Reset: the settings the panel started with"); + assert_eq!(h.ctx.data(|d| d.get_temp::(tone)), Some(2), "Tone choice kept"); + clicks_with(&mut h, reset.center(), 1, egui::Modifiers::NONE); + assert_eq!(cb(&h), ([0.0; 3], [0.0; 3], [0.0; 3], false), "second Reset: defaults, Preserve Luminosity kept"); + assert_eq!(h.ctx.data(|d| d.get_temp::(tone)), Some(1), "defaults show Midtones"); + clicks_with(&mut h, reset.center(), 1, egui::Modifiers::NONE); + assert_eq!(cb(&h), ([0.0; 3], [0.0; 3], [0.0; 3], false), "third Reset: still the defaults"); + assert_eq!(steps(&h), before, "the edit and the Resets share one history step"); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f5b3ce323a8..1b25956ea1f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -226,7 +226,16 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::file_ui::ok_label(&d.fields).unwrap_or(tl!("OK")) }; let ok = DialogButton::new(ButtonRole::Default, ok_label, 84.0); - let cancel = DialogButton::new(ButtonRole::Cancel, if d.kind == DialogKind::NewDocument { tl!("Close") } else { tl!("Cancel") }, 84.0); + // Photoshop: holding Alt turns Cancel into Reset (the dialog stays open). + let reset = ui.input(|i| i.modifiers.alt) && crate::adjust_dialog::resets(&fields); + let cancel_label = if reset { + tl!("Reset") + } else if d.kind == DialogKind::NewDocument { + tl!("Close") + } else { + tl!("Cancel") + }; + let cancel = DialogButton::new(ButtonRole::Cancel, cancel_label, 84.0); let clicked = if d.kind == DialogKind::Command && crate::prefs_ui::is_preferences(&fields) { let changed = crate::prefs_ui::preferences_changed(app, &fields); dialog_buttons(ui, &[ok, cancel, DialogButton::new(ButtonRole::Apply, tl!("Apply"), 84.0).enabled(changed)]) @@ -234,6 +243,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { dialog_buttons(ui, &[ok, cancel]) }; match clicked { + Some(ButtonRole::Cancel) if reset => crate::adjust_dialog::reset(ui.ctx(), &mut fields), Some(ButtonRole::Cancel) => outcome = Some(false), Some(ButtonRole::Apply) => apply_requested = true, Some(_) => outcome = Some(true), diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 2dd0b92bb3d..f030cd35285 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2184,3 +2184,4 @@ cameraRaw Color Barvy Indigo Indigová Fuchsia Fuchsiová Violet Fialová + Reset Obnovit diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d443b190b3b..0e55d7e5229 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -807,6 +807,7 @@ Cache Level: Cache-Stufe: Camera Raw isn't open Camera Raw ist nicht geöffnet Cancel Abbrechen + Reset Zurücksetzen Cancel (Esc) Abbrechen (Esc) Cancel any current edits (Esc) Aktuelle Bearbeitungen abbrechen (Esc) Cancel current crop operation (Esc) Aktuelle Freistellung abbrechen (Esc) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 929c6471a81..0ee2cf18312 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2254,3 +2254,4 @@ cameraRaw Amount Cantidad Indigo Índigo Fuchsia Fucsia Violet Violeta + Reset Restaurar diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 3bcba9f5c28..c014e1da641 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -809,6 +809,7 @@ Cache Level: Livello cache: Camera Raw isn't open Camera Raw non è aperto Cancel Annulla + Reset Ripristina Cancel (Esc) Annulla (Esc) Cancel any current edits (Esc) Annulla modifiche correnti (Esc) Cancel current crop operation (Esc) Annulla operazione ritaglio corrente (Esc) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 2725faf7951..ae751365013 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2167,3 +2167,4 @@ cameraRaw Color カラー Indigo インディゴ Fuchsia フクシア Violet 紫 + Reset 初期化 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 570dbe579b4..0a46b04f670 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -794,6 +794,7 @@ Cache Level: 캐시 레벨: Camera Raw isn't open Camera Raw가 열려 있지 않습니다 Cancel 취소 + Reset 재설정 Cancel (Esc) 취소 (Esc) Cancel any current edits (Esc) 현재 편집 취소 (Esc) Cancel current crop operation (Esc) 현재 자르기 작업 취소 (Esc) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a561de37db3..5a2ac844e18 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2192,3 +2192,4 @@ cameraRaw Blending 混合 Indigo 靛蓝色 Fuchsia 紫红色 Violet 紫罗兰色 + Reset 复位 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 089d6e2790d..d2ed310a282 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2161,3 +2161,4 @@ cameraRaw Blending 混合 Indigo 靛藍色 Fuchsia 紫紅色 Violet 紫羅蘭色 + Reset 重設 diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 1d944a1db69..e57f790523a 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2255,7 +2255,10 @@ fn adjustment_controls(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, } ui.add_space(6.0); if widgets::secondary_button(ui, tl!("Reset to defaults"), ui.available_width()).clicked() { - let _ = app.run("layer.setAdjustment", json!({"layer": id.0})); + let doc = app.session.active().map_or(0, |s| s.doc.id.0); + // Photoshop's two-step Reset where measured (Color Balance), else the defaults. + let params = crate::adjust_editors::properties_reset(ui.ctx(), doc, id, adj).unwrap_or_else(|| json!({"layer": id.0})); + let _ = app.run("layer.setAdjustment", params); app.live_adjust = None; } } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 823518801bc..4f581e2050d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -247,6 +247,90 @@ fn arrow_step(ui: &mut Ui, slot: egui::Id, step: f32) -> (f32, f32) { /// Thin-track slider with a round knob. `gradient` paints the track (e.g. hue spectrum). pub fn slider(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, gradient: Option<&[Color32]>) -> Response { + slider_with(ui, value, range, gradient, RowGestures::default()) +} + +/// Photoshop's gestures on a slider row beyond click and drag, as measured on Color Balance in +/// Photoshop 25.4 (Image › Adjustments dialog and the adjustment layer's Properties). Shift, Ctrl +/// and Alt change nothing about clicks, double-clicks or drags; the wheel takes ten steps with +/// Shift. (Up/Down in the field are every value field's, see [`value_field`].) +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct RowGestures { + /// A double-click on the slider (knob or track; not the label or field) sets this value. + pub reset: Option, + /// Each wheel notch over the slider moves the value by this step (up = higher; ×10 with + /// Shift). Photoshop does this in dialogs, not in the Properties panel. + pub wheel_step: Option, +} + +/// Wheel notches this frame while the pointer is over `resp` (Shift ×10). Wheel lines add up in +/// egui memory until they make whole notches (high-resolution wheels report fractions of one); +/// smooth (point) deltas count `line_scroll_speed` points per notch, like the canvas wheel. +fn wheel_notches(ui: &Ui, resp: &Response) -> f32 { + if !resp.hovered() { + return 0.0; + } + let acc_id = resp.id.with("wheel-acc"); + let mut acc: f32 = ui.data(|d| d.get_temp(acc_id)).unwrap_or(0.0); + let per_line = ui.ctx().options(|o| o.input_options.line_scroll_speed); + let per_line = if per_line.is_finite() && per_line > 0.0 { per_line } else { 40.0 }; + let mut notches = 0.0; + let wheel: Vec<(egui::MouseWheelUnit, Vec2, bool)> = ui.input(|i| { + i.events + .iter() + .filter_map(|e| match e { + egui::Event::MouseWheel { unit, delta, modifiers, .. } => Some((*unit, *delta, modifiers.shift)), + _ => None, + }) + .collect() + }); + for (unit, delta, shift) in wheel { + // Some systems turn Shift+wheel into a horizontal scroll. + let d = if delta.y != 0.0 { delta.y } else { delta.x }; + acc += match unit { + egui::MouseWheelUnit::Point => d / per_line, + _ => d, + }; + let whole = acc.trunc(); + acc -= whole; + notches += if shift { whole * 10.0 } else { whole }; + } + if !acc.is_finite() { + acc = 0.0; + } + ui.data_mut(|d| d.insert_temp(acc_id, acc)); + if notches.is_finite() { notches } else { 0.0 } +} + +/// Windows' default double-click time (Photoshop's; egui's own default is 0.3 s). +const DOUBLE_CLICK_S: f64 = 0.5; + +/// Whether this click on `resp` completes a double-click, counted the Windows way (Photoshop): +/// a click soon after a lone click at the same spot; the click after a double-click starts over. +/// (egui would call a third quick click a triple-click even when the first two weren't a double.) +fn second_click(ui: &Ui, resp: &Response) -> bool { + if !resp.clicked() { + return false; + } + let key = resp.id.with("pc-last-click"); + let (time, pos) = ui.input(|i| (i.time, i.pointer.interact_pos())); + let dist = ui.ctx().options(|o| o.input_options.max_click_dist); + let last: Option<(f64, Pos2)> = ui.data(|d| d.get_temp(key)); + let double = match (last, pos) { + (Some((t, p)), Some(q)) => time - t < DOUBLE_CLICK_S && p.distance(q) < dist, + _ => false, + }; + ui.data_mut(|d| { + if let (false, Some(q)) = (double, pos) { + d.insert_temp(key, (time, q)); + } else { + d.remove::<(f64, Pos2)>(key); + } + }); + double +} + +fn slider_with(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, gradient: Option<&[Color32]>, g: RowGestures) -> Response { let t = Tokens::get(ui.ctx()); let width = ui.available_width().max(60.0); let (rect, mut resp) = ui.allocate_exact_size(vec2(width, 18.0), Sense::click_and_drag()); @@ -262,6 +346,23 @@ pub fn slider(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive resp.mark_changed(); } } + // The double-click's first click has moved the knob to the pointer; the second resets. + if let Some(reset) = g.reset + && second_click(ui, &resp) + { + *value = reset; + resp.mark_changed(); + } + if let Some(step) = g.wheel_step { + let n = wheel_notches(ui, &resp); + if n != 0.0 { + let nv = (*value + n * step).clamp(lo, hi); + if nv != *value { + *value = nv; + resp.mark_changed(); + } + } + } let f = ((*value - lo) / (hi - lo)).clamp(0.0, 1.0); let knob_x = track.left() + f * track.width(); let painter = ui.painter(); @@ -308,6 +409,19 @@ pub fn slider(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive /// Labelled slider row: `Label ........ [value field]` above a full-width thin slider. pub fn slider_row(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, gradient: Option<&[Color32]>) -> Response { + slider_row_with(ui, label, value, range, suffix, gradient, RowGestures::default()) +} + +/// [`slider_row`] with Photoshop's extra gestures ([`RowGestures`]). +pub fn slider_row_with( + ui: &mut Ui, + label: &str, + value: &mut f32, + range: std::ops::RangeInclusive, + suffix: &str, + gradient: Option<&[Color32]>, + g: RowGestures, +) -> Response { let t = Tokens::get(ui.ctx()); let mut changed_resp = None; ui.horizontal(|ui| { @@ -316,7 +430,7 @@ pub fn slider_row(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Ra changed_resp = Some(value_field(ui, value, range.clone(), suffix, 74.0)); }); }); - let s = slider(ui, value, range, gradient); + let s = slider_with(ui, value, range, gradient, g); let mut r = s.clone(); if let Some(v) = changed_resp && v.changed()