Keep healing source coverage and clone overlays consistent

This commit is contained in:
Ian committed 2026-11-11 18:12:44 -05:00
1 parent 85446b50e5
commit d209bb863e
8 files changed
+206 -9

No files matched your search

+1 -1
View File
@@ -235,7 +235,7 @@ mod dab;
mod heal;
mod sampling;
pub use clone::{LiveRetouch, clone_destination_preview, clone_preview, clone_preview_periodic, healing_preview};
pub use clone::{LiveRetouch, clone_destination_preview, clone_preview, clone_preview_periodic, healing_preview, healing_preview_periodic};
use clone::{blend_param, clamp_samples, clone_stamp};
pub(crate) use dab::DabEffect;
#[cfg(test)]
+15 -2
View File
@@ -129,7 +129,18 @@ pub fn clone_preview_periodic(
/// Healing Brush's source overlay, including its documented cross-document Grayscale exception.
pub fn healing_preview(s: &Session, rect: Rect, map: &crate::presets::clone_source::Mapping, sample_layer: &str) -> Result<photocraft_compose::Buffer> {
preview_periodic(s, rect, map, sample_layer, false, PreviewSource::Healing)
healing_preview_periodic(s, rect, map, sample_layer, false)
}
/// Healing Brush's source overlay with the same Pattern Preview repetition as its stroke.
pub fn healing_preview_periodic(
s: &Session,
rect: Rect,
map: &crate::presets::clone_source::Mapping,
sample_layer: &str,
wrap: bool,
) -> Result<photocraft_compose::Buffer> {
preview_periodic(s, rect, map, sample_layer, wrap, PreviewSource::Healing)
}
/// The image beneath a clone overlay, always from the document being painted.
@@ -177,7 +188,9 @@ fn preview_periodic(
PreviewSource::Destination => CloneFrom::default(),
PreviewSource::Clone | PreviewSource::Healing => {
let cmd = if matches!(kind, PreviewSource::Healing) { "healing.preview" } else { "clone.preview" };
clone_sampling::resolve(s, &json!({"sampleLayer": sample_layer}), cmd)?
let paint_cmd = if matches!(kind, PreviewSource::Healing) { "paint.healingBrush" } else { "paint.cloneStamp" };
let params = crate::channel_cmds::inject_target(s, paint_cmd, json!({"sampleLayer": sample_layer}));
clone_sampling::resolve(s, &params, cmd)?
}
};
let region = clone_sample(&d.doc, Some(id), surf, which, &source, rect, map, wrap, "clone.preview")?;
@@ -862,6 +862,81 @@ fn clone_no_alpha_healing_sources_match_alpha_sources_in_preview_and_commit() {
}
}
/// Hover sampling must refuse the same cross-document grayscale targets as painting.
#[test]
fn clone_cross_document_hover_rejects_targeted_masks_and_channels_like_strokes() {
use crate::channel_cmds::ChannelTarget;
for target_mask in [false, true] {
let (mut s, _, _) = setup(8, "rgb");
s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
if target_mask {
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
s.active_mut().unwrap().channel_view.target = ChannelTarget::LayerMask;
} else {
s.execute("channel.new", json!({"fill": "white"})).unwrap();
}
let map = Mapping { source: (16.0, 16.0), anchor: (32.0, 32.0), m: [1.0, 0.0, 0.0, 1.0] };
let rect = Rect::new(30, 30, 34, 34);
assert!(s.execute("paint.cloneStamp", json!({"points": [[32,32]], "size": 8})).is_err());
assert!(clone_preview(&s, rect, &map, "current").is_err(), "a refused cross-document target cannot have a source overlay");
assert!(super::clone::healing_preview(&s, rect, &map, "current").is_err());
}
}
/// A Poisson boundary cannot create source coverage for an absent sampled pixel.
#[test]
fn clone_healing_absent_source_preserves_nonuniform_destinations() {
for depth in [8, 16, 32] {
for mode in ["rgb", "gray", "cmyk", "lab"] {
for wrap in [false, true] {
for source_alpha in [false, true] {
for target_alpha in [false, true] {
for source_point in [[-100, -100], [0, 0]] {
for blend in ["normal", "multiply"] {
let (mut s, target) = no_alpha_scene(depth, mode, source_alpha, target_alpha, true, source_point, [0.5, 0.5, 0.5, 1.0]);
s.edit("nonuniform destination", |doc, _| {
let bounds = doc.bounds();
let surf = doc.layer_mut(target).unwrap().surface_mut().unwrap();
let fmt = surf.format();
surf.fill_rect(bounds, &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0]));
for (x, y) in [(30, 32), (34, 34)] {
surf.write_region(Rect::new(x, y, x + 1, y + 1), &photocraft_raster::from_rgba(&fmt, [0.25, 0.25, 0.25, 1.0]));
}
Ok(())
})
.unwrap();
let before = s.active().unwrap().doc.layer(target).unwrap().surface().unwrap().clone();
let p = json!({"points": [[32,32]], "size": 14, "hardness": 100, "mode": blend, "wrap": wrap});
let live = LiveRetouch::begin(&s, "paint.healingBrush", &p).unwrap();
if !wrap {
assert_eq!(live.doc.layer(target).unwrap().surface().unwrap().rgba(30, 32), before.rgba(30, 32));
}
s.execute("paint.healingBrush", p).unwrap();
let after = s.active().unwrap().doc.layer(target).unwrap().surface().unwrap();
assert_eq!(after.format(), before.format());
if wrap {
assert_ne!(after.rgba(30, 32), before.rgba(30, 32), "wrapped source pixels still heal: {depth}/{mode}/{blend}");
continue;
}
assert_eq!(
after.rgba(30, 32),
before.rgba(30, 32),
"absent source {source_point:?}, depth {depth}, alpha {source_alpha}/{target_alpha}, {blend}"
);
if source_point[0] < 0 {
assert_eq!(after.read_region(Rect::new(0, 0, 80, 80)), before.read_region(Rect::new(0, 0, 80, 80)));
} else {
assert_ne!(after.rgba(34, 34), before.rgba(34, 34), "valid source pixels still heal");
}
}
}
}
}
}
}
}
}
/// Nonuniform soft-tip coverage must stay aligned across the opaque destination's working tiles.
#[test]
fn clone_no_alpha_soft_stroke_matches_reference_across_multiple_working_patches() {
+11 -2
View File
@@ -79,8 +79,17 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result<Value> {
composite_region(pre, id, which, g, surf.format())
};
let dst = if fmt.alpha && !surf.format().alpha { super::clone_sampling::opaque_alpha(dst, surf.format()) } else { dst };
let mask: Vec<bool> = cov.iter().map(|c| *c > 0.0).collect();
let healed = heal_region(&fmt, &src, &dst, &mask);
// The solver can reconstruct positive alpha from the destination boundary even where
// no source pixel exists. Keep source availability separate from the solved channels.
let alpha = super::alpha_index(&fmt);
let has_source = |pixel: &[f32]| alpha.is_none_or(|a| pixel.get(a).is_some_and(|value| *value > 0.0));
let mask: Vec<bool> = cov.iter().zip(src.data.chunks_exact(fmt.channels())).map(|(c, pixel)| *c > 0.0 && has_source(pixel)).collect();
let mut healed = heal_region(&fmt, &src, &dst, &mask);
for (pixel, sample) in healed.data.chunks_exact_mut(fmt.channels()).zip(src.data.chunks_exact(fmt.channels())) {
if !has_source(sample) {
pixel.fill(0.0);
}
}
if wrap {
return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, fmt, |_, r| {
let part = healed.crop(r);
+28
View File
@@ -161,6 +161,10 @@ pub fn over_native(fmt: &PixelFormat, dst: &mut [f32], src: &[f32], k: f32, lock
match alpha_index(fmt) {
Some(a) => {
let (da, sa) = (dst[a], src[a] * k);
// Zero-weight source-over must preserve even the native float channel bits.
if sa <= 0.0 {
return;
}
if lock_transparency {
// Alpha kept: source atop, the colour moves by the source alpha alone (#5783).
for c in 0..a {
@@ -232,6 +236,11 @@ pub fn apply_coverage(
continue;
}
let src = paint.px(x, y);
// A transparent source cannot paint. Skip it before a blend-mode RGB round trip can
// change untouched native CMYK/Lab values (or Normal blending can round float values).
if a.and_then(|a| src.get(a)).is_some_and(|alpha| *alpha <= 0.0) {
continue;
}
if blend == BlendMode::Normal {
over_native(&fmt, px, src, k, lock_transparency);
} else {
@@ -634,6 +643,25 @@ mod tests {
}
}
/// Missing source pixels must preserve native ink values even for non-Normal blend modes.
#[test]
fn transparent_retouch_source_preserves_native_channels_in_every_blend_mode() {
use photocraft_color::{ColorMode, SampleType};
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
let fmt = PixelFormat::new(mode, sample, true);
for blend in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) {
let mut target = Surface::with_default(fmt, &vec![0.3; fmt.channels()]);
let rect = Rect::new(0, 0, 2, 2);
let before = target.read_region(rect);
let paint = Region::new(rect, fmt.channels());
apply_coverage(&mut target, rect, &[1.0; 4], 1.0, None, false, &paint, blend);
assert_eq!(target.read_region(rect), before, "{fmt:?}, {blend:?}");
}
}
}
}
#[test]
fn a_dab_stroke_between_distant_points_is_refused_before_reading() {
assert!(fits_dab_stroke_budget(Rect::new(0, 0, 4096, 4096), 4));
+8 -4
View File
@@ -86,10 +86,14 @@ pub(super) fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painte
if !radius.is_finite() || radius <= 0.0 || radius > 500.0 || !at.iter().all(|v| v.is_finite() && v.abs() < 1_000_000.0) {
return;
}
// View › Pattern Preview repeats the source for the Clone Stamp only (`paint.cloneStamp`'s
// `wrap`); the Healing Brush samples it as it is.
let wrap = tool == Tool::CloneStamp && app.ui.view.pattern_preview;
// Both tools repeat source reads in Pattern Preview; this also refreshes a stationary hover.
let wrap = app.ui.view.pattern_preview;
let Some(st) = app.session.active() else { return };
let target = paint_target(app);
if slot.document.is_some_and(|id| id != st.doc.id) && photocraft_engine::channel_cmds::gray_target(&json!({"target": target})).is_some() {
// Strokes reject these cross-document targets, including a mask selected only in the UI.
return;
}
let source_revision =
slot.document.and_then(|id| app.session.documents().iter().find(|st| st.doc.id == id)).map(|st| (st.doc.id, st.revision, st.active_layer));
let source_document = slot.document.and_then(|id| app.session.documents().iter().find(|st| st.doc.id == id)).map(|st| std::sync::Arc::downgrade(&st.doc));
@@ -131,7 +135,7 @@ pub(super) fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painte
),
};
let preview = if tool == Tool::Healing {
photocraft_engine::retouch_cmds::healing_preview(&app.session, rect, &map, &app.ui.tool_options.clone_sample)
photocraft_engine::retouch_cmds::healing_preview_periodic(&app.session, rect, &map, &app.ui.tool_options.clone_sample, wrap)
} else {
photocraft_engine::retouch_cmds::clone_preview_periodic(&app.session, rect, &map, &app.ui.tool_options.clone_sample, wrap)
};
+67
View File
@@ -1772,6 +1772,73 @@ fn clone_overlay_shows_for_the_healing_brush_too() {
}
}
/// Pattern Preview changes the Healing Brush source overlay at a stationary cursor.
#[test]
fn clone_healing_overlay_wraps_with_the_live_texture_at_source_edges() {
let ctx = egui::Context::default();
let xf = clone_overlay_view(100.0, 1.0);
let mut app = clone_overlay_app(12.0);
app.ui.tool = Tool::Healing;
app.run("cloneSource.set", json!({"source": [0,0]})).unwrap();
app.run("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap();
let mut output = clone_overlay_frame(&ctx, &mut app, &xf);
assert_eq!(clone_overlay_alpha(&app, &mut output)(30, 32), 0);
app.ui.view.pattern_preview = true;
assert_eq!(crate::retouch_ui::clone_params(&app).unwrap()["wrap"], true);
let mut output = clone_overlay_frame(&ctx, &mut app, &xf);
assert_eq!(clone_overlay_alpha(&app, &mut output)(30, 32), 255, "the repeated source is visible before painting");
let live = photocraft_engine::retouch_cmds::LiveRetouch::begin(
&app.session,
"paint.healingBrush",
&json!({"points": [[32,32]], "size": 12, "hardness": 100, "wrap": true}),
)
.unwrap();
let st = app.session.active().unwrap();
assert_eq!(live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(30, 32), [1.0; 4]);
app.ui.view.pattern_preview = false;
let mut output = clone_overlay_frame(&ctx, &mut app, &xf);
assert_eq!(clone_overlay_alpha(&app, &mut output)(30, 32), 0);
}
/// Unsupported cross-document targets never reuse a cached pixel-layer source overlay.
#[test]
fn clone_overlay_suppresses_cross_document_masks_and_channels() {
for tool in [Tool::CloneStamp, Tool::Healing] {
for mask in [false, true] {
let ctx = egui::Context::default();
let xf = clone_overlay_view(100.0, 1.0);
let mut app = clone_overlay_app(12.0);
app.ui.tool = tool;
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
if mask {
app.run("layer.layerMask.revealAll", json!({})).unwrap();
} else {
app.run("channel.new", json!({"fill": "white"})).unwrap();
}
app.run("channel.target", json!({"channel": "composite"})).unwrap();
app.ui.mask_target = false;
let mut output = clone_overlay_frame(&ctx, &mut app, &xf);
assert!(output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Mesh(_))));
output.textures_delta.clear();
let revision = app.session.active().unwrap().revision;
if mask {
app.ui.mask_target = true;
} else {
app.session.active_mut().unwrap().channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Alpha(0);
}
assert_eq!(app.session.active().unwrap().revision, revision, "only the target changed");
let mut output = clone_overlay_frame(&ctx, &mut app, &xf);
assert!(!output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Mesh(_))), "{tool:?}, mask={mask}: the gesture has no supported source");
output.textures_delta.clear();
app.ui.mask_target = false;
app.run("channel.target", json!({"channel": "composite"})).unwrap();
let mut output = clone_overlay_frame(&ctx, &mut app, &xf);
assert!(output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Mesh(_))), "returning to pixels restores the source overlay");
output.textures_delta.clear();
}
}
}
#[test]
fn clone_overlay_keeps_magnified_pixels_crisp_on_upload_and_refresh() {
let ctx = egui::Context::default();
+1
View File
@@ -77,6 +77,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- For pixel-layer destinations, Clone Stamp and Healing Brush source slots remember the picked document and layer. A paint command uses the picked slot when both `source` and `offset` are omitted or null. Current Layer then reads the picked pixel layer even after switching destination layers. A non-null `source` or `offset` instead selects coordinates in the destination document, ignoring the slot's document and layer; Current Layer reads the destination surface unless `sourceLayer` selects another layer in that document. Null optional coordinates do not select this explicit-coordinate path.
A paint command's `sourceLayer` overrides the sampled layer for Current Layer and cross-document Current & Below sampling; without an override, slot-based sampling uses the picked layer. If the sampled layer has no pixel surface (such as a group or adjustment layer), Current Layer falls back to the destination surface for a same-document source and returns an error for a cross-document source; it does not sample the non-pixel layer itself. Current & Below composites the destination layer and everything below it for a same-document source; for a cross-document source it composites the picked source layer (or `sourceLayer` override) and everything below it. All Layers reads the entire sampled document composite.
Alt-click in one open document, switch tabs, and paint in another to clone across documents. Clone Stamp requires matching document color modes; Healing Brush additionally allows Grayscale on either side. Compatible cross-document colors use the document ICC profiles through the CMS. `cloneSource.set {"source":[x,y],"document":index}` selects an open source document explicitly; `cloneSource.list` reports its current index and `documentId`. A closed source document or deleted sampled layer returns an error until a new source is picked. Empty slots do not reuse an earlier slot's coordinates. Source canvas coverage is retained independently of stored alpha: no-alpha pixels inside the canvas are opaque, including black; pixels outside it do not paint. Wrapped sampling repeats the source canvas. Opaque destination surfaces retain their original native format after blending. Cross-document mask/channel destinations return an unsupported-target error instead of sampling the wrong document.
Both source overlays honor Pattern Preview. Unsupported cross-document mask/alpha-channel gestures have no source overlay. Healing Brush excludes absent source pixels from its solve and paint coverage, independently of alpha reconstructed by the solver.
- Clone Source X/Y are signed document-pixel offsets, using the existing `source - destination` convention. The panel derives the current preview/stroke pairing without anchoring it on hover. `cloneSource.list` exposes `anchor` (persistent Aligned pairing), `lastAnchor` (most recently used successful pairing), and `offset` (source minus that last reference). Unaligned strokes update the readout while restarting at the sample point each time; failed or canceled strokes do not commit a pairing. To edit the offset shown for a preview, use `cloneSource.set {"offset":[dx,dy],"anchor":[destinationX,destinationY]}`; without an explicit anchor an edit uses the last reported reference, then the existing aligned reference or sample point. Source picking clears both anchors; resetTransform retains them. Null optional coordinates are omitted consistently in mapping and source-document selection. Invalid coordinates, slot indexes, and oversized transformed sampling windows return errors without painting.
- Brush Pose's `pose.overrideTiltX` and `pose.overrideTiltY` are independent booleans. For example, `engine.execute {"command":"tools.setBrush","params":{"pose":{"enabled":true,"tiltX":45,"overrideTiltX":true,"overrideTiltY":false}}}` fixes X at 45° while Y follows the stylus. Pose tilts are degrees (±90); the Brush Settings panel displays percentages (±100). Old stored `overrideTilt` values migrate to both axes. In command patches, `overrideTilt` sets both axes unless an explicit axis field in the same patch overrides it. `brush.get` includes both axis flags and the legacy combined readback (`overrideTilt` is true only when both flags are true). Axis-only journals omit that derived combined key so replay retains the other axis. Present flag values must be booleans; null and other types return an error.
- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks, as four floats 0..1 (not 0..255).