Skip to content

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

Replace Color: a canvas eyedropper picks the From colour (#4143) (#4247)

mroxsocee010ef5a60
diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs
index 15c3af206..738ef921f 100644
--- a/crates/engine/src/adjust_cmds.rs
+++ b/crates/engine/src/adjust_cmds.rs
@@ -454,7 +454,7 @@ pub fn specs() -> Vec<CommandSpec> {
"image.adjustments.replaceColor",
"Replace Color…",
["Image", "Adjustments"],
- r##"{"color":json,"fuzziness":0..200=40,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0} (color: "#rrggbb", default the foreground colour)"##,
+ r##"{"color":color,"fuzziness":0..200=40,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0} (color: "#rrggbb", default the foreground colour)"##,
has_pixels,
replace_color
),
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index d4a1cbb58..4f78b853f 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -3022,10 +3022,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
if under_dialog {
// With a colour dialog picker armed the image is its eyedropper, whatever the tool; Space
- // and the middle button still pan. Curves uses the same merged-composite sampler as the
- // Color Picker, never the reduced adjustment preview.
+ // and the middle button still pan. Curves and Replace Color use the same merged-composite
+ // sampler as the Color Picker, never the reduced adjustment preview.
let curves_picking = crate::adjust_dialog::picker_armed(app);
- let picking = primary && (crate::color_picker_ui::top(app).is_some() || curves_picking);
+ let replace_picking = crate::filter_dialog::color_eyedropper_armed(app);
+ let picking = primary && (crate::color_picker_ui::top(app).is_some() || curves_picking || replace_picking);
let range_picking =
primary && app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields) && crate::color_range_ui::controls(&d.fields).sampling);
// Select and Mask's Refine Edge Brush paints on the image.
@@ -3049,6 +3050,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
let d = xf.to_doc(p);
if curves_picking {
crate::adjust_dialog::sample_at(app, d[0], d[1]);
+ } else if replace_picking {
+ crate::filter_dialog::color_eyedropper_sample(app, d[0], d[1]);
} else {
crate::color_picker_ui::sample_at(app, d[0], d[1]);
}
diff --git a/crates/ui-egui/src/filter_dialog.rs b/crates/ui-egui/src/filter_dialog.rs
index 8f588fbc9..31ef15711 100644
--- a/crates/ui-egui/src/filter_dialog.rs
+++ b/crates/ui-egui/src/filter_dialog.rs
@@ -343,6 +343,11 @@ fn default_value(app: &PhotocraftApp, command: &str, p: &Param) -> Option<Value>
// Identity kernel: 1 in the centre.
Kind::Grid(n) => json!((0..*n).map(|i| i64::from(i == *n / 2)).collect::<Vec<_>>()),
Kind::Color(Some(rgb)) => json!(crate::color_picker_ui::hex(*rgb)),
+ // Replace Color starts from the foreground colour and can sample a new one off the canvas.
+ Kind::Color(None) if command == REPLACE_COLOR => {
+ let fg = app.session.tools.foreground;
+ json!(crate::color_picker_ui::hex([fg[0], fg[1], fg[2]]))
+ }
Kind::Color(None) => return None,
// Colour inputs come from the current swatches, so the proxy preview matches the result.
Kind::Json if p.key == "foreground" => json!(app.session.tools.foreground),
@@ -542,6 +547,38 @@ fn uses_angle_dial(command: &str, key: &str) -> bool {
key == "angle" && ANGLE_DIAL.contains(&command)
}
+/// Replace Color (#4143): the dialog's "From" colour, sampled from the image with a canvas
+/// eyedropper like Photoshop's. While armed, the next click on the image writes the merged
+/// composite colour into the `color` field (the same sampler the Color Picker uses).
+const REPLACE_COLOR: &str = "image.adjustments.replaceColor";
+const COLOR_EYEDROPPER: &str = "__colorEyedropper";
+
+fn color_eyedropper_owns(f: &Map<String, Value>) -> bool {
+ f.get("__filter").and_then(Value::as_bool) == Some(true)
+ && f.get("__command").and_then(Value::as_str) == Some(REPLACE_COLOR)
+ && f.get(COLOR_EYEDROPPER).and_then(Value::as_bool) == Some(true)
+}
+
+/// Whether the top dialog is a Replace Color with its canvas eyedropper armed.
+pub(crate) fn color_eyedropper_armed(app: &PhotocraftApp) -> bool {
+ app.ui.dialogs.last().is_some_and(|d| color_eyedropper_owns(&d.fields))
+}
+
+/// Sample the merged image at document point (x, y) into the armed dialog's "From" colour.
+/// Returns true when the click was consumed, even off-image or over transparency, where nothing
+/// changes and the eyedropper stays armed (like the Curves picker).
+pub(crate) fn color_eyedropper_sample(app: &mut PhotocraftApp, x: f64, y: f64) -> bool {
+ let Some(id) = app.ui.dialogs.last().filter(|d| color_eyedropper_owns(&d.fields)).map(|d| d.id) else {
+ return false;
+ };
+ if let Some(rgb) = crate::canvas::composite_color(app, x, y)
+ && let Some(d) = app.ui.dialog_mut(id)
+ {
+ d.fields.insert("color".into(), json!(crate::color_picker_ui::hex(rgb)));
+ }
+ true
+}
+
/// Dialog body for filter commands.
pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
let t = Tokens::get(ui.ctx());
@@ -684,11 +721,18 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
let bytes = rgb.map(q);
let name = label(&p.key);
let mut clicked = false;
+ let eyedropper = cmd == REPLACE_COLOR && p.key == "color";
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| {
// PhotoCraft's Color Picker, as everywhere else (#2144).
clicked = crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(bytes[0], bytes[1], bytes[2]), &name).clicked();
+ if eyedropper {
+ let armed = f.get(COLOR_EYEDROPPER).and_then(Value::as_bool).unwrap_or(false);
+ if crate::icons::button(ui, "pipette", 24.0, armed, "Pick Color From Image").clicked() {
+ f.insert(COLOR_EYEDROPPER.into(), json!(!armed));
+ }
+ }
ui.label(egui::RichText::new(crate::color_picker_ui::hex(rgb)).color(t.text_dim).monospace());
});
});
@@ -1911,4 +1955,50 @@ mod tests {
let fields = &app.ui.dialogs.last().unwrap().fields;
assert_eq!(fields["direction"], json!("cw"), "Explicit default matching first option is preserved");
}
+
+ /// #4143: Replace Color shows the From colour (defaulting to the foreground) and its canvas
+ /// eyedropper samples the merged image into the dialog.
+ #[test]
+ fn replace_color_eyedropper_samples_the_image() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 16, "background": "#00ff00"})).unwrap();
+ let mut app = PhotocraftApp::new(s, crate::Services::default());
+ app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap();
+ let id = open(&mut app, REPLACE_COLOR).unwrap();
+ assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#ff0000"), "the dialog starts from the foreground colour");
+ assert!(!color_eyedropper_armed(&app));
+ app.ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(true));
+ assert!(color_eyedropper_armed(&app));
+ assert!(color_eyedropper_sample(&mut app, 4.0, 4.0));
+ assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00"));
+ // Off-image: the click is consumed, nothing changes and the eyedropper stays armed.
+ assert!(color_eyedropper_sample(&mut app, -1.0, 4.0));
+ assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00"));
+ assert!(color_eyedropper_armed(&app));
+ // Disarmed, the dialog never claims the click.
+ app.ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(false));
+ assert!(!color_eyedropper_armed(&app));
+ assert!(!color_eyedropper_sample(&mut app, 4.0, 4.0));
+ }
+
+ /// #4143: the eyedropper button arms and disarms the canvas picker.
+ #[test]
+ fn replace_color_dialog_arms_the_eyedropper_button() {
+ 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());
+ let mut h = Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), &mut app);
+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
+ open(h.state_mut(), REPLACE_COLOR).unwrap();
+ h.run_steps(3);
+ h.get_by_label("Pick Color From Image").click();
+ h.run_steps(2);
+ assert!(color_eyedropper_armed(h.state()));
+ h.get_by_label("Pick Color From Image").click();
+ h.run_steps(2);
+ assert!(!color_eyedropper_armed(h.state()));
+ }
}
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index 0775780a4..9476ed77a 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -3396,6 +3396,7 @@ cameraRaw Yellow Sárga
Photomerge Fotóegyesítés
Pick a screen pixel or press Esc to cancel Válassz egy pixelt a képernyőn, vagy nyomd meg az Esc billentyűt a megszakításhoz
Pick screen color Szín kiválasztása a képernyőről
+ Pick Color From Image Szín felvétele a képről
Pins Tűk
Pixel Layer Pixelréteg
Place Scale Marker Méretarány-jelölő elhelyezése
diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv
index c67ccd013..c34e67336 100644
--- a/crates/ui-egui/src/i18n/tr.tsv
+++ b/crates/ui-egui/src/i18n/tr.tsv
@@ -2316,6 +2316,7 @@
Color Picker (Stroke Color) Renk Seçici (Kontur Rengi)
Stroke color Kontur rengi
Pick screen color Ekran rengini seç
+ Pick Color From Image Görüntüden Renk Seç
Sample a pixel anywhere on the screen Ekranın herhangi bir yerinde bir pikseli örnekleyin
Click to pick · Esc to cancel Seçmek için tıklayın · İptal etmek için Esc
Pick a screen pixel or press Esc to cancel Bir ekran pikseli seçin veya iptal etmek için Esc tuşuna basın
diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv
index 5157c3d46..9fc122a76 100644
--- a/crates/ui-egui/src/i18n/vi.tsv
+++ b/crates/ui-egui/src/i18n/vi.tsv
@@ -2033,6 +2033,7 @@ layers Fill: Độ tô:
Option-click to define a source point to clone from Option+nhấp để chỉ định điểm nguồn nhân bản
Out of gamut for printing: click for the nearest printable colour Ngoài gamut in: nhấp để lấy màu in được gần nhất
Pick screen color Lấy màu màn hình
+ Pick Color From Image Lấy màu từ hình ảnh
Point Sample Mẫu điểm
Pupil Size Kích thước đồng tử
Quick Selection found nothing there Chọn nhanh không tìm thấy gì