diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs index 7e422ce629..7d493fa672 100644 --- a/crates/engine/src/retouch_cmds.rs +++ b/crates/engine/src/retouch_cmds.rs @@ -220,6 +220,33 @@ fn clone_sample( Ok(crate::presets::clone_source::resample(&src, rect, map, alpha_index(&surf.format()))) } +/// Read-only clone overlay. Shares the stroke sampler without anchoring a source or editing history. +/// Both destination and transformed source allocations are bounded for interactive use. +pub fn clone_preview(s: &Session, rect: Rect, map: &crate::presets::clone_source::Mapping, sample_layer: &str) -> Result { + if ![map.source.0, map.source.1, map.anchor.0, map.anchor.1].into_iter().chain(map.m).all(|v| v.is_finite() && v.abs() < 1_000_000.0) { + return Err(bad("clone.preview", "invalid preview mapping")); + } + if ![rect.x0, rect.y0, rect.x1, rect.y1].into_iter().all(|v| v.abs_diff(0) < 1_000_000) + || ![(rect.x0, rect.y0), (rect.x1, rect.y1), (rect.x0, rect.y1), (rect.x1, rect.y0)].into_iter().all(|(x, y)| { + let (x, y) = map.map(f64::from(x), f64::from(y)); + x.is_finite() && y.is_finite() && x.abs() < 1_000_000.0 && y.abs() < 1_000_000.0 + }) + { + return Err(bad("clone.preview", "preview coordinates exceed their budget")); + } + let bounded = |r: Rect| r.width() > 0 && r.height() > 0 && r.width() <= 1024 && r.height() <= 1024; + if !bounded(rect) || !bounded(map.source_rect(rect)) { + return Err(bad("clone.preview", "preview region exceeds its budget")); + } + let d = s.active().ok_or(EngineError::NoDocument)?; + let id = d.active_layer.ok_or_else(|| bad("clone.preview", "no active layer"))?; + let surf = d.doc.layer(id).and_then(|l| l.surface()).ok_or_else(|| bad("clone.preview", "no pixel surface"))?; + let which = sample_layers(&json!({"sampleLayer": sample_layer}), "clone.preview")?; + let region = clone_sample(&d.doc, Some(id), surf, which, rect, map, "clone.preview")?; + let px = region.data.chunks_exact(surf.format().channels()).map(|p| to_rgba(&surf.format(), p)).collect(); + Ok(photocraft_compose::Buffer { rect, px }) +} + /// Result JSON shared by Clone Stamp and Healing Brush: the offset used and where the next stroke /// should sample from if the UI keeps Photoshop's "Aligned" semantics. fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value, stroke: &Stroke) -> Value { diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs index 72fd9112af..b4a7f30a5e 100644 --- a/crates/engine/src/retouch_cmds/tests.rs +++ b/crates/engine/src/retouch_cmds/tests.rs @@ -3,6 +3,30 @@ use photocraft_color::ColorMode; const DEPTHS: [u64; 3] = [8, 16, 32]; +#[test] +fn clone_preview_matches_source_without_mutating_session() { + use crate::presets::clone_source::Mapping; + for depth in DEPTHS { + let mut s = session(32, 32, depth, "rgb"); + paint_layer(&mut s, |x, y| [x as f32 / 32.0, y as f32 / 32.0, 0.25, 1.0]); + s.execute("cloneSource.set", json!({"source": [8,8]})).unwrap(); + let revision = s.active().unwrap().revision; + let slots = s.presets.clone.clone(); + let map = Mapping { source: (8.0, 8.0), anchor: (20.0, 20.0), m: [1.0, 0.0, 0.0, 1.0] }; + let buf = clone_preview(&s, Rect::new(20, 20, 21, 21), &map, "current").unwrap(); + let expected = rgba(&s, 8, 8); + for (actual, expected) in buf.px[0].iter().zip(expected) { + assert!((actual - expected).abs() < 0.001); + } + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.presets.clone, slots); + assert!(clone_preview(&s, Rect::new(0, 0, 2048, 2048), &map, "current").is_err()); + assert!(clone_preview(&s, Rect::new(20, 20, 21, 21), &map, "invalid").is_err()); + let invalid = Mapping { source: (f64::NAN, 0.0), ..map }; + assert!(clone_preview(&s, Rect::new(0, 0, 1, 1), &invalid, "current").is_err()); + } +} + fn session(w: u32, h: u32, depth: u64, mode: &str) -> Session { let mut s = Session::new(); s.execute("file.new", json!({"width": w, "height": h, "depth": depth, "mode": mode})).unwrap(); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 2bf52005ae..248a3a7e44 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -15,6 +15,81 @@ use crate::state::{Tool, View}; /// Largest texture side we upload; bigger documents display downsampled until the GPU path lands. pub const MAX_TEXTURE: u32 = 4096; +pub(crate) struct ClonePreviewCache { + key: String, + texture: egui::TextureHandle, +} + +/// 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) { + use photocraft_engine::presets::clone_source::{Mapping, 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; + } + let slot = app.session.presets.clone.active().clone(); + let Some(source) = slot.source else { return }; + let radius = f64::from(app.session.tools.brush.size) / 2.0; + if !radius.is_finite() || radius <= 0.0 || radius > 500.0 || !at.iter().all(|v| v.is_finite() && v.abs() < 1_000_000.0) { + return; + } + let stroke_start = app.drag.as_ref().map(|d| d.start); + let anchor = if app.ui.tool_options.clone_aligned { slot.anchor.or(stroke_start) } else { stroke_start }.unwrap_or(at); + let map = + Mapping { source: (source[0], source[1]), anchor: (anchor[0], anchor[1]), m: transform_matrix(slot.scale, slot.rotation, slot.flip_h, slot.flip_v) }; + let rect = DRect::new((at[0] - radius).floor() as i32, (at[1] - radius).floor() as i32, (at[0] + radius).ceil() as i32, (at[1] + radius).ceil() as i32); + let 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 + ); + 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 }; + if overlay.invert { + for px in &mut buf.px { + for c in px.iter_mut().take(3) { + *c = 1.0 - *c; + } + } + } + let image = display_image(display.as_deref(), &buf); + match app.clone_preview.as_mut() { + Some(cache) => { + cache.texture.set(image, TextureOptions::LINEAR); + cache.key = key; + } + None => app.clone_preview = Some(ClonePreviewCache { key, texture: painter.ctx().load_texture("clone-preview", image, TextureOptions::LINEAR) }), + } + } + let Some(cache) = &app.clone_preview else { return }; + let tint = Color32::from_white_alpha((overlay.opacity.clamp(0.0, 100.0) * 2.55).round() as u8); + // A textured triangle fan provides a circular clip, including mirrored canvas views. + let mut mesh = egui::Mesh::with_texture(cache.texture.id()); + let vertex = |x: f64, y: f64| egui::epaint::Vertex { + pos: xf.to_screen(x as f32, y as f32), + uv: pos2((x - f64::from(rect.x0)) as f32 / rect.width() as f32, (y - f64::from(rect.y0)) as f32 / rect.height() as f32), + color: tint, + }; + if !overlay.clipped { + for (x, y) in [(rect.x0, rect.y0), (rect.x1, rect.y0), (rect.x1, rect.y1), (rect.x0, rect.y1)] { + mesh.vertices.push(vertex(f64::from(x), f64::from(y))); + } + mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]); + painter.add(egui::Shape::mesh(mesh)); + return; + } + mesh.vertices.push(vertex(at[0], at[1])); + for i in 0..=64 { + let angle = f64::from(i) * std::f64::consts::TAU / 64.0; + mesh.vertices.push(vertex(at[0] + radius * angle.cos(), at[1] + radius * angle.sin())); + } + for i in 1..=64 { + mesh.indices.extend_from_slice(&[0, i, i + 1]); + } + painter.add(egui::Shape::mesh(mesh)); +} + pub struct CanvasCache { pub revision: u64, pub texture: Option, @@ -2032,6 +2107,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: ui.ctx().set_cursor_icon(egui::CursorIcon::Move); } else if let Some(p) = response.hover_pos() { let alt = ui.input(|i| i.modifiers.alt); + if !resizing && !alt && !app.ui.shell.sticky_alt { + draw_clone_preview(app, &painter, &xf, xf.to_doc(p), output); + } let icon = match tool { // Resizing the brush: the circle stays where the drag began (`brush_resize`). t if resizing && crate::brush_resize::applies(t) => egui::CursorIcon::None, @@ -3164,6 +3242,45 @@ mod tests { assert_eq!(app.session.documents().len(), 2); } + #[test] + fn clone_overlay_is_circular_and_respects_visibility() { + 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 }; + let revision = app.session.active().unwrap().revision; + let mut output = ctx.run_ui(Default::default(), |ui| { + let ctx = ui.ctx(); + let painter = 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); + }); + output.textures_delta.clear(); + let mesh = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(m) => Some(m), + _ => None, + }) + .unwrap(); + assert_eq!(mesh.indices.len(), 64 * 3); + let center = xf.to_screen(32.0, 32.0); + assert!(mesh.vertices.iter().all(|v| v.pos.distance(center) <= 10.01)); + assert_eq!(app.session.active().unwrap().revision, revision); + assert!(app.session.presets.clone.active().anchor.is_none()); + app.session.presets.clone.overlay.show = false; + let mut output = ctx.run_ui(Default::default(), |ui| { + let ctx = ui.ctx(); + let painter = 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); + }); + output.textures_delta.clear(); + assert!(output.shapes.iter().all(|s| !matches!(s.shape, egui::Shape::Mesh(_)))); + } + #[test] fn wayland_start_screen_hint_does_not_claim_file_drop_works() { assert_ne!(start_screen_drop_hint(true), start_screen_drop_hint(false)); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index baf7924657..ac44a5d3ee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -425,6 +425,7 @@ pub struct PhotocraftApp { pub(crate) clip_read_for_paste: bool, /// Pointer position over the canvas (document px), for the Info panel and status bar. pub(crate) hover_doc: Option<[f64; 2]>, + pub(crate) clone_preview: Option, /// Info panel sample cache: ((x, y, revision), composite RGBA). info_sample: Option<((i32, i32, u64), [f32; 4])>, /// Guide being dragged (from a ruler or with the Move tool). @@ -524,6 +525,7 @@ impl PhotocraftApp { guide_drag: None, crop: Default::default(), hover_doc: None, + clone_preview: None, info_sample: None, os_clip_sig: None, clip_external: false, diff --git a/docs/scorecard.md b/docs/scorecard.md index f74c351801..8748956be0 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -128,7 +128,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 | missing | [#213](https://github.com/storytold/photocraft/issues/213) | Live stroke only for Brush and Eraser (canvas.rs:1684) | -| 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) | Panel W/H + overlay settings (preset_panels.rs:946-1015); no link, overlay never drawn | +| 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-9 | Eyedropper comparison ring (new colour above, current below) while sampling | missing | [#213](https://github.com/storytold/photocraft/issues/213) | sample_eyedropper (canvas.rs:1552) draws no ring | | TOOL-213-10 | Ctrl+Alt drag resizes brush size/hardness with an on-canvas readout | missing | [#213](https://github.com/storytold/photocraft/issues/213) | Only [ ] resize (shortcuts.rs:270) | | TOOL-213-11 | Editable pressure curve, global and per control | missing | [#213](https://github.com/storytold/photocraft/issues/213) | No pressure curve in engine, paint or ui-egui | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index ba24bf9557..146d6d4940 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 = "Panel W/H + overlay settings (preset_panels.rs:946-1015); no link, overlay never drawn" +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" [[item]] id = "TOOL-213-9"