Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Replace Color: a Result swatch whose Color Picker sets the sliders (#6278)

itsF4LCONf71eb28f844f
diff --git a/crates/algo/src/tone.rs b/crates/algo/src/tone.rs
index 2632d4a29..5a0f752fa 100644
--- a/crates/algo/src/tone.rs
+++ b/crates/algo/src/tone.rs
@@ -65,6 +65,35 @@ pub fn replace_color(px: &mut [[f32; 4]], color: [f32; 3], fuzziness: f32, hue:
mask
}
+/// Replace Color's Result swatch: `color` after the hue (±180°), saturation and lightness (±100)
+/// shift, as a fully matched pixel of that colour becomes.
+pub fn replace_color_result(color: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [f32; 3] {
+ let mut px = [[color[0], color[1], color[2], 1.0]];
+ replace_color_masked(&mut px, &[1.0], hue, saturation, lightness);
+ [px[0][0], px[0][1], px[0][2]]
+}
+
+/// The hue (±180°), saturation and lightness (±100) shift that turns `from` into `to`, as
+/// Photoshop's Result Color Picker sets the sliders. A shift the sliders can't reach (a grey has
+/// no hue to turn, black or white no saturation to give) goes as far as they do.
+pub fn replace_color_shift(from: [f32; 3], to: [f32; 3]) -> (f32, f32, f32) {
+ let [fh, fs, fl] = rgb_to_hsl(from);
+ let [th, ts, tl] = rgb_to_hsl(to);
+ // Hue turns the short way round; a grey target keeps the hue where it is.
+ let hue = if ts <= 0.0 { 0.0 } else { ((th - fh + 0.5).rem_euclid(1.0) - 0.5) * 360.0 };
+ // Inverse of the shift in `replace_color_masked`: up moves toward 1, down toward 0.
+ let amount = |from: f32, to: f32| {
+ if to >= from {
+ if from >= 1.0 { 0.0 } else { (to - from) / (1.0 - from) * 100.0 }
+ } else if from <= 0.0 {
+ 0.0
+ } else {
+ (to / from - 1.0) * 100.0
+ }
+ };
+ (hue.clamp(-180.0, 180.0), amount(fs, ts).clamp(-100.0, 100.0), amount(fl, tl).clamp(-100.0, 100.0))
+}
+
/// Replace Color's hue, saturation and lightness shift, applied to each pixel as far as `mask`
/// (`0..=1`, one per pixel: the colour match, localized or not) covers it.
pub fn replace_color_masked(px: &mut [[f32; 4]], mask: &[f32], hue: f32, saturation: f32, lightness: f32) {
@@ -277,6 +306,28 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) {
mod tests {
use super::*;
+ /// #6278: the Result swatch is the sampled colour after the shift, and a picked Result sets
+ /// the sliders that give it.
+ #[test]
+ fn replace_color_result_and_shift_round_trip() {
+ let from = [0.8, 0.2, 0.2];
+ let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 2e-3);
+ assert!(near(replace_color_result(from, 0.0, 0.0, 0.0), from), "no shift, no change");
+ for to in [[0.2, 0.3, 0.9], [0.9, 0.85, 0.1], [0.4, 0.1, 0.1], [0.95, 0.6, 0.6], [0.1, 0.6, 0.3]] {
+ let (h, s, l) = replace_color_shift(from, to);
+ assert!((-180.0..=180.0).contains(&h) && (-100.0..=100.0).contains(&s) && (-100.0..=100.0).contains(&l));
+ assert!(near(replace_color_result(from, h, s, l), to), "{to:?}: ({h}, {s}, {l}) gives {:?}", replace_color_result(from, h, s, l));
+ }
+ // Red to blue turns the short way (−120°, not +240°).
+ assert!((replace_color_shift([1.0, 0.0, 0.0], [0.0, 0.0, 1.0]).0 + 120.0).abs() < 0.5);
+ // A grey target: saturation all the way down, the hue left alone.
+ let (h, s, _) = replace_color_shift(from, [0.5, 0.5, 0.5]);
+ assert_eq!((h, s), (0.0, -100.0));
+ // Black has no saturation to raise: the slider stays put rather than dividing by zero.
+ let (h, s, l) = replace_color_shift([0.0, 0.0, 0.0], [0.2, 0.6, 0.3]);
+ assert!(h.is_finite() && s.is_finite() && l > 0.0);
+ }
+
fn ramp(w: usize, h: usize) -> Vec<[f32; 4]> {
(0..w * h)
.map(|i| {
diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs
index fa7cb9524..f2212efa6 100644
--- a/crates/ui-egui/src/filter_dialog.rs
+++ b/crates/ui-egui/src/filter_dialog.rs
@@ -637,6 +637,49 @@ pub(crate) fn color_eyedropper_sample(app: &mut PhotocraftApp, x: f64, y: f64) -
true
}
+/// The Color Picker of Replace Color's Result swatch writes here (#6278).
+const RESULT_PICKED: &str = "__resultPicked";
+/// The Result the picker opened on: a picked colour that differs from it sets the sliders.
+const RESULT_FROM: &str = "__resultFrom";
+
+/// Replace Color's Result swatch (#6278), as in Photoshop: the sampled colour after the Hue,
+/// Saturation and Lightness shift. Picking a Result in its Color Picker sets the three sliders so
+/// the sampled colour becomes it.
+fn replace_color_result(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ use photocraft_algo::tone;
+ let t = Tokens::get(ui.ctx());
+ let from = f.get("color").and_then(Value::as_str).and_then(crate::color_picker_ui::parse_hex).unwrap_or([0.0; 3]);
+ let picked = f.get(RESULT_PICKED).and_then(Value::as_str).and_then(crate::color_picker_ui::parse_hex);
+ if let Some(to) = picked
+ && f.get(RESULT_PICKED) != f.get(RESULT_FROM)
+ {
+ let (hue, saturation, lightness) = tone::replace_color_shift(from, to);
+ for (key, v) in [("hue", hue), ("saturation", saturation), ("lightness", lightness)] {
+ f.insert(key.into(), json!(v.round()));
+ }
+ f.remove(RESULT_PICKED);
+ f.remove(RESULT_FROM);
+ }
+ let num = |key: &str| f.get(key).and_then(Value::as_f64).unwrap_or(0.0) as f32;
+ let rgb = tone::replace_color_result(from, num("hue"), num("saturation"), num("lightness"));
+ let bytes = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
+ let name = tl!("Result");
+ let mut clicked = false;
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new(name).color(t.text_dim));
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ clicked = crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(bytes[0], bytes[1], bytes[2]), name).clicked();
+ ui.label(egui::RichText::new(crate::color_picker_ui::hex(rgb)).color(t.text_dim).monospace());
+ });
+ });
+ if clicked {
+ let hex = json!(crate::color_picker_ui::hex(rgb));
+ f.insert(RESULT_PICKED.into(), hex.clone());
+ f.insert(RESULT_FROM.into(), hex);
+ crate::color_picker_ui::request_field(f, RESULT_PICKED, &crate::color_picker_ui::title_for(name));
+ }
+}
+
/// Dialog body for filter commands.
pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
let t = Tokens::get(ui.ctx());
@@ -832,6 +875,9 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
}
}
}
+ if cmd == REPLACE_COLOR {
+ replace_color_result(ui, f);
+ }
// Read-only context the dialog opener supplies (e.g. the monitor profile in use).
if let Some(note) = f.get("__note").and_then(Value::as_str) {
ui.add_space(4.0);
@@ -2383,6 +2429,45 @@ mod tests {
assert!(!color_eyedropper_armed(h.state()));
}
+ /// #6278: the Result swatch shows the sampled colour after the shift, and a colour picked for
+ /// it sets Hue, Saturation and Lightness so the sampled colour becomes it.
+ #[test]
+ fn replace_color_result_swatch_sets_the_sliders() {
+ use egui_kittest::Harness;
+ use egui_kittest::kittest::Queryable;
+
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
+ let mut app = PhotocraftApp::new(s, crate::Services::default());
+ app.run("tools.setColors", json!({"foreground": "#cc3333"})).unwrap();
+ let mut h = Harness::builder().with_size(egui::vec2(900.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app);
+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
+ let id = open(h.state_mut(), REPLACE_COLOR).unwrap();
+ h.run_steps(3);
+ // No shift yet: the Result is the sampled colour.
+ assert_eq!(h.get_all_by_label("#cc3333").count(), 2, "the sampled colour and the Result both read #cc3333");
+ h.get_by_role_and_label(egui::accesskit::Role::ColorWell, "Result").click();
+ h.run_steps(3);
+ let picker = h.state().ui.dialogs.last().unwrap();
+ assert_ne!(picker.id, id, "the Color Picker opened over the dialog");
+ assert_eq!(picker.fields["color"], json!("#cc3333"), "on the current Result");
+ let picker = picker.id;
+ h.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), json!("#3355cc"));
+ crate::dialogs::confirm(h.state_mut(), picker).unwrap();
+ h.state_mut().ui.dialogs.retain(|d| d.id != picker);
+ h.run_steps(3);
+ let f = h.state_mut().ui.dialog_mut(id).unwrap().fields.clone();
+ let n = |k: &str| f[k].as_f64().unwrap() as f32;
+ let got = photocraft_algo::tone::replace_color_result([0.8, 0.2, 0.2], n("hue"), n("saturation"), n("lightness"));
+ let want = crate::color_picker_ui::parse_hex("#3355cc").unwrap();
+ assert!(got.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.02), "the sliders turn the sampled colour into the pick: {got:?}");
+ assert!(n("hue") != 0.0, "the hue moved");
+ // Moving a slider afterwards is not mistaken for another pick.
+ h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("lightness".into(), json!(10.0));
+ h.run_steps(2);
+ assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields["lightness"], json!(10.0));
+ }
+
/// #4457: Localized Color Clusters and its Range, as in Photoshop's dialog; the sampled point
/// and both settings reach the command.
#[test]
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 2e12c3379..723d04856 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -3374,3 +3374,4 @@ curves Smooth 매끄럽게
Take the shortcut from the other command and select it 다른 명령에서 단축키를 빼고 그 명령 선택
Undo Changes 변경 사항 취소
{shortcut} is reserved by the system and can't be assigned. {shortcut}은(는) 시스템에서 예약되어 할당할 수 없습니다.
+ Result 결과
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index cbf3c9d08..f02dfc1ff 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2812,3 +2812,4 @@ curves Smooth 平滑
Take the shortcut from the other command and select it 从另一个命令移除该快捷键并选中它
Undo Changes 撤消更改
{shortcut} is reserved by the system and can't be assigned. {shortcut} 由系统保留,无法指定。
+ Result 结果
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 30aa3f5a9..3d82e5b4d 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2797,3 +2797,4 @@ curves Smooth 平滑
Take the shortcut from the other command and select it 從另一個指令移除該快速鍵並選取它
Undo Changes 還原變更
{shortcut} is reserved by the system and can't be assigned. {shortcut} 由系統保留,無法指定。
+ Result 結果