diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index 783d757991f..ec8a7f753a3 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -641,6 +641,16 @@ pub fn specs() -> Vec { has_doc, hdr_toning ), + CommandSpec { + id: "image.adjustments.blackWhite.auto", + label: "Black & White Auto", + menu: &[], + shortcut: None, + params: r##"{"layer":id?,"filter":index?} → {"reds","yellows","greens","cyans","blues","magentas"} (%: the Auto mix for the image a Black & White adjustment layer sees, a smart object's pixels below its smart filter `filter`, or a pixel layer's own pixels; nothing changes)"##, + enabled: has_doc, + run: black_white_auto, + journal: false, + }, CommandSpec { id: "image.adjustments.colorLookup.list", label: "List Color Lookup Looks", @@ -654,5 +664,129 @@ pub fn specs() -> Vec { ] } +/// At most this many pixels are sampled for [`auto_black_white`]. +const AUTO_BW_SAMPLES: usize = 1 << 16; +/// Grey levels [`auto_black_white`] tells apart. +const AUTO_BW_BINS: usize = 32; + +/// Black & White's Auto (#9269): the colour weights (%, in [`crate::adjust_params::HUE_RANGES`] +/// order) that spread the image's greys over the most grey levels. PhotoCraft's own search, not +/// Photoshop's: from the default mix, each weight in turn steps through 0..=150 % to the value +/// that most raises the entropy of the greys' histogram ([`AUTO_BW_BINS`] levels), less a pull +/// back towards the default, until a pass changes nothing. So colours the default mix turns into +/// the same grey are told apart, with the mildest change that does it; colours the image lacks +/// keep their default weight. +pub fn auto_black_white(px: &[[f32; 3]]) -> [f32; 6] { + let defaults = crate::adjust_params::BW_DEFAULTS; + let score = |w: &[f32; 6]| -> f32 { + if px.is_empty() { + return 0.0; + } + let mut bins = [0u32; AUTO_BW_BINS]; + for c in px { + let g = photocraft_compose::adjust::black_white_gray(*c, w).clamp(0.0, 1.0); + if let Some(b) = bins.get_mut(((g * AUTO_BW_BINS as f32) as usize).min(AUTO_BW_BINS - 1)) { + *b += 1; + } + } + let n = px.len() as f32; + let entropy: f32 = bins.iter().filter(|&&k| k > 0).map(|&k| k as f32 / n).map(|q| -q * q.log2()).sum(); + let pull: f32 = w.iter().zip(defaults).map(|(v, d)| (v - d).abs()).sum::() / 100.0; + entropy - 0.05 * pull + }; + let mut w = defaults; + let mut best = score(&w); + for _ in 0..4 { + let mut changed = false; + for k in 0..6 { + for step in 0..=15 { + let mut t = w; + t[k] = step as f32 * 10.0; + let s = score(&t); + if s > best + 1e-6 { + (best, w, changed) = (s, t, true); + } + } + } + if !changed { + break; + } + } + w +} + +/// At most [`AUTO_BW_SAMPLES`] of the pixels with alpha: one from each run of `stride` of them, at +/// a position that varies from run to run (Fibonacci hashing of the run's index), so a pattern +/// whose period divides `stride` (alternating columns on an even-width canvas) isn't only ever +/// sampled in one phase. +fn auto_bw_sample(rgba: &[[f32; 4]]) -> Vec<[f32; 3]> { + let covered = || rgba.iter().filter(|c| c[3] > 0.0); + let stride = covered().count().div_ceil(AUTO_BW_SAMPLES).max(1); + let pick = |run: usize| ((run as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32) as usize % stride; + covered().enumerate().filter(|(i, _)| i % stride == pick(i / stride)).map(|(_, c)| [c[0], c[1], c[2]]).collect() +} + +/// Hides `id` and everything composited above it. Returns whether `id` is in `layers`. +fn hide_from(layers: &mut [Layer], id: photocraft_doc::LayerId) -> bool { + let mut found = false; + for l in layers.iter_mut() { + if found || l.id == id { + found = true; + l.visible = false; + } else if l.children_mut().is_some_and(|c| hide_from(c, id)) { + found = true; + } + } + found +} + +/// `image.adjustments.blackWhite.auto`: [`auto_black_white`] for `layer` (default the active one): +/// the composite of what lies below a Black & White adjustment layer (what it adjusts), a smart +/// object's pixels below smart filter `filter` (what that filter edits), or a pixel layer's own +/// pixels (what Image › Adjustments › Black & White changes). As in the reference application, +/// the whole canvas counts: a selection, the adjustment's mask and its clip base don't narrow it. +fn black_white_auto(s: &mut Session, p: &Value) -> Result { + let cmd = "image.adjustments.blackWhite.auto"; + let st = s.active().ok_or(EngineError::NoDocument)?; + let id = match p.get("layer") { + None | Some(Value::Null) => st.active_layer.ok_or_else(|| EngineError::Other("no active layer".into()))?, + Some(v) => photocraft_doc::LayerId(v.as_u64().ok_or_else(|| bad(cmd, "`layer` must be a layer id"))?), + }; + let filter = match p.get("filter") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(cmd, "`filter` must be a smart filter index"))?), + }; + let layer = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let area = st.doc.bounds(); + // Rendering or reading a canvas past the render limit gives nothing to sample: say so rather + // than answer with the default mix. + if u64::from(area.width()) * u64::from(area.height()) > photocraft_compose::MAX_RENDER_PIXELS { + return Err(bad(cmd, "the canvas is too large to analyse")); + } + let read = |surf: &Surface| -> Vec<[f32; 4]> { + let fmt = surf.format(); + surf.read_region(area).chunks_exact(fmt.channels()).map(|c| to_rgba(&fmt, c)).collect() + }; + let rgba: Vec<[f32; 4]> = match (&layer.content, filter) { + (LayerContent::Smart(sm), Some(i)) => { + if i >= sm.smart_filters.len() { + return Err(bad(cmd, format!("layer \"{}\" has no smart filter {i}", layer.name))); + } + let below = crate::smart_cmds::render_below_filter(&st.doc, sm, i)? + .ok_or_else(|| EngineError::Other("the smart object's contents are unavailable".into()))?; + read(&below) + } + (_, Some(_)) => return Err(bad(cmd, "`filter` needs a smart object layer")), + (LayerContent::Adjustment(_), None) => { + let mut below = (*st.doc).clone(); + hide_from(&mut below.layers, id); + photocraft_compose::render(&below, area).into_px() + } + (_, None) => read(layer.surface().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no pixels", layer.name)))?), + }; + let w = auto_black_white(&auto_bw_sample(&rgba)); + Ok(Value::Object(crate::adjust_params::HUE_RANGES.iter().zip(w).map(|(k, v)| ((*k).to_string(), json!(v))).collect())) +} + #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index 162524367d7..0efa30e1492 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -1062,3 +1062,134 @@ fn folder_luts_lists_lut_files_by_name() { assert!(folder_luts("").is_empty()); assert!(folder_luts(dir.path().join("missing").to_str().unwrap()).is_empty()); } + +/// #9269: Black & White's Auto spreads an image's greys wider than the default mix, leaves the +/// weights of colours the image lacks at their defaults, and changes nothing in the document. +#[test] +fn black_white_auto_spreads_the_greys() { + use crate::adjust_params::{BW_DEFAULTS, HUE_RANGES}; + // A red and a blue the default mix turns into the same grey (0.43). + let (red, blue) = ([0.776, 0.2, 0.2], [0.29, 0.29, 1.0]); + let gray = |c: [f32; 3], w: &[f32; 6]| photocraft_compose::adjust::black_white_gray(c, w); + let w = auto_black_white(&[red, blue]); + let gap = |w: &[f32; 6]| (gray(red, w) - gray(blue, w)).abs(); + assert!(gap(&BW_DEFAULTS) < 0.01); + assert!(gap(&w) > 1.0 / 32.0, "{w:?}: {}", gap(&w)); + assert!(w.iter().all(|v| (0.0..=150.0).contains(v)), "{w:?}"); + // Yellows, greens, cyans and magentas aren't in the image: they keep their defaults. + for k in [1, 2, 3, 5] { + assert_eq!(w[k], BW_DEFAULTS[k], "{}", HUE_RANGES[k]); + } + // A grey image (and no pixels at all) keeps the default mix. + assert_eq!(auto_black_white(&[[0.2; 3], [0.7; 3]]), BW_DEFAULTS); + assert_eq!(auto_black_white(&[]), BW_DEFAULTS); + + // The command: an adjustment layer reads the image under it; the document is unchanged. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + paint(&mut s, |x, _| if x < 10 { [0.776, 0.2, 0.2, 1.0] } else { [0.29, 0.29, 1.0, 1.0] }); + let id = s.execute("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap()["layer"].as_u64().unwrap(); + let rev = s.active().unwrap().revision; + let r = s.execute("image.adjustments.blackWhite.auto", json!({"layer": id})).unwrap(); + let got: Vec = HUE_RANGES.iter().map(|k| r[*k].as_f64().unwrap() as f32).collect(); + assert_eq!(got, w.to_vec()); + assert_eq!(s.active().unwrap().revision, rev, "nothing changes"); + assert!(s.execute("image.adjustments.blackWhite.auto", json!({"layer": 999})).is_err()); + assert!(s.execute("image.adjustments.blackWhite.auto", json!({"layer": "x"})).is_err()); + + // A layer above the adjustment isn't part of what it adjusts. + s.execute("layer.new.layer", json!({})).unwrap(); + paint(&mut s, |_, _| [0.5, 0.5, 0.5, 1.0]); + assert_eq!(s.execute("image.adjustments.blackWhite.auto", json!({"layer": id})).unwrap(), r); + + // Sampling a big canvas still finds a thin painted stripe. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 512, "height": 512, "background": "transparent"})).unwrap(); + paint(&mut s, |x, y| match (x, y < 256) { + (1, true) => [0.776, 0.2, 0.2, 1.0], + (1, false) => [0.29, 0.29, 1.0, 1.0], + _ => [0.0; 4], + }); + let r = s.execute("image.adjustments.blackWhite.auto", json!({})).unwrap(); + let got: Vec = HUE_RANGES.iter().map(|k| r[*k].as_f64().unwrap() as f32).collect(); + assert_eq!(got, w.to_vec()); + + // Columns alternating with a period that divides the sampling stride (4 here): both colours + // are still sampled, not only the even columns. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 512, "height": 512})).unwrap(); + paint(&mut s, |x, _| if x % 2 == 0 { [0.776, 0.2, 0.2, 1.0] } else { [0.29, 0.29, 1.0, 1.0] }); + let r = s.execute("image.adjustments.blackWhite.auto", json!({})).unwrap(); + let got: Vec = HUE_RANGES.iter().map(|k| r[*k].as_f64().unwrap() as f32).collect(); + assert_ne!(got, BW_DEFAULTS.to_vec(), "only one colour was sampled"); + assert!(gap(&got.clone().try_into().unwrap()) > 1.0 / 32.0, "{got:?}"); +} + +/// #9301 review: as in the reference application, Auto reads the whole canvas whatever the +/// selection, the adjustment's mask or its clip base; a smart filter's Auto reads the pixels below +/// that filter, not the filtered result; a canvas too large to analyse is an error, not the +/// default mix. +#[test] +fn black_white_auto_reads_the_whole_input() { + use crate::adjust_params::{BW_DEFAULTS, HUE_RANGES}; + let (red, blue) = ([0.776, 0.2, 0.2, 1.0], [0.29, 0.29, 1.0, 1.0]); + let mix = auto_black_white(&[[red[0], red[1], red[2]], [blue[0], blue[1], blue[2]]]); + assert_ne!(mix, BW_DEFAULTS); + let auto = |s: &mut Session, p: Value| -> Vec { + let r = s.execute("image.adjustments.blackWhite.auto", p).unwrap(); + HUE_RANGES.iter().map(|k| r[*k].as_f64().unwrap() as f32).collect() + }; + let split = |x: i32, _| if x < 10 { red } else { blue }; + + // A selection over the red half doesn't narrow Image › Adjustments' Auto. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + paint(&mut s, split); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + assert_eq!(auto(&mut s, json!({})), mix.to_vec()); + + // Nor does an adjustment layer's mask hiding the blue half. + s.execute("select.deselect", json!({})).unwrap(); + let id = s.execute("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.edit("mask", |doc, _| { + let b = doc.bounds(); + let mut m = photocraft_doc::LayerMask::reveal_all(); + m.surface.write_region(Rect::new(10, 0, b.x1, b.y1), &vec![0.0; 10 * 10]); + doc.layer_mut(photocraft_doc::LayerId(id)).unwrap().mask = Some(m); + Ok(()) + }) + .unwrap(); + assert_eq!(auto(&mut s, json!({"layer": id})), mix.to_vec()); + + // Nor clipping it to a layer that only covers the red half. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + paint(&mut s, |_, _| blue); + s.execute("layer.new.layer", json!({})).unwrap(); + paint(&mut s, |x, _| if x < 10 { red } else { [0.0; 4] }); + let id = s.execute("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.createClippingMask", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().clipped); + assert_eq!(auto(&mut s, json!({"layer": id})), mix.to_vec()); + + // A Black & White smart filter: its own result is grey, its input is the colours. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + paint(&mut s, split); + s.execute("filter.convertForSmartFilters", json!({})).unwrap(); + s.execute("image.adjustments.blackWhite", json!({})).unwrap(); + let smart = s.active().unwrap().active_layer.unwrap().0; + assert_eq!(auto(&mut s, json!({"layer": smart})), BW_DEFAULTS.to_vec(), "the filtered result is grey"); + assert_eq!(auto(&mut s, json!({"layer": smart, "filter": 0})), mix.to_vec()); + for bad in [json!({"layer": smart, "filter": 1}), json!({"layer": smart, "filter": "x"}), json!({"layer": smart, "filter": -1})] { + assert!(s.execute("image.adjustments.blackWhite.auto", bad).is_err()); + } + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + assert!(s.execute("image.adjustments.blackWhite.auto", json!({"filter": 0})).is_err(), "not a smart object"); + + // Past the render limit there is nothing to sample. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40000, "height": 30000, "background": "transparent"})).unwrap(); + let id = s.execute("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap()["layer"].as_u64().unwrap(); + assert!(s.execute("image.adjustments.blackWhite.auto", json!({"layer": id})).is_err()); +} diff --git a/crates/ui-egui/src/dialogs/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs index e2044f01bc2..ac11967b8c2 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -664,10 +664,15 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map Self { Edit { changed, commit: changed, ..Default::default() } diff --git a/crates/ui-egui/src/dialogs/adjust_editors/basic.rs b/crates/ui-egui/src/dialogs/adjust_editors/basic.rs index e10d32652b0..38018b6e8ba 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/basic.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/basic.rs @@ -181,6 +181,9 @@ pub(super) fn black_white(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Ed v["tintColor"] = json!(adjust_params::hex(c)); } e.add(r); + if widgets::secondary_button(ui, tl!("Auto"), 0.0).on_hover_text(tl!("A grey mix that spreads the image's tones")).clicked() { + e.auto = true; + } if widgets::secondary_button(ui, tl!("Default"), 0.0).clicked() { for (i, key) in HUE_RANGES.iter().enumerate() { v[*key] = json!(adjust_params::BW_DEFAULTS[i]); @@ -191,6 +194,27 @@ pub(super) fn black_white(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Ed e } +/// Black & White's Auto (#9269): the weights `image.adjustments.blackWhite.auto` finds for +/// `layer` (an adjustment layer: the image under it; a pixel layer: its pixels; with `filter`, the +/// smart object's pixels below that smart filter) into `v`, as +/// one discrete edit of `e`. +pub fn apply_auto(app: &mut crate::PhotocraftApp, v: &mut Value, layer: Option, filter: Option, e: &mut Edit) { + let mut p = layer.map_or(json!({}), |id| json!({"layer": id.0})); + if let Some(i) = filter { + p["filter"] = json!(i); + } + match app.run("image.adjustments.blackWhite.auto", p) { + Ok(Value::Object(w)) => { + for (k, x) in w { + v[k] = x; + } + e.add(Edit::discrete(true)); + } + Ok(_) => {} + Err(err) => app.ui.status = err, + } +} + // --------------------------------------------------------------------------------------------- // Photo Filter diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index d254b49bbab..4ac51812464 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -1,4 +1,4 @@ -use super::basic::reset_color_balance; +use super::basic::{apply_auto, reset_color_balance}; use super::gradient_map::{gradient_presets, is_gray, swatches}; use super::{Adjustment, EditorCx, HistSource, LayerId, PhotocraftApp, RichText, Tokens, Value, adjust_params, editor, json, needs_histogram, space_of, tone}; @@ -121,10 +121,13 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj if matches!(kind, "levels" | "curves") { crate::layer_picker::controls(app, ui, id); } - let e = editor(ui, kind, &mut values, &cx); + let mut e = editor(ui, kind, &mut values, &cx); if e.import_gradients { crate::preset_files_ui::import_gradients_dialog(app); } + if e.auto { + apply_auto(app, &mut values, Some(id), None, &mut e); + } if e.changed { app.live_adjust = Some((id, values.clone())); } diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index be8cc729abd..ec386a7e9ac 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -1348,3 +1348,41 @@ fn selective_color_properties_method_radios_commit() { assert!(matches!(layer(&h).1, Adjustment::SelectiveColor { relative: true, .. })); assert_eq!(steps(&h), start + 2); } + +/// #9269: Black & White's Auto button sets the layer's weights from the image under it, as one +/// history step. +#[test] +fn black_white_auto_button_sets_the_weights() { + let mut h = app_harness("blackWhite", "rgb", 8); + // A red and a blue the default mix turns into the same grey, under the adjustment layer. + h.state_mut() + .session + .edit("setup", |doc, _| { + let b = doc.bounds(); + let bg = doc.layers.first_mut().and_then(|l| l.surface_mut()).unwrap(); + let fmt = bg.format(); + let mut data = Vec::new(); + for _ in b.y0..b.y1 { + for x in b.x0..b.x1 { + let c = if x < b.x1 / 2 { [0.776, 0.2, 0.2, 1.0] } else { [0.29, 0.29, 1.0, 1.0] }; + data.extend(photocraft_raster::from_rgba(&fmt, c)); + } + } + bg.write_region(b, &data); + Ok(()) + }) + .unwrap(); + h.run_steps(2); + let (_, before) = layer(&h); + let steps = h.state().session.active().unwrap().history.past_len(); + let auto = h.query_all_by_label("Auto").last().map(|n| n.rect().center()).expect("an Auto button"); + click(&mut h, auto); + let (_, after) = layer(&h); + let Adjustment::BlackWhite { weights, .. } = &after else { panic!("{after:?}") }; + let id = layer(&h).0; + let expected = h.state_mut().run("image.adjustments.blackWhite.auto", json!({"layer": id.0})).unwrap(); + let want: Vec = photocraft_engine::adjust_params::HUE_RANGES.iter().map(|k| expected[*k].as_f64().unwrap() as f32).collect(); + assert_eq!(weights.to_vec(), want); + assert_ne!(after, before, "the red and blue are told apart"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); +}