From 7e15585d92b04d57164b78e452052a8b9c292497 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:08:41 -0400 Subject: [PATCH 1/3] feat: Black & White Auto (#9269) An Auto button beside Default in the Black & White editor (Properties panel and Image > Adjustments) sets the colour weights for the image: the image under the adjustment layer, or the layer's pixels. The new read-only command image.adjustments.blackWhite.auto finds them with our own search: from the default mix, each weight steps through 0..150 % to raise the entropy of a 32-level grey histogram, less a pull back to the default, so colours the default turns into one grey are told apart with the mildest change. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/adjust_cmds.rs | 106 ++++++++++++++++++ crates/engine/src/cmd/adjust_cmds/tests.rs | 52 +++++++++ crates/ui-egui/src/dialogs/adjust_dialog.rs | 5 +- crates/ui-egui/src/dialogs/adjust_editors.rs | 5 +- .../src/dialogs/adjust_editors/basic.rs | 20 ++++ .../src/dialogs/adjust_editors/session.rs | 7 +- .../src/dialogs/adjust_editors/ui_tests.rs | 38 +++++++ 7 files changed, 229 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index 7f31b8d2268..7ebe7dd8ddb 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -607,6 +607,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?} → {"reds","yellows","greens","cyans","blues","magentas"} (%: the Auto mix for the image a Black & White adjustment layer sees, or for 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", @@ -620,5 +630,101 @@ 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 +} + +/// 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), or a pixel +/// layer's own pixels (what Image › Adjustments › Black & White changes). +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 layer = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let area = st.doc.bounds(); + let rgba: Vec<[f32; 4]> = match &layer.content { + LayerContent::Adjustment(_) => { + let mut below = (*st.doc).clone(); + hide_from(&mut below.layers, id); + photocraft_compose::render(&below, area).into_px() + } + _ => { + let surf = layer.surface().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no pixels", layer.name)))?; + let fmt = surf.format(); + surf.read_region(area).chunks_exact(fmt.channels()).map(|c| to_rgba(&fmt, c)).collect() + } + }; + let covered = || rgba.iter().filter(|c| c[3] > 0.0); + let stride = covered().count().div_ceil(AUTO_BW_SAMPLES).max(1); + let px: Vec<[f32; 3]> = covered().step_by(stride).map(|c| [c[0], c[1], c[2]]).collect(); + let w = auto_black_white(&px); + 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 51843ae0226..ca319078191 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -823,3 +823,55 @@ 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()); +} diff --git a/crates/ui-egui/src/dialogs/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs index ba349065488..b729973d093 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -489,10 +489,13 @@ 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 6a0e9694b61..3bf3109fb63 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,23 @@ 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) into `v`, as one +/// discrete edit of `e`. +pub fn apply_auto(app: &mut crate::PhotocraftApp, v: &mut Value, layer: Option, e: &mut Edit) { + let p = layer.map_or(json!({}), |id| json!({"layer": id.0})); + 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..a4d5ba0ddc9 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), &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 88dcbaf0625..1595195d4a4 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -1067,3 +1067,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); +} From 4bbf55a970ae9abaad438535dff4f6660960f08f Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 8 Nov 2026 18:30:47 +0100 Subject: [PATCH 2/3] Black & White Auto: vary the sample phase per run (#9301) The sample took every stride-th covered pixel, so a pattern whose period divides the stride (alternating columns on an even-width canvas) was only sampled in one phase and Auto missed one of the colours. Each run of stride pixels now contributes one pixel at a position that varies by run. Co-Authored-By: DuBearte Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/adjust_cmds.rs | 16 ++++++++++++---- crates/engine/src/cmd/adjust_cmds/tests.rs | 10 ++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index 4f066cde6b5..5774e608f86 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -708,6 +708,17 @@ pub fn auto_black_white(px: &[[f32; 3]]) -> [f32; 6] { 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; @@ -746,10 +757,7 @@ fn black_white_auto(s: &mut Session, p: &Value) -> Result { surf.read_region(area).chunks_exact(fmt.channels()).map(|c| to_rgba(&fmt, c)).collect() } }; - let covered = || rgba.iter().filter(|c| c[3] > 0.0); - let stride = covered().count().div_ceil(AUTO_BW_SAMPLES).max(1); - let px: Vec<[f32; 3]> = covered().step_by(stride).map(|c| [c[0], c[1], c[2]]).collect(); - let w = auto_black_white(&px); + 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())) } diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index 1d48ace49c7..b228f333b9f 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -1113,4 +1113,14 @@ fn black_white_auto_spreads_the_greys() { 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:?}"); } From 7e40b73f3bc73d7af07803e368f7bf8f176a5507 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 9 Nov 2026 19:38:11 +0100 Subject: [PATCH 3/3] Black & White Auto: read a smart filter's input, refuse oversized canvases (#9301) Reopening a Black & White smart filter ran Auto on the smart object's filtered cache, which that filter has already turned grey, so Auto always answered the default mix. The dialog now passes the filter index and the command reads the pixels below that filter, as the reference application does. A canvas past the render limit rendered nothing and also gave the default mix; it is now an error. Selection, the adjustment's mask and its clip base stay out of the analysis: measured in the reference application, none of them changes its Auto result. Co-Authored-By: DuBearte Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/adjust_cmds.rs | 40 ++++++++--- crates/engine/src/cmd/adjust_cmds/tests.rs | 69 +++++++++++++++++++ crates/ui-egui/src/dialogs/adjust_dialog.rs | 4 +- .../src/dialogs/adjust_editors/basic.rs | 12 ++-- .../src/dialogs/adjust_editors/session.rs | 2 +- 5 files changed, 111 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index 5774e608f86..b9a144075c3 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -639,7 +639,7 @@ pub fn specs() -> Vec { label: "Black & White Auto", menu: &[], shortcut: None, - params: r##"{"layer":id?} → {"reds","yellows","greens","cyans","blues","magentas"} (%: the Auto mix for the image a Black & White adjustment layer sees, or for a pixel layer's own pixels; nothing changes)"##, + 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, @@ -734,8 +734,10 @@ fn hide_from(layers: &mut [Layer], id: photocraft_doc::LayerId) -> bool { } /// `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), or a pixel -/// layer's own pixels (what Image › Adjustments › Black & White changes). +/// 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)?; @@ -743,19 +745,37 @@ fn black_white_auto(s: &mut Session, p: &Value) -> Result { 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(); - let rgba: Vec<[f32; 4]> = match &layer.content { - LayerContent::Adjustment(_) => { + // 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() } - _ => { - let surf = layer.surface().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no pixels", layer.name)))?; - let fmt = surf.format(); - surf.read_region(area).chunks_exact(fmt.channels()).map(|c| to_rgba(&fmt, c)).collect() - } + (_, 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())) diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index b228f333b9f..0efa30e1492 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -1124,3 +1124,72 @@ fn black_white_auto_spreads_the_greys() { 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 ddc0de5908a..f226200235b 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -543,7 +543,9 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map Ed } /// 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) into `v`, as one -/// discrete edit of `e`. -pub fn apply_auto(app: &mut crate::PhotocraftApp, v: &mut Value, layer: Option, e: &mut Edit) { - let p = layer.map_or(json!({}), |id| json!({"layer": id.0})); +/// `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 { diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index a4d5ba0ddc9..4ac51812464 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -126,7 +126,7 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj crate::preset_files_ui::import_gradients_dialog(app); } if e.auto { - apply_auto(app, &mut values, Some(id), &mut e); + apply_auto(app, &mut values, Some(id), None, &mut e); } if e.changed { app.live_adjust = Some((id, values.clone()));