Add Black & White adjustment presets

This commit is contained in:
Dan committed 2026-11-24 22:56:23 +00:00
1 parent dd56106df2
commit aec5cee320
4 files changed
+205 -12

No files matched your search

+5 -8
View File
@@ -17,9 +17,9 @@ use craft::behavior::{EditEvent, EditEvents, Mixed};
use craft::color_ui::ui::gradient::{ColorStop, GradientStops};
use craft::draw::ui::gradient::{GradientGroup, GradientItem, GradientMap, GradientMapEditor, GradientMapOutput};
use craft::imaging::ui::adjust::{
AdjustDialogCx, AdjustField, AdjustSliders, AdjustWords, BlackWhite, BlackWhiteEditor, BrightnessContrast, BrightnessContrastEditor, ChannelMixer,
ChannelMixerEditor, ColorBalance, ColorBalanceEditor, ColorBalanceTone, CurvesPanel, HueSaturation, HueSaturationEditor, Levels, LevelsPanel, PhotoFilter,
PhotoFilterEditor, SelectiveColor, SelectiveColorEditor, ThresholdEditor, ToneChannels, ToneCurves, ToneSpace,
AdjustDialogCx, AdjustField, AdjustSliders, AdjustWords, BlackWhite, BrightnessContrast, BrightnessContrastEditor, ChannelMixer, ChannelMixerEditor,
ColorBalance, ColorBalanceEditor, ColorBalanceTone, CurvesPanel, HueSaturation, HueSaturationEditor, Levels, LevelsPanel, PhotoFilter, PhotoFilterEditor,
SelectiveColor, SelectiveColorEditor, ThresholdEditor, ToneChannels, ToneCurves, ToneSpace,
};
use craft::imaging::ui::histogram::{ChannelColor, HistogramData};
use craft::theme::Srgba;
@@ -35,6 +35,7 @@ use serde_json::{Value, json};
use crate::PhotocraftApp;
mod black_white_presets;
mod session;
pub mod values;
@@ -306,11 +307,7 @@ fn show(kind: &str, setup: &EditorSetup, ui: &mut Ui, value: &mut AdjustValue, c
let out = editor.show(ui);
lifted(out.edit.events, |value| AdjustValue::ColorBalance { value })
}
("blackWhite", AdjustValue::BlackWhite { value }) => {
let out = BlackWhiteEditor::new("Black & White", Bind::bound(value)).context(context).show(ui);
let ask = if out.auto { Some(AdjustAsk::Auto) } else { out.pick_color.map(AdjustAsk::PickColor) };
AdjustOut { ask, edit: out.edit.events.map(|value| AdjustValue::BlackWhite { value }) }
}
("blackWhite", AdjustValue::BlackWhite { value }) => black_white_presets::show(ui, value, context),
("photoFilter", AdjustValue::PhotoFilter { value }) => {
let out = PhotoFilterEditor::new("Photo Filter", Bind::bound(value)).context(context).show(ui);
AdjustOut { ask: out.pick_color.map(AdjustAsk::PickColor), edit: out.edit.events.map(|value| AdjustValue::PhotoFilter { value }) }
@@ -0,0 +1,96 @@
//! Original Black & White recipes for tonal shifts and the effect of color filters.
use std::sync::Arc;
use craft::behavior::{EditEvent, EditEvents, Mixed};
use craft::imaging::ui::adjust::{AdjustContext, AdjustWords, BlackWhite, BlackWhiteEditor};
use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _};
use craft::ui::form::Field;
use craft::ui::pickers::Select;
use craft::ui::runtime::env::Env;
use egui::Ui;
use super::{AdjustAsk, AdjustOut, AdjustValue};
type Mix = [f64; 6];
/// The presets change the grayscale mix and keep the layer's tint settings.
fn entries() -> [Entry<Option<Mix>>; 14] {
[
Entry::new(Some(BlackWhite::DEFAULT_WEIGHTS), tl!("Default")),
Entry::new(Some([22.0, 38.0, 25.0, 36.0, 10.0, 50.0]), tl!("Darker")),
Entry::new(Some([60.0, 77.0, 64.0, 78.0, 47.0, 92.0]), tl!("Lighter")),
Entry::new(Some([8.0; 6]), tl!("Deep Shadows")),
Entry::new(Some([92.0; 6]), tl!("Bright Highlights")),
Entry::new(Some([48.0; 6]), tl!("Even Color Weights")),
Entry::new(Some([86.0, 65.0, 33.0, 23.0, 15.0, 72.0]), tl!("Red Filter")),
Entry::new(Some([64.0, 91.0, 64.0, 41.0, 13.0, 53.0]), tl!("Yellow Filter")),
Entry::new(Some([28.0, 67.0, 91.0, 74.0, 17.0, 45.0]), tl!("Green Filter")),
Entry::new(Some([24.0, 35.0, 45.0, 77.0, 92.0, 53.0]), tl!("Blue Filter")),
Entry::new(Some([100.0, 73.0, 24.0, 7.0, 5.0, 64.0]), tl!("Strong Red Filter")),
Entry::new(Some([4.0, 12.0, 27.0, 71.0, 100.0, 44.0]), tl!("Strong Blue Filter")),
Entry::new(Some([58.0, 89.0, 97.0, 38.0, 8.0, 33.0]), tl!("Infrared Foliage")),
Entry::new(None, tl!("Custom")),
]
}
/// A manual edit can land on exactly the weights of a named recipe. Remember that edit locally
/// so its value still shows as Custom. The Properties inspector scopes this memory to its target.
#[derive(Clone, Copy, PartialEq)]
struct ManualValue {
weights: Mix,
tint: Option<[u8; 3]>,
}
impl From<BlackWhite> for ManualValue {
fn from(value: BlackWhite) -> Self {
let [r, g, b, _] = value.tint_color.to_rgba().0;
Self { weights: value.weights, tint: value.tint.then_some([r, g, b]) }
}
}
fn manual_id(ui: &Ui) -> egui::Id {
ui.make_persistent_id("black-white-manual-value")
}
/// The Properties host applies accepted Color Picker colors and Auto outside the editor's pass.
pub(super) fn mark_custom(ui: &Ui, value: &AdjustValue) {
if let AdjustValue::BlackWhite { value } = value {
ui.data_mut(|d| d.insert_temp(manual_id(ui), ManualValue::from(*value)));
}
}
pub(super) fn show(ui: &mut Ui, value: &mut BlackWhite, context: AdjustContext) -> AdjustOut {
let id = manual_id(ui);
let mut manual = ui.data(|d| d.get_temp::<ManualValue>(id));
let entries = entries();
let shown = (manual != Some((*value).into()) && entries.iter().any(|entry| entry.value() == Some(&Some(value.weights)))).then_some(value.weights);
let label = tl!("Preset");
let picked = Field::new(label).show(ui, |ui, _| Select::new(label, Bind::given(shown), &entries).show(ui).events.committed().copied()).inner.flatten();
let mut edit = EditEvents::new();
if let Some(picked) = picked {
manual = picked.is_none().then(|| (*value).into());
if let Some(weights) = picked
&& weights != value.weights
{
let before = *value;
value.weights = weights;
edit.push(EditEvent::set(Mixed::Same(before), *value, Arc::from(label), None));
}
}
let out = BlackWhiteEditor::new("Black & White", Bind::bound(&mut *value)).context(context).show(ui);
if let Some(after) = out.edit.events.committed() {
let words = Env::of(ui).words::<AdjustWords>();
let reset = matches!(out.edit.events.ended(), Some(EditEvent::Set { label, .. }) if label.as_ref() == words.default_button.as_str());
manual = (!reset).then(|| (*after).into());
}
ui.data_mut(|d| match manual {
Some(value) => d.insert_temp(id, value),
None => d.remove::<ManualValue>(id),
});
let ask = if out.auto { Some(AdjustAsk::Auto) } else { out.pick_color.map(AdjustAsk::PickColor) };
edit.extend(out.edit.events);
AdjustOut { ask, edit: edit.map(|value| AdjustValue::BlackWhite { value }) }
}
@@ -13,7 +13,7 @@ use photocraft_engine::adjust_params;
use serde_json::{Value, json};
use super::values::{self, ValueCx};
use super::{AdjustAsk, AdjustValue, EditorSetup, answer_color, black_white_auto, editor, gradient_presets, is_gray, swatches};
use super::{AdjustAsk, AdjustValue, EditorSetup, answer_color, black_white_auto, black_white_presets, editor, gradient_presets, is_gray, swatches};
use crate::PhotocraftApp;
use crate::color_picker_ui::PickWindow;
use crate::theme::Tokens;
@@ -189,7 +189,7 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj
record.session.track(session_target(doc, id), app.properties_hidden, &committed);
app.properties_tracked = true;
}
follow_color_pick(app, id, &mut record, &committed, &vcx);
follow_color_pick(app, ui, id, &mut record, &committed, &vcx);
let mut value = match &app.live_adjust {
Some((layer, params)) if *layer == id => values::from_params(kind, params, &vcx).unwrap_or_else(|_| committed.clone()),
_ => committed.clone(),
@@ -240,7 +240,12 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj
target.extend(weights);
}
match values::from_params(kind, &params, &vcx) {
Ok(auto) => commit(app, id, &mut record, &committed, &auto, &vcx, None),
Ok(auto) => {
if auto != committed {
black_white_presets::mark_custom(ui, &auto);
}
commit(app, id, &mut record, &committed, &auto, &vcx, None);
}
Err(err) => app.ui.status = err,
}
}
@@ -288,7 +293,7 @@ fn commit(
/// A colour well's Color Picker while it is open: its colour previews on the layer. Once it
/// closed, OK's colour is one edit and Cancel (or OK without a colour) leaves the layer as it was.
fn follow_color_pick(app: &mut PhotocraftApp, id: LayerId, record: &mut PropertiesAdjust, committed: &AdjustValue, vcx: &ValueCx) {
fn follow_color_pick(app: &mut PhotocraftApp, ui: &egui::Ui, id: LayerId, record: &mut PropertiesAdjust, committed: &AdjustValue, vcx: &ValueCx) {
let Some(pick) = record.pick.take() else { return };
match app.framework.dialogs.get_by_id::<ColorPickerDialog>(pick.dialog).map(ColorPickerDialog::current) {
Some(current) => {
@@ -304,6 +309,9 @@ fn follow_color_pick(app: &mut PhotocraftApp, id: LayerId, record: &mut Properti
Some((key, color)) if key == pick.key && Some(color) != pick.opened => {
let mut answered = pick.before;
if answer_color(&mut answered, &key, color) {
if answered != *committed {
black_white_presets::mark_custom(ui, &answered);
}
commit(app, id, record, committed, &answered, vcx, None);
} else {
app.live_adjust = None;
@@ -492,3 +492,95 @@ fn black_white_auto_button_sets_the_weights() {
assert_ne!(after, before, "the red and blue are told apart");
assert_eq!(history_len(&h), steps + 1);
}
fn assert_black_white_preset(h: &Harness<'_, Box<PhotocraftApp>>, name: &str) {
assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Preset").accesskit_node().value().as_deref(), Some(name));
}
#[test]
fn black_white_presets_apply_through_properties_and_undo() {
let mut h = app_harness("blackWhite", "rgb", 8);
let (id, _) = layer(&h);
h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "tint": true, "tintColor": "#336699"})).unwrap();
h.run_steps(4);
let (_, before) = layer(&h);
let Adjustment::BlackWhite { weights: original, tint: original_tint } = &before else { panic!("{before:?}") };
let history = history_len(&h);
let pixel = h.state_mut().run("document.pixel", json!({"x": 10, "y": 10})).unwrap();
assert_black_white_preset(&h, "Default");
h.get_by_role_and_label(Role::ComboBox, "Preset").click();
h.run_steps(3);
h.get_by_role_and_label(Role::ListBoxOption, "Darker").click();
h.run_steps(4);
assert_black_white_preset(&h, "Darker");
let (_, after) = layer(&h);
let Adjustment::BlackWhite { weights, tint } = &after else { panic!("{after:?}") };
assert!(weights.iter().zip(original).all(|(weight, original)| weight < original));
assert_eq!(tint, original_tint);
assert_ne!(h.state_mut().run("document.pixel", json!({"x": 10, "y": 10})).unwrap(), pixel);
assert_eq!(history_len(&h), history + 1);
assert!(h.state().live_adjust.is_none());
let ctx = h.ctx.clone();
let picker = open_picker(&mut h, "Tint Color");
show_in_picker(&mut h, picker, "#ad632a");
h.state_mut().framework.dialogs.cancel_by_id(&ctx, picker);
h.run_steps(4);
assert_black_white_preset(&h, "Darker");
assert_eq!(layer(&h).1, after);
assert_eq!(history_len(&h), history + 1);
let picker = open_picker(&mut h, "Tint Color");
show_in_picker(&mut h, picker, "#ad632a");
crate::dialogs::confirm(h.state_mut(), &ctx, picker).expect("OK is enabled");
h.run_steps(4);
assert_black_white_preset(&h, "Custom");
assert_eq!(history_len(&h), history + 2);
h.state_mut().run("edit.undo", json!({})).unwrap();
h.run_steps(4);
assert_eq!(layer(&h).1, after);
assert_black_white_preset(&h, "Darker");
h.state_mut().run("edit.undo", json!({})).unwrap();
h.run_steps(4);
assert_eq!(layer(&h).1, before);
assert_black_white_preset(&h, "Default");
}
#[test]
fn black_white_presets_distinguish_manual_edits_from_named_choices() {
let mut h = app_harness("blackWhite", "rgb", 8);
let (id, defaults) = layer(&h);
let Adjustment::BlackWhite { weights, .. } = &defaults else { panic!("{defaults:?}") };
let red = weights[0];
h.state_mut().run("layer.setAdjustment", json!({"layer": id.0, "reds": red + 7.0})).unwrap();
h.run_steps(4);
assert_black_white_preset(&h, "Custom");
h.get_by_role_and_label(Role::SpinButton, "Reds").click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text(red.to_string()));
h.run_steps(1);
h.key_press(egui::Key::Tab);
h.run_steps(4);
assert_eq!(layer(&h).1, defaults);
assert_black_white_preset(&h, "Custom");
h.state_mut().run("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap();
h.run_steps(4);
assert_black_white_preset(&h, "Default");
h.state_mut().run("layer.select", json!({"layer": id.0})).unwrap();
h.run_steps(4);
assert_black_white_preset(&h, "Custom");
let history = history_len(&h);
h.get_by_role_and_label(Role::ComboBox, "Preset").click();
h.run_steps(3);
h.get_by_role_and_label(Role::ListBoxOption, "Default").click();
h.run_steps(4);
assert_black_white_preset(&h, "Default");
assert_eq!(layer(&h).1, defaults);
assert_eq!(history_len(&h), history);
}