Skip to content

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

Color Picker: sample colours from the image with a pipette (#508)

Carter Smithb41442c46651
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs
index eed14cf0e..1ac57b82e 100644
--- a/crates/automation/src/server.rs
+++ b/crates/automation/src/server.rs
@@ -574,7 +574,9 @@ impl PhotocraftMcp {
}
}
- #[tool(description = "Bridge mode: send pointer events (document coordinates) to the active tool.")]
+ #[tool(
+ description = "Bridge mode: send pointer events (document coordinates) to the active tool; with a Color Picker open they sample the image into it instead."
+ )]
async fn ui_pointer(&self, Parameters(p): Parameters<PointerParams>) -> Result<CallToolResult, McpError> {
match self.bridge_client() {
Some(b) => {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index b6398e2af..e9376aa58 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1532,12 +1532,28 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
};
if under_dialog {
- if let Some(d) = crate::dialogs::pan_delta(&ctx, rect, app.ui.tool == Tool::Hand) {
+ // With the Color Picker on top the image is its eyedropper, whatever the tool; Space and
+ // the middle button still pan (`color_picker_ui::sample_at`).
+ let picking = primary && crate::color_picker_ui::top(app).is_some();
+ let hand = app.ui.tool == Tool::Hand && !picking;
+ if let Some(d) = crate::dialogs::pan_delta(&ctx, rect, hand) {
view.center[0] -= d.x / view.zoom * if flip { -1.0 } else { 1.0 };
view.center[1] -= d.y / view.zoom;
ctx.set_cursor_icon(egui::CursorIcon::Grabbing);
- } else if free_hover && (space_pan || app.ui.tool == Tool::Hand) {
+ } else if free_hover && (space_pan || hand) {
ctx.set_cursor_icon(egui::CursorIcon::Grab);
+ } else if picking && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect) {
+ if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise {
+ ctx.set_cursor_icon(egui::CursorIcon::Crosshair);
+ } else {
+ // The tip of the icon's pipette is at (2, 22) of its 24-unit box.
+ crate::icons::cursor(&ctx, "pipette", p, vec2(2.0, 22.0) / 24.0, 20.0);
+ ctx.set_cursor_icon(egui::CursorIcon::None);
+ }
+ if let Some(p) = crate::dialogs::free_press(&ctx, rect) {
+ let d = xf.to_doc(p);
+ crate::color_picker_ui::sample_at(app, d[0], d[1]);
+ }
}
}
if tool == Tool::Hand && response.dragged() {
@@ -2060,12 +2076,22 @@ fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
}
fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) {
- if let Ok(v) = app.run("document.pixel", json!({"x": x.floor(), "y": y.floor()})) {
- let color: Vec<f32> = serde_json::from_value(v).unwrap_or_default();
- if color.len() == 4 && color[3] > 0.0 {
- let key = if mods.alt { "background" } else { "foreground" };
- let _ = app.run("tools.setColors", json!({ key: [color[0], color[1], color[2], 1.0] }));
- }
+ if let Some([r, g, b]) = composite_color(app, x, y) {
+ let key = if mods.alt { "background" } else { "foreground" };
+ let _ = app.run("tools.setColors", json!({ key: [r, g, b, 1.0] }));
+ }
+}
+
+/// The active document's composite colour at document point (x, y): what the Eyedropper picks.
+/// `None` off the image or over transparency.
+pub(crate) fn composite_color(app: &mut PhotocraftApp, x: f64, y: f64) -> Option<[f32; 3]> {
+ if !(x.is_finite() && y.is_finite()) {
+ return None;
+ }
+ let v = app.run("document.pixel", json!({"x": x.floor(), "y": y.floor()})).ok()?;
+ match serde_json::from_value::<Vec<f32>>(v).ok()?[..] {
+ [r, g, b, a] if a > 0.0 => Some([r, g, b]),
+ _ => None,
}
}
diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rs
index 2f769cadf..2e74de984 100644
--- a/crates/ui-egui/src/color_picker_ui.rs
+++ b/crates/ui-egui/src/color_picker_ui.rs
@@ -2,6 +2,8 @@
//! for the selected component (H, S, B, R, G or B radio), new/current swatches, and HSB, RGB, Lab,
//! CMYK and hex fields. The colour lives in the dialog fields (`color` as `#rrggbb`, plus the HSB
//! floats so hue survives greys), so `ui.dialog.set` drives it; OK runs `tools.setColors`.
+//! While it is the top dialog the image is its eyedropper, as in Photoshop: the pointer over the
+//! canvas is a pipette, and a click or drag there samples into the new colour ([`sample_at`]).
use egui::{Color32, Mesh, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use serde_json::{Map, Value, json};
@@ -140,6 +142,21 @@ pub fn owns(f: &Map<String, Value>) -> bool {
f.contains_key("__colorPicker")
}
+/// The Color Picker, when it is the top dialog (another dialog opened over it takes the input).
+pub fn top(app: &PhotocraftApp) -> Option<u64> {
+ app.ui.dialogs.last().filter(|d| owns(&d.fields)).map(|d| d.id)
+}
+
+/// Eyedropper: the top Color Picker's new colour becomes the image's composite colour at document
+/// point (x, y). Off the image or over transparency nothing changes.
+pub fn sample_at(app: &mut PhotocraftApp, x: f64, y: f64) {
+ let Some(id) = top(app) else { return };
+ let Some(rgb) = crate::canvas::composite_color(app, x, y) else { return };
+ if let Some(d) = app.ui.dialog_mut(id) {
+ set_rgb(&mut d.fields, rgb, Keep::Nothing);
+ }
+}
+
/// The colour in every model the dialog shows.
pub struct Components {
pub rgb: [f32; 3],
@@ -513,4 +530,46 @@ mod tests {
confirm(&mut app, &fields).unwrap();
assert_eq!(hex([app.session.tools.background[0], app.session.tools.background[1], app.session.tools.background[2]]), "#3366cc");
}
+
+ fn dialog_color(app: &PhotocraftApp, id: u64) -> &str {
+ app.ui.dialogs.iter().find(|d| d.id == id).and_then(|d| d.fields.get("color")).and_then(Value::as_str).unwrap()
+ }
+
+ #[test]
+ fn the_top_picker_samples_the_image() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 40, "height": 20, "background": "transparent"})).unwrap();
+ app.run("shape.create", json!({"kind": "rect", "rect": [0, 0, 20, 20], "fill": "#ff0000"})).unwrap();
+ app.run("shape.create", json!({"kind": "rect", "rect": [20, 0, 10, 20], "fill": "#00ff00"})).unwrap();
+ let id = open(&mut app, "foreground");
+ assert_eq!(top(&app), Some(id));
+ sample_at(&mut app, 25.5, 5.5);
+ assert_eq!(dialog_color(&app, id), "#00ff00");
+ assert_eq!(app.ui.dialog_mut(id).unwrap().fields["__orig"], json!("#000000"), "the current colour stays");
+ // Off the image or over transparency nothing changes.
+ for (x, y) in [(35.0, 5.0), (-3.0, 5.0), (5.0, 20.0), (1e12, -1e12), (f64::NAN, f64::INFINITY)] {
+ sample_at(&mut app, x, y);
+ assert_eq!(dialog_color(&app, id), "#00ff00", "({x}, {y})");
+ }
+
+ // Agents: `ui.pointer` samples into the picker instead of driving the tool.
+ app.ui.tool = crate::state::Tool::Brush;
+ let rev = app.session.active().unwrap().revision;
+ let ctx = egui::Context::default();
+ let events = json!([{"kind": "down", "x": 5, "y": 5}, {"kind": "up", "x": 5, "y": 5}]);
+ let (req, _rx) = crate::control::ControlRequest::new("ui.pointer", json!({"events": events}));
+ let _ = crate::control::handle(&mut app, &ctx, &req);
+ assert_eq!(dialog_color(&app, id), "#ff0000");
+ assert_eq!(app.session.active().unwrap().revision, rev, "the Brush must not paint");
+ assert_eq!(app.session.tools.foreground, [0.0, 0.0, 0.0, 1.0], "only OK sets the foreground");
+
+ // A dialog opened over the picker takes the input.
+ let about = app.ui.open_dialog(DialogKind::About, Map::new());
+ assert_eq!(top(&app), None);
+ sample_at(&mut app, 25.0, 5.0);
+ assert_eq!(dialog_color(&app, id), "#ff0000");
+ app.ui.close_dialog(about);
+ sample_at(&mut app, 25.0, 5.0);
+ assert_eq!(dialog_color(&app, id), "#00ff00");
+ }
}
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index abf11d70b..d9ec92fb8 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -376,6 +376,13 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
"up" => ToolEvent::Up { x, y },
_ => ToolEvent::Move { x, y, pressure: pr },
};
+ // With the Color Picker on top the image is its eyedropper, as for the mouse.
+ if crate::color_picker_ui::top(app).is_some() {
+ if !matches!(ev, ToolEvent::Up { .. }) {
+ crate::color_picker_ui::sample_at(app, x, y);
+ }
+ continue;
+ }
if matches!(s("button"), Some("secondary" | "right")) {
let down = matches!(ev, ToolEvent::Down { .. });
// Right-click with the Move tool, or ⌘/Ctrl+right-click: list the layers there.
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 51e4e30ae..919b54304 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -37,6 +37,31 @@ pub fn pan_delta(ctx: &egui::Context, canvas: egui::Rect, hand: bool) -> Option<
(panning && canvas.contains(origin) && !rects.iter().any(|r| r.contains(origin))).then_some(delta)
}
+/// A click or drag with the primary button started on the free canvas under an open dialog, Space
+/// not held: where the pointer is this frame. The press itself counts even when it is released in
+/// the same frame (a quick click, `ui.click`); the drag only while it stays on the free canvas.
+pub fn free_press(ctx: &egui::Context, canvas: egui::Rect) -> Option<egui::Pos2> {
+ if egui::Popup::is_any_open(ctx) {
+ return None;
+ }
+ let rects = rects(ctx);
+ let free = |p: egui::Pos2| canvas.contains(p) && !rects.iter().any(|r| r.contains(p));
+ ctx.input(|i| {
+ if i.key_down(egui::Key::Space) {
+ return None;
+ }
+ let pressed = i.events.iter().rev().find_map(|e| match e {
+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos),
+ _ => None,
+ });
+ if let Some(p) = pressed {
+ return free(p).then_some(p);
+ }
+ let held = i.pointer.primary_down() && i.pointer.press_origin().is_some_and(free);
+ i.pointer.latest_pos().filter(|p| held && free(*p))
+ })
+}
+
pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
let dialogs = app.ui.dialogs.clone();
let mut shown = Vec::new();
diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs
index e0d4a6b71..ecd902e3e 100644
--- a/crates/ui-egui/src/icons.rs
+++ b/crates/ui-egui/src/icons.rs
@@ -42,6 +42,21 @@ pub fn paint(ui: &egui::Ui, rect: Rect, name: &str, size: f32, tint: Color32) {
image(name, size, tint).paint_at(ui, r);
}
+/// An icon as the pointer, above every window: `name` with its hotspot `hot` (a fraction of the
+/// icon box) on `p`, white with a dark outline so it reads on any image. The caller hides the OS
+/// cursor (`CursorIcon::None`).
+pub fn cursor(ctx: &egui::Context, name: &str, p: egui::Pos2, hot: Vec2, size: f32) {
+ let rect = Rect::from_min_size(p - hot * size, Vec2::splat(size));
+ let area = egui::Area::new(egui::Id::new("pc-icon-cursor")).order(egui::Order::Tooltip).fixed_pos(rect.min).constrain(false).interactable(false);
+ area.show(ctx, |ui| {
+ let outline = image(name, size, Color32::from_black_alpha(200));
+ for (dx, dy) in [(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (-1.0, -1.0), (1.0, 1.0), (-1.0, 1.0), (1.0, -1.0)] {
+ outline.paint_at(ui, rect.translate(egui::vec2(dx, dy)));
+ }
+ image(name, size, Color32::WHITE).paint_at(ui, rect);
+ });
+}
+
pub fn tool_icon(t: Tool) -> &'static str {
match t {
Tool::Move => "move",
diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs
index 646cf25b4..897b76477 100644
--- a/crates/ui-egui/src/input_tests.rs
+++ b/crates/ui-egui/src/input_tests.rs
@@ -133,6 +133,86 @@ fn clicking_outside_a_dialog_keeps_it_open_and_the_canvas_pans_and_zooms() {
assert!(h.state().ui.dialogs.is_empty());
}
+fn press(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, pressed: bool) {
+ h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
+ h.run_steps(1);
+}
+
+fn picker_color(h: &Harness<'static, PhotocraftApp>) -> String {
+ let d = h.state().ui.dialogs.last().unwrap();
+ d.fields.get("color").and_then(serde_json::Value::as_str).unwrap().to_string()
+}
+
+/// The Color Picker's eyedropper, as in Photoshop: over the image the pointer is a pipette, and a
+/// click or drag there samples into the picker's new colour, whatever the tool. OK applies it.
+#[test]
+fn color_picker_samples_the_image_under_its_pipette() {
+ let mut h = harness();
+ h.state_mut().run("shape.create", json!({"kind": "rect", "rect": [0, 0, 200, 300], "fill": "#ff0000"})).unwrap();
+ h.state_mut().run("shape.create", json!({"kind": "rect", "rect": [200, 0, 200, 300], "fill": "#00ff00"})).unwrap();
+ // 400 %: the image covers the whole canvas, red on the left of the dialog, green on its right.
+ let v = &mut h.state_mut().ui.views[0];
+ (v.zoom, v.center, v.fit_pending) = (4.0, [200.0, 150.0], false);
+ crate::color_picker_ui::open(h.state_mut(), "foreground");
+ h.run_steps(3);
+ let r = h.state().last_canvas_rect;
+ let (red, green) = (pos2(r.left() + 60.0, r.center().y), pos2(r.right() - 60.0, r.center().y));
+ assert_eq!(doc_at(&h, red)[0] < 200.0, doc_at(&h, green)[0] > 200.0);
+ let foreground = h.state().session.tools.foreground;
+
+ h.hover_at(red);
+ h.run_steps(1);
+ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "the pipette replaces the pointer");
+ h.hover_at(r.center());
+ h.run_steps(1);
+ assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "over the dialog it is the normal pointer");
+
+ // A click samples; the press and release may land in one frame (`ui.click`).
+ h.hover_at(red);
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: red, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
+ press(&mut h, red, false);
+ assert_eq!(picker_color(&h), "#ff0000");
+ assert_eq!(h.state().session.tools.foreground, foreground, "only OK sets the foreground");
+
+ // A drag keeps sampling, skipping the dialog on the way.
+ press(&mut h, red, true);
+ for i in 1..=6 {
+ h.hover_at(red + (green - red) * (i as f32 / 6.0));
+ h.run_steps(1);
+ }
+ press(&mut h, green, false);
+ assert_eq!(picker_color(&h), "#00ff00");
+
+ // Space-drag still pans instead of sampling.
+ h.hover_at(red);
+ h.run_steps(1);
+ let c0 = h.state().ui.views[0].center;
+ h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
+ h.run_steps(1);
+ press(&mut h, red, true);
+ h.hover_at(red + vec2(40.0, 0.0));
+ h.run_steps(1);
+ press(&mut h, red + vec2(40.0, 0.0), false);
+ h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });
+ h.run_steps(2);
+ let c1 = h.state().ui.views[0].center;
+ assert!((c1[0] - (c0[0] - 10.0)).abs() < 0.5, "space-drag pans by 40 pt at 400 %: {c0:?} -> {c1:?}");
+ assert_eq!(picker_color(&h), "#00ff00");
+
+ // With the Hand tool a click samples too (the tool doesn't matter); OK applies the sample.
+ h.state_mut().ui.tool = crate::state::Tool::Hand;
+ h.hover_at(red);
+ h.run_steps(1);
+ press(&mut h, red, true);
+ press(&mut h, red, false);
+ assert_eq!(picker_color(&h), "#ff0000");
+ h.key_press(Key::Enter);
+ h.run_steps(2);
+ assert!(h.state().ui.dialogs.is_empty());
+ assert_eq!(h.state().session.tools.foreground, [1.0, 0.0, 0.0, 1.0]);
+}
+
/// Type tool (#206): Alt+←/→ at a collapsed caret kerns the pair before it by 20/1000 em (100
/// with ⌘/Ctrl), one history step per press; ⌘/Ctrl+←/→ moves by word; Alt+Shift+→ extends
/// the selection by a word.
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 67395aaac..243f4e541 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -42,7 +42,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`).
- A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing.
- `ui.window.open {document?}` / `ui.window.close {window}`: extra document windows
-- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu instead (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. Both menus open at the screen position of the pressed document point, like a mouse right-click's
+- `ui.pointer {events: [{kind: down|move|up, x, y, pressure?, tiltX?, tiltY?, rotation?}], modifiers?, button?}`: drive the active tool in document coordinates (pressure 0..1, tilt in degrees -90..90, barrel rotation 0..360: a simulated pen). Modifier flags (`shift`, `alt`, `command`, `ctrl`, `space`) go either at the top level or grouped under `modifiers`; when `modifiers` is present, top-level flags are ignored. `space: true` holds Space (the Crop frame, marquee, lasso or shape being drawn then moves instead of growing). `button: "right"` (or `"secondary"`) is the right button: with the Move tool (or `command: true` with any tool) it opens the canvas layer menu instead (`layerMenu` in `ui.inspect` lists the layers there, topmost first; select one with `layer.select`); with a painting tool it opens the Brush Preset picker, or erases with Preferences › Tools › Right-click with painting tools = erase. Both menus open at the screen position of the pressed document point, like a mouse right-click's. With a Color Picker as the top dialog, `down` and `move` sample the image into its new colour instead (its eyedropper, like a click on the canvas) and the tool is not driven.
- `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`
- `ui.type {text}`: type text (goes to the focused widget, or to the canvas while the Type tool is editing)
- `ui.resize {width, height}`: resize the main window