PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Clone Source: W/H link and overlay blend modes (#3298) (#3310)
Valentin Klein638b5cc4e6d2
diff --git a/crates/engine/src/presets/clone_source.rs b/crates/engine/src/presets/clone_source.rsindex e2a4a8485..1ee134133 100644--- a/crates/engine/src/presets/clone_source.rs+++ b/crates/engine/src/presets/clone_source.rs@@ -33,11 +33,15 @@ pub struct CloneSource {pub rotation: f64,pub flip_h: bool,pub flip_v: bool,+ /// The panel's W/H link (Maintain aspect ratio): setting one of W and H scales the other+ /// by the same factor.+ #[serde(default)]+ pub linked: bool,}impl Default for CloneSource {fn default() -> Self {- CloneSource { source: None, anchor: None, layer: None, scale: [100.0, 100.0], rotation: 0.0, flip_h: false, flip_v: false }+ CloneSource { source: None, anchor: None, layer: None, scale: [100.0, 100.0], rotation: 0.0, flip_h: false, flip_v: false, linked: false }}}@@ -56,7 +60,7 @@ impl CloneSource {fn to_json(&self, i: usize) -> Value {json!({"index": i, "source": self.source, "anchor": self.anchor, "offset": self.offset(), "layer": self.layer,- "width": self.scale[0], "height": self.scale[1], "rotation": self.rotation, "flipH": self.flip_h, "flipV": self.flip_v,+ "width": self.scale[0], "height": self.scale[1], "linked": self.linked, "rotation": self.rotation, "flipH": self.flip_h, "flipV": self.flip_v,})}}@@ -196,6 +200,25 @@ pub fn resolve(s: &Session, p: &Value, first: (f64, f64), cmd: &str) -> Result<(Ok((Mapping { source: src, anchor, m }, aligned.then_some([anchor.0, anchor.1])))}+/// The Clone Source overlay's blend mode applied to one pixel: the source `src` over the image+/// under the brush `dst`, both straight RGBA. Where the image is transparent the source shows+/// unchanged; the result keeps the source's alpha (the overlay's opacity applies on top).+/// Unknown modes draw as Normal.+pub fn overlay_blend(mode: &str, src: [f32; 4], dst: [f32; 4]) -> [f32; 4] {+ let f: fn(f32, f32) -> f32 = match mode {+ "darken" => f32::min,+ "lighten" => f32::max,+ "difference" => |s, d| (s - d).abs(),+ _ => return src,+ };+ let a = dst[3].clamp(0.0, 1.0);+ let mut out = src;+ for (o, (&s, &d)) in out.iter_mut().zip(src.iter().zip(&dst)).take(3) {+ *o = s + (f(s, d) - s) * a;+ }+ out+}+/// Bilinear resample of `src` (covering [`Mapping::source_rect`]) onto `dst`, interpolating/// premultiplied by the alpha channel `alpha` when there is one. Outside `src` is transparent.pub fn resample(src: &Region, dst: Rect, map: &Mapping, alpha: Option<usize>) -> Region {@@ -292,13 +315,26 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {if let Some(a) = p.get("scale").and_then(Value::as_array) {slot.scale = [a.first().and_then(Value::as_f64).unwrap_or(100.0), a.get(1).and_then(Value::as_f64).unwrap_or(100.0)];}+ if let Some(b) = p.get("linked").and_then(Value::as_bool) {+ slot.linked = b;+ }let num = |k: &str| p.get(k).and_then(Value::as_f64);- if let Some(w) = num("width") {+ let before = slot.scale;+ let (w, h) = (num("width"), num("height"));+ if let Some(w) = w {slot.scale[0] = w;}- if let Some(h) = num("height") {+ if let Some(h) = h {slot.scale[1] = h;}+ // Linked W/H keep their ratio: the field that was not given follows the one that was.+ if slot.linked {+ match (w, h) {+ (Some(w), None) if before[0].abs() > 1e-9 => slot.scale[1] = before[1] * w / before[0],+ (None, Some(h)) if before[1].abs() > 1e-9 => slot.scale[0] = before[0] * h / before[1],+ _ => {}+ }+ }if slot.scale.iter().any(|v| !(1.0..=1000.0).contains(&v.abs())) {slot.scale = slot.scale.map(|v| v.clamp(1.0, 1000.0));}@@ -361,7 +397,7 @@ pub fn specs() -> Vec<CommandSpec> {label: "Clone Sources",menu: &[],shortcut: None,- params: "{} → {active,sources:[{index,source,anchor,offset,layer,width,height,rotation,flipH,flipV}],overlay}",+ params: "{} → {active,sources:[{index,source,anchor,offset,layer,width,height,linked,rotation,flipH,flipV}],overlay}",enabled: always,run: list,journal: false,@@ -381,7 +417,7 @@ pub fn specs() -> Vec<CommandSpec> {label: "Set Clone Source",menu: &[],shortcut: None,- params: r##"{"index":0..4?=active,"source":[x,y]? (⌥-click; re-pairs with the next stroke),"offset":[dx,dy]?,"width":%?,"height":%?|"scale":[w%,h%]?,"rotation":deg?,"flipH":bool?,"flipV":bool?,"layer":id?,"clear":bool?,"select":bool=true}"##,+ params: r##"{"index":0..4?=active,"source":[x,y]? (⌥-click; re-pairs with the next stroke),"offset":[dx,dy]?,"width":%?,"height":%?|"scale":[w%,h%]?,"linked":bool? (W/H link: a lone width or height scales the other by the same factor),"rotation":deg?,"flipH":bool?,"flipV":bool?,"layer":id?,"clear":bool?,"select":bool=true}"##,enabled: always,run: set,journal: true,@@ -426,6 +462,29 @@ mod tests {assert!(r.x0 <= r.x1 && r.y0 <= r.y1, "rect must stay ordered: {r:?}");}+ #[test]+ fn linked_width_and_height_keep_their_ratio() {+ let mut s = Session::new();+ s.execute("cloneSource.set", json!({"width": 50, "height": 200})).unwrap();+ s.execute("cloneSource.set", json!({"width": 100})).unwrap();+ assert_eq!(s.presets.clone.active().scale, [100.0, 200.0], "unlinked: H stays");+ let r = s.execute("cloneSource.set", json!({"linked": true, "width": 150})).unwrap();+ assert_eq!((r["width"].as_f64(), r["height"].as_f64(), r["linked"].as_bool()), (Some(150.0), Some(300.0), Some(true)));+ s.execute("cloneSource.set", json!({"height": 60})).unwrap();+ assert_eq!(s.presets.clone.active().scale, [30.0, 60.0], "linked: W follows H");+ }++ #[test]+ fn overlay_blend_modes_mix_with_the_image_under_the_brush() {+ let (src, dst) = ([0.8, 0.2, 0.5, 1.0], [0.3, 0.6, 0.5, 1.0]);+ let close = |a: [f32; 4], b: [f32; 4]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6);+ assert_eq!(overlay_blend("normal", src, dst), src);+ assert!(close(overlay_blend("darken", src, dst), [0.3, 0.2, 0.5, 1.0]));+ assert!(close(overlay_blend("lighten", src, dst), [0.8, 0.6, 0.5, 1.0]));+ assert!(close(overlay_blend("difference", src, dst), [0.5, 0.4, 0.0, 1.0]));+ assert_eq!(overlay_blend("difference", src, [0.3, 0.6, 0.5, 0.0]), src, "a transparent image leaves the source as is");+ }+#[test]fn source_rect_normal_case_unchanged() {let m = Mapping { source: (200.0, 0.0), anchor: (10.0, 10.0), m: [1.0, 0.0, 0.0, 1.0] };diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 0f53e35d9..12aa1c10f 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -22,7 +22,7 @@ pub(crate) struct ClonePreviewCache {/// A transient source image beneath the brush outline; never part of the document render.fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, at: [f64; 2], output: Option<u32>) {- use photocraft_engine::presets::clone_source::{Mapping, transform_matrix};+ use photocraft_engine::presets::clone_source::{Mapping, overlay_blend, transform_matrix};let overlay = app.session.presets.clone.overlay.clone();if app.ui.tool != Tool::CloneStamp || !overlay.show || (overlay.auto_hide && app.drag.is_some()) {return;@@ -41,8 +41,8 @@ fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &Vielet Some(st) = app.session.active() else { return };let (display, display_key) = canvas_display(app, &st.doc, output);let key = format!(- "{:?}:{}:{:?}:{rect:?}:{map:?}:{}:{}:{}",- st.doc.id, st.revision, st.active_layer, app.ui.tool_options.clone_sample, display_key, overlay.invert+ "{:?}:{}:{:?}:{rect:?}:{map:?}:{}:{}:{}:{}",+ st.doc.id, st.revision, st.active_layer, app.ui.tool_options.clone_sample, display_key, overlay.invert, overlay.blend);if app.clone_preview.as_ref().is_none_or(|c| c.key != key) {let Ok(mut buf) = photocraft_engine::retouch_cmds::clone_preview(&app.session, rect, &map, &app.ui.tool_options.clone_sample) else { return };@@ -53,6 +53,15 @@ fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &Vie}}}+ // Darken, Lighten and Difference mix the source with the image under the brush (the+ // composite, whatever Sample reads), so Difference turns black where they line up.+ if overlay.blend != "normal" {+ let here = Mapping { source: (0.0, 0.0), anchor: (0.0, 0.0), m: [1.0, 0.0, 0.0, 1.0] };+ let Ok(under) = photocraft_engine::retouch_cmds::clone_preview(&app.session, rect, &here, "all") else { return };+ for (px, d) in buf.px.iter_mut().zip(&under.px) {+ *px = overlay_blend(&overlay.blend, *px, *d);+ }+ }let image = display_image(display.as_deref(), &buf);match app.clone_preview.as_mut() {Some(cache) => {@@ -5673,6 +5682,38 @@ mod tests {assert!(output.shapes.iter().all(|s| !matches!(s.shape, egui::Shape::Mesh(_))));}+ #[test]+ fn clone_overlay_blend_mode_mixes_with_the_image_under_the_brush() {+ let ctx = egui::Context::default();+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.run("file.new", json!({"width": 64, "height": 64})).unwrap();+ app.run("cloneSource.set", json!({"source": [16,16]})).unwrap();+ app.ui.tool = Tool::CloneStamp;+ app.session.tools.brush.size = 20.0;+ let xf =+ ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)), zoom: 1.0, center: [32.0, 32.0], flip: false, rotation: 0.0, aspect: 1.0 };+ // The centre texel of the overlay texture uploaded for `mode`.+ let mut centre = |mode: &str| {+ app.run("cloneSource.overlay", json!({"blend": mode})).unwrap();+ let mut output = ctx.run_ui(Default::default(), |ui| {+ let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::new("clone-test")));+ draw_clone_preview(&mut app, &painter, &xf, [32.0, 32.0], None);+ });+ // The brush's 20 × 20 px square (the font atlas may upload too).+ let image = output.textures_delta.set.values().flatten().find_map(|d| match &d.image {+ egui::ImageData::Color(c) if c.size == [20, 20] => Some(c.clone()),+ _ => None,+ });+ output.textures_delta.clear();+ let image = image.expect("the overlay uploads a texture");+ image.pixels[image.width() * (image.height() / 2) + image.width() / 2]+ };+ // A white source over the white image: Normal shows white, Difference black.+ assert_eq!(centre("normal"), Color32::WHITE);+ assert_eq!(centre("difference"), Color32::BLACK, "Difference turns black where source and image match");+ assert_eq!(centre("lighten"), Color32::WHITE);+ }+#[test]fn wayland_start_screen_hint_does_not_claim_file_drop_works() {let x11 = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/preset_panels.rsindex e2da49f3e..2528ec697 100644--- a/crates/ui-egui/src/preset_panels.rs+++ b/crates/ui-egui/src/preset_panels.rs@@ -1007,7 +1007,7 @@ pub fn clone_source_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let (mut ox, mut oy) = (off[0] as f32, off[1] as f32);let (mut w, mut h) = (slot.scale[0] as f32, slot.scale[1] as f32);let mut rot = slot.rotation as f32;- egui::Grid::new("clone-src-grid").num_columns(4).spacing(vec2(6.0, 4.0)).show(ui, |ui| {+ egui::Grid::new("clone-src-grid").num_columns(5).spacing(vec2(6.0, 4.0)).show(ui, |ui| {lbl(ui, "X:");if crate::widgets::value_field(ui, &mut ox, -30000.0..=30000.0, "px", 72.0).changed() && slot.source.is_some() {action = Some(json!({"offset": [ox, oy]}));@@ -1016,6 +1016,11 @@ pub fn clone_source_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {if crate::widgets::value_field(ui, &mut w, -1000.0..=1000.0, "%", 64.0).changed() {action = Some(json!({"width": w}));}+ // The W/H chain: with it on, a new W or H scales the other by the same factor.+ let icon = if slot.linked { "link" } else { "unlink" };+ if crate::icons::button(ui, icon, 22.0, slot.linked, tl!("Maintain aspect ratio")).clicked() {+ action = Some(json!({"linked": !slot.linked}));+ }ui.end_row();lbl(ui, "Y:");if crate::widgets::value_field(ui, &mut oy, -30000.0..=30000.0, "px", 72.0).changed() && slot.source.is_some() {diff --git a/docs/scorecard.md b/docs/scorecard.mdindex a06e61cd4..32099f753 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -137,7 +137,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t| TOOL-213-5 | Painting a type/shape/smart/fill layer offers to rasterize, then continues the stroke | done | [#213](https://github.com/storytold/photocraft/issues/213) | rasterize_prompt.rs: OK rasterizes then paints (two history states), Cancel does nothing; drivable via ui.dialog.confirm || TOOL-213-6 | Fill dialog: contents, blend, opacity, preserve transparency; remembered; Shift+Backspace | done | [#213](https://github.com/storytold/photocraft/issues/213) | fill_ui.rs dialog over edit.fill (fill_cmds.rs): all contents, mode, opacity, preserve; remembered in prefs; Shift+F5 / Shift+Backspace || TOOL-213-7 | Live stroke preview for every brush-based retouch tool | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Live (canvas.rs strokes_live): Brush, Pencil, Eraser, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Clone Stamp, Healing Brush, History Brush (#1026, #1040); the release commits the live stroke's pixels (P32). Not yet live: Spot Healing Brush, Mixer Brush, Background Eraser, Pattern Stamp |-| TOOL-213-8 | Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Clone Source overlay drawn with opacity, inversion, circular clipping and auto-hide; W/H link, custom-tip clipping and overlay blend modes remain missing |+| TOOL-213-8 | Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Clone Source overlay drawn with opacity, inversion, circular clipping, auto-hide and the Normal/Darken/Lighten/Difference blend against the image under the brush (canvas.rs draw_clone_preview, clone_source::overlay_blend); W/H link (cloneSource.set linked, panel chain button, #3298); custom-tip clipping remains missing || TOOL-213-9 | Eyedropper comparison ring (new colour above, current below) while sampling | done | [#213](https://github.com/storytold/photocraft/issues/213) | eyedropper_ring (canvas.rs): the sampled colour on the upper arc, the foreground below, drawn for the Eyedropper and Alt-sampling while the button is held; the Precise-cursor preference keeps the crosshair || TOOL-213-10 | Ctrl+Alt drag resizes brush size/hardness with an on-canvas readout | done | [#213](https://github.com/storytold/photocraft/issues/213) | brush_resize.rs (#297, #370): Alt+right-drag, or Control+Option-drag on macOS (Control+Alt everywhere), sets diameter horizontally and hardness vertically, circle plus Diameter/Hardness readout, one coalesced tools.setBrush, no paint or history; 9 tests there || TOOL-213-11 | Editable pressure curve, global and per control | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Global: Preferences › Tools › Pressure Curve (prefs tools.pressureCurve; monotone cubic, engine prefs::PressureCurve; applied to every pen sample in ui-egui stylus.rs before any brush; editor pressure_curve_ui.rs with Linear/Soft/Hard presets). Missing: per-control curves (each brush dynamic's own response to pressure, tilt, rotation) |diff --git a/scorecard/tools.toml b/scorecard/tools.tomlindex 2b4b19684..7f7e7ebc3 100644--- a/scorecard/tools.toml+++ b/scorecard/tools.toml@@ -59,7 +59,7 @@ id = "TOOL-213-8"target = "Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor"status = "partial"issue = 213-note = "Clone Source overlay drawn with opacity, inversion, circular clipping and auto-hide; W/H link, custom-tip clipping and overlay blend modes remain missing"+note = "Clone Source overlay drawn with opacity, inversion, circular clipping, auto-hide and the Normal/Darken/Lighten/Difference blend against the image under the brush (canvas.rs draw_clone_preview, clone_source::overlay_blend); W/H link (cloneSource.set linked, panel chain button, #3298); custom-tip clipping remains missing"[[item]]id = "TOOL-213-9"