From 9538c52bf3b18d883ee65739f8f35ca780ccb3e4 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 11 Oct 2026 18:40:13 +0200 Subject: [PATCH 01/65] Image Adjustments: Desaturate, Equalize and Replace Color record smart filters on a smart object (#3606) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/adjust_cmds.rs | 38 +++++++++++++++++++++++--- crates/engine/src/adjust_cmds/tests.rs | 27 ++++++++++++++++-- crates/engine/src/commands.rs | 23 +++++++--------- crates/engine/src/extra_cmds.rs | 14 ++++++++-- 4 files changed, 80 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs index 42dd44d767b..b1fa7917b46 100644 --- a/crates/engine/src/adjust_cmds.rs +++ b/crates/engine/src/adjust_cmds.rs @@ -306,7 +306,20 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { /// object): the adjustment applied to a copy of `surf`. `None` for kinds or params it can't run. pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Option { let mut out = surf.clone(); - if kind == "shadowsHighlights" { + if kind == "replaceColor" { + let (c, fuzz, h, sat, l) = replace_color_params(p, [0.0, 0.0, 0.0, 1.0]); + process_surface(&mut out, None, &mut |px, _| { + tone::replace_color(px, [c[0], c[1], c[2]], fuzz, h, sat, l); + }); + } else if kind == "desaturate" { + let mode = surf.format().mode; + crate::pixels::adjust_surface(&mut out, &crate::commands::desaturate_adjustment(), None, mode); + } else if kind == "equalize" { + process_surface(&mut out, None, &mut |px, _| { + let cover = vec![1.0; px.len()]; + crate::extra_cmds::equalize_pixels(px, &cover); + }); + } else if kind == "shadowsHighlights" { let sh = shadows_highlights_params(p); process_surface(&mut out, None, &mut |px, r| tone::shadows_highlights(px, r.width() as usize, r.height() as usize, &sh)); } else { @@ -342,10 +355,27 @@ fn shadows_highlights_params(p: &Value) -> ShadowsHighlights { } } -fn replace_color(s: &mut Session, p: &Value) -> Result { - let c = crate::commands::color_param(p, "color", s.tools.foreground); +fn replace_color_params(p: &Value, default_color: [f32; 4]) -> ([f32; 4], f32, f32, f32, f32) { + let c = crate::commands::color_param(p, "color", default_color); let fuzz = num(p, "fuzziness", 40.0).clamp(0.0, 200.0); let (h, sat, l) = (num(p, "hue", 0.0).clamp(-180.0, 180.0), num(p, "saturation", 0.0).clamp(-100.0, 100.0), num(p, "lightness", 0.0).clamp(-100.0, 100.0)); + (c, fuzz, h, sat, l) +} + +fn replace_color(s: &mut Session, p: &Value) -> Result { + // A smart object records the foreground colour it was sampled with, so the filter does not + // change when the foreground does. + let mut q = p.clone(); + if p.get("color").is_none() + && let Value::Object(m) = &mut q + { + let f = s.tools.foreground; + m.insert("color".into(), json!([f[0], f[1], f[2], f[3]])); + } + if adjust_as_smart_filter(s, "replaceColor", "Replace Color", &q)? { + return Ok(Value::Null); + } + let (c, fuzz, h, sat, l) = replace_color_params(p, s.tools.foreground); rgba_edit(s, "Replace Color", p, |px, _| { tone::replace_color(px, [c[0], c[1], c[2]], fuzz, h, sat, l); }) @@ -463,7 +493,7 @@ pub fn specs() -> Vec { "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)"##, - has_pixels, + has_adjustable, replace_color ), spec!( diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/adjust_cmds/tests.rs index 9f8f07db634..4e394537b3f 100644 --- a/crates/engine/src/adjust_cmds/tests.rs +++ b/crates/engine/src/adjust_cmds/tests.rs @@ -456,7 +456,7 @@ fn adjustment_smart_filters_take_a_selection_as_their_mask() { } /// A wrong-typed value errors before anything is recorded (never a panic), and the adjustments -/// that can't re-render from a source (Replace Color, Match Color) stay off a smart object. +/// that can't re-render from a source (Match Color) stays off a smart object. #[test] fn a_bad_adjustment_param_on_a_smart_object_is_an_error() { let mut s = smart_session(); @@ -466,7 +466,6 @@ fn a_bad_adjustment_param_on_a_smart_object_is_an_error() { assert_eq!(smart_filters_of(&s).len(), filters, "nothing recorded"); assert_eq!(s.active().unwrap().history.past_len(), steps, "no history step"); assert_eq!(flatten(&s), flat, "pixels untouched"); - assert!(!s.is_enabled("image.adjustments.replaceColor"), "only adjustments that re-render become smart filters"); assert!(!s.is_enabled("image.adjustments.matchColor"), "only adjustments that re-render become smart filters"); } @@ -503,3 +502,27 @@ fn a_targeted_mask_enables_editing_it_on_any_layer() { assert!(s.execute("image.adjustments.invert", mask).is_err()); assert_eq!(rgba(&s, 23, 3), pixels); } + +/// Desaturate, Equalize and Replace Color on a smart object record a smart filter that renders +/// what the destructive command bakes into the same pixels (they used to be refused). +#[test] +fn desaturate_equalize_and_replace_color_record_smart_filters() { + let replace = json!({"color": "#ff0000", "fuzziness": 120, "hue": 90}); + for (id, params) in [("image.adjustments.desaturate", json!({})), ("image.adjustments.equalize", json!({})), ("image.adjustments.replaceColor", replace)] { + let mut plain = session(8, "rgb"); + let original = flatten(&plain); + plain.execute(id, params.clone()).unwrap(); + let baked = flatten(&plain); + assert!(max_diff(&original, &baked) > 0.02, "{id}: the control changes the pixels"); + + let mut s = smart_session(); + assert!(s.is_enabled(id), "{id} runs on a smart object"); + s.execute(id, params).unwrap(); + let sf = smart_filters_of(&s); + assert_eq!(sf.len(), 1, "{id}"); + assert_eq!(sf[0].command, id); + assert_eq!(max_diff(&flatten(&s), &baked), 0.0, "{id}: the smart filter renders the destructive result"); + s.undo(); + assert!(smart_filters_of(&s).is_empty(), "{id}: undo removes the filter"); + } +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 3d4b73f4d2d..87f89d974f2 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -37,6 +37,11 @@ fn has_layer(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document open")?; d.active_layer.filter(|id| d.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into()) } +/// Image › Adjustments › Desaturate: Hue/Saturation with saturation at -100. +pub(crate) fn desaturate_adjustment() -> Adjustment { + Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() } +} + fn has_pixel_layer(s: &Session) -> std::result::Result<(), String> { let l = crate::active_layer_of(s)?; if matches!(l.content, LayerContent::Raster(_)) { @@ -851,19 +856,11 @@ fn build() -> Vec { cmd!("image.imageRotation.90ccw", "90° Counter Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| { turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Ccw90) }), - cmd!("image.adjustments.desaturate", "Desaturate", ["Image", "Adjustments"], Some("Cmd+Shift+U"), "{}", has_pixel_layer, |s, _| { - destructive_adjust( - s, - "Desaturate", - Adjustment::HueSaturation { - hue: 0.0, - saturation: -100.0, - lightness: 0.0, - colorize: false, - ranges: photocraft_doc::adjust::HueRange::defaults(), - }, - &Value::Null, - ) + cmd!("image.adjustments.desaturate", "Desaturate", ["Image", "Adjustments"], Some("Cmd+Shift+U"), "{}", crate::adjust_cmds::has_adjustable, |s, p| { + if crate::adjust_cmds::adjust_as_smart_filter(s, "desaturate", "Desaturate", p)? { + return Ok(Value::Null); + } + destructive_adjust(s, "Desaturate", desaturate_adjustment(), p) }), // Paint cmd!( diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index f25ea9a2e99..af44b7a4dd1 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -229,7 +229,15 @@ fn stroke(s: &mut Session, p: &Value) -> Result { /// Histogram equalization, like Photoshop's: one CDF over the R, G and B values of /// the selected pixels, applied to every channel. fn equalize(s: &mut Session, p: &Value) -> Result { - map_pixels(s, "Equalize", p, |_, px, cover| { + if crate::adjust_cmds::adjust_as_smart_filter(s, "equalize", "Equalize", p)? { + return Ok(Value::Null); + } + map_pixels(s, "Equalize", p, |_, px, cover| equalize_pixels(px, cover)) +} + +/// [`equalize`] on straight RGBA pixels with a coverage weight each (also run as a smart filter). +pub(crate) fn equalize_pixels(px: &mut [[f32; 4]], cover: &[f32]) { + { let mut hist = [0f64; 256]; for (p, &k) in px.iter().zip(cover) { if k > 0.0 && p[3] > 0.0 { @@ -256,7 +264,7 @@ fn equalize(s: &mut Session, p: &Value) -> Result { *v = map(*v); } } - }) + } } /// Filter › Blur › Average: the selection (or layer) filled with its mean colour. @@ -787,7 +795,7 @@ pub fn specs() -> Vec { })?; Ok(json!({"selected": true})) }), - spec!("image.adjustments.equalize", "Equalize", &["Image", "Adjustments"], None, "{}", has_pixels, equalize), + spec!("image.adjustments.equalize", "Equalize", &["Image", "Adjustments"], None, "{}", crate::adjust_cmds::has_adjustable, equalize), spec!("image.revealAll", "Reveal All", &["Image"], None, "{}", has_doc, |s, _| { let d = s.active().ok_or(EngineError::NoDocument)?; let all = reveal_all_bounds(&d.doc); From a74b4c1325f17335c5a9774b2bb1247528517cb6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 13 Oct 2026 19:50:44 +0200 Subject: [PATCH 02/65] Fix duplicated test attribute after merge --- crates/engine/src/adjust_cmds/tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/adjust_cmds/tests.rs index f7489b683aa..d704d35e289 100644 --- a/crates/engine/src/adjust_cmds/tests.rs +++ b/crates/engine/src/adjust_cmds/tests.rs @@ -527,7 +527,6 @@ fn desaturate_equalize_and_replace_color_record_smart_filters() { } } -#[test] #[test] fn replace_color_localized_clusters_only_change_the_colour_near_the_sample() { // The same cream on the left (x < 8) and the right (x ≥ 40), grey between. From 6aad21817b20f6a16ddd491ccd21843c090af68a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 21 Oct 2026 20:27:50 +0200 Subject: [PATCH 03/65] Honor selection in Equalize smart filters and validate Replace Color --- crates/engine/src/adjust_cmds.rs | 22 +++++------ crates/engine/src/adjust_cmds/tests.rs | 43 +++++++++++++++++++++ crates/engine/src/filters.rs | 2 +- crates/engine/src/smart_cmds.rs | 16 +++++--- crates/engine/src/smart_cmds/stack_cache.rs | 15 ++++++- 5 files changed, 79 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs index e8c4d2eb400..d9c07346d0b 100644 --- a/crates/engine/src/adjust_cmds.rs +++ b/crates/engine/src/adjust_cmds.rs @@ -297,7 +297,7 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { /// Image › Adjustments run as a smart filter (`image.adjustments.` recorded on a smart /// object): the adjustment applied to a copy of `surf`. `None` for kinds or params it can't run. -pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Option { +pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface, histogram_mask: Option<&photocraft_doc::LayerMask>) -> Option { // A Color Lookup filter re-reads its LUT `file`, a path stored in the document: followed only // as `doc_path` allows, else the filter can't run (like a missing file). let resolved; @@ -320,8 +320,10 @@ pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Option< let mode = surf.format().mode; crate::pixels::adjust_surface(&mut out, &crate::commands::desaturate_adjustment(), None, mode); } else if kind == "equalize" { - process_surface(&mut out, None, &mut |px, _| { - let cover = vec![1.0; px.len()]; + process_surface(&mut out, None, &mut |px, area| { + let width = area.width() as usize; + let cover = + (0..px.len()).map(|i| histogram_mask.map_or(1.0, |m| m.value(area.x0 + (i % width) as i32, area.y0 + (i / width) as i32))).collect::>(); crate::extra_cmds::equalize_pixels(px, &cover); }); } else if kind == "shadowsHighlights" { @@ -374,21 +376,17 @@ fn replace_color(s: &mut Session, p: &Value) -> Result { if localized_requested && on_smart { return Err(bad(CMD, "Localized Color Clusters are not available as a smart filter yet")); } + let (c, fuzz, h, sat, l) = replace_color_params(CMD, p, s.tools.foreground)?; if !localized_requested { - // A smart object records the foreground colour it was sampled with, so the filter does not - // change when the foreground does. - let mut q = p.clone(); - if p.get("color").is_none() - && let Value::Object(m) = &mut q - { - let f = s.tools.foreground; - m.insert("color".into(), json!([f[0], f[1], f[2], f[3]])); + // Resolve and validate before recording, including the null foreground fallback. + let mut q = Value::Object(p.as_object().cloned().unwrap_or_default()); + if let Value::Object(m) = &mut q { + m.insert("color".into(), json!(c)); } if adjust_as_smart_filter(s, "replaceColor", "Replace Color", &q)? { return Ok(Value::Null); } } - let (c, fuzz, h, sat, l) = replace_color_params(CMD, p, s.tools.foreground)?; // Localized Color Clusters, as in Select › Color Range: the colour only matches within Range // (a percentage of the canvas's longer side) of where it was picked. let points = sample_points(p).map_err(|m| bad(CMD, m))?; diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/adjust_cmds/tests.rs index ba98f3b69cb..3db39915c32 100644 --- a/crates/engine/src/adjust_cmds/tests.rs +++ b/crates/engine/src/adjust_cmds/tests.rs @@ -780,3 +780,46 @@ fn invert_turns_the_black_of_quick_mask_and_alpha_channels_white() { } } } + +#[test] +fn equalize_smart_filter_uses_selected_pixels_for_its_histogram() { + for depth in DEPTHS { + let mut plain = session(depth, "rgb"); + let mut smart = session(depth, "rgb"); + smart.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + for s in [&mut plain, &mut smart] { + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 12, "height": 32})).unwrap(); + s.execute("image.adjustments.equalize", json!({})).unwrap(); + } + assert!(max_diff(&flatten(&plain), &flatten(&smart)) < 2.0 / 255.0, "depth={depth}"); + // Disabling the filter mask changes the histogram too: no stale cached stage. + let mut full = session(depth, "rgb"); + full.execute("image.adjustments.equalize", json!({})).unwrap(); + smart.execute("select.deselect", json!({})).unwrap(); + smart.execute("layer.smartFilter.disableFilterMask", json!({"enabled": false})).unwrap(); + assert!(max_diff(&flatten(&full), &flatten(&smart)) < 2.0 / 255.0, "disabled mask, depth={depth}"); + } +} + +#[test] +fn replace_color_null_records_foreground_and_bad_color_does_not_edit() { + for depth in DEPTHS { + let mut plain = session(depth, "rgb"); + let mut smart = session(depth, "rgb"); + smart.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let params = json!({"color": null, "fuzziness": 200, "hue": 90}); + for s in [&mut plain, &mut smart] { + s.tools.foreground = [0.27, 0.6, 0.52, 1.0]; + s.execute("image.adjustments.replaceColor", params.clone()).unwrap(); + } + assert_eq!(max_diff(&flatten(&plain), &flatten(&smart)), 0.0); + assert_eq!(smart_filters_of(&smart)[0].params["color"], json!([0.27_f32, 0.6_f32, 0.52_f32, 1.0_f32])); + let before = smart.active().unwrap().doc.clone(); + let steps = smart.active().unwrap().history.past_len(); + for color in [json!(3), json!("wrong"), json!([1, 2])] { + assert!(smart.execute("image.adjustments.replaceColor", json!({"color": color})).is_err()); + assert!(std::sync::Arc::ptr_eq(&smart.active().unwrap().doc, &before)); + assert_eq!(smart.active().unwrap().history.past_len(), steps); + } + } +} diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index c3059dca2ff..c8a581c9ce4 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -198,7 +198,7 @@ pub fn apply_filter_to_surface( } // Image › Adjustments recorded as smart filters (Levels, Curves, Shadows/Highlights… from PSD). if let Some(kind) = id.strip_prefix("image.adjustments.") { - return Ok(crate::adjust_cmds::adjust_as_filter(kind, params, surf)); + return Ok(crate::adjust_cmds::adjust_as_filter(kind, params, surf, None)); } // WebAssembly plug-in smart filters (plugin_cmds). if id == crate::plugin_cmds::RUN { diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs index 3ca10083b9c..efe278c0ac4 100644 --- a/crates/engine/src/smart_cmds.rs +++ b/crates/engine/src/smart_cmds.rs @@ -314,7 +314,7 @@ pub fn apply_smart_filters(placed: &Surface, sm: &SmartObject, canvas: Rect) -> // Edge pixels repeat at the canvas ∪ placed-content edge, as for layer filters. let extent = canvas.union(&placed.content_bounds()); for f in sm.smart_filters.iter().filter(|f| f.visible) { - cur = apply_smart_filter(f, &cur, canvas, extent)?; + cur = apply_smart_filter(f, &cur, canvas, extent, sm.filter_mask.as_ref())?; } Ok(match sm.filter_mask.as_ref().filter(|m| m.enabled) { Some(m) => photocraft_compose::filter_mask::mix(placed, &cur, m), @@ -325,8 +325,14 @@ pub fn apply_smart_filters(placed: &Surface, sm: &SmartObject, canvas: Rect) -> /// One visible smart filter over `cur`, blended with its blend mode and opacity. `Err` when the /// requesting session's authority denies the filter's params: callers surface the error instead of /// rendering (and caching) unfiltered pixels. -fn apply_smart_filter(f: &SmartFilter, cur: &Surface, canvas: Rect, extent: Rect) -> Result { - let out = match crate::filters::apply_filter_to_surface(&f.command, &f.params, cur, canvas, None, extent)? { +fn apply_smart_filter(f: &SmartFilter, cur: &Surface, canvas: Rect, extent: Rect, mask: Option<&photocraft_doc::LayerMask>) -> Result { + crate::jobs::authorize_render_command(&f.command, &f.params)?; + let rendered = if f.command == "image.adjustments.equalize" { + crate::adjust_cmds::adjust_as_filter("equalize", &f.params, cur, mask) + } else { + crate::filters::apply_filter_to_surface(&f.command, &f.params, cur, canvas, None, extent)? + }; + let out = match rendered { // Unknown ids (e.g. Photoshop filters we don't implement) leave the pixels alone. Some(out) => out, None => cur.clone(), @@ -414,7 +420,7 @@ fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Result = filters .iter() .scan(placed_key, |key, f| { - *key = stack_cache::filter_key(key, f); + *key = stack_cache::filter_key(key, f, sm.filter_mask.as_ref()); Some(*key) }) .collect(); @@ -427,7 +433,7 @@ fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Result StageKey { +pub(super) fn filter_key(below: &StageKey, f: &SmartFilter, mask: Option<&photocraft_doc::LayerMask>) -> StageKey { let mut h = blake3::Hasher::new(); h.update(below); h.update(format!("{}\0{}\0{:?}\0", f.command, f.params, f.blend).as_bytes()); h.update(&f.opacity.to_bits().to_le_bytes()); + // Equalize's histogram depends on coverage; downstream stages inherit this key. + if f.command == "image.adjustments.equalize" + && let Some(mask) = mask.filter(|m| m.enabled) + { + h.update(format!("{:?}|{}", mask.surface.format(), mask.density).as_bytes()); + h.update(mask.surface.default_bytes()); + let mut tiles: Vec<_> = mask.surface.tiles().collect(); + tiles.sort_by_key(|(coord, _)| **coord); + for (coord, tile) in tiles { + h.update(format!("{coord:?}").as_bytes()); + h.update(tile.bytes()); + } + } *h.finalize().as_bytes() } From b1f54773a678faa76ae8f3e0072a7bd683f90ebd Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 21 Oct 2026 20:32:48 +0200 Subject: [PATCH 04/65] Reject malformed Replace Color colours before recording a filter --- crates/engine/src/adjust_cmds.rs | 6 ++++++ crates/engine/src/adjust_cmds/tests.rs | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs index d9c07346d0b..59d25db417c 100644 --- a/crates/engine/src/adjust_cmds.rs +++ b/crates/engine/src/adjust_cmds.rs @@ -363,6 +363,12 @@ fn shadows_highlights_params(p: &Value) -> ShadowsHighlights { } fn replace_color_params(cmd: &str, p: &Value, default_color: [f32; 4]) -> Result<([f32; 4], f32, f32, f32, f32)> { + match given(p, "color") { + None => {} + Some(Value::String(s)) if crate::commands::parse_hex(s).is_some() => {} + Some(Value::Array(a)) if (3..=4).contains(&a.len()) && a.iter().all(Value::is_number) => {} + Some(_) => return Err(bad(cmd, "`color` must be a hex colour or an array of 3 or 4 finite numbers")), + } let c = crate::commands::color_param(cmd, p, "color", default_color)?; let fuzz = num(p, "fuzziness", 40.0).clamp(0.0, 200.0); let (h, sat, l) = (num(p, "hue", 0.0).clamp(-180.0, 180.0), num(p, "saturation", 0.0).clamp(-100.0, 100.0), num(p, "lightness", 0.0).clamp(-100.0, 100.0)); diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/adjust_cmds/tests.rs index 3db39915c32..9780f88d3e1 100644 --- a/crates/engine/src/adjust_cmds/tests.rs +++ b/crates/engine/src/adjust_cmds/tests.rs @@ -816,7 +816,7 @@ fn replace_color_null_records_foreground_and_bad_color_does_not_edit() { assert_eq!(smart_filters_of(&smart)[0].params["color"], json!([0.27_f32, 0.6_f32, 0.52_f32, 1.0_f32])); let before = smart.active().unwrap().doc.clone(); let steps = smart.active().unwrap().history.past_len(); - for color in [json!(3), json!("wrong"), json!([1, 2])] { + for color in [json!(3), json!("wrong"), json!([1, 2]), json!([1e300, 0, 0]), json!(["red", 0, 0])] { assert!(smart.execute("image.adjustments.replaceColor", json!({"color": color})).is_err()); assert!(std::sync::Arc::ptr_eq(&smart.active().unwrap().doc, &before)); assert_eq!(smart.active().unwrap().history.past_len(), steps); From 8a5a8c8679c34fd965353dc69b98379460b91931 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 25 Oct 2026 11:52:10 +0100 Subject: [PATCH 05/65] Affinity import: budget type layers and shape caches, honour Cancel The Affinity import drew every type layer's raster (up to 64 MP each) and every shape cache without a document-wide limit, so a file with 2000 type layers needed tens of GB, and 50 000 tiny shapes 7 GB (each cache keeps whole 256x256 tiles, which the old charge for the shape's own pixel area ignored). - Type layers are charged to the import's remaining pixel budget (the same 1 GiB the images and shapes use). A layer that does not fit keeps an empty cache until it is edited, as one over 64 MP already did, and the import warns how many were left out. - A shape cache is charged for the tiles it covers, not for its pixel area. - affinity::import takes the Interrupt and checks it per layer, so Cancel stops a long import. Fixes #9411 Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/affinity.rs | 119 ++++++++++++++++++++++++++++++++--- crates/io/src/lib.rs | 2 +- crates/io/src/text_import.rs | 67 +++++++++++++++++--- 3 files changed, 171 insertions(+), 17 deletions(-) diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index f794e1be401..d9d93499777 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -37,17 +37,23 @@ pub fn has_extension(name: &str) -> bool { name.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).is_some_and(|(_, ext)| EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e))) } -pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { +pub(crate) fn import(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -> Result { match photocraft_affinity::read(bytes, photocraft_affinity::Limits::default()) { Ok(d) => { let mut b = Builder::new(name, &d)?; + b.ctl = *ctl; b.document(&d)?; + ctl.check().map_err(|_| IoError::Cancelled)?; let mut warnings: Vec = d.warnings.iter().map(|w| format!("Affinity: not imported or approximated: {w}.")).collect(); warnings.extend(b.warnings.iter().map(|w| format!("Affinity: {w}."))); // Type layers draw from their model, within the import's raster bound: the sizes and - // frames come from an untrusted file. + // frames come from an untrusted file. They share what the images and shapes left of + // the pixel budget, so a file with thousands of type layers can't allocate without end. let mut document = b.doc; - crate::text_import::prepare(&mut document, None); + let unrendered = crate::text_import::prepare_within(&mut document, None, &mut b.pixel_budget, ctl).map_err(|_| IoError::Cancelled)?; + if unrendered > 0 { + warnings.push(format!("Affinity: {unrendered} type layers beyond the import's memory limit were left without pixels until they are edited.")); + } // Save never writes back over the Affinity file. Ok(ImportResult { document, warnings, source_read_only: true, preview_only: false }) } @@ -80,7 +86,7 @@ fn preview(name: &str, bytes: &[u8], native: &photocraft_affinity::Error) -> Res Ok(r) } -struct Builder { +struct Builder<'a> { doc: Document, warnings: Vec, /// Document pixels (in the canvas) per Affinity document pixel: always 1; spreads are offset. @@ -88,6 +94,8 @@ struct Builder { canvas: Rect, /// Decoded pixel bytes left for embedded images and their resampled surfaces. pixel_budget: u64, + /// Checked per layer: a cancelled import stops building. + ctl: photocraft_raster::Interrupt<'a>, } /// Deduct `cost` bytes from a decoded-pixel budget; `false` (leaving the budget alone) when it @@ -110,7 +118,7 @@ fn point(p: af::Point) -> Point { Point::new(p.x, p.y) } -impl Builder { +impl Builder<'_> { fn new(name: &str, d: &af::Document) -> Result { // Spreads (Publisher pages) side by side, 64 px apart. let mut w: f64 = 0.0; @@ -126,7 +134,7 @@ impl Builder { let mut doc = Document::new(name, size, ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = d.dpi as f32; let canvas = Rect::new(0, 0, size.width as i32, size.height as i32); - Ok(Self { doc, warnings: Vec::new(), format: PixelFormat::RGBA8, canvas, pixel_budget: MAX_PIXEL_BYTES }) + Ok(Self { doc, warnings: Vec::new(), format: PixelFormat::RGBA8, canvas, pixel_budget: MAX_PIXEL_BYTES, ctl: photocraft_raster::Interrupt::NONE }) } fn warn(&mut self, w: &str) { @@ -249,6 +257,9 @@ impl Builder { /// One Affinity node and its subtree; `to_doc` maps Affinity document pixels to the canvas. fn layer(&mut self, n: &af::Node, to_doc: Affine, top: bool) -> Option { + if self.ctl.cancelled() { + return None; + } let children: Vec = n.children.iter().filter_map(|c| self.layer(c, to_doc, false)).collect(); let mut l = match &n.kind { Kind::Layer | Kind::Group => self.group(n, children), @@ -448,7 +459,8 @@ impl Builder { // geometry across a 300000 px canvas would otherwise be rasterized for every shape. let reach = sh.stroke.as_ref().map_or(0, |s| (s.width.ceil() as i32).saturating_add(1)); let area = frame.inflate(reach).intersect(&self.canvas); - let cost = u64::from(area.width()).saturating_mul(u64::from(area.height())).saturating_mul(self.format.bytes_per_pixel() as u64); + // Whole tiles: even a 2x2 px shape keeps one, which 50 000 small shapes add up to gigabytes. + let cost = crate::text_import::cache_bytes(area, self.format.bytes_per_pixel()); if charge(&mut self.pixel_budget, cost) { sh.cache = Some(photocraft_vector::render_shape(&sh, self.format, self.canvas)); } else { @@ -726,4 +738,97 @@ mod tests { ok.document(&d).unwrap(); assert_eq!(ok.doc.layers.len(), 1, "within the budget the image imports as a smart object"); } + + fn node(kind: Kind) -> af::Node { + af::Node { + class: photocraft_affinity::synth::tag(b"ImgN"), + name: "n".into(), + visible: true, + locked: false, + opacity: 1.0, + blend: Blend::Normal, + kind, + mask: None, + pixel_mask: None, + children: Vec::new(), + } + } + + fn page(nodes: Vec) -> af::Document { + af::Document { + dpi: 72.0, + spreads: vec![af::Spread { bounds: af::Rect { x0: 0.0, y0: 0.0, x1: 64.0, y1: 64.0 }, pages: Vec::new(), transparent: true, nodes }], + saved_by: None, + warnings: Vec::new(), + } + } + + /// A 2×2 px solid rectangle. + fn tiny_shape(i: usize) -> af::Node { + let p = |x: f64, y: f64| af::Point { x, y }; + let (x, y) = ((i % 30) as f64, (i / 30 % 30) as f64); + let corners = [p(x, y), p(x + 2.0, y), p(x + 2.0, y + 2.0), p(x, y + 2.0)]; + let sub = af::SubPath { start: corners[0], segments: (1..=4).map(|k| [corners[k % 4]; 3]).collect(), closed: true }; + node(Kind::Shape { + path: af::Path { subpaths: vec![sub] }, + fills: vec![ap::Paint::Solid(ap::Color::Rgb { r: 1.0, g: 0.0, b: 0.0, a: 1.0 })], + strokes: Vec::new(), + even_odd: false, + }) + } + + #[test] + fn small_shapes_are_charged_a_whole_tile_each() { + // Surfaces keep whole tiles, so 2×2 px shapes cost a tile each: 50 000 of them were + // 7 GB. A budget of three tiles keeps the pixel cache of the first three only. + let d = page((0..10).map(tiny_shape).collect()); + let mut b = Builder::new("shapes", &d).unwrap(); + b.pixel_budget = 3 * 256 * 256 * 4; + b.document(&d).unwrap(); + let cached = |l: &Layer| matches!(&l.content, LayerContent::Shape(s) if s.cache.is_some()); + assert_eq!(b.doc.layers.iter().filter(|l| cached(l)).count(), 3); + assert_eq!(b.doc.layers.iter().filter(|l| matches!(l.content, LayerContent::Shape(_))).count(), 10, "every shape still imports"); + assert!(b.warnings.iter().any(|w| w.contains("pixel cache")), "{:?}", b.warnings); + assert_eq!(b.pixel_budget, 0); + } + + #[test] + fn a_cancelled_import_stops_building_layers() { + let d = page((0..10).map(tiny_shape).collect()); + let mut b = Builder::new("cancel", &d).unwrap(); + let cancel = || true; + b.ctl = photocraft_raster::Interrupt::cancel_only(&cancel); + b.document(&d).unwrap(); + assert!(b.doc.layers.is_empty(), "no layer is built once cancelled"); + let mut doc = Document::new("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let mut budget = u64::MAX; + doc.layers.push(Layer::new("t", LayerContent::Text(TextLayer { text: "x".into(), ..TextLayer::default() }))); + assert!(crate::text_import::prepare_within(&mut doc, None, &mut budget, &b.ctl).is_err()); + } + + #[test] + fn type_layers_share_the_pixel_budget_and_keep_going_without_pixels() { + // Each layer's ink is charged to the budget; one that doesn't fit keeps an empty cache and + // is counted, instead of every layer of a 2000-layer file drawing its own raster. + let mut doc = Document::new("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); + for i in 0..20 { + let text = "Budget".to_string(); + let mut t = TextLayer { text, font_family: "sans-serif".into(), size_pt: 24.0, ..TextLayer::default() }; + t.runs = vec![TextRun { len: t.text.len(), style: CharStyle { size_pt: 24.0, ..CharStyle::default() } }]; + doc.layers.push(Layer::new(format!("t{i}"), LayerContent::Text(t))); + } + // What one layer costs, then room for two and a half. + let mut probe = u64::MAX; + let mut one = doc.clone(); + one.layers.truncate(1); + crate::text_import::prepare_within(&mut one, None, &mut probe, &photocraft_raster::Interrupt::NONE).unwrap(); + let cost = u64::MAX - probe; + assert!(cost > 0); + let mut budget = cost * 5 / 2; + let skipped = crate::text_import::prepare_within(&mut doc, None, &mut budget, &photocraft_raster::Interrupt::NONE).unwrap(); + let drawn = doc.layers.iter().filter(|l| matches!(&l.content, LayerContent::Text(t) if t.cache.as_ref().is_some_and(|c| c.tile_count() > 0))).count(); + assert_eq!((drawn, skipped), (2, 18)); + assert!(drawn + skipped == 20, "drawn {drawn} skipped {skipped}"); + assert!(doc.layers.iter().all(|l| matches!(&l.content, LayerContent::Text(t) if t.cache.is_some())), "every layer has a cache, empty or not"); + } } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 44beb59d47a..976b0adb225 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -407,7 +407,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o return import_psd(name, bytes, ctl, damaged); } if affinity::is_affinity(bytes) || affinity::has_extension(name) { - return affinity::import(name, bytes); + return affinity::import(name, bytes, ctl); } if ora::is_ora(bytes) || has_extension(name, "ora") { return ora::import(name, bytes, ctl); diff --git a/crates/io/src/text_import.rs b/crates/io/src/text_import.rs index 0522f39e908..cb5c0a3232c 100644 --- a/crates/io/src/text_import.rs +++ b/crates/io/src/text_import.rs @@ -8,17 +8,45 @@ use photocraft_doc::{Document, Layer, LayerContent, TextLayer}; /// it is edited. pub(crate) const MAX_RENDER_PIXELS: u64 = 64 * 1024 * 1024; -/// Renders `t` from its model unless its ink would exceed [`MAX_RENDER_PIXELS`]. -fn render_bounded(eng: &mut photocraft_text::TextEngine, t: &mut TextLayer, dpi: f32, format: photocraft_color::PixelFormat) { +/// Bytes a pixel cache covering `area` holds: surfaces store whole tiles, so a 2x2 px shape +/// still keeps a tile. +pub(crate) fn cache_bytes(area: photocraft_geom::Rect, bytes_per_pixel: usize) -> u64 { + if area.is_empty() { + return 0; + } + let tile = i64::from(photocraft_geom::TILE_SIZE); + let tiles = |a: i32, b: i32| (i64::from(b) - 1).div_euclid(tile) - i64::from(a).div_euclid(tile) + 1; + let n = tiles(area.x0, area.x1) as u64 * tiles(area.y0, area.y1) as u64; + n.saturating_mul((tile * tile) as u64).saturating_mul(bytes_per_pixel as u64) +} + +/// Renders `t` from its model unless its ink would exceed [`MAX_RENDER_PIXELS`] or the +/// document-wide `budget` (bytes of cache still allowed). Returns `false` when the layer went +/// without pixels because of the budget. +fn render_bounded(eng: &mut photocraft_text::TextEngine, t: &mut TextLayer, dpi: f32, format: photocraft_color::PixelFormat, budget: &mut u64) -> bool { + let empty = || photocraft_raster::Surface::new(photocraft_color::PixelFormat { alpha: true, ..format }); + let tile_bytes = cache_bytes(photocraft_geom::Rect::new(0, 0, 1, 1), photocraft_color::PixelFormat { alpha: true, ..format }.bytes_per_pixel()); + if *budget < tile_bytes { + // Nothing with ink fits any more: don't lay the text out just to find that out. + t.cache = Some(empty()); + return false; + } let layout = eng.layout(t, dpi); let warp = photocraft_text::render::layout_deform(&layout, t); let ink = photocraft_text::render::ink_rect_warped(&layout, &t.transform, warp.as_ref()); if u64::from(ink.width()).saturating_mul(u64::from(ink.height())) > MAX_RENDER_PIXELS { - t.cache = Some(photocraft_raster::Surface::new(photocraft_color::PixelFormat { alpha: true, ..format })); - return; + t.cache = Some(empty()); + return true; } + let cost = cache_bytes(ink, photocraft_color::PixelFormat { alpha: true, ..format }.bytes_per_pixel()); + let Some(rest) = budget.checked_sub(cost) else { + t.cache = Some(empty()); + return false; + }; + *budget = rest; let r = photocraft_text::render::rasterize_warped(&layout, &t.transform, format, t.antialias, warp.as_ref()); t.cache = Some(r.surface); + true } /// Prepares the type layers of a document that was just imported: @@ -29,14 +57,32 @@ fn render_bounded(eng: &mut photocraft_text::TextEngine, t: &mut TextLayer, dpi: /// let Photoshop re-render on open) is rendered from its model, instead of staying empty /// until it is edited. pub(crate) fn prepare(doc: &mut Document, txt2: Option<&photocraft_text::engine_data::Value>) { + let mut unlimited = u64::MAX; + let _ = prepare_within(doc, txt2, &mut unlimited, &photocraft_raster::Interrupt::NONE); +} + +/// [`prepare`] with the pixels it may draw limited to `budget` bytes for the whole document +/// (type layers past it keep empty pixels, as past [`MAX_RENDER_PIXELS`]) and stopping early +/// when `ctl` is cancelled. Returns how many layers the budget left without pixels. +pub(crate) fn prepare_within( + doc: &mut Document, + txt2: Option<&photocraft_text::engine_data::Value>, + budget: &mut u64, + ctl: &photocraft_raster::Interrupt, +) -> Result { + #[allow(clippy::too_many_arguments)] fn visit( layers: &mut [Layer], eng: &mut photocraft_text::TextEngine, dpi: f32, format: photocraft_color::PixelFormat, txt2: Option<&photocraft_text::engine_data::Value>, - ) { + budget: &mut u64, + ctl: &photocraft_raster::Interrupt, + skipped: &mut usize, + ) -> Result<(), photocraft_raster::Cancelled> { for l in layers { + ctl.check()?; match &mut l.content { LayerContent::Text(t) => { let mut changed = false; @@ -63,17 +109,20 @@ pub(crate) fn prepare(doc: &mut Document, txt2: Option<&photocraft_text::engine_ t.sync_summary(); } photocraft_text::psd::refine_legacy_point_origin(t, dpi, eng, txt2); - if t.cache.is_none() { - render_bounded(eng, t, dpi, format); + if t.cache.is_none() && !render_bounded(eng, t, dpi, format, budget) { + *skipped += 1; } } - LayerContent::Group(g) => visit(&mut g.children, eng, dpi, format, txt2), + LayerContent::Group(g) => visit(&mut g.children, eng, dpi, format, txt2, budget, ctl, skipped)?, _ => {} } } + Ok(()) } let dpi = doc.resolution_dpi; let format = doc.pixel_format(); let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()); - visit(&mut doc.layers, &mut eng, dpi, format, txt2); + let mut skipped = 0; + visit(&mut doc.layers, &mut eng, dpi, format, txt2, budget, ctl, &mut skipped)?; + Ok(skipped) } From 9bd432016a04ebb2e10d721aa9ad7b540890ca76 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 25 Oct 2026 12:15:05 +0100 Subject: [PATCH 06/65] Affinity import: separate budget for optional shape and type caches Shape and type-layer pixel caches are redrawn on the first edit, while raster layers and embedded images are lost for good when they do not fit. Sharing the 1 GiB pool let thousands of cheap caches early in a file use it up and drop images later. The caches now draw on their own 512 MiB pool; the 1 GiB pool is for images only. Past the cache pool a shape or type layer imports without pixels and one warning per kind gives the count. Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/affinity.rs | 57 ++++++++++++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 10 deletions(-) diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index d9d93499777..49d679388ef 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -32,6 +32,11 @@ const MAX_SIDE: f64 = 300_000.0; /// container of embedded images could still decode (and keep) a surface each until the process /// dies. ORA and KRA budget their decoded pixels the same way. const MAX_PIXEL_BYTES: u64 = 1 << 30; +/// Bytes the import's optional pixel caches (shapes, type layers) may hold together. They are +/// drawn again on the first edit, so running out costs nothing but speed; raster layers and +/// embedded images are lost for good when they don't fit. A separate pool keeps thousands of +/// cheap caches early in a file from using up [`MAX_PIXEL_BYTES`] and dropping images later. +const MAX_CACHE_BYTES: u64 = 512 << 20; pub fn has_extension(name: &str) -> bool { name.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).is_some_and(|(_, ext)| EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e))) @@ -47,13 +52,16 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrup let mut warnings: Vec = d.warnings.iter().map(|w| format!("Affinity: not imported or approximated: {w}.")).collect(); warnings.extend(b.warnings.iter().map(|w| format!("Affinity: {w}."))); // Type layers draw from their model, within the import's raster bound: the sizes and - // frames come from an untrusted file. They share what the images and shapes left of - // the pixel budget, so a file with thousands of type layers can't allocate without end. + // frames come from an untrusted file. They share the optional-cache budget with the + // shapes, so a file with thousands of type layers can't allocate without end. let mut document = b.doc; - let unrendered = crate::text_import::prepare_within(&mut document, None, &mut b.pixel_budget, ctl).map_err(|_| IoError::Cancelled)?; + let unrendered = crate::text_import::prepare_within(&mut document, None, &mut b.cache_budget, ctl).map_err(|_| IoError::Cancelled)?; if unrendered > 0 { warnings.push(format!("Affinity: {unrendered} type layers beyond the import's memory limit were left without pixels until they are edited.")); } + if b.uncached_shapes > 0 { + warnings.push(format!("Affinity: {} shapes beyond the import's memory limit were left without a pixel cache.", b.uncached_shapes)); + } // Save never writes back over the Affinity file. Ok(ImportResult { document, warnings, source_read_only: true, preview_only: false }) } @@ -94,6 +102,10 @@ struct Builder<'a> { canvas: Rect, /// Decoded pixel bytes left for embedded images and their resampled surfaces. pixel_budget: u64, + /// Bytes left for the optional shape and type caches ([`MAX_CACHE_BYTES`]). + cache_budget: u64, + /// Shapes that went without a cache because `cache_budget` ran out. + uncached_shapes: usize, /// Checked per layer: a cancelled import stops building. ctl: photocraft_raster::Interrupt<'a>, } @@ -134,7 +146,16 @@ impl Builder<'_> { let mut doc = Document::new(name, size, ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = d.dpi as f32; let canvas = Rect::new(0, 0, size.width as i32, size.height as i32); - Ok(Self { doc, warnings: Vec::new(), format: PixelFormat::RGBA8, canvas, pixel_budget: MAX_PIXEL_BYTES, ctl: photocraft_raster::Interrupt::NONE }) + Ok(Self { + doc, + warnings: Vec::new(), + format: PixelFormat::RGBA8, + canvas, + pixel_budget: MAX_PIXEL_BYTES, + cache_budget: MAX_CACHE_BYTES, + uncached_shapes: 0, + ctl: photocraft_raster::Interrupt::NONE, + }) } fn warn(&mut self, w: &str) { @@ -461,10 +482,10 @@ impl Builder<'_> { let area = frame.inflate(reach).intersect(&self.canvas); // Whole tiles: even a 2x2 px shape keeps one, which 50 000 small shapes add up to gigabytes. let cost = crate::text_import::cache_bytes(area, self.format.bytes_per_pixel()); - if charge(&mut self.pixel_budget, cost) { + if charge(&mut self.cache_budget, cost) { sh.cache = Some(photocraft_vector::render_shape(&sh, self.format, self.canvas)); } else { - self.warn("shapes covering more pixels than the import's memory allows were left without a pixel cache"); + self.uncached_shapes += 1; } sh } @@ -783,13 +804,14 @@ mod tests { // 7 GB. A budget of three tiles keeps the pixel cache of the first three only. let d = page((0..10).map(tiny_shape).collect()); let mut b = Builder::new("shapes", &d).unwrap(); - b.pixel_budget = 3 * 256 * 256 * 4; + b.cache_budget = 3 * 256 * 256 * 4; b.document(&d).unwrap(); let cached = |l: &Layer| matches!(&l.content, LayerContent::Shape(s) if s.cache.is_some()); assert_eq!(b.doc.layers.iter().filter(|l| cached(l)).count(), 3); assert_eq!(b.doc.layers.iter().filter(|l| matches!(l.content, LayerContent::Shape(_))).count(), 10, "every shape still imports"); - assert!(b.warnings.iter().any(|w| w.contains("pixel cache")), "{:?}", b.warnings); - assert_eq!(b.pixel_budget, 0); + assert_eq!(b.uncached_shapes, 7); + assert_eq!(b.cache_budget, 0); + assert_eq!(b.pixel_budget, MAX_PIXEL_BYTES, "caches don't draw on the pool images need"); } #[test] @@ -807,7 +829,7 @@ mod tests { } #[test] - fn type_layers_share_the_pixel_budget_and_keep_going_without_pixels() { + fn type_layers_share_the_cache_budget_and_keep_going_without_pixels() { // Each layer's ink is charged to the budget; one that doesn't fit keeps an empty cache and // is counted, instead of every layer of a 2000-layer file drawing its own raster. let mut doc = Document::new("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); @@ -831,4 +853,19 @@ mod tests { assert!(drawn + skipped == 20, "drawn {drawn} skipped {skipped}"); assert!(doc.layers.iter().all(|l| matches!(&l.content, LayerContent::Text(t) if t.cache.is_some())), "every layer has a cache, empty or not"); } + + #[test] + fn shape_caches_leave_room_for_images() { + // 64 shapes overrun the cache pool; the image after them still imports. + let mut nodes: Vec = (0..64).map(tiny_shape).collect(); + nodes.extend(affinity_document(vec![(64, 64, Pixels::Rgba8(vec![0; 64 * 64 * 4]))]).spreads.remove(0).nodes); + let d = page(nodes); + let mut b = Builder::new("mixed", &d).unwrap(); + b.cache_budget = 4 * 256 * 256 * 4; + b.pixel_budget = 64 * 64 * 4; + b.document(&d).unwrap(); + assert_eq!(b.uncached_shapes, 60); + assert!(b.doc.layers.iter().any(|l| matches!(l.content, LayerContent::Smart(_) | LayerContent::Raster(_))), "the image must import"); + assert!(!b.warnings.iter().any(|w| w.contains("pixel memory")), "{:?}", b.warnings); + } } From 71b646deb267fe5521bb93e16fa9081ca37657ed Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 25 Oct 2026 14:39:37 +0100 Subject: [PATCH 07/65] Camera Raw open: decode the raw once, not three times A Camera Raw open decoded the file in the open, again on the UI thread when the dialog appeared (for the preview's tone curve), and again for Open's re-develop, fitting the look each time. The open now keeps its sensor data and fitted look (ImportOptions::keep_raw, set for interactive opens that show the dialog). The dialog takes them over, reads the tone curve from them and hands them to the re-develop (import_raw_tuned_from). They are freed with the dialog. A decode of another file is never used (length + digest check), and a missed one falls back to decoding as before. The developed pixels are unchanged. queue_open_dialog also no longer copies the whole file. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/jobs.rs | 4 +- crates/io/examples/bench_abr.rs | 123 ----- crates/io/examples/bench_shuffles.rs | 54 -- crates/io/examples/big_psb_check.rs | 80 --- crates/io/examples/gen_abr_library.rs | 163 ------ crates/io/examples/oracle_diff.rs | 514 ------------------ crates/io/examples/rawlook.rs | 237 -------- crates/io/src/lib.rs | 7 +- crates/io/src/raw.rs | 174 +++++- crates/io/tests/it/raw.rs | 71 +++ .../ui-egui/src/camera_raw_identity_tests.rs | 7 +- crates/ui-egui/src/camera_raw_ui.rs | 67 ++- crates/ui-egui/src/jobs_ui.rs | 2 +- crates/ui-egui/src/lib.rs | 5 +- crates/ui-egui/src/open_prompt.rs | 2 +- 15 files changed, 307 insertions(+), 1203 deletions(-) delete mode 100644 crates/io/examples/bench_abr.rs delete mode 100644 crates/io/examples/bench_shuffles.rs delete mode 100644 crates/io/examples/big_psb_check.rs delete mode 100644 crates/io/examples/gen_abr_library.rs delete mode 100644 crates/io/examples/oracle_diff.rs delete mode 100644 crates/io/examples/rawlook.rs diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 5c26e41cba2..fba40cbe3f0 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -501,6 +501,7 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor photocraft_io::ImportOptions { max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize, demosaic: prefs.raw_defaults.demosaic.method(), + keep_raw: false, } } @@ -545,7 +546,8 @@ impl Session { let label = format!("Opening {name}"); let name_w = name.to_string(); let name_a = name.to_string(); - let opts = import_options(self.prefs()); + // An interactive raw open keeps its sensor data for the Camera Raw dialog it may show. + let opts = photocraft_io::ImportOptions { keep_raw: confirm_damage && self.prefs().raw_defaults.open_in_camera_raw, ..import_options(self.prefs()) }; self.start_job( OPEN_JOB, json!({"name": name}), diff --git a/crates/io/examples/bench_abr.rs b/crates/io/examples/bench_abr.rs deleted file mode 100644 index 0811cb0ae80..00000000000 --- a/crates/io/examples/bench_abr.rs +++ /dev/null @@ -1,123 +0,0 @@ -//! Brush import and painting benchmark: parse + map a synthetic 100-brush ABR v6 file (256 px -//! RLE-compressed tips, full dynamics descriptors), then paint a 5000-dab stroke with an imported -//! brush on a 6000×6000 RGBA8 layer. -//! -//! `cargo run --release -p photocraft-io --example bench_abr` -#![allow(clippy::unwrap_used)] - -use std::time::Instant; - -use photocraft_color::PixelFormat; -use photocraft_paint::{StrokePoint, render_stroke}; -use photocraft_psd::abr::{AbrSample, write_v6}; -use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; -use photocraft_raster::Surface; - -fn prc(v: f64) -> Value { - Value::UnitFloat { unit: *b"#Prc", value: v } -} - -fn var(control: i32, jitter: f64) -> Value { - Value::Descriptor(Descriptor::new("brVr").with("bVTy", Value::Integer(control)).with("jitter", prc(jitter))) -} - -fn main() { - let n = 256u32; - let samples: Vec = (0..100) - .map(|i| { - let data = (0..n * n) - .map(|k| { - let (x, y) = ((k % n) as f32 - 128.0, (k / n) as f32 - 128.0); - let r = (x * x + y * y).sqrt() / 128.0; - (((1.0 - r) * 255.0).clamp(0.0, 255.0) as u8) & if (k + i) % 7 == 0 { 0x7f } else { 0xff } - }) - .collect(); - AbrSample { id: format!("$tip-{i}"), width: n, height: n, depth: 8, data } - }) - .collect(); - let presets: Vec = (0..100) - .map(|i| { - Descriptor::new("brushPreset") - .with("Nm ", Value::Text(UnicodeString::new_nul(&format!("Brush {i}")))) - .with( - "Brsh", - Value::Descriptor( - Descriptor::new("sampledBrush") - .with("Dmtr", Value::UnitFloat { unit: *b"#Pxl", value: 60.0 }) - .with("Spcn", prc(25.0)) - .with("sampledData", Value::Text(UnicodeString::new_nul(&format!("$tip-{i}")))), - ), - ) - .with("useTipDynamics", Value::Boolean(true)) - .with("szVr", var(2, 20.0)) - .with("angleDynamics", var(0, 100.0)) - .with("useScatter", Value::Boolean(true)) - .with("scatterDynamics", var(0, 120.0)) - .with("Cnt ", Value::Integer(2)) - .with("usePaintDynamics", Value::Boolean(true)) - .with("opVr", var(2, 0.0)) - }) - .collect(); - let bytes = write_v6(2, &samples, &[], &presets, true).unwrap(); - // `--write `: also save a small showcase file (procedural tips) for UI snapshots. - let args: Vec = std::env::args().collect(); - if let Some(path) = args.iter().position(|a| a == "--write").and_then(|i| args.get(i + 1)) { - use photocraft_paint::procedural::*; - let tips = [("Leafy", leaf_tip(96)), ("Charcoal Stick", charcoal_tip(96, 3)), ("Sea Sponge", sponge_tip(96, 5)), ("Star Burst", star_tip(96))]; - let samples: Vec = tips - .iter() - .enumerate() - .map(|(i, (_, t))| AbrSample { - id: format!("$show-{i}"), - width: t.width, - height: t.height, - depth: 16, - data: t.data.iter().flat_map(|v| v.to_be_bytes()).collect(), - }) - .collect(); - let presets: Vec = tips - .iter() - .enumerate() - .map(|(i, (name, _))| { - let mut d = presets[i].clone(); - d.items.retain(|(k, _)| !k.is("Nm ") && !k.is("Brsh")); - d.with("Nm ", Value::Text(UnicodeString::new_nul(name))).with( - "Brsh", - Value::Descriptor( - Descriptor::new("sampledBrush") - .with("Dmtr", Value::UnitFloat { unit: *b"#Pxl", value: 50.0 }) - .with("Spcn", prc(if i == 1 { 10.0 } else { 45.0 })) - .with("sampledData", Value::Text(UnicodeString::new_nul(&format!("$show-{i}")))), - ), - ) - }) - .collect(); - std::fs::write(path, write_v6(2, &samples, &[], &presets, true).unwrap()).unwrap(); - println!("wrote {path}"); - } - let mut best = f64::MAX; - let mut imp = None; - for _ in 0..5 { - let t = Instant::now(); - imp = Some(photocraft_io::abr_map::read_abr(&bytes, "Bench").unwrap()); - best = best.min(t.elapsed().as_secs_f64() * 1000.0); - } - let imp = imp.unwrap(); - println!("ABR import: {} brushes, {:.1} MB file, best of 5: {best:.1} ms", imp.presets.len(), bytes.len() as f64 / 1e6); - - // A long pressure-varied stroke with the first imported brush (size, angle, scatter, opacity dynamics). - let mut brush = imp.presets[0].brush.clone(); - brush.seed = 1; - let mut s = Surface::new(PixelFormat::RGBA8); - let size = 6000.0; - let pts: Vec = (0..=2000) - .map(|i| { - let t = i as f64 / 2000.0; - StrokePoint::new(200.0 + t * (size - 400.0), size / 2.0 + (t * 24.0).sin() * 1500.0, (0.3 + 0.7 * (t * 25.0).sin().abs()) as f32) - }) - .collect(); - let dabs = photocraft_paint::dabs(&photocraft_paint::Stroke { brush: brush.clone(), points: pts.clone() }).len(); - let t = Instant::now(); - render_stroke(&mut s, &brush, &pts, None, false, 1.0); - println!("Stroke: {dabs} primary dabs (scatter count 2), {:.1} ms", t.elapsed().as_secs_f64() * 1000.0); -} diff --git a/crates/io/examples/bench_shuffles.rs b/crates/io/examples/bench_shuffles.rs deleted file mode 100644 index 9bd29fecee1..00000000000 --- a/crates/io/examples/bench_shuffles.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! BEFORE/AFTER helper for the banded interleave/deinterleave: `--serial` runs the old -//! sequential implementation inline, the default runs the current parallel one. -fn main() { - use photocraft_color::SampleType; - let serial = std::env::args().any(|a| a == "--serial"); - for (label, s, ch) in [("u16 rgb", SampleType::U16, 3usize), ("f32 rgba", SampleType::F32, 4)] { - let bps = s.bytes(); - let n = 20_000_000usize; - let planes: Vec> = (0..ch).map(|c| (0..n * bps).map(|i| (i * 7 + c) as u8).collect()).collect(); - let refs: Vec> = planes.iter().map(|p| Some(&p[..])).collect(); - let fill: Vec> = (0..ch).map(|_| vec![0u8; bps]).collect(); - let invert = [false; 4]; - let t0 = std::time::Instant::now(); - let interleaved = if serial { - let mut out = vec![0u8; n * ch * bps]; - for (c, plane) in refs.iter().enumerate() { - for i in 0..n { - let dst = &mut out[(i * ch + c) * bps..(i * ch + c + 1) * bps]; - if let Some(p) = plane - && p.len() >= (i + 1) * bps - { - let src = &p[i * bps..(i + 1) * bps]; - for k in 0..bps { - dst[k] = src[bps - 1 - k]; - } - } - } - } - out - } else { - photocraft_io::pixels::interleave(&refs, &fill, n, s, &invert) - }; - let t1 = t0.elapsed().as_secs_f64() * 1000.0; - let t2 = std::time::Instant::now(); - if serial { - let mut acc: Vec> = Vec::new(); - for _ in 0..ch { - acc.push(Vec::with_capacity(n * bps)); - } - let mut tmp = [0u8; 4]; - for i in 0..n { - for (c, plane) in acc.iter_mut().enumerate() { - let src = &interleaved[(i * ch + c) * bps..(i * ch + c + 1) * bps]; - tmp[..bps].copy_from_slice(src); - plane.extend(tmp[..bps].iter().rev()); - } - } - } else { - let _ = photocraft_io::pixels::deinterleave(&interleaved, ch, s, &invert); - } - let t3 = t2.elapsed().as_secs_f64() * 1000.0; - println!("{label}: interleave {t1:.1} ms, deinterleave {t3:.1} ms (20 MP, release, {})", if serial { "serial (before)" } else { "parallel (after)" }); - } -} diff --git a/crates/io/examples/big_psb_check.rs b/crates/io/examples/big_psb_check.rs deleted file mode 100644 index 3b1c21034b0..00000000000 --- a/crates/io/examples/big_psb_check.rs +++ /dev/null @@ -1,80 +0,0 @@ -//! Opens the files written by `photocraft-psd`'s `big_psb` example and checks their pixels. -//! -//! `cargo run --release -p photocraft-io --example big_psb_check -- ...` -//! -//! The opt-in tests in `tests/it/large_files.rs` generate and check the same files. - -use photocraft_psd::fixtures::sample; - -fn main() { - for path in std::env::args().skip(1) { - let rle = path.contains("rle"); - let t = std::time::Instant::now(); - let bytes = match std::fs::read(&path) { - Ok(b) => b, - Err(e) => { - println!("{path}: read failed: {e}"); - continue; - } - }; - let read_s = t.elapsed().as_secs_f64(); - let t = std::time::Instant::now(); - let res = match photocraft_io::import(&path, &bytes) { - Ok(r) => r, - Err(e) => { - println!("{path}: import failed: {e}"); - continue; - } - }; - drop(bytes); - // With SAVE set: save as PSB, then check the re-opened file instead. - let res = if std::env::var_os("SAVE").is_some() { - let t = std::time::Instant::now(); - let out = match photocraft_io::export(&res.document, "x.psb", &photocraft_io::ExportOptions::default()) { - Ok(o) => o, - Err(e) => { - println!("{path}: save failed: {e}"); - continue; - } - }; - println!("{path}: saved {:.2} GB in {:.1} s, warnings {:?}", out.bytes.len() as f64 / 1e9, t.elapsed().as_secs_f64(), out.warnings); - drop(res); - match photocraft_io::import("x.psb", &out.bytes) { - Ok(r) => r, - Err(e) => { - println!("{path}: re-open failed: {e}"); - continue; - } - } - } else { - res - }; - let doc = &res.document; - println!( - "{path}: read {read_s:.1} s, import {:.1} s, {}x{}, {} layer(s)", - t.elapsed().as_secs_f64(), - doc.size.width, - doc.size.height, - doc.layers.len() - ); - for w in &res.warnings { - println!(" warning: {w}"); - } - let Some(s) = doc.layers.first().and_then(|l| l.surface()) else { - println!(" FAIL: no pixel layer"); - continue; - }; - let (w, h) = (doc.size.width, doc.size.height); - let mut bad = 0; - let points = [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1), (w / 2, h / 2), (w / 3, h * 2 / 3), (12_345 % w, (h - 7) % h)]; - for &(x, y) in &points { - let got = s.pixel(x as i32, y as i32); - let want: Vec = (0..4).map(|c| f32::from(sample(x, y, c, rle)) / 255.0).collect(); - if got.len() != 4 || got.iter().zip(&want).any(|(g, w)| (g - w).abs() > 1.0 / 510.0) { - bad += 1; - println!(" mismatch at ({x}, {y}): got {got:?}, want {want:?}"); - } - } - println!(" {}", if bad == 0 { "OK: all sampled pixels match" } else { "FAIL" }); - } -} diff --git a/crates/io/examples/gen_abr_library.rs b/crates/io/examples/gen_abr_library.rs deleted file mode 100644 index cbb2ad303c6..00000000000 --- a/crates/io/examples/gen_abr_library.rs +++ /dev/null @@ -1,163 +0,0 @@ -//! Generates a large, redistributable ABR v6 brush library for memory and import testing (#1843). -//! -//! Real painting packs are commercial or "personal use only", so we can't test against them. This -//! writes a deterministic stand-in with the same shape: hundreds of presets with big 16-bit sampled -//! tips (RLE-compressed, like Photoshop CC), full dynamics descriptors, split over several files. -//! Every tip comes from `photocraft_paint::procedural` (original, seeded generators), so the output -//! carries no third-party rights. Nothing it writes is committed; regenerate it when needed. -//! -//! `cargo run --release -p photocraft-io --example gen_abr_library -- --out ` -//! -//! Options (defaults in brackets): `--brushes N` [600], `--edge PX` largest tip edge [2000], -//! `--min-edge PX` smallest tip edge [800], `--depth 8|16` [16], `--per-file N` presets per file [100], -//! `--raw` store tips uncompressed (bigger files). Each file stays under the reader's decoded cap (1 GiB; 512 MiB on 32-bit). -#![allow(clippy::unwrap_used, clippy::expect_used)] - -use photocraft_paint::procedural::*; -use photocraft_paint::tile::GrayTile; -use photocraft_psd::abr::{AbrSample, MAX_TOTAL_BYTES, write_v6}; -use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; -use std::path::PathBuf; -use std::time::Instant; - -const KINDS: [&str; 9] = ["Chalk", "Spatter", "Bristle", "Charcoal", "Leaf", "Grass", "Sponge", "Star", "Rake"]; - -fn tip(kind: usize, n: u32, seed: u32) -> GrayTile { - match kind { - 0 => chalk_tip(n, seed), - 1 => spatter_tip(n, seed, 20 + seed % 40), - 2 => bristle_tip(n, seed), - 3 => charcoal_tip(n, seed), - 4 => leaf_tip(n), - 5 => grass_tip(n, seed, 8 + seed % 16), - 6 => sponge_tip(n, seed), - 7 => star_tip(n), - _ => rake_tip(n, seed, 6 + seed % 12), - } -} - -fn prc(v: f64) -> Value { - Value::UnitFloat { unit: *b"#Prc", value: v } -} - -fn var(control: i32, jitter: f64) -> Value { - Value::Descriptor(Descriptor::new("brVr").with("bVTy", Value::Integer(control)).with("jitter", prc(jitter))) -} - -fn text(s: &str) -> Value { - Value::Text(UnicodeString::new_nul(s)) -} - -/// A cheap deterministic 0..1 value per (brush, salt), to vary the presets. -fn h(i: u32, salt: u32) -> f64 { - let mut x = (u64::from(i) << 32 | u64::from(salt)).wrapping_mul(0x9E37_79B9_7F4A_7C15); - x ^= x >> 31; - x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9); - x ^= x >> 29; - (x % 10_000) as f64 / 10_000.0 -} - -fn preset(i: u32, id: &str, name: &str, edge: u32) -> Descriptor { - let mut d = Descriptor::new("brushPreset").with("Nm ", text(name)).with( - "Brsh", - Value::Descriptor( - Descriptor::new("sampledBrush") - .with("Dmtr", Value::UnitFloat { unit: *b"#Pxl", value: f64::from(edge) * (0.1 + 0.4 * h(i, 1)) }) - .with("Angl", Value::UnitFloat { unit: *b"#Ang", value: (h(i, 2) * 360.0 - 180.0).round() }) - .with("Rndn", prc((50.0 + 50.0 * h(i, 3)).round())) - .with("Spcn", prc((5.0 + 60.0 * h(i, 4)).round())) - .with("Intr", Value::Boolean(true)) - .with("flipX", Value::Boolean(h(i, 5) < 0.2)) - .with("sampledData", text(id)), - ), - ); - d = d.with("useTipDynamics", Value::Boolean(true)).with("szVr", var(2, (h(i, 6) * 40.0).round())).with("angleDynamics", var(0, (h(i, 7) * 100.0).round())); - if h(i, 8) < 0.5 { - d = d - .with("useScatter", Value::Boolean(true)) - .with("scatterDynamics", var(0, (h(i, 9) * 200.0).round())) - .with("Cnt ", Value::Integer(1 + (h(i, 10) * 4.0) as i32)); - } - if h(i, 11) < 0.6 { - d = d.with("usePaintDynamics", Value::Boolean(true)).with("opVr", var(2, 0.0)).with("prVr", var(2, 0.0)); - } - d -} - -fn main() { - let args: Vec = std::env::args().collect(); - let arg = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned(); - let num = |name: &str, default: u32| arg(name).map_or(default, |v| v.parse().expect("numeric option")); - let out = PathBuf::from(arg("--out").unwrap_or_else(|| "target/abr-library".into())); - let brushes = num("--brushes", 600); - let max_edge = num("--edge", 2000).clamp(16, photocraft_psd::abr::MAX_EDGE); - let min_edge = num("--min-edge", 800).clamp(16, max_edge); - let depth = num("--depth", 16) as u16; - assert!(matches!(depth, 8 | 16), "--depth must be 8 or 16"); - let per_file = num("--per-file", 100).max(1); - let rle = !args.iter().any(|a| a == "--raw"); - std::fs::create_dir_all(&out).unwrap(); - - let started = Instant::now(); - let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); - let (mut file_no, mut first, mut total_bytes, mut total_decoded) = (0u32, 0u32, 0u64, 0u64); - while first < brushes { - // Fill one file up to `per_file` presets, keeping its decoded samples well under the reader's cap. - let mut ids = Vec::new(); - let mut decoded = 0usize; - let mut i = first; - while i < brushes && ids.len() < per_file as usize { - let edge = min_edge + ((max_edge - min_edge) as f64 * h(i, 0)) as u32; - let bytes = edge as usize * edge as usize * usize::from(depth / 8); - if !ids.is_empty() && decoded + bytes > MAX_TOTAL_BYTES * 3 / 4 { - break; - } - decoded += bytes; - ids.push((i, edge)); - i += 1; - } - let samples: Vec = std::thread::scope(|s| { - let chunk = ids.len().div_ceil(threads); - let handles: Vec<_> = ids - .chunks(chunk) - .map(|part| { - s.spawn(move || { - part.iter() - .map(|&(i, edge)| { - let t = tip(i as usize % KINDS.len(), edge, i); - let data = if depth == 16 { - t.data.iter().flat_map(|v| v.to_be_bytes()).collect() - } else { - t.data.iter().map(|v| (v >> 8) as u8).collect() - }; - AbrSample { id: format!("$pc-gen-{i:05}"), width: edge, height: edge, depth, data } - }) - .collect::>() - }) - }) - .collect(); - handles.into_iter().flat_map(|h| h.join().unwrap()).collect() - }); - let presets: Vec = ids - .iter() - .map(|&(i, edge)| preset(i, &format!("$pc-gen-{i:05}"), &format!("{} {:03} ({edge} px)", KINDS[i as usize % KINDS.len()], i + 1), edge)) - .collect(); - let bytes = write_v6(2, &samples, &[], &presets, rle).unwrap(); - // Sanity: our own importer must accept every preset. - let imported = photocraft_io::abr_map::read_abr(&bytes, "Generated").unwrap(); - assert_eq!(imported.presets.len(), ids.len(), "every generated preset imports"); - file_no += 1; - let path = out.join(format!("photocraft-test-brushes-{file_no:02}.abr")); - std::fs::write(&path, &bytes).unwrap(); - println!("{}: {} brushes, {:.1} MB on disk, {:.1} MB decoded", path.display(), ids.len(), bytes.len() as f64 / 1e6, decoded as f64 / 1e6); - total_bytes += bytes.len() as u64; - total_decoded += decoded as u64; - first = i; - } - println!( - "{brushes} brushes in {file_no} files: {:.1} MB on disk, {:.1} MB of decoded tips, {:.1} s", - total_bytes as f64 / 1e6, - total_decoded as f64 / 1e6, - started.elapsed().as_secs_f64() - ); -} diff --git a/crates/io/examples/oracle_diff.rs b/crates/io/examples/oracle_diff.rs deleted file mode 100644 index fddef567a96..00000000000 --- a/crates/io/examples/oracle_diff.rs +++ /dev/null @@ -1,514 +0,0 @@ -//! Compare our composite with Photoshop's merged image for one PSD (rendering-fidelity work). -//! -//! ```sh -//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd [N] # layers + first N pixels -//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 png out.png # ours | Photoshop | diff heatmap -//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 col [x] # column samples -//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 row y x0 x1 # row samples -//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 worst [n] # n worst pixels -//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 grid x0 y0 x1 y1 [ch] # value grids -//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 layerpx x y # each layer's pixel -//! cargo run --release -p photocraft-io --example oracle_diff -- corpus/psd # every file: max err, bad %, PASS/DIFF -//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 dump prefix # raw f32 planes for offline fitting -//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 bylayer # max error around each layer -//! SCALE=4 … # upscale the png -//! HIDE_ADJ=1 … # adjustment layers hidden -//! ONLY="name,name" … # only these top-level layers (+ the bottom one) -//! DUMP_FX=1 … # raw effects descriptors -//! ``` -fn main() { - let path = std::env::args().nth(1).expect("path"); - if std::path::Path::new(&path).is_dir() { - corpus_summary(std::path::Path::new(&path)); - return; - } - let bytes = std::fs::read(&path).unwrap(); - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); - let mut imp = photocraft_io::import(&path, &bytes).unwrap(); - if std::env::var_os("HIDE_ADJ").is_some() { - // Composite without adjustment layers (their input, for fitting transfer curves). - fn hide(ls: &mut [photocraft_doc::Layer]) { - for l in ls { - if matches!(l.content, photocraft_doc::LayerContent::Adjustment(_)) { - l.visible = false; - } - if let photocraft_doc::LayerContent::Group(g) = &mut l.content { - hide(&mut g.children); - } - } - } - hide(&mut imp.document.layers); - } - if let Some(keep) = std::env::var_os("ONLY") { - // Hide every top-level layer but the bottom one and those named in ONLY (comma-separated). - let keep = keep.to_string_lossy().to_string(); - let names: Vec<&str> = keep.split(',').collect(); - for l in imp.document.layers.iter_mut().skip(1) { - l.visible = names.contains(&l.name.as_str()); - } - } - let doc = &imp.document; - println!("mode {:?} depth {:?} layers {} warnings {:?} light {:?}", doc.mode, doc.depth, doc.layer_count(), imp.warnings, doc.global_light); - for l in doc.walk() { - let l = l.2; - println!( - " layer {:?} {:?} blend {:?} op {} fill {} fill_cache {} visible {}", - l.name, - l.content.kind_name(), - l.blend, - l.opacity, - l.fill_opacity, - l.fill_cache.is_some(), - l.visible - ); - if let photocraft_doc::LayerContent::Adjustment(a) = &l.content { - println!(" {}", format!("{a:?}").chars().take(800).collect::()); - } - if let photocraft_doc::LayerContent::Fill(f) = &l.content { - println!(" {f:?}"); - } - if let Some(m) = &l.mask { - println!(" mask default {:?} bounds {:?} enabled {}", m.surface.default_pixel(), m.surface.content_bounds(), m.enabled); - let b = m.surface.content_bounds(); - let cx = (b.x0 + b.x1) / 2; - let col: Vec = (b.y0..b.y0 + 6).chain(b.y1 - 6..b.y1).map(|y| format!("{y}:{:.2}", m.surface.pixel(cx, y)[0])).collect(); - println!(" mask column x={cx}: {}", col.join(" ")); - let row: Vec = (b.x0..b.x0 + 4).chain(b.x1 - 4..b.x1).map(|x| format!("{x}:{:.2}", m.surface.pixel(x, (b.y0 + b.y1) / 2)[0])).collect(); - println!(" mask row: {}", row.join(" ")); - } - if let Some(sf) = l.surface() { - let b = sf.content_bounds(); - let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); - for y in b.y0..b.y1 { - for x in b.x0..b.x1 { - let p = sf.pixel(x, y); - if p[p.len() - 1] > 0.0 { - (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)); - } - } - } - println!(" alpha bounds ({x0},{y0})-({x1},{y1})"); - } - if let photocraft_doc::LayerContent::Shape(sh) = &l.content { - println!( - " shape path bounds {:?} subpaths {} rule {:?} inverted {} fill {} stroke {} outline {}", - sh.path.control_bounds(), - sh.path.subpaths.len(), - sh.path.fill_rule, - sh.path.inverted, - sh.fill.is_some(), - sh.stroke.is_some(), - photocraft_compose::effect_outline(l).is_some() - ); - if std::env::var_os("PATHS").is_some() { - for s in &sh.path.subpaths { - println!(" subpath {:?} closed {} knots {:?}", s.op, s.closed, s.knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect::>()); - } - } - } - if let Some(vm) = &l.vector_mask { - println!(" vector mask bounds {:?}", vm.path.control_bounds()); - } - println!(" clipped {} frame {:?} bounds {:?}", l.clipped, photocraft_compose::fill_frame(l, doc.bounds()), l.surface().map(|s| s.content_bounds())); - for e in &l.effects.items { - if let photocraft_doc::Effect::GradientOverlay { common, gradient, .. } = e - && common.enabled - { - let g = format!("{gradient:?}"); - println!(" gradient overlay: {g}"); - } else if format!("{e:?}").contains("enabled: true") { - println!(" fx {}", format!("{e:?}").chars().take(if std::env::var_os("FULL").is_some() { 100_000 } else { 200 }).collect::()); - } - } - println!(" blocks {:?}", l.psd_blocks.iter().map(|(k, v)| format!("{}({})", String::from_utf8_lossy(k), v.len())).collect::>()); - for (k, v) in &l.psd_blocks { - if k == b"lfx2" || k == b"lmfx" { - // Recursively list descriptor keys (effects), skipping colour stop lists. - fn walk(d: &photocraft_psd::descriptor::Descriptor, depth: usize, out: &mut Vec) { - for (k, v) in &d.items { - let key = match k { - photocraft_psd::descriptor::Id::Code(c) => String::from_utf8_lossy(c).to_string(), - other => String::from_utf8_lossy(other.as_bytes()).to_string(), - }; - let vs = format!("{v:?}"); - match v { - photocraft_psd::descriptor::Value::Descriptor(sub) => { - out.push(format!("{}{key}:", " ".repeat(depth))); - walk(sub, depth + 1, out); - } - _ => out.push(format!("{}{key} = {}", " ".repeat(depth), vs.chars().take(90).collect::())), - } - } - } - if let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(&v[4..]) { - let mut out = Vec::new(); - walk(&vd.descriptor, 3, &mut out); - for l in out.iter().filter(|l| !l.trim_start().starts_with("Clrs") && !l.trim_start().starts_with("Trns")) { - println!("{l}"); - } - } - } - if k == b"TySh" - && let Some(Ok((vd, _))) = v.get(52..).map(photocraft_psd::descriptor::VersionedDescriptor::parse_prefix) - { - // Text bounds (text space) and the transform. - let t: Vec = (0..6).map(|i| f64::from_be_bytes(v[2 + i * 8..10 + i * 8].try_into().unwrap())).collect(); - println!(" TySh transform {t:?}"); - for key in ["bounds", "boundingBox"] { - if let Some(photocraft_psd::descriptor::Value::Descriptor(d)) = vd.descriptor.get(key) { - let n: Vec = d.items.iter().map(|(k, v)| format!("{}={v:?}", String::from_utf8_lossy(k.as_bytes()))).collect(); - println!(" TySh {key}: {}", n.join(" ")); - } - } - } - if k == b"GdFl" { - // Skip the 4-byte version before the descriptor. - if let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(v) { - println!( - " GdFl keys: {:?}", - vd.descriptor - .items - .iter() - .filter(|(k, _)| !format!("{k:?}").contains("71, 114, 97, 100")) - .map(|(k, v)| format!( - "{:?}={}", - match k { - photocraft_psd::descriptor::Id::Code(c) => String::from_utf8_lossy(c).to_string(), - other => format!("{other:?}"), - }, - format!("{v:?}").chars().take(120).collect::() - )) - .collect::>() - ); - } - } - } - } - if std::env::var_os("DUMP_FX").is_some() { - fn walk(d: &photocraft_psd::descriptor::Descriptor, depth: usize) { - for (k, v) in &d.items { - let key = String::from_utf8_lossy(k.as_bytes()).to_string(); - if key == "Clrs" || key == "Trns" { - continue; - } - match v { - photocraft_psd::descriptor::Value::Descriptor(sub) => { - println!("{}{key}:", " ".repeat(depth)); - walk(sub, depth + 1); - } - photocraft_psd::descriptor::Value::Text(t) => println!("{}{key} = {:?}", " ".repeat(depth), t.to_string_lossy()), - photocraft_psd::descriptor::Value::List(items) if items.iter().all(|i| matches!(i, photocraft_psd::descriptor::Value::Descriptor(_))) => { - println!("{}{key} = [{} items]", " ".repeat(depth), items.len()); - for (i, it) in items.iter().enumerate() { - if let photocraft_psd::descriptor::Value::Descriptor(sub) = it { - println!("{}[{i}]:", " ".repeat(depth + 1)); - walk(sub, depth + 2); - } - } - } - _ => println!("{}{key} = {}", " ".repeat(depth), format!("{v:?}").chars().take(600).collect::()), - } - } - } - for rec in file.layers() { - println!("-- layer {:?} rect {:?}", String::from_utf8_lossy(&rec.name), rec.rect); - if let Some(b) = rec.block(b"lmfx").or(rec.block(b"lfx2")).or(rec.block(b"lfxs")) - && let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(&b.data[4..]) - { - walk(&vd.descriptor, 1); - } - } - } - let ours = photocraft_compose::flatten(doc).px; - let merged = photocraft_io::merged_composite(&file).unwrap(); - if std::env::args().nth(3).as_deref() == Some("png") { - // ours | photoshop | diff heatmap, side by side (over white). - let out = std::env::args().nth(4).expect("out.png"); - let (w, h) = (doc.size.width as usize, doc.size.height as usize); - let mut img = vec![0u8; w * 3 * h * 4]; - let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - for y in 0..h { - for x in 0..w { - let (a, b) = (ours[y * w + x], merged[y * w + x]); - let over = |p: [f32; 4]| [p[0] * p[3] + 1.0 - p[3], p[1] * p[3] + 1.0 - p[3], p[2] * p[3] + 1.0 - p[3]]; - let (oa, ob) = (over(a), over(b)); - let d = (0..3).map(|c| (oa[c] - ob[c]).abs()).fold(0.0f32, f32::max); - let heat = [q((d * 4.0).min(1.0)), q((1.0 - d * 4.0).max(0.0) * 0.3), 0]; - for (k, px) in [[q(oa[0]), q(oa[1]), q(oa[2])], [q(ob[0]), q(ob[1]), q(ob[2])], heat].iter().enumerate() { - let o = (y * w * 3 + k * w + x) * 4; - img[o..o + 3].copy_from_slice(px); - img[o + 3] = 255; - } - } - } - // SCALE=n: nearest-neighbour upscale (small files). - let k: usize = std::env::var("SCALE").ok().and_then(|s| s.parse().ok()).unwrap_or(1).clamp(1, 16); - let (img, w, h) = if k > 1 { - let mut big = vec![0u8; w * 3 * k * h * k * 4]; - for y in 0..h * k { - for x in 0..w * 3 * k { - let (s, d) = (((y / k) * w * 3 + x / k) * 4, (y * w * 3 * k + x) * 4); - big[d..d + 4].copy_from_slice(&img[s..s + 4]); - } - } - (big, w * k, h * k) - } else { - (img, w, h) - }; - let image = - photocraft_codecs::Image::from_raw((w * 3) as u32, h as u32, photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8, img) - .unwrap(); - std::fs::write(&out, photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); - println!("wrote {out}"); - return; - } - if std::env::args().nth(3).as_deref() == Some("dump") { - // dump prefix: raw little-endian f32 RGBA (straight) planes for offline fitting: - // prefix_ours.f32, prefix_ps.f32, prefix_L.f32 (each top-level layer's own pixels, - // masks not applied) and prefix.txt (width, height, layer names). - let out = std::env::args().nth(4).expect("prefix"); - let wr = |name: String, px: &[[f32; 4]]| { - let bytes: Vec = px.iter().flat_map(|p| p.iter().flat_map(|v| v.to_le_bytes())).collect(); - std::fs::write(name, bytes).unwrap(); - }; - wr(format!("{out}_ours.f32"), &ours); - wr(format!("{out}_ps.f32"), &merged); - let mut meta = format!("{} {}\n", doc.size.width, doc.size.height); - for (i, l) in doc.layers.iter().enumerate() { - let b = photocraft_compose::surface_to_buffer( - l.surface().unwrap_or(&photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8)), - doc.bounds(), - ); - wr(format!("{out}_L{i}.f32"), &b.px); - meta += &format!("{i} {}\n", l.name); - } - std::fs::write(format!("{out}.txt"), meta).unwrap(); - return; - } - if std::env::args().nth(3).as_deref() == Some("layerpx") { - // layerpx x y: each layer's own pixel (0-255). - let x: i32 = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0); - let y: i32 = std::env::args().nth(5).and_then(|s| s.parse().ok()).unwrap_or(0); - for l in doc.walk() { - if let Some(s) = l.2.surface() { - println!("{:?}: {:?}", l.2.name, s.pixel(x, y).iter().map(|v| (v * 255.0 * 100.0).round() / 100.0).collect::>()); - } - } - return; - } - if std::env::args().nth(3).as_deref() == Some("grid") { - // grid x0 y0 x1 y1 [channel]: ours / photoshop values (0-255, premultiplied colour). - let w = doc.size.width as usize; - let a: Vec = (4..8).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); - let ch: usize = std::env::args().nth(8).and_then(|s| s.parse().ok()).unwrap_or(3); - for (label, img) in [("ours", &ours), ("ps", &merged)] { - println!("{label} (channel {ch}):"); - for y in a[1]..a[3] { - let row: Vec = (a[0]..a[2]) - .map(|x| { - let p = img[y * w + x]; - let v = if ch == 3 { p[3] } else { p[ch] * p[3] }; - format!("{:4}", (v * 255.0).round()) - }) - .collect(); - println!(" y={y:4} {}", row.join("")); - } - } - return; - } - if std::env::args().nth(3).as_deref() == Some("bylayer") { - // Max error and bad-pixel count inside each layer's bounds grown by its effects' reach - // (regions overlap; a quick way to tell which layer or effect is off). - let (w, h) = (doc.size.width as i32, doc.size.height as i32); - for (_, _, l) in doc.walk() { - let Some(sf) = l.surface() else { continue }; - let cb = sf.content_bounds(); - let mut b = photocraft_geom::Rect::new(i32::MAX, i32::MAX, i32::MIN, i32::MIN); - for y in cb.y0..cb.y1 { - for x in cb.x0..cb.x1 { - let p = sf.pixel(x, y); - if p[p.len() - 1] > 0.0 { - b = photocraft_geom::Rect::new(b.x0.min(x), b.y0.min(y), b.x1.max(x + 1), b.y1.max(y + 1)); - } - } - } - if b.x0 > b.x1 { - continue; - } - let m = photocraft_compose::effects::margin(l); - let r = photocraft_geom::Rect::new((b.x0 - m).max(0), (b.y0 - m).max(0), (b.x1 + m).min(w), (b.y1 + m).min(h)); - let (mut worst, mut at, mut bad) = (0.0f32, (0, 0), 0usize); - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let i = (y * w + x) as usize; - let (a, b) = (ours[i], merged[i]); - let d = (0..3).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max); - if d > 2.0 / 255.0 { - bad += 1; - } - if d > worst { - (worst, at) = (d, (x, y)); - } - } - } - let fx: Vec<&str> = l.effects.items.iter().filter(|e| e.enabled()).map(|e| e.label()).collect(); - println!("{:<32} {:>6.1} at {:?} bad {:>6} {:?} {:?}", l.name, worst * 255.0, at, bad, l.blend, fx); - } - return; - } - if std::env::args().nth(3).as_deref() == Some("worst") { - // The N worst pixels (premultiplied max channel error), with coordinates. - let w = doc.size.width as usize; - let n: usize = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(20); - let mut v: Vec<(f32, usize)> = ours - .iter() - .zip(&merged) - .enumerate() - .map(|(i, (a, b))| ((0..4).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max), i)) - .collect(); - v.sort_by(|a, b| b.0.total_cmp(&a.0)); - for (d, i) in v.into_iter().take(n) { - let (a, b) = (ours[i], merged[i]); - println!("({:4},{:4}) d={:5.1} ours {:?} ps {:?}", i % w, i / w, d * 255.0, a.map(|v| (v * 255.0).round()), b.map(|v| (v * 255.0).round())); - } - return; - } - if std::env::args().nth(3).as_deref() == Some("row") { - let w = doc.size.width as usize; - let y: usize = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0); - let (x0, x1): (usize, usize) = - (std::env::args().nth(5).and_then(|s| s.parse().ok()).unwrap_or(0), std::env::args().nth(6).and_then(|s| s.parse().ok()).unwrap_or(w)); - for x in (x0..x1).step_by(((x1 - x0) / 20).max(1)) { - let (a, b) = (ours[y * w + x], merged[y * w + x]); - println!("x={x:5} ours {:?} ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); - } - return; - } - if std::env::args().nth(3).as_deref() == Some("solve") { - // solve layer-name x0 y0 x1 y1: per pixel the layer's content alpha `l`, its shape's path - // coverage `cov`, Photoshop's alpha `A` and the alpha `s` an effect beneath the layer - // would need (A = s + l (1 - s)) over a transparent backdrop. - let name = std::env::args().nth(4).expect("layer name"); - let a: Vec = (5..9).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); - let w = doc.size.width as usize; - let l = doc.walk().into_iter().map(|t| t.2).find(|l| l.name == name).expect("layer"); - let r = photocraft_geom::Rect::new(a[0], a[1], a[2], a[3]); - let cov = match &l.content { - photocraft_doc::LayerContent::Shape(sh) => photocraft_vector::path_coverage(&sh.path, r), - _ => vec![0.0; r.width() as usize * r.height() as usize], - }; - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let la = l.surface().map_or(0.0, |s| s.pixel(x, y)[3]); - let c = cov[((y - r.y0) * r.width() as i32 + x - r.x0) as usize]; - let p = merged[y as usize * w + x as usize]; - let o = ours[y as usize * w + x as usize]; - let s = if la < 1.0 { (p[3] - la) / (1.0 - la) } else { f32::NAN }; - println!("({x:3},{y:3}) l {la:.3} cov {c:.3} A {:.3} ours {:.3} s {s:.3} ps {:?}", p[3], o[3], p.map(|v| (v * 255.0).round())); - } - } - return; - } - if std::env::args().nth(3).as_deref() == Some("line") { - // line x0 y0 x1 y1: every pixel on the segment, straight RGBA 0-255, ours | ps. - let w = doc.size.width as usize; - let a: Vec = (4..8).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); - let n = (a[2] - a[0]).abs().max((a[3] - a[1]).abs()).max(1); - for k in 0..=n { - let (x, y) = ((a[0] + (a[2] - a[0]) * k / n) as usize, (a[1] + (a[3] - a[1]) * k / n) as usize); - let (o, p) = (ours[y * w + x], merged[y * w + x]); - println!("({x:4},{y:4}) ours {:?} ps {:?}", o.map(|v| (v * 255.0).round()), p.map(|v| (v * 255.0).round())); - } - return; - } - if std::env::args().nth(3).as_deref() == Some("col") { - let (w, h) = (doc.size.width as usize, doc.size.height as usize); - let x = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(w / 2); - for k in 0..=16 { - let y = ((h - 1) * k / 16).min(h - 1); - let (a, b) = (ours[y * w + x], merged[y * w + x]); - println!("y={y:5} ours {:?} ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); - } - return; - } - let n = std::env::args().nth(2).and_then(|s| s.parse().ok()).unwrap_or(8usize); - for (i, (a, b)) in ours.iter().zip(&merged).enumerate().take(n) { - println!("{i:4}: ours {:?}\n ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); - } -} - -/// The corpus oracle table (as `tests/it/corpus.rs`), files in parallel, without a test build. -fn corpus_summary(root: &std::path::Path) { - fn collect(dir: &std::path::Path, out: &mut Vec) { - let Ok(rd) = std::fs::read_dir(dir) else { return }; - for e in rd.flatten() { - let p = e.path(); - if p.is_dir() { - collect(&p, out); - } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("psd") || e.eq_ignore_ascii_case("psb")) { - out.push(p); - } - } - } - let mut files = Vec::new(); - collect(root, &mut files); - files.sort(); - const TOL: f32 = 2.0 / 255.0; - type Row = (String, Option<(f32, f32)>); - let row = |p: &std::path::PathBuf| -> Row { - let name = p.strip_prefix(root).unwrap_or(p).display().to_string(); - let Ok(bytes) = std::fs::read(p) else { return (name, None) }; - let Ok(file) = photocraft_psd::PsdFile::from_bytes(&bytes) else { return (name, None) }; - let Ok(imp) = photocraft_io::import(&name, &bytes) else { return (name, None) }; - if file.has_real_merged_data() == Some(false) || file.layers().is_empty() { - return (name, None); - } - let Ok(merged) = photocraft_io::merged_composite(&file) else { return (name, None) }; - let ours = photocraft_compose::flatten(&imp.document).px; - let mut m = 0.0f32; - let mut bad = 0usize; - for (a, b) in ours.iter().zip(&merged) { - let d = (0..4).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max); - m = m.max(d); - if (0..4).any(|c| (a[c] * a[3] - b[c] * b[3]).abs() > TOL) { - bad += 1; - } - } - (name, Some((m, 100.0 * bad as f32 / ours.len().max(1) as f32))) - }; - // Files in parallel (a few threads; flatten itself is tile-parallel). - let next = std::sync::atomic::AtomicUsize::new(0); - let mut rows: Vec<(usize, Row)> = std::thread::scope(|sc| { - let hs: Vec<_> = (0..4) - .map(|_| { - sc.spawn(|| { - let mut out = Vec::new(); - loop { - let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let Some(p) = files.get(i) else { break }; - out.push((i, row(p))); - } - out - }) - }) - .collect(); - hs.into_iter().flat_map(|h| h.join().unwrap()).collect() - }); - rows.sort_by_key(|r| r.0); - let rows: Vec = rows.into_iter().map(|r| r.1).collect(); - let (mut pass, mut diff, mut skip) = (0, 0, 0); - for (name, r) in &rows { - match r { - Some((m, pct)) if *m <= TOL => { - pass += 1; - println!("{name:<60} {m:>9.4} {pct:>7.2}% PASS"); - } - Some((m, pct)) => { - diff += 1; - println!("{name:<60} {m:>9.4} {pct:>7.2}% DIFF"); - } - None => skip += 1, - } - } - println!("{} files: {pass} pass, {diff} differ, {skip} skipped/errors", rows.len()); -} diff --git a/crates/io/examples/rawlook.rs b/crates/io/examples/rawlook.rs deleted file mode 100644 index dfec1a6ef96..00000000000 --- a/crates/io/examples/rawlook.rs +++ /dev/null @@ -1,237 +0,0 @@ -//! Measure the camera-JPEG colour fit on real raw files: times the fit, compares the -//! neutral fallback and the fitted look with the camera's embedded JPEG (mean CIE76 ΔE in -//! sRGB-clipped Lab D50, measured on the full develop output against the largest preview, -//! independently of the fit's own grid) and can write 1200-px sRGB PNGs of both renderings -//! and of the JPEG. -//! -//! ```sh -//! cargo run --release -p photocraft-io --example rawlook -- [--png DIR] FILE... -//! cargo run --release -p photocraft-io --example rawlook -- --synthetic # time a 24 MP synthetic NEF -//! ``` - -use std::time::Instant; - -use photocraft_cms::{Builtin, Intent, Transform}; -use photocraft_codecs::{self as codecs, ChannelLayout, EncodeOptions, Format, Image}; -use photocraft_raw::{DevelopOptions, develop_sensor}; - -/// Box-downsamples interleaved RGB to at most `edge` pixels on the long side. -fn shrink(px: &[f32], w: usize, h: usize, edge: usize) -> (Vec, usize, usize) { - let f = w.max(h).div_ceil(edge).max(1); - let (ow, oh) = (w / f, h / f); - let mut out = vec![0.0f32; ow * oh * 3]; - for y in 0..oh * f { - for x in 0..ow * f { - let (i, o) = ((y * w + x) * 3, ((y / f) * ow + x / f) * 3); - for k in 0..3 { - out[o + k] += px[i + k]; - } - } - } - let n = (f * f) as f32; - out.iter_mut().for_each(|v| *v /= n); - (out, ow, oh) -} - -/// Resamples to exactly `tw × th` by box averaging over the matching source area. -fn resample(px: &[f32], w: usize, h: usize, tw: usize, th: usize) -> Vec { - let mut out = vec![0.0f32; tw * th * 3]; - for ty in 0..th { - let (y0, y1) = (ty * h / th, ((ty + 1) * h / th).max(ty * h / th + 1)); - for tx in 0..tw { - let (x0, x1) = (tx * w / tw, ((tx + 1) * w / tw).max(tx * w / tw + 1)); - let mut s = [0.0f32; 3]; - for y in y0..y1 { - for x in x0..x1 { - for k in 0..3 { - s[k] += px[(y * w + x) * 3 + k]; - } - } - } - let n = ((y1 - y0) * (x1 - x0)) as f32; - for k in 0..3 { - out[(ty * tw + tx) * 3 + k] = s[k] / n; - } - } - } - out -} - -fn lin(v: f32) -> f64 { - let v = f64::from(v); - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } -} - -/// Lab (D50) of display sRGB 0..1 (Bradford-adapted sRGB → XYZ D50). -fn lab(p: &[f32]) -> [f64; 3] { - let m = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]]; - let l = [lin(p[0]), lin(p[1]), lin(p[2])]; - let xyz: [f64; 3] = std::array::from_fn(|i| m[i][0] * l[0] + m[i][1] * l[1] + m[i][2] * l[2]); - let w = [0.9642, 1.0, 0.8249]; - let f = |t: f64| if t > 216.0 / 24389.0 { t.cbrt() } else { (24389.0 / 27.0 * t + 16.0) / 116.0 }; - let [fx, fy, fz] = [0, 1, 2].map(|k| f(xyz[k] / w[k])); - [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)] -} - -fn mean_de(a: &[f32], b: &[f32]) -> f64 { - let n = a.len() / 3; - a.as_chunks::<3>() - .0 - .iter() - .zip(b.as_chunks::<3>().0) - .map(|(p, q)| { - let (x, y) = (lab(p), lab(q)); - ((x[0] - y[0]).powi(2) + (x[1] - y[1]).powi(2) + (x[2] - y[2]).powi(2)).sqrt() - }) - .sum::() - / n as f64 -} - -/// Developed ProPhoto 16-bit → display sRGB 0..1. -fn to_srgb(rgb: &[u16]) -> Vec { - let t = Transform::new(Builtin::ProPhotoCompat.profile(), Builtin::Srgb.profile(), Intent::RelativeColorimetric, false).expect("transform"); - let mut out = vec![0u16; rgb.len()]; - t.convert_u16(rgb, 3, &mut out, 3, false); - out.iter().map(|v| f32::from(*v) / 65535.0).collect() -} - -fn write_png(path: &str, px: &[f32], w: usize, h: usize) { - let (s, sw, sh) = shrink(px, w, h, 1200); - let bytes: Vec = s.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8).collect(); - let img = Image::from_u8(sw as u32, sh as u32, ChannelLayout::Rgb, bytes).expect("image"); - std::fs::write(path, codecs::encode(&img, Format::Png, &EncodeOptions::default()).expect("png")).expect("write"); -} - -/// Times the fit on a synthetic 6034×4012 NEF-like raw with a 1632×1086 camera-style preview. -fn synthetic() { - use photocraft_raw::testgen::{TiffBuilder, Val, mosaic}; - let (w, h) = (6034usize, 4012usize); - let colours: Vec<[f32; 3]> = (0..96u32).map(|i| [0.1 + 0.05 * (i % 9) as f32, 0.1 + 0.04 * (i % 11) as f32, 0.1 + 0.06 * (i % 7) as f32]).collect(); - let at = |x: usize, y: usize| { - let ramp = 0.15 + 0.85 * ((x * 12) % w) as f32 / w as f32; - colours[(y * 8 / h) * 12 + x * 12 / w].map(|v| v * ramp) - }; - let cam: Vec<[f32; 3]> = (0..w * h).map(|i| at(i % w, i / w)).collect(); - let data = mosaic(&cam, w, [0, 1, 1, 2], 0, 4095); - drop(cam); - let (pw, ph) = (1632usize, 1086usize); - let px: Vec = (0..pw * ph) - .flat_map(|i| { - let c = at((i % pw) * w / pw, (i / pw) * h / ph); - c.map(|v| { - let v = (1.6 * v / (1.0 + 0.6 * v)).clamp(0.0, 1.0); - ((if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }) * 255.0).round() as u8 - }) - }) - .collect(); - let jpeg = - codecs::encode(&Image::from_u8(pw as u32, ph as u32, ChannelLayout::Rgb, px).expect("image"), Format::Jpeg, &EncodeOptions::default()).expect("jpeg"); - let mut t = TiffBuilder::default(); - let strip = t.blob(data.iter().flat_map(|v| v.to_le_bytes()).collect()); - let raw = t.ifd(vec![ - (256, Val::Long(vec![w as u32])), - (257, Val::Long(vec![h as u32])), - (258, Val::Short(vec![12])), - (259, Val::Short(vec![1])), - (262, Val::Short(vec![32803])), - (273, Val::Blobs(vec![strip])), - (277, Val::Short(vec![1])), - (278, Val::Long(vec![h as u32])), - (279, Val::Long(vec![(data.len() * 2) as u32])), - (33421, Val::Short(vec![2, 2])), - (33422, Val::Byte(vec![0, 1, 1, 2])), - ]); - let len = jpeg.len() as u32; - let jb = t.blob(jpeg); - let ifd0 = - t.ifd(vec![(271, Val::Ascii("NIKON CORPORATION".into())), (330, Val::Ifds(vec![raw])), (513, Val::Blobs(vec![jb])), (514, Val::Long(vec![len]))]); - t.chain = vec![ifd0]; - let bytes = t.build(); - let opts = DevelopOptions::default(); - let sensor = photocraft_raw::decode(&bytes, &opts.limits).expect("decode"); - let _ = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts); - let mut times: Vec = (0..7) - .map(|_| { - let t = Instant::now(); - let r = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts); - assert!(r.is_ok(), "{r:?}"); - t.elapsed().as_secs_f64() * 1e3 - }) - .collect(); - times.sort_by(f64::total_cmp); - let p = photocraft_raw::embedded_preview(&bytes).expect("preview"); - let t = Instant::now(); - let img = codecs::decode_as(Format::Jpeg, p.jpeg).expect("jpeg"); - let dec = t.elapsed().as_secs_f64() * 1e3; - let r = photocraft_raw::Reference { width: img.width(), height: img.height(), rgb: img.data() }; - let t = Instant::now(); - let _ = photocraft_raw::fit_look(&sensor, &opts, &r); - println!(" preview decode {dec:.1} ms, fit_look {:.1} ms", t.elapsed().as_secs_f64() * 1e3); - println!("synthetic {w}x{h}: preview decode + fit median {:.1} ms (min {:.1}, max {:.1})", times[3], times[0], times[6]); -} - -fn main() { - let mut args = std::env::args().skip(1); - let mut png: Option = None; - let mut files = Vec::new(); - while let Some(a) = args.next() { - match a.as_str() { - "--png" => png = args.next(), - "--synthetic" => { - synthetic(); - return; - } - _ => files.push(a), - } - } - println!("| file | fit | ΔE grid fallback → fit | ΔE full fallback → fit | fit ms | develop ms |"); - println!("|---|---|---|---|---|---|"); - for f in files { - let bytes = std::fs::read(&f).expect("read"); - let name = std::path::Path::new(&f).file_stem().and_then(|s| s.to_str()).unwrap_or("raw").to_string(); - let opts = DevelopOptions::default(); - let sensor = photocraft_raw::decode(&bytes, &opts.limits).expect("decode"); - // Warm up (thread pool), then time the fit. - let _ = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts); - let t = Instant::now(); - let fit = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts); - let fit_ms = t.elapsed().as_secs_f64() * 1e3; - let before = develop_sensor(&sensor, &opts).expect("develop"); - let t = Instant::now(); - let after = match &fit { - Ok(look) => Some(develop_sensor(&sensor, &DevelopOptions { camera_look: Some(look.clone()), ..opts.clone() }).expect("develop")), - Err(_) => None, - }; - let dev_ms = t.elapsed().as_secs_f64() * 1e3; - // Independent check against the largest preview. - let p = photocraft_raw::embedded_preview(&bytes).expect("preview"); - let raw_jpeg = codecs::decode_as_with(Format::Jpeg, p.jpeg, &codecs::DecodeOptions { keep_orientation: true, ..Default::default() }).expect("jpeg"); - let own = raw_jpeg.meta.exif.as_deref().map_or(1, codecs::exif_orientation); - let o = if own != 1 { own } else { codecs::exif_orientation(&bytes) }; - let jpeg = raw_jpeg.oriented(o).expect("orient").converted(ChannelLayout::Rgb, photocraft_codecs::SampleType::U8).into_owned(); - let (jw, jh) = (jpeg.width() as usize, jpeg.height() as usize); - let jpx: Vec = jpeg.data().iter().map(|v| f32::from(*v) / 255.0).collect(); - let (dw, dh) = (before.width as usize, before.height as usize); - let (gw, gh) = (300, (300 * dh).div_ceil(dw)); - let jref = resample(&jpx, jw, jh, gw, gh); - let b = to_srgb(&before.rgb); - let de_before = mean_de(&resample(&b, dw, dh, gw, gh), &jref); - let a = after.as_ref().map(|d| to_srgb(&d.rgb)); - let de_after = a.as_ref().map(|a| mean_de(&resample(a, dw, dh, gw, gh), &jref)); - let (verdict, grid) = match &fit { - Ok(l) => ("used".to_string(), format!("{:.1} → {:.1}", l.delta_e_fallback, l.delta_e)), - Err(e) => (format!("rejected: {e}"), "-".into()), - }; - println!("| {name} | {verdict} | {grid} | {de_before:.1} → {} | {fit_ms:.0} | {dev_ms:.0} |", de_after.map_or("-".into(), |v| format!("{v:.1}"))); - if let Ok(l) = &fit { - eprintln!("{name}: to_xyz {:?}\n tone {:?}", l.to_xyz, l.tone.as_ref().map(|t| t.knots())); - } - if let Some(dir) = &png { - write_png(&format!("{dir}/{name}-before.png"), &b, dw, dh); - if let Some(a) = &a { - write_png(&format!("{dir}/{name}-after.png"), a, dw, dh); - } - write_png(&format!("{dir}/{name}-camera-jpeg.png"), &jpx, jw, jh); - } - } -} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 44beb59d47a..e8ae028ed5d 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -333,11 +333,14 @@ pub struct ImportOptions { pub max_group_depth: usize, /// The demosaic method camera raws are developed with. pub demosaic: raw::Demosaic, + /// Keep a developed raw's sensor data for its open-time Camera Raw dialog + /// ([`raw::take_kept_decode`]) instead of decoding the file again there. + pub keep_raw: bool, } impl Default for ImportOptions { fn default() -> Self { - ImportOptions { max_group_depth: photocraft_doc::MAX_GROUP_DEPTH, demosaic: raw::Demosaic::default() } + ImportOptions { max_group_depth: photocraft_doc::MAX_GROUP_DEPTH, demosaic: raw::Demosaic::default(), keep_raw: false } } } @@ -429,7 +432,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o return pdn::import(name, bytes, ctl); } if raw::is_raw(bytes) { - return raw::import_raw_demosaic(name, bytes, opts.demosaic); + return if opts.keep_raw { raw::import_raw_demosaic_keeping(name, bytes, opts.demosaic) } else { raw::import_raw_demosaic(name, bytes, opts.demosaic) }; } if is_svg_input(name, bytes) { return svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth); diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rs index 04158deddc1..1f9c328fd97 100644 --- a/crates/io/src/raw.rs +++ b/crates/io/src/raw.rs @@ -10,7 +10,7 @@ //! fit is not clearly better. use std::borrow::Cow; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use photocraft_cms::{Builtin, Intent, Profile, Transform}; use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType}; @@ -80,12 +80,31 @@ pub struct RawTuning { /// no as-shot white balance: Temperature / Tint were then not applied, and the caller keeps /// them as RGB adjustments. pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result<(ImportResult, bool), IoError> { + import_raw_tuned_inner(name, bytes, tuning, None) +} + +/// [`import_raw_tuned`] from what the open already learned about `bytes` ([`take_kept_decode`], +/// [`RawDecode::new`]): the same pixels without decoding the file and fitting its look again. +/// A `decode` of another file is ignored. +pub fn import_raw_tuned_from(name: &str, bytes: &[u8], tuning: &RawTuning, decode: &RawDecode) -> Result<(ImportResult, bool), IoError> { + import_raw_tuned_inner(name, bytes, tuning, Some(decode)) +} + +fn import_raw_tuned_inner(name: &str, bytes: &[u8], tuning: &RawTuning, decode: Option<&RawDecode>) -> Result<(ImportResult, bool), IoError> { let format = photocraft_raw::identify(bytes).map(|f| f.name()).unwrap_or("camera raw"); let exposure = f64::from(tuning.exposure); if !exposure.is_finite() || !(-10.0..=10.0).contains(&exposure) { return Err(IoError::Raw(RawError::Malformed(format!("exposure {} EV is out of range", tuning.exposure)))); } - let sensor = photocraft_raw::decode(bytes, &limits()).map_err(IoError::Raw)?; + let fresh; + let decode = match decode.filter(|d| d.is_of(bytes)) { + Some(d) => d, + None => { + fresh = RawDecode::new(bytes)?; + &fresh + } + }; + let sensor = &decode.sensor; let slider = |v: f32| if v.is_finite() { v.clamp(-100.0, 100.0) } else { 0.0 }; let tone = photocraft_raw::Tone { shadows: slider(tuning.shadows), @@ -96,7 +115,7 @@ pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result< }; // The colour rendering the default open used (a look fitted to the camera's JPEG for files // without colour calibration), so re-developing changes only what the sliders change. - let camera_look = default_look(bytes, &sensor); + let camera_look = decode.look.clone(); let mut opts = DevelopOptions { limits: limits(), exposure, demosaic: tuning.demosaic, tone, camera_look, ..Default::default() }; let wb_applied = match sensor.camera_wb { Some(m) => { @@ -106,7 +125,7 @@ pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result< } None => false, }; - let dev = photocraft_raw::develop_sensor(&sensor, &opts).map_err(IoError::Raw)?; + let dev = photocraft_raw::develop_sensor(sensor, &opts).map_err(IoError::Raw)?; let wb = if wb_applied { format!("as-shot white balance, temperature {:+.0}, tint {:+.0}", tuning.temperature, tuning.tint) } else { @@ -126,13 +145,117 @@ pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result< /// this crate decodes). For previews of the open-time raw-stage sliders /// ([`photocraft_raw::retone`]), in linear-light knots. pub fn tone_curve(bytes: &[u8]) -> Vec<[f32; 2]> { - let Ok(sensor) = photocraft_raw::decode(bytes, &limits()) else { return Vec::new() }; - match default_look(bytes, &sensor) { - Some(look) => look.tone.as_ref().map(look_knots).unwrap_or_default(), - None => sensor.tone_curve, + RawDecode::new(bytes).map(|d| d.tone_curve).unwrap_or_default() +} + +/// A raw file decoded once for the open-time Camera Raw dialog: the sensor data, the look fitted +/// to the camera's JPEG (for a file without colour calibration, see [`default_look`]) and the +/// tone curve the default develop uses. The dialog's preview and its Open re-develop +/// ([`import_raw_tuned_from`]) share one instead of decoding and fitting the file again each +/// (the sensor is 2 bytes per pixel: drop it when the dialog closes). +pub struct RawDecode { + fingerprint: Fingerprint, + sensor: Sensor, + look: Option, + tone_curve: Vec<[f32; 2]>, +} + +impl std::fmt::Debug for RawDecode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Not the sensor data: tens of millions of samples. + f.debug_struct("RawDecode").field("fingerprint", &self.fingerprint).field("look", &self.look.is_some()).finish_non_exhaustive() } } +impl RawDecode { + /// Decodes `bytes` and fits its look, as a default open does. + pub fn new(bytes: &[u8]) -> Result { + let sensor = decode_sensor(bytes)?; + let look = default_look(bytes, &sensor); + Ok(RawDecode::from_parts(bytes, sensor, look)) + } + + fn from_parts(bytes: &[u8], sensor: Sensor, look: Option) -> RawDecode { + let tone_curve = match &look { + Some(look) => look.tone.as_ref().map(look_knots).unwrap_or_default(), + None => sensor.tone_curve.clone(), + }; + RawDecode { fingerprint: Fingerprint::of(bytes), sensor, look, tone_curve } + } + + /// The tone curve a default develop uses, as [`tone_curve`] returns it. + pub fn tone_curve(&self) -> &[[f32; 2]] { + &self.tone_curve + } + + /// `true` if this was decoded from `bytes`. + fn is_of(&self, bytes: &[u8]) -> bool { + self.fingerprint == Fingerprint::of(bytes) + } +} + +/// The sensor data of `bytes` under the shared limits. +fn decode_sensor(bytes: &[u8]) -> Result { + DECODES.with(|n| n.set(n.get() + 1)); + photocraft_raw::decode(bytes, &limits()).map_err(IoError::Raw) +} + +thread_local! { + static DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many raw files this thread has decoded so far (for tests that count decodes). +#[doc(hidden)] +pub fn decodes_on_this_thread() -> usize { + DECODES.with(std::cell::Cell::get) +} + +/// A file's length and a 64-bit digest of its bytes: tells the file a [`RawDecode`] was made +/// from from any other (not a cryptographic hash). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Fingerprint(usize, u64); + +impl Fingerprint { + fn of(bytes: &[u8]) -> Fingerprint { + const K: u64 = 0x9E37_79B9_7F4A_7C15; + let mix = |lane: u64, word: u64| (lane ^ word).wrapping_mul(K).rotate_left(29); + let mut lanes = [0x243F_6A88_85A3_08D3u64, 0x1319_8A2E_0370_7344, 0xA409_3822_299F_31D0, 0x082E_FA98_EC4E_6C89]; + let mut chunks = bytes.chunks_exact(32); + for chunk in &mut chunks { + for (lane, w) in lanes.iter_mut().zip(chunk.chunks_exact(8)) { + *lane = mix(*lane, u64::from_le_bytes(w.try_into().expect("8 bytes"))); + } + } + let mut tail = [0u8; 32]; + tail[..chunks.remainder().len()].copy_from_slice(chunks.remainder()); + for (lane, w) in lanes.iter_mut().zip(tail.chunks_exact(8)) { + *lane = mix(*lane, u64::from_le_bytes(w.try_into().expect("8 bytes"))); + } + let digest = lanes.iter().fold(bytes.len() as u64, |acc, &lane| mix(acc, lane)); + Fingerprint(bytes.len(), digest) + } +} + +/// The decodes of the last opens that await their Camera Raw dialog (see +/// [`ImportOptions::keep_raw`](crate::ImportOptions::keep_raw)): at most two, so several raws +/// opened at once each find theirs, and the oldest goes first. The dialog takes its own out. +static KEPT: Mutex>> = Mutex::new(Vec::new()); + +const KEPT_MAX: usize = 2; + +fn kept() -> std::sync::MutexGuard<'static, Vec>> { + KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Hands over (removes) the decode a default open of exactly `bytes` kept for its dialog, if it +/// is still there. Whoever takes it owns the sensor data: dropping it frees it. +pub fn take_kept_decode(bytes: &[u8]) -> Option> { + let want = Fingerprint::of(bytes); + let mut kept = kept(); + let at = kept.iter().position(|d| d.fingerprint == want)?; + Some(kept.remove(at)) +} + /// A fitted look's tone curve as knots for [`photocraft_raw::retone`] (which reads them /// log-linearly): sampled densely enough that the two agree within a fraction of a code value. fn look_knots(t: &photocraft_raw::ToneCurve) -> Vec<[f32; 2]> { @@ -198,6 +321,12 @@ pub fn import_raw_demosaic(name: &str, bytes: &[u8], demosaic: Demosaic) -> Resu import_raw_with(name, bytes, &DevelopOptions { limits: limits(), demosaic, ..Default::default() }) } +/// [`import_raw_demosaic`] that also keeps the sensor data and the fitted look for the file's +/// Camera Raw dialog ([`take_kept_decode`]). +pub fn import_raw_demosaic_keeping(name: &str, bytes: &[u8], demosaic: Demosaic) -> Result { + import_raw_with_inner(name, bytes, &DevelopOptions { limits: limits(), demosaic, ..Default::default() }, true) +} + /// Smallest preview long edge preferred for the colour fit (a smaller preview decodes faster; /// the fit grid is at most `PROXY_EDGE` cells and wants about two pixels per cell). const FIT_PREVIEW_EDGE: u32 = 2 * photocraft_raw::PROXY_EDGE as u32; @@ -244,9 +373,15 @@ pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> R } /// Decodes and develops; a file without colour calibration gets a look fitted to its preview. -fn develop_fitted(bytes: &[u8], opts: &DevelopOptions) -> Result { - let sensor = photocraft_raw::decode(bytes, &opts.limits)?; +/// With `keep`, also hands back the sensor and the look it fitted (the default look, when +/// `opts` named none) instead of freeing them. +fn develop_fitted(bytes: &[u8], opts: &DevelopOptions, keep: bool) -> Result<(photocraft_raw::Developed, Option<(Sensor, Option)>), RawError> { + let sensor = decode_sensor(bytes).map_err(|e| match e { + IoError::Raw(e) => e, + e => RawError::Malformed(e.to_string()), + })?; let mut opts = Cow::Borrowed(opts); + let named_look = opts.camera_look.is_some(); if opts.camera_look.is_none() && sensor.color.calibrations.is_empty() && !sensor.is_monochrome() @@ -254,7 +389,9 @@ fn develop_fitted(bytes: &[u8], opts: &DevelopOptions) -> Result Option { /// Develops a raw file with explicit settings. Without `opts.camera_look`, a file without /// colour calibration gets one fitted to its embedded JPEG when that clearly helps. pub fn import_raw_with(name: &str, bytes: &[u8], opts: &DevelopOptions) -> Result { + import_raw_with_inner(name, bytes, opts, false) +} + +fn import_raw_with_inner(name: &str, bytes: &[u8], opts: &DevelopOptions, keep: bool) -> Result { let format = photocraft_raw::identify(bytes).map(|f| f.name()).unwrap_or("camera raw"); - match develop_fitted(bytes, opts) { - Ok(dev) => { + match develop_fitted(bytes, opts, keep) { + Ok((dev, kept_parts)) => { + if let Some((sensor, look)) = kept_parts { + let mut kept = kept(); + if kept.len() == KEPT_MAX { + kept.remove(0); + } + kept.push(Arc::new(RawDecode::from_parts(bytes, sensor, look))); + } let summary = format!("{DEVELOPED_NOTE} ({} demosaic, as-shot white balance)", opts.demosaic.id()); developed_document(name, bytes, format, dev, &summary) } diff --git a/crates/io/tests/it/raw.rs b/crates/io/tests/it/raw.rs index 29276349934..99bf6e0c321 100644 --- a/crates/io/tests/it/raw.rs +++ b/crates/io/tests/it/raw.rs @@ -436,3 +436,74 @@ fn a_re_develop_keeps_the_fitted_look() { let mid = curve.iter().find(|k| k[0] >= 0.18).unwrap(); assert!(mid[1] > mid[0], "{mid:?}"); } + +/// The open-time Camera Raw dialog decodes the file once, in the open: its preview curve and +/// Open's re-develop reuse that decode and fitted look, and the developed pixels are those of +/// decoding and fitting again (#9432). +#[test] +fn a_kept_decode_gives_the_same_pixels_and_decodes_once() { + use photocraft_io::raw::{ + Demosaic, RawDecode, RawTuning, decodes_on_this_thread, import_raw_demosaic_keeping, import_raw_tuned, import_raw_tuned_from, take_kept_decode, + }; + let pixels = |r: &photocraft_io::ImportResult| photocraft_io::document_to_image(&r.document, &mut Vec::new()).unwrap().data().to_vec(); + + let (w, h) = (480, 320); + let cam = patches(w, h); + let nef = nef_uncompressed(&cam, w, h, Some(camera_rendering(&cam, w, h))); + let (dw, dh) = (40, 24); + let mut dng = DngSpec::cfa(dw, dh, mosaic(&scene(dw, dh), dw, [0, 1, 1, 2], 0, 65535)); + dng.as_shot_neutral = Some([0.6, 1.0, 0.8]); + let dng = dng.build(); + let (cw, ch) = (48, 16); + let cr2 = Cr2Spec { + width: cw, + height: ch, + data: mosaic(&scene(cw, ch), cw, [0, 1, 1, 2], 256, 12000), + precision: 14, + components: 2, + slices: vec![24, 24], + borders: None, + wb_rggb: None, + orientation: 6, + model_id: None, + } + .build(); + + for (name, bytes) in [("a.nef", &nef), ("b.dng", &dng), ("c.cr2", &cr2)] { + // The open, keeping its decode: one decode in all. + let before = decodes_on_this_thread(); + let opened = import_raw_demosaic_keeping(name, bytes, Demosaic::default()).unwrap(); + assert_eq!(decodes_on_this_thread() - before, 1, "{name}: the open"); + let kept = take_kept_decode(bytes).expect("the open kept its decode"); + assert!(take_kept_decode(bytes).is_none(), "{name}: taking it removes it"); + let mut reference = pixels(&import(name, bytes).unwrap()); + assert_eq!(pixels(&opened), reference, "{name}: keeping changes nothing about the open"); + assert_eq!(kept.tone_curve(), photocraft_io::raw::tone_curve(bytes), "{name}: curve"); + + for tuning in [ + RawTuning::default(), + RawTuning { exposure: 0.5, temperature: 20.0, tint: -15.0, shadows: 30.0, clarity: 20.0, ..Default::default() }, + RawTuning { demosaic: Demosaic::Bilinear, highlights: -40.0, ..Default::default() }, + ] { + let (old, old_wb) = import_raw_tuned(name, bytes, &tuning).unwrap(); + let before = decodes_on_this_thread(); + let (new, new_wb) = import_raw_tuned_from(name, bytes, &tuning, &kept).unwrap(); + assert_eq!(decodes_on_this_thread() - before, 0, "{name}: Open decodes nothing again"); + assert_eq!((old_wb, &old.warnings), (new_wb, &new.warnings), "{name}"); + reference = pixels(&old); + assert_eq!(pixels(&new), reference, "{name}: {tuning:?}"); + } + // A decode made from the same bytes later (a miss of the open's) is as good. + let later = RawDecode::new(bytes).unwrap(); + let (a, _) = import_raw_tuned_from(name, bytes, &RawTuning::default(), &later).unwrap(); + assert_eq!(pixels(&a), pixels(&import_raw_tuned(name, bytes, &RawTuning::default()).unwrap().0)); + } + + // A decode of another file is not used for this one. + let other = RawDecode::new(&dng).unwrap(); + let before = decodes_on_this_thread(); + let (got, _) = import_raw_tuned_from("a.nef", &nef, &RawTuning::default(), &other).unwrap(); + assert_eq!(decodes_on_this_thread() - before, 1); + assert_eq!(pixels(&got), pixels(&import_raw_tuned("a.nef", &nef, &RawTuning::default()).unwrap().0)); + assert_eq!((got.document.size.width, got.document.size.height), (w as u32, h as u32)); +} diff --git a/crates/ui-egui/src/camera_raw_identity_tests.rs b/crates/ui-egui/src/camera_raw_identity_tests.rs index 17c4967ba6f..879ac0642af 100644 --- a/crates/ui-egui/src/camera_raw_identity_tests.rs +++ b/crates/ui-egui/src/camera_raw_identity_tests.rs @@ -52,6 +52,7 @@ fn identity_app() -> (PhotocraftApp, RawOpen, Control) { bytes: Some(bytes), developed_with: Default::default(), demosaic: Default::default(), + decoded: None, }; let mut app = PhotocraftApp::new(session, crate::Services::default()); app.sync_views(); @@ -146,7 +147,7 @@ fn queue_identity_targets_an_inactive_raw_without_changing_the_active_document() let (mut app, raw, control) = identity_app(); app.session.set_active(0); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); - queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_deref().map(Vec::as_slice), &[]).unwrap(); + queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_ref(), &[]).unwrap(); let queued = app.pending_raw_open.as_ref().expect("the explicitly named RAW was queued"); assert_eq!(queued.document, raw.document); assert_eq!((&queued.name, &queued.path, &queued.bytes), (&raw.name, &raw.path, &raw.bytes)); @@ -157,12 +158,12 @@ fn queue_identity_targets_an_inactive_raw_without_changing_the_active_document() #[test] fn queue_identity_rejects_a_missing_document_without_replacing_the_pending_review() { let (mut app, raw, control) = identity_app(); - queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_deref().map(Vec::as_slice), &[]).unwrap(); + queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_ref(), &[]).unwrap(); let pending = app.pending_raw_open.as_ref().unwrap().clone(); app.session.set_active(0); let missing = photocraft_doc::DocId::fresh(); assert!(!app.session.documents().iter().any(|state| state.doc.id == missing)); - assert!(queue_open_dialog(&mut app, missing, "missing.dng", Some("missing.dng"), Some(&[1, 2, 3]), &[]).is_err()); + assert!(queue_open_dialog(&mut app, missing, "missing.dng", Some("missing.dng"), Some(&std::sync::Arc::new(vec![1, 2, 3])), &[]).is_err()); let queued = app.pending_raw_open.as_ref().expect("the existing review is preserved"); assert_eq!(queued.document, pending.document); assert_eq!((&queued.name, &queued.path, &queued.bytes), (&pending.name, &pending.path, &pending.bytes)); diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs index f78d467b7c2..f10cad58742 100644 --- a/crates/ui-egui/src/camera_raw_ui.rs +++ b/crates/ui-egui/src/camera_raw_ui.rs @@ -346,6 +346,9 @@ pub struct RawOpen { pub developed_with: photocraft_io::raw::Demosaic, /// The method chosen in the dialog: Open re-develops when it differs from `developed_with`. pub demosaic: photocraft_io::raw::Demosaic, + /// The file decoded once for the dialog's preview and for Open's re-develop (the sensor data + /// is 2 bytes per pixel): freed with the last copy of this, when the dialog closes. + pub decoded: Option>, } /// Should an interactive open of `name` show the open-time Camera Raw dialog? `warnings` are @@ -368,7 +371,7 @@ pub fn queue_open_dialog( document: photocraft_doc::DocId, name: &str, path: Option<&str>, - bytes: Option<&[u8]>, + bytes: Option<&std::sync::Arc>>, warnings: &[String], ) -> Result<(), String> { if document_index(app, document).is_none() { @@ -381,25 +384,31 @@ pub fn queue_open_dialog( document, name: name.to_string(), path: path.map(str::to_string), - bytes: bytes.map(|b| std::sync::Arc::new(b.to_vec())), + bytes: bytes.cloned(), developed_with: method, demosaic: method, + decoded: None, }); Ok(()) } /// Opens the queued open-time dialog on its document's (only) layer. -fn open_raw(app: &mut PhotocraftApp, ctx: &egui::Context, raw: RawOpen) -> Result<(), String> { +fn open_raw(app: &mut PhotocraftApp, ctx: &egui::Context, mut raw: RawOpen) -> Result<(), String> { let index = document_index(app, raw.document).ok_or("the raw document was closed")?; app.session.set_active(index); let (layer, surf, _) = crate::distort_ui::active_pixels(app)?; open_pixels(app, ctx, layer, surf, CameraRaw::default(), Coverage::None, Target::OpenRaw)?; - let curve = match (&raw.bytes, &raw.path) { - (Some(b), _) => Some(photocraft_io::raw::tone_curve(b)), + // The decode the open kept, else (a file opened before the dialog could keep it) one made now. + let file = match (&raw.bytes, &raw.path) { + (Some(b), _) => Some(std::borrow::Cow::Borrowed(b.as_slice())), #[cfg(not(target_arch = "wasm32"))] - (None, Some(p)) => std::fs::read(p).ok().map(|b| photocraft_io::raw::tone_curve(&b)), + (None, Some(p)) => std::fs::read(p).ok().map(std::borrow::Cow::Owned), _ => None, }; + let decoded = + file.as_deref().and_then(|b| photocraft_io::raw::take_kept_decode(b).or_else(|| photocraft_io::raw::RawDecode::new(b).ok().map(std::sync::Arc::new))); + let curve = file.map(|_| decoded.as_ref().map(|d| d.tone_curve().to_vec()).unwrap_or_default()); + raw.decoded = decoded; if let Some(d) = app.camera_raw.as_mut() { d.layer_name = raw.name.clone(); // The full-size preview retones the whole frame with it, as Open will. @@ -481,7 +490,7 @@ fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen) - return finish_open_raw(app, index, params.clone(), None, Some(raw)); }; app.session.set_active(index); - let (name, doc_id) = (raw.name.clone(), raw.document); + let (name, doc_id, decoded) = (raw.name.clone(), raw.document, raw.decoded.clone()); let work = move |ctx: &photocraft_engine::jobs::JobCtx| -> photocraft_engine::Result<(photocraft_io::ImportResult, bool)> { ctx.progress(0.0, "Reading"); let bytes = match source { @@ -495,7 +504,11 @@ fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: &RawOpen) - }; ctx.check()?; ctx.progress(0.05, "Developing"); - photocraft_io::raw::import_raw_tuned(&name, &bytes, &tuning).map_err(|e| photocraft_engine::EngineError::Other(e.to_string())) + match &decoded { + Some(d) => photocraft_io::raw::import_raw_tuned_from(&name, &bytes, &tuning, d), + None => photocraft_io::raw::import_raw_tuned(&name, &bytes, &tuning), + } + .map_err(|e| photocraft_engine::EngineError::Other(e.to_string())) }; let apply = move |s: &mut photocraft_engine::Session, (r, wb): (photocraft_io::ImportResult, bool)| replace_raw_document(s, doc_id, r, wb); let label = crate::i18n::fmt(tl!("Developing {name}"), &[("name", &raw.name)]); @@ -1891,6 +1904,39 @@ mod tests { (0..32).flat_map(|y| (0..48).map(move |x| (x, y))).flat_map(|(x, y)| s.rgba(x, y)).collect() } + /// #9432: a raw open decodes the file once. The dialog's preview curve and Open's re-develop + /// reuse the open's sensor data and look, give the pixels of decoding again, and let go of + /// the sensor data when the dialog closes. + #[test] + fn a_raw_open_decodes_the_file_once_and_frees_it_with_the_dialog() { + use photocraft_io::raw::decodes_on_this_thread; + let ctx = egui::Context::default(); + let develop = |reuse: bool, commit: bool| { + let (mut app, dng) = raw_app(); + let before = decodes_on_this_thread(); + app.open_bytes("IMG_0007.dng", &dng).unwrap(); + let raw = app.pending_raw_open.take().unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + let raw_open = app.camera_raw.as_mut().unwrap().raw_open.as_mut().unwrap(); + let sensor = raw_open.decoded.as_ref().map(std::sync::Arc::downgrade).expect("the dialog holds the open's decode"); + if !reuse { + raw_open.decoded = None; + } + assert!(sensor.upgrade().is_some() || !reuse); + let ui = if commit { json!({"set": {"exposure": 1.0, "temperature": 30}, "commit": true}) } else { json!({"cancel": true}) }; + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": ui})).unwrap().unwrap(); + assert!(app.camera_raw.is_none()); + assert!(sensor.upgrade().is_none(), "the sensor data is freed when the dialog is closed"); + (decodes_on_this_thread() - before, if commit { pixels(&app) } else { Vec::new() }) + }; + let (decodes, reused) = develop(true, true); + assert_eq!(decodes, 1, "open, dialog and commit share one decode"); + let (decodes, again) = develop(false, true); + assert_eq!(decodes, 2, "without the kept decode the commit decodes again"); + assert_eq!(reused, again, "the same pixels either way"); + assert_eq!(develop(true, false).0, 1, "Cancel decodes nothing more"); + } + #[test] fn the_demosaic_method_is_chosen_at_open() { let (mut app, dng) = raw_app(); @@ -1931,7 +1977,7 @@ mod tests { app.pending_raw_open.take(); app.run("prefs.set", json!({"path": "rawDefaults.demosaic", "value": "ahd"})).unwrap(); let document = app.session.active().unwrap().doc.id; - queue_open_dialog(&mut app, document, "IMG_0004.dng", None, Some(&dng), &warnings).unwrap(); + queue_open_dialog(&mut app, document, "IMG_0004.dng", None, Some(&std::sync::Arc::new(dng.clone())), &warnings).unwrap(); let raw = app.pending_raw_open.take().unwrap(); use photocraft_io::raw::Demosaic; assert_eq!((raw.developed_with, raw.demosaic), (Demosaic::Bilinear, Demosaic::Bilinear)); @@ -2066,7 +2112,8 @@ mod tests { path: None, bytes: None, developed_with: Default::default(), - demosaic: Default::default() + demosaic: Default::default(), + decoded: None, } ) .is_err() diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index 980aff20eb1..323f9992507 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -595,7 +595,7 @@ pub(crate) fn after_open( name: &str, path: Option<&str>, warnings: &[String], - bytes: Option<&[u8]>, + bytes: Option<&Arc>>, ) -> Result<(), String> { let index = app.session.documents().iter().position(|st| st.doc.id == document).ok_or("the opened document is missing")?; app.session.set_active(index); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4db3dc2a344..fa1248027d9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1628,7 +1628,10 @@ impl PhotocraftApp { return Ok(Vec::new()); } let import = self.services.import.as_ref().ok_or("no importer configured")?; - let opts = photocraft_engine::jobs::import_options(self.session.prefs()); + let opts = photocraft_io::ImportOptions { + keep_raw: self.session.prefs().raw_defaults.open_in_camera_raw, + ..photocraft_engine::jobs::import_options(self.session.prefs()) + }; let (mut doc, warnings, damaged) = if photocraft_io::is_psd(bytes) { // Read PSD damage as structured information in the same decode, not by // retrying an error or matching the text of a compatibility warning. diff --git a/crates/ui-egui/src/open_prompt.rs b/crates/ui-egui/src/open_prompt.rs index ef04f0b5767..c3f1500752e 100644 --- a/crates/ui-egui/src/open_prompt.rs +++ b/crates/ui-egui/src/open_prompt.rs @@ -264,6 +264,6 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result index, }; app.session.set_active(index); - crate::jobs_ui::after_open(app, document, &name, path.as_deref(), &warnings, bytes.as_deref().map(Vec::as_slice))?; + crate::jobs_ui::after_open(app, document, &name, path.as_deref(), &warnings, bytes.as_ref())?; Ok(json!({"document": index, "action": action})) } From 6bc424285dba0abbe5a5c6d446967f2dab595187 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 25 Oct 2026 15:17:02 +0100 Subject: [PATCH 08/65] Camera Raw open: keep clippy and test-isolation fixes Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/raw.rs | 22 ++++++++++++---------- crates/ui-egui/src/camera_raw_ui.rs | 4 +++- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rs index 1f9c328fd97..3486bf546d9 100644 --- a/crates/io/src/raw.rs +++ b/crates/io/src/raw.rs @@ -220,17 +220,16 @@ impl Fingerprint { const K: u64 = 0x9E37_79B9_7F4A_7C15; let mix = |lane: u64, word: u64| (lane ^ word).wrapping_mul(K).rotate_left(29); let mut lanes = [0x243F_6A88_85A3_08D3u64, 0x1319_8A2E_0370_7344, 0xA409_3822_299F_31D0, 0x082E_FA98_EC4E_6C89]; - let mut chunks = bytes.chunks_exact(32); - for chunk in &mut chunks { - for (lane, w) in lanes.iter_mut().zip(chunk.chunks_exact(8)) { - *lane = mix(*lane, u64::from_le_bytes(w.try_into().expect("8 bytes"))); + let (blocks, rest) = bytes.as_chunks::<32>(); + let mut absorb = |block: &[u8; 32]| { + for (lane, word) in lanes.iter_mut().zip(block.as_chunks::<8>().0) { + *lane = mix(*lane, u64::from_le_bytes(*word)); } - } + }; + blocks.iter().for_each(&mut absorb); let mut tail = [0u8; 32]; - tail[..chunks.remainder().len()].copy_from_slice(chunks.remainder()); - for (lane, w) in lanes.iter_mut().zip(tail.chunks_exact(8)) { - *lane = mix(*lane, u64::from_le_bytes(w.try_into().expect("8 bytes"))); - } + tail[..rest.len()].copy_from_slice(rest); + absorb(&tail); let digest = lanes.iter().fold(bytes.len() as u64, |acc, &lane| mix(acc, lane)); Fingerprint(bytes.len(), digest) } @@ -372,10 +371,13 @@ pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> R photocraft_raw::fit_look(sensor, opts, &Reference { width: w, height: h, rgb: &rgb }).map_err(|e| e.to_string()) } +/// A sensor and the look fitted to it, as [`develop_fitted`] hands them back. +type Kept = (Sensor, Option); + /// Decodes and develops; a file without colour calibration gets a look fitted to its preview. /// With `keep`, also hands back the sensor and the look it fitted (the default look, when /// `opts` named none) instead of freeing them. -fn develop_fitted(bytes: &[u8], opts: &DevelopOptions, keep: bool) -> Result<(photocraft_raw::Developed, Option<(Sensor, Option)>), RawError> { +fn develop_fitted(bytes: &[u8], opts: &DevelopOptions, keep: bool) -> Result<(photocraft_raw::Developed, Option), RawError> { let sensor = decode_sensor(bytes).map_err(|e| match e { IoError::Raw(e) => e, e => RawError::Malformed(e.to_string()), diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs index f10cad58742..93e5548871b 100644 --- a/crates/ui-egui/src/camera_raw_ui.rs +++ b/crates/ui-egui/src/camera_raw_ui.rs @@ -1912,7 +1912,9 @@ mod tests { use photocraft_io::raw::decodes_on_this_thread; let ctx = egui::Context::default(); let develop = |reuse: bool, commit: bool| { - let (mut app, dng) = raw_app(); + let (mut app, mut dng) = raw_app(); + // Kept decodes are found by file contents: other tests open the same synthetic DNG. + dng.extend_from_slice(b"a_raw_open_decodes_the_file_once"); let before = decodes_on_this_thread(); app.open_bytes("IMG_0007.dng", &dng).unwrap(); let raw = app.pending_raw_open.take().unwrap(); From 13f7ce7a32bf0b27f63196554757aeac0bb9d2e1 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 01:48:12 +0100 Subject: [PATCH 09/65] Camera Raw single decode: restore io examples, init RawOpen.decoded in the no-dialog open Co-Authored-By: Claude Sonnet 5.5 --- crates/io/examples/bench_abr.rs | 123 ++++++ crates/io/examples/bench_shuffles.rs | 54 +++ crates/io/examples/big_psb_check.rs | 80 ++++ crates/io/examples/gen_abr_library.rs | 163 ++++++++ crates/io/examples/oracle_diff.rs | 514 ++++++++++++++++++++++++++ crates/io/examples/rawlook.rs | 237 ++++++++++++ crates/ui-egui/src/camera_raw_ui.rs | 3 +- 7 files changed, 1173 insertions(+), 1 deletion(-) create mode 100644 crates/io/examples/bench_abr.rs create mode 100644 crates/io/examples/bench_shuffles.rs create mode 100644 crates/io/examples/big_psb_check.rs create mode 100644 crates/io/examples/gen_abr_library.rs create mode 100644 crates/io/examples/oracle_diff.rs create mode 100644 crates/io/examples/rawlook.rs diff --git a/crates/io/examples/bench_abr.rs b/crates/io/examples/bench_abr.rs new file mode 100644 index 00000000000..0811cb0ae80 --- /dev/null +++ b/crates/io/examples/bench_abr.rs @@ -0,0 +1,123 @@ +//! Brush import and painting benchmark: parse + map a synthetic 100-brush ABR v6 file (256 px +//! RLE-compressed tips, full dynamics descriptors), then paint a 5000-dab stroke with an imported +//! brush on a 6000×6000 RGBA8 layer. +//! +//! `cargo run --release -p photocraft-io --example bench_abr` +#![allow(clippy::unwrap_used)] + +use std::time::Instant; + +use photocraft_color::PixelFormat; +use photocraft_paint::{StrokePoint, render_stroke}; +use photocraft_psd::abr::{AbrSample, write_v6}; +use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; +use photocraft_raster::Surface; + +fn prc(v: f64) -> Value { + Value::UnitFloat { unit: *b"#Prc", value: v } +} + +fn var(control: i32, jitter: f64) -> Value { + Value::Descriptor(Descriptor::new("brVr").with("bVTy", Value::Integer(control)).with("jitter", prc(jitter))) +} + +fn main() { + let n = 256u32; + let samples: Vec = (0..100) + .map(|i| { + let data = (0..n * n) + .map(|k| { + let (x, y) = ((k % n) as f32 - 128.0, (k / n) as f32 - 128.0); + let r = (x * x + y * y).sqrt() / 128.0; + (((1.0 - r) * 255.0).clamp(0.0, 255.0) as u8) & if (k + i) % 7 == 0 { 0x7f } else { 0xff } + }) + .collect(); + AbrSample { id: format!("$tip-{i}"), width: n, height: n, depth: 8, data } + }) + .collect(); + let presets: Vec = (0..100) + .map(|i| { + Descriptor::new("brushPreset") + .with("Nm ", Value::Text(UnicodeString::new_nul(&format!("Brush {i}")))) + .with( + "Brsh", + Value::Descriptor( + Descriptor::new("sampledBrush") + .with("Dmtr", Value::UnitFloat { unit: *b"#Pxl", value: 60.0 }) + .with("Spcn", prc(25.0)) + .with("sampledData", Value::Text(UnicodeString::new_nul(&format!("$tip-{i}")))), + ), + ) + .with("useTipDynamics", Value::Boolean(true)) + .with("szVr", var(2, 20.0)) + .with("angleDynamics", var(0, 100.0)) + .with("useScatter", Value::Boolean(true)) + .with("scatterDynamics", var(0, 120.0)) + .with("Cnt ", Value::Integer(2)) + .with("usePaintDynamics", Value::Boolean(true)) + .with("opVr", var(2, 0.0)) + }) + .collect(); + let bytes = write_v6(2, &samples, &[], &presets, true).unwrap(); + // `--write `: also save a small showcase file (procedural tips) for UI snapshots. + let args: Vec = std::env::args().collect(); + if let Some(path) = args.iter().position(|a| a == "--write").and_then(|i| args.get(i + 1)) { + use photocraft_paint::procedural::*; + let tips = [("Leafy", leaf_tip(96)), ("Charcoal Stick", charcoal_tip(96, 3)), ("Sea Sponge", sponge_tip(96, 5)), ("Star Burst", star_tip(96))]; + let samples: Vec = tips + .iter() + .enumerate() + .map(|(i, (_, t))| AbrSample { + id: format!("$show-{i}"), + width: t.width, + height: t.height, + depth: 16, + data: t.data.iter().flat_map(|v| v.to_be_bytes()).collect(), + }) + .collect(); + let presets: Vec = tips + .iter() + .enumerate() + .map(|(i, (name, _))| { + let mut d = presets[i].clone(); + d.items.retain(|(k, _)| !k.is("Nm ") && !k.is("Brsh")); + d.with("Nm ", Value::Text(UnicodeString::new_nul(name))).with( + "Brsh", + Value::Descriptor( + Descriptor::new("sampledBrush") + .with("Dmtr", Value::UnitFloat { unit: *b"#Pxl", value: 50.0 }) + .with("Spcn", prc(if i == 1 { 10.0 } else { 45.0 })) + .with("sampledData", Value::Text(UnicodeString::new_nul(&format!("$show-{i}")))), + ), + ) + }) + .collect(); + std::fs::write(path, write_v6(2, &samples, &[], &presets, true).unwrap()).unwrap(); + println!("wrote {path}"); + } + let mut best = f64::MAX; + let mut imp = None; + for _ in 0..5 { + let t = Instant::now(); + imp = Some(photocraft_io::abr_map::read_abr(&bytes, "Bench").unwrap()); + best = best.min(t.elapsed().as_secs_f64() * 1000.0); + } + let imp = imp.unwrap(); + println!("ABR import: {} brushes, {:.1} MB file, best of 5: {best:.1} ms", imp.presets.len(), bytes.len() as f64 / 1e6); + + // A long pressure-varied stroke with the first imported brush (size, angle, scatter, opacity dynamics). + let mut brush = imp.presets[0].brush.clone(); + brush.seed = 1; + let mut s = Surface::new(PixelFormat::RGBA8); + let size = 6000.0; + let pts: Vec = (0..=2000) + .map(|i| { + let t = i as f64 / 2000.0; + StrokePoint::new(200.0 + t * (size - 400.0), size / 2.0 + (t * 24.0).sin() * 1500.0, (0.3 + 0.7 * (t * 25.0).sin().abs()) as f32) + }) + .collect(); + let dabs = photocraft_paint::dabs(&photocraft_paint::Stroke { brush: brush.clone(), points: pts.clone() }).len(); + let t = Instant::now(); + render_stroke(&mut s, &brush, &pts, None, false, 1.0); + println!("Stroke: {dabs} primary dabs (scatter count 2), {:.1} ms", t.elapsed().as_secs_f64() * 1000.0); +} diff --git a/crates/io/examples/bench_shuffles.rs b/crates/io/examples/bench_shuffles.rs new file mode 100644 index 00000000000..9bd29fecee1 --- /dev/null +++ b/crates/io/examples/bench_shuffles.rs @@ -0,0 +1,54 @@ +//! BEFORE/AFTER helper for the banded interleave/deinterleave: `--serial` runs the old +//! sequential implementation inline, the default runs the current parallel one. +fn main() { + use photocraft_color::SampleType; + let serial = std::env::args().any(|a| a == "--serial"); + for (label, s, ch) in [("u16 rgb", SampleType::U16, 3usize), ("f32 rgba", SampleType::F32, 4)] { + let bps = s.bytes(); + let n = 20_000_000usize; + let planes: Vec> = (0..ch).map(|c| (0..n * bps).map(|i| (i * 7 + c) as u8).collect()).collect(); + let refs: Vec> = planes.iter().map(|p| Some(&p[..])).collect(); + let fill: Vec> = (0..ch).map(|_| vec![0u8; bps]).collect(); + let invert = [false; 4]; + let t0 = std::time::Instant::now(); + let interleaved = if serial { + let mut out = vec![0u8; n * ch * bps]; + for (c, plane) in refs.iter().enumerate() { + for i in 0..n { + let dst = &mut out[(i * ch + c) * bps..(i * ch + c + 1) * bps]; + if let Some(p) = plane + && p.len() >= (i + 1) * bps + { + let src = &p[i * bps..(i + 1) * bps]; + for k in 0..bps { + dst[k] = src[bps - 1 - k]; + } + } + } + } + out + } else { + photocraft_io::pixels::interleave(&refs, &fill, n, s, &invert) + }; + let t1 = t0.elapsed().as_secs_f64() * 1000.0; + let t2 = std::time::Instant::now(); + if serial { + let mut acc: Vec> = Vec::new(); + for _ in 0..ch { + acc.push(Vec::with_capacity(n * bps)); + } + let mut tmp = [0u8; 4]; + for i in 0..n { + for (c, plane) in acc.iter_mut().enumerate() { + let src = &interleaved[(i * ch + c) * bps..(i * ch + c + 1) * bps]; + tmp[..bps].copy_from_slice(src); + plane.extend(tmp[..bps].iter().rev()); + } + } + } else { + let _ = photocraft_io::pixels::deinterleave(&interleaved, ch, s, &invert); + } + let t3 = t2.elapsed().as_secs_f64() * 1000.0; + println!("{label}: interleave {t1:.1} ms, deinterleave {t3:.1} ms (20 MP, release, {})", if serial { "serial (before)" } else { "parallel (after)" }); + } +} diff --git a/crates/io/examples/big_psb_check.rs b/crates/io/examples/big_psb_check.rs new file mode 100644 index 00000000000..3b1c21034b0 --- /dev/null +++ b/crates/io/examples/big_psb_check.rs @@ -0,0 +1,80 @@ +//! Opens the files written by `photocraft-psd`'s `big_psb` example and checks their pixels. +//! +//! `cargo run --release -p photocraft-io --example big_psb_check -- ...` +//! +//! The opt-in tests in `tests/it/large_files.rs` generate and check the same files. + +use photocraft_psd::fixtures::sample; + +fn main() { + for path in std::env::args().skip(1) { + let rle = path.contains("rle"); + let t = std::time::Instant::now(); + let bytes = match std::fs::read(&path) { + Ok(b) => b, + Err(e) => { + println!("{path}: read failed: {e}"); + continue; + } + }; + let read_s = t.elapsed().as_secs_f64(); + let t = std::time::Instant::now(); + let res = match photocraft_io::import(&path, &bytes) { + Ok(r) => r, + Err(e) => { + println!("{path}: import failed: {e}"); + continue; + } + }; + drop(bytes); + // With SAVE set: save as PSB, then check the re-opened file instead. + let res = if std::env::var_os("SAVE").is_some() { + let t = std::time::Instant::now(); + let out = match photocraft_io::export(&res.document, "x.psb", &photocraft_io::ExportOptions::default()) { + Ok(o) => o, + Err(e) => { + println!("{path}: save failed: {e}"); + continue; + } + }; + println!("{path}: saved {:.2} GB in {:.1} s, warnings {:?}", out.bytes.len() as f64 / 1e9, t.elapsed().as_secs_f64(), out.warnings); + drop(res); + match photocraft_io::import("x.psb", &out.bytes) { + Ok(r) => r, + Err(e) => { + println!("{path}: re-open failed: {e}"); + continue; + } + } + } else { + res + }; + let doc = &res.document; + println!( + "{path}: read {read_s:.1} s, import {:.1} s, {}x{}, {} layer(s)", + t.elapsed().as_secs_f64(), + doc.size.width, + doc.size.height, + doc.layers.len() + ); + for w in &res.warnings { + println!(" warning: {w}"); + } + let Some(s) = doc.layers.first().and_then(|l| l.surface()) else { + println!(" FAIL: no pixel layer"); + continue; + }; + let (w, h) = (doc.size.width, doc.size.height); + let mut bad = 0; + let points = [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1), (w / 2, h / 2), (w / 3, h * 2 / 3), (12_345 % w, (h - 7) % h)]; + for &(x, y) in &points { + let got = s.pixel(x as i32, y as i32); + let want: Vec = (0..4).map(|c| f32::from(sample(x, y, c, rle)) / 255.0).collect(); + if got.len() != 4 || got.iter().zip(&want).any(|(g, w)| (g - w).abs() > 1.0 / 510.0) { + bad += 1; + println!(" mismatch at ({x}, {y}): got {got:?}, want {want:?}"); + } + } + println!(" {}", if bad == 0 { "OK: all sampled pixels match" } else { "FAIL" }); + } +} diff --git a/crates/io/examples/gen_abr_library.rs b/crates/io/examples/gen_abr_library.rs new file mode 100644 index 00000000000..cbb2ad303c6 --- /dev/null +++ b/crates/io/examples/gen_abr_library.rs @@ -0,0 +1,163 @@ +//! Generates a large, redistributable ABR v6 brush library for memory and import testing (#1843). +//! +//! Real painting packs are commercial or "personal use only", so we can't test against them. This +//! writes a deterministic stand-in with the same shape: hundreds of presets with big 16-bit sampled +//! tips (RLE-compressed, like Photoshop CC), full dynamics descriptors, split over several files. +//! Every tip comes from `photocraft_paint::procedural` (original, seeded generators), so the output +//! carries no third-party rights. Nothing it writes is committed; regenerate it when needed. +//! +//! `cargo run --release -p photocraft-io --example gen_abr_library -- --out ` +//! +//! Options (defaults in brackets): `--brushes N` [600], `--edge PX` largest tip edge [2000], +//! `--min-edge PX` smallest tip edge [800], `--depth 8|16` [16], `--per-file N` presets per file [100], +//! `--raw` store tips uncompressed (bigger files). Each file stays under the reader's decoded cap (1 GiB; 512 MiB on 32-bit). +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use photocraft_paint::procedural::*; +use photocraft_paint::tile::GrayTile; +use photocraft_psd::abr::{AbrSample, MAX_TOTAL_BYTES, write_v6}; +use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; +use std::path::PathBuf; +use std::time::Instant; + +const KINDS: [&str; 9] = ["Chalk", "Spatter", "Bristle", "Charcoal", "Leaf", "Grass", "Sponge", "Star", "Rake"]; + +fn tip(kind: usize, n: u32, seed: u32) -> GrayTile { + match kind { + 0 => chalk_tip(n, seed), + 1 => spatter_tip(n, seed, 20 + seed % 40), + 2 => bristle_tip(n, seed), + 3 => charcoal_tip(n, seed), + 4 => leaf_tip(n), + 5 => grass_tip(n, seed, 8 + seed % 16), + 6 => sponge_tip(n, seed), + 7 => star_tip(n), + _ => rake_tip(n, seed, 6 + seed % 12), + } +} + +fn prc(v: f64) -> Value { + Value::UnitFloat { unit: *b"#Prc", value: v } +} + +fn var(control: i32, jitter: f64) -> Value { + Value::Descriptor(Descriptor::new("brVr").with("bVTy", Value::Integer(control)).with("jitter", prc(jitter))) +} + +fn text(s: &str) -> Value { + Value::Text(UnicodeString::new_nul(s)) +} + +/// A cheap deterministic 0..1 value per (brush, salt), to vary the presets. +fn h(i: u32, salt: u32) -> f64 { + let mut x = (u64::from(i) << 32 | u64::from(salt)).wrapping_mul(0x9E37_79B9_7F4A_7C15); + x ^= x >> 31; + x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9); + x ^= x >> 29; + (x % 10_000) as f64 / 10_000.0 +} + +fn preset(i: u32, id: &str, name: &str, edge: u32) -> Descriptor { + let mut d = Descriptor::new("brushPreset").with("Nm ", text(name)).with( + "Brsh", + Value::Descriptor( + Descriptor::new("sampledBrush") + .with("Dmtr", Value::UnitFloat { unit: *b"#Pxl", value: f64::from(edge) * (0.1 + 0.4 * h(i, 1)) }) + .with("Angl", Value::UnitFloat { unit: *b"#Ang", value: (h(i, 2) * 360.0 - 180.0).round() }) + .with("Rndn", prc((50.0 + 50.0 * h(i, 3)).round())) + .with("Spcn", prc((5.0 + 60.0 * h(i, 4)).round())) + .with("Intr", Value::Boolean(true)) + .with("flipX", Value::Boolean(h(i, 5) < 0.2)) + .with("sampledData", text(id)), + ), + ); + d = d.with("useTipDynamics", Value::Boolean(true)).with("szVr", var(2, (h(i, 6) * 40.0).round())).with("angleDynamics", var(0, (h(i, 7) * 100.0).round())); + if h(i, 8) < 0.5 { + d = d + .with("useScatter", Value::Boolean(true)) + .with("scatterDynamics", var(0, (h(i, 9) * 200.0).round())) + .with("Cnt ", Value::Integer(1 + (h(i, 10) * 4.0) as i32)); + } + if h(i, 11) < 0.6 { + d = d.with("usePaintDynamics", Value::Boolean(true)).with("opVr", var(2, 0.0)).with("prVr", var(2, 0.0)); + } + d +} + +fn main() { + let args: Vec = std::env::args().collect(); + let arg = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned(); + let num = |name: &str, default: u32| arg(name).map_or(default, |v| v.parse().expect("numeric option")); + let out = PathBuf::from(arg("--out").unwrap_or_else(|| "target/abr-library".into())); + let brushes = num("--brushes", 600); + let max_edge = num("--edge", 2000).clamp(16, photocraft_psd::abr::MAX_EDGE); + let min_edge = num("--min-edge", 800).clamp(16, max_edge); + let depth = num("--depth", 16) as u16; + assert!(matches!(depth, 8 | 16), "--depth must be 8 or 16"); + let per_file = num("--per-file", 100).max(1); + let rle = !args.iter().any(|a| a == "--raw"); + std::fs::create_dir_all(&out).unwrap(); + + let started = Instant::now(); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); + let (mut file_no, mut first, mut total_bytes, mut total_decoded) = (0u32, 0u32, 0u64, 0u64); + while first < brushes { + // Fill one file up to `per_file` presets, keeping its decoded samples well under the reader's cap. + let mut ids = Vec::new(); + let mut decoded = 0usize; + let mut i = first; + while i < brushes && ids.len() < per_file as usize { + let edge = min_edge + ((max_edge - min_edge) as f64 * h(i, 0)) as u32; + let bytes = edge as usize * edge as usize * usize::from(depth / 8); + if !ids.is_empty() && decoded + bytes > MAX_TOTAL_BYTES * 3 / 4 { + break; + } + decoded += bytes; + ids.push((i, edge)); + i += 1; + } + let samples: Vec = std::thread::scope(|s| { + let chunk = ids.len().div_ceil(threads); + let handles: Vec<_> = ids + .chunks(chunk) + .map(|part| { + s.spawn(move || { + part.iter() + .map(|&(i, edge)| { + let t = tip(i as usize % KINDS.len(), edge, i); + let data = if depth == 16 { + t.data.iter().flat_map(|v| v.to_be_bytes()).collect() + } else { + t.data.iter().map(|v| (v >> 8) as u8).collect() + }; + AbrSample { id: format!("$pc-gen-{i:05}"), width: edge, height: edge, depth, data } + }) + .collect::>() + }) + }) + .collect(); + handles.into_iter().flat_map(|h| h.join().unwrap()).collect() + }); + let presets: Vec = ids + .iter() + .map(|&(i, edge)| preset(i, &format!("$pc-gen-{i:05}"), &format!("{} {:03} ({edge} px)", KINDS[i as usize % KINDS.len()], i + 1), edge)) + .collect(); + let bytes = write_v6(2, &samples, &[], &presets, rle).unwrap(); + // Sanity: our own importer must accept every preset. + let imported = photocraft_io::abr_map::read_abr(&bytes, "Generated").unwrap(); + assert_eq!(imported.presets.len(), ids.len(), "every generated preset imports"); + file_no += 1; + let path = out.join(format!("photocraft-test-brushes-{file_no:02}.abr")); + std::fs::write(&path, &bytes).unwrap(); + println!("{}: {} brushes, {:.1} MB on disk, {:.1} MB decoded", path.display(), ids.len(), bytes.len() as f64 / 1e6, decoded as f64 / 1e6); + total_bytes += bytes.len() as u64; + total_decoded += decoded as u64; + first = i; + } + println!( + "{brushes} brushes in {file_no} files: {:.1} MB on disk, {:.1} MB of decoded tips, {:.1} s", + total_bytes as f64 / 1e6, + total_decoded as f64 / 1e6, + started.elapsed().as_secs_f64() + ); +} diff --git a/crates/io/examples/oracle_diff.rs b/crates/io/examples/oracle_diff.rs new file mode 100644 index 00000000000..fddef567a96 --- /dev/null +++ b/crates/io/examples/oracle_diff.rs @@ -0,0 +1,514 @@ +//! Compare our composite with Photoshop's merged image for one PSD (rendering-fidelity work). +//! +//! ```sh +//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd [N] # layers + first N pixels +//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 png out.png # ours | Photoshop | diff heatmap +//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 col [x] # column samples +//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 row y x0 x1 # row samples +//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 worst [n] # n worst pixels +//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 grid x0 y0 x1 y1 [ch] # value grids +//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 layerpx x y # each layer's pixel +//! cargo run --release -p photocraft-io --example oracle_diff -- corpus/psd # every file: max err, bad %, PASS/DIFF +//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 dump prefix # raw f32 planes for offline fitting +//! cargo run --release -p photocraft-io --example oracle_diff -- file.psd 0 bylayer # max error around each layer +//! SCALE=4 … # upscale the png +//! HIDE_ADJ=1 … # adjustment layers hidden +//! ONLY="name,name" … # only these top-level layers (+ the bottom one) +//! DUMP_FX=1 … # raw effects descriptors +//! ``` +fn main() { + let path = std::env::args().nth(1).expect("path"); + if std::path::Path::new(&path).is_dir() { + corpus_summary(std::path::Path::new(&path)); + return; + } + let bytes = std::fs::read(&path).unwrap(); + let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let mut imp = photocraft_io::import(&path, &bytes).unwrap(); + if std::env::var_os("HIDE_ADJ").is_some() { + // Composite without adjustment layers (their input, for fitting transfer curves). + fn hide(ls: &mut [photocraft_doc::Layer]) { + for l in ls { + if matches!(l.content, photocraft_doc::LayerContent::Adjustment(_)) { + l.visible = false; + } + if let photocraft_doc::LayerContent::Group(g) = &mut l.content { + hide(&mut g.children); + } + } + } + hide(&mut imp.document.layers); + } + if let Some(keep) = std::env::var_os("ONLY") { + // Hide every top-level layer but the bottom one and those named in ONLY (comma-separated). + let keep = keep.to_string_lossy().to_string(); + let names: Vec<&str> = keep.split(',').collect(); + for l in imp.document.layers.iter_mut().skip(1) { + l.visible = names.contains(&l.name.as_str()); + } + } + let doc = &imp.document; + println!("mode {:?} depth {:?} layers {} warnings {:?} light {:?}", doc.mode, doc.depth, doc.layer_count(), imp.warnings, doc.global_light); + for l in doc.walk() { + let l = l.2; + println!( + " layer {:?} {:?} blend {:?} op {} fill {} fill_cache {} visible {}", + l.name, + l.content.kind_name(), + l.blend, + l.opacity, + l.fill_opacity, + l.fill_cache.is_some(), + l.visible + ); + if let photocraft_doc::LayerContent::Adjustment(a) = &l.content { + println!(" {}", format!("{a:?}").chars().take(800).collect::()); + } + if let photocraft_doc::LayerContent::Fill(f) = &l.content { + println!(" {f:?}"); + } + if let Some(m) = &l.mask { + println!(" mask default {:?} bounds {:?} enabled {}", m.surface.default_pixel(), m.surface.content_bounds(), m.enabled); + let b = m.surface.content_bounds(); + let cx = (b.x0 + b.x1) / 2; + let col: Vec = (b.y0..b.y0 + 6).chain(b.y1 - 6..b.y1).map(|y| format!("{y}:{:.2}", m.surface.pixel(cx, y)[0])).collect(); + println!(" mask column x={cx}: {}", col.join(" ")); + let row: Vec = (b.x0..b.x0 + 4).chain(b.x1 - 4..b.x1).map(|x| format!("{x}:{:.2}", m.surface.pixel(x, (b.y0 + b.y1) / 2)[0])).collect(); + println!(" mask row: {}", row.join(" ")); + } + if let Some(sf) = l.surface() { + let b = sf.content_bounds(); + let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); + for y in b.y0..b.y1 { + for x in b.x0..b.x1 { + let p = sf.pixel(x, y); + if p[p.len() - 1] > 0.0 { + (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)); + } + } + } + println!(" alpha bounds ({x0},{y0})-({x1},{y1})"); + } + if let photocraft_doc::LayerContent::Shape(sh) = &l.content { + println!( + " shape path bounds {:?} subpaths {} rule {:?} inverted {} fill {} stroke {} outline {}", + sh.path.control_bounds(), + sh.path.subpaths.len(), + sh.path.fill_rule, + sh.path.inverted, + sh.fill.is_some(), + sh.stroke.is_some(), + photocraft_compose::effect_outline(l).is_some() + ); + if std::env::var_os("PATHS").is_some() { + for s in &sh.path.subpaths { + println!(" subpath {:?} closed {} knots {:?}", s.op, s.closed, s.knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect::>()); + } + } + } + if let Some(vm) = &l.vector_mask { + println!(" vector mask bounds {:?}", vm.path.control_bounds()); + } + println!(" clipped {} frame {:?} bounds {:?}", l.clipped, photocraft_compose::fill_frame(l, doc.bounds()), l.surface().map(|s| s.content_bounds())); + for e in &l.effects.items { + if let photocraft_doc::Effect::GradientOverlay { common, gradient, .. } = e + && common.enabled + { + let g = format!("{gradient:?}"); + println!(" gradient overlay: {g}"); + } else if format!("{e:?}").contains("enabled: true") { + println!(" fx {}", format!("{e:?}").chars().take(if std::env::var_os("FULL").is_some() { 100_000 } else { 200 }).collect::()); + } + } + println!(" blocks {:?}", l.psd_blocks.iter().map(|(k, v)| format!("{}({})", String::from_utf8_lossy(k), v.len())).collect::>()); + for (k, v) in &l.psd_blocks { + if k == b"lfx2" || k == b"lmfx" { + // Recursively list descriptor keys (effects), skipping colour stop lists. + fn walk(d: &photocraft_psd::descriptor::Descriptor, depth: usize, out: &mut Vec) { + for (k, v) in &d.items { + let key = match k { + photocraft_psd::descriptor::Id::Code(c) => String::from_utf8_lossy(c).to_string(), + other => String::from_utf8_lossy(other.as_bytes()).to_string(), + }; + let vs = format!("{v:?}"); + match v { + photocraft_psd::descriptor::Value::Descriptor(sub) => { + out.push(format!("{}{key}:", " ".repeat(depth))); + walk(sub, depth + 1, out); + } + _ => out.push(format!("{}{key} = {}", " ".repeat(depth), vs.chars().take(90).collect::())), + } + } + } + if let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(&v[4..]) { + let mut out = Vec::new(); + walk(&vd.descriptor, 3, &mut out); + for l in out.iter().filter(|l| !l.trim_start().starts_with("Clrs") && !l.trim_start().starts_with("Trns")) { + println!("{l}"); + } + } + } + if k == b"TySh" + && let Some(Ok((vd, _))) = v.get(52..).map(photocraft_psd::descriptor::VersionedDescriptor::parse_prefix) + { + // Text bounds (text space) and the transform. + let t: Vec = (0..6).map(|i| f64::from_be_bytes(v[2 + i * 8..10 + i * 8].try_into().unwrap())).collect(); + println!(" TySh transform {t:?}"); + for key in ["bounds", "boundingBox"] { + if let Some(photocraft_psd::descriptor::Value::Descriptor(d)) = vd.descriptor.get(key) { + let n: Vec = d.items.iter().map(|(k, v)| format!("{}={v:?}", String::from_utf8_lossy(k.as_bytes()))).collect(); + println!(" TySh {key}: {}", n.join(" ")); + } + } + } + if k == b"GdFl" { + // Skip the 4-byte version before the descriptor. + if let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(v) { + println!( + " GdFl keys: {:?}", + vd.descriptor + .items + .iter() + .filter(|(k, _)| !format!("{k:?}").contains("71, 114, 97, 100")) + .map(|(k, v)| format!( + "{:?}={}", + match k { + photocraft_psd::descriptor::Id::Code(c) => String::from_utf8_lossy(c).to_string(), + other => format!("{other:?}"), + }, + format!("{v:?}").chars().take(120).collect::() + )) + .collect::>() + ); + } + } + } + } + if std::env::var_os("DUMP_FX").is_some() { + fn walk(d: &photocraft_psd::descriptor::Descriptor, depth: usize) { + for (k, v) in &d.items { + let key = String::from_utf8_lossy(k.as_bytes()).to_string(); + if key == "Clrs" || key == "Trns" { + continue; + } + match v { + photocraft_psd::descriptor::Value::Descriptor(sub) => { + println!("{}{key}:", " ".repeat(depth)); + walk(sub, depth + 1); + } + photocraft_psd::descriptor::Value::Text(t) => println!("{}{key} = {:?}", " ".repeat(depth), t.to_string_lossy()), + photocraft_psd::descriptor::Value::List(items) if items.iter().all(|i| matches!(i, photocraft_psd::descriptor::Value::Descriptor(_))) => { + println!("{}{key} = [{} items]", " ".repeat(depth), items.len()); + for (i, it) in items.iter().enumerate() { + if let photocraft_psd::descriptor::Value::Descriptor(sub) = it { + println!("{}[{i}]:", " ".repeat(depth + 1)); + walk(sub, depth + 2); + } + } + } + _ => println!("{}{key} = {}", " ".repeat(depth), format!("{v:?}").chars().take(600).collect::()), + } + } + } + for rec in file.layers() { + println!("-- layer {:?} rect {:?}", String::from_utf8_lossy(&rec.name), rec.rect); + if let Some(b) = rec.block(b"lmfx").or(rec.block(b"lfx2")).or(rec.block(b"lfxs")) + && let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(&b.data[4..]) + { + walk(&vd.descriptor, 1); + } + } + } + let ours = photocraft_compose::flatten(doc).px; + let merged = photocraft_io::merged_composite(&file).unwrap(); + if std::env::args().nth(3).as_deref() == Some("png") { + // ours | photoshop | diff heatmap, side by side (over white). + let out = std::env::args().nth(4).expect("out.png"); + let (w, h) = (doc.size.width as usize, doc.size.height as usize); + let mut img = vec![0u8; w * 3 * h * 4]; + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + for y in 0..h { + for x in 0..w { + let (a, b) = (ours[y * w + x], merged[y * w + x]); + let over = |p: [f32; 4]| [p[0] * p[3] + 1.0 - p[3], p[1] * p[3] + 1.0 - p[3], p[2] * p[3] + 1.0 - p[3]]; + let (oa, ob) = (over(a), over(b)); + let d = (0..3).map(|c| (oa[c] - ob[c]).abs()).fold(0.0f32, f32::max); + let heat = [q((d * 4.0).min(1.0)), q((1.0 - d * 4.0).max(0.0) * 0.3), 0]; + for (k, px) in [[q(oa[0]), q(oa[1]), q(oa[2])], [q(ob[0]), q(ob[1]), q(ob[2])], heat].iter().enumerate() { + let o = (y * w * 3 + k * w + x) * 4; + img[o..o + 3].copy_from_slice(px); + img[o + 3] = 255; + } + } + } + // SCALE=n: nearest-neighbour upscale (small files). + let k: usize = std::env::var("SCALE").ok().and_then(|s| s.parse().ok()).unwrap_or(1).clamp(1, 16); + let (img, w, h) = if k > 1 { + let mut big = vec![0u8; w * 3 * k * h * k * 4]; + for y in 0..h * k { + for x in 0..w * 3 * k { + let (s, d) = (((y / k) * w * 3 + x / k) * 4, (y * w * 3 * k + x) * 4); + big[d..d + 4].copy_from_slice(&img[s..s + 4]); + } + } + (big, w * k, h * k) + } else { + (img, w, h) + }; + let image = + photocraft_codecs::Image::from_raw((w * 3) as u32, h as u32, photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8, img) + .unwrap(); + std::fs::write(&out, photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap(); + println!("wrote {out}"); + return; + } + if std::env::args().nth(3).as_deref() == Some("dump") { + // dump prefix: raw little-endian f32 RGBA (straight) planes for offline fitting: + // prefix_ours.f32, prefix_ps.f32, prefix_L.f32 (each top-level layer's own pixels, + // masks not applied) and prefix.txt (width, height, layer names). + let out = std::env::args().nth(4).expect("prefix"); + let wr = |name: String, px: &[[f32; 4]]| { + let bytes: Vec = px.iter().flat_map(|p| p.iter().flat_map(|v| v.to_le_bytes())).collect(); + std::fs::write(name, bytes).unwrap(); + }; + wr(format!("{out}_ours.f32"), &ours); + wr(format!("{out}_ps.f32"), &merged); + let mut meta = format!("{} {}\n", doc.size.width, doc.size.height); + for (i, l) in doc.layers.iter().enumerate() { + let b = photocraft_compose::surface_to_buffer( + l.surface().unwrap_or(&photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8)), + doc.bounds(), + ); + wr(format!("{out}_L{i}.f32"), &b.px); + meta += &format!("{i} {}\n", l.name); + } + std::fs::write(format!("{out}.txt"), meta).unwrap(); + return; + } + if std::env::args().nth(3).as_deref() == Some("layerpx") { + // layerpx x y: each layer's own pixel (0-255). + let x: i32 = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0); + let y: i32 = std::env::args().nth(5).and_then(|s| s.parse().ok()).unwrap_or(0); + for l in doc.walk() { + if let Some(s) = l.2.surface() { + println!("{:?}: {:?}", l.2.name, s.pixel(x, y).iter().map(|v| (v * 255.0 * 100.0).round() / 100.0).collect::>()); + } + } + return; + } + if std::env::args().nth(3).as_deref() == Some("grid") { + // grid x0 y0 x1 y1 [channel]: ours / photoshop values (0-255, premultiplied colour). + let w = doc.size.width as usize; + let a: Vec = (4..8).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); + let ch: usize = std::env::args().nth(8).and_then(|s| s.parse().ok()).unwrap_or(3); + for (label, img) in [("ours", &ours), ("ps", &merged)] { + println!("{label} (channel {ch}):"); + for y in a[1]..a[3] { + let row: Vec = (a[0]..a[2]) + .map(|x| { + let p = img[y * w + x]; + let v = if ch == 3 { p[3] } else { p[ch] * p[3] }; + format!("{:4}", (v * 255.0).round()) + }) + .collect(); + println!(" y={y:4} {}", row.join("")); + } + } + return; + } + if std::env::args().nth(3).as_deref() == Some("bylayer") { + // Max error and bad-pixel count inside each layer's bounds grown by its effects' reach + // (regions overlap; a quick way to tell which layer or effect is off). + let (w, h) = (doc.size.width as i32, doc.size.height as i32); + for (_, _, l) in doc.walk() { + let Some(sf) = l.surface() else { continue }; + let cb = sf.content_bounds(); + let mut b = photocraft_geom::Rect::new(i32::MAX, i32::MAX, i32::MIN, i32::MIN); + for y in cb.y0..cb.y1 { + for x in cb.x0..cb.x1 { + let p = sf.pixel(x, y); + if p[p.len() - 1] > 0.0 { + b = photocraft_geom::Rect::new(b.x0.min(x), b.y0.min(y), b.x1.max(x + 1), b.y1.max(y + 1)); + } + } + } + if b.x0 > b.x1 { + continue; + } + let m = photocraft_compose::effects::margin(l); + let r = photocraft_geom::Rect::new((b.x0 - m).max(0), (b.y0 - m).max(0), (b.x1 + m).min(w), (b.y1 + m).min(h)); + let (mut worst, mut at, mut bad) = (0.0f32, (0, 0), 0usize); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let i = (y * w + x) as usize; + let (a, b) = (ours[i], merged[i]); + let d = (0..3).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max); + if d > 2.0 / 255.0 { + bad += 1; + } + if d > worst { + (worst, at) = (d, (x, y)); + } + } + } + let fx: Vec<&str> = l.effects.items.iter().filter(|e| e.enabled()).map(|e| e.label()).collect(); + println!("{:<32} {:>6.1} at {:?} bad {:>6} {:?} {:?}", l.name, worst * 255.0, at, bad, l.blend, fx); + } + return; + } + if std::env::args().nth(3).as_deref() == Some("worst") { + // The N worst pixels (premultiplied max channel error), with coordinates. + let w = doc.size.width as usize; + let n: usize = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(20); + let mut v: Vec<(f32, usize)> = ours + .iter() + .zip(&merged) + .enumerate() + .map(|(i, (a, b))| ((0..4).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max), i)) + .collect(); + v.sort_by(|a, b| b.0.total_cmp(&a.0)); + for (d, i) in v.into_iter().take(n) { + let (a, b) = (ours[i], merged[i]); + println!("({:4},{:4}) d={:5.1} ours {:?} ps {:?}", i % w, i / w, d * 255.0, a.map(|v| (v * 255.0).round()), b.map(|v| (v * 255.0).round())); + } + return; + } + if std::env::args().nth(3).as_deref() == Some("row") { + let w = doc.size.width as usize; + let y: usize = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(0); + let (x0, x1): (usize, usize) = + (std::env::args().nth(5).and_then(|s| s.parse().ok()).unwrap_or(0), std::env::args().nth(6).and_then(|s| s.parse().ok()).unwrap_or(w)); + for x in (x0..x1).step_by(((x1 - x0) / 20).max(1)) { + let (a, b) = (ours[y * w + x], merged[y * w + x]); + println!("x={x:5} ours {:?} ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); + } + return; + } + if std::env::args().nth(3).as_deref() == Some("solve") { + // solve layer-name x0 y0 x1 y1: per pixel the layer's content alpha `l`, its shape's path + // coverage `cov`, Photoshop's alpha `A` and the alpha `s` an effect beneath the layer + // would need (A = s + l (1 - s)) over a transparent backdrop. + let name = std::env::args().nth(4).expect("layer name"); + let a: Vec = (5..9).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); + let w = doc.size.width as usize; + let l = doc.walk().into_iter().map(|t| t.2).find(|l| l.name == name).expect("layer"); + let r = photocraft_geom::Rect::new(a[0], a[1], a[2], a[3]); + let cov = match &l.content { + photocraft_doc::LayerContent::Shape(sh) => photocraft_vector::path_coverage(&sh.path, r), + _ => vec![0.0; r.width() as usize * r.height() as usize], + }; + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let la = l.surface().map_or(0.0, |s| s.pixel(x, y)[3]); + let c = cov[((y - r.y0) * r.width() as i32 + x - r.x0) as usize]; + let p = merged[y as usize * w + x as usize]; + let o = ours[y as usize * w + x as usize]; + let s = if la < 1.0 { (p[3] - la) / (1.0 - la) } else { f32::NAN }; + println!("({x:3},{y:3}) l {la:.3} cov {c:.3} A {:.3} ours {:.3} s {s:.3} ps {:?}", p[3], o[3], p.map(|v| (v * 255.0).round())); + } + } + return; + } + if std::env::args().nth(3).as_deref() == Some("line") { + // line x0 y0 x1 y1: every pixel on the segment, straight RGBA 0-255, ours | ps. + let w = doc.size.width as usize; + let a: Vec = (4..8).map(|i| std::env::args().nth(i).and_then(|s| s.parse().ok()).unwrap_or(0)).collect(); + let n = (a[2] - a[0]).abs().max((a[3] - a[1]).abs()).max(1); + for k in 0..=n { + let (x, y) = ((a[0] + (a[2] - a[0]) * k / n) as usize, (a[1] + (a[3] - a[1]) * k / n) as usize); + let (o, p) = (ours[y * w + x], merged[y * w + x]); + println!("({x:4},{y:4}) ours {:?} ps {:?}", o.map(|v| (v * 255.0).round()), p.map(|v| (v * 255.0).round())); + } + return; + } + if std::env::args().nth(3).as_deref() == Some("col") { + let (w, h) = (doc.size.width as usize, doc.size.height as usize); + let x = std::env::args().nth(4).and_then(|s| s.parse().ok()).unwrap_or(w / 2); + for k in 0..=16 { + let y = ((h - 1) * k / 16).min(h - 1); + let (a, b) = (ours[y * w + x], merged[y * w + x]); + println!("y={y:5} ours {:?} ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); + } + return; + } + let n = std::env::args().nth(2).and_then(|s| s.parse().ok()).unwrap_or(8usize); + for (i, (a, b)) in ours.iter().zip(&merged).enumerate().take(n) { + println!("{i:4}: ours {:?}\n ps {:?}", a.map(|v| (v * 1000.0).round() / 1000.0), b.map(|v| (v * 1000.0).round() / 1000.0)); + } +} + +/// The corpus oracle table (as `tests/it/corpus.rs`), files in parallel, without a test build. +fn corpus_summary(root: &std::path::Path) { + fn collect(dir: &std::path::Path, out: &mut Vec) { + let Ok(rd) = std::fs::read_dir(dir) else { return }; + for e in rd.flatten() { + let p = e.path(); + if p.is_dir() { + collect(&p, out); + } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("psd") || e.eq_ignore_ascii_case("psb")) { + out.push(p); + } + } + } + let mut files = Vec::new(); + collect(root, &mut files); + files.sort(); + const TOL: f32 = 2.0 / 255.0; + type Row = (String, Option<(f32, f32)>); + let row = |p: &std::path::PathBuf| -> Row { + let name = p.strip_prefix(root).unwrap_or(p).display().to_string(); + let Ok(bytes) = std::fs::read(p) else { return (name, None) }; + let Ok(file) = photocraft_psd::PsdFile::from_bytes(&bytes) else { return (name, None) }; + let Ok(imp) = photocraft_io::import(&name, &bytes) else { return (name, None) }; + if file.has_real_merged_data() == Some(false) || file.layers().is_empty() { + return (name, None); + } + let Ok(merged) = photocraft_io::merged_composite(&file) else { return (name, None) }; + let ours = photocraft_compose::flatten(&imp.document).px; + let mut m = 0.0f32; + let mut bad = 0usize; + for (a, b) in ours.iter().zip(&merged) { + let d = (0..4).map(|c| (a[c] * a[3] - b[c] * b[3]).abs()).fold((a[3] - b[3]).abs(), f32::max); + m = m.max(d); + if (0..4).any(|c| (a[c] * a[3] - b[c] * b[3]).abs() > TOL) { + bad += 1; + } + } + (name, Some((m, 100.0 * bad as f32 / ours.len().max(1) as f32))) + }; + // Files in parallel (a few threads; flatten itself is tile-parallel). + let next = std::sync::atomic::AtomicUsize::new(0); + let mut rows: Vec<(usize, Row)> = std::thread::scope(|sc| { + let hs: Vec<_> = (0..4) + .map(|_| { + sc.spawn(|| { + let mut out = Vec::new(); + loop { + let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let Some(p) = files.get(i) else { break }; + out.push((i, row(p))); + } + out + }) + }) + .collect(); + hs.into_iter().flat_map(|h| h.join().unwrap()).collect() + }); + rows.sort_by_key(|r| r.0); + let rows: Vec = rows.into_iter().map(|r| r.1).collect(); + let (mut pass, mut diff, mut skip) = (0, 0, 0); + for (name, r) in &rows { + match r { + Some((m, pct)) if *m <= TOL => { + pass += 1; + println!("{name:<60} {m:>9.4} {pct:>7.2}% PASS"); + } + Some((m, pct)) => { + diff += 1; + println!("{name:<60} {m:>9.4} {pct:>7.2}% DIFF"); + } + None => skip += 1, + } + } + println!("{} files: {pass} pass, {diff} differ, {skip} skipped/errors", rows.len()); +} diff --git a/crates/io/examples/rawlook.rs b/crates/io/examples/rawlook.rs new file mode 100644 index 00000000000..dfec1a6ef96 --- /dev/null +++ b/crates/io/examples/rawlook.rs @@ -0,0 +1,237 @@ +//! Measure the camera-JPEG colour fit on real raw files: times the fit, compares the +//! neutral fallback and the fitted look with the camera's embedded JPEG (mean CIE76 ΔE in +//! sRGB-clipped Lab D50, measured on the full develop output against the largest preview, +//! independently of the fit's own grid) and can write 1200-px sRGB PNGs of both renderings +//! and of the JPEG. +//! +//! ```sh +//! cargo run --release -p photocraft-io --example rawlook -- [--png DIR] FILE... +//! cargo run --release -p photocraft-io --example rawlook -- --synthetic # time a 24 MP synthetic NEF +//! ``` + +use std::time::Instant; + +use photocraft_cms::{Builtin, Intent, Transform}; +use photocraft_codecs::{self as codecs, ChannelLayout, EncodeOptions, Format, Image}; +use photocraft_raw::{DevelopOptions, develop_sensor}; + +/// Box-downsamples interleaved RGB to at most `edge` pixels on the long side. +fn shrink(px: &[f32], w: usize, h: usize, edge: usize) -> (Vec, usize, usize) { + let f = w.max(h).div_ceil(edge).max(1); + let (ow, oh) = (w / f, h / f); + let mut out = vec![0.0f32; ow * oh * 3]; + for y in 0..oh * f { + for x in 0..ow * f { + let (i, o) = ((y * w + x) * 3, ((y / f) * ow + x / f) * 3); + for k in 0..3 { + out[o + k] += px[i + k]; + } + } + } + let n = (f * f) as f32; + out.iter_mut().for_each(|v| *v /= n); + (out, ow, oh) +} + +/// Resamples to exactly `tw × th` by box averaging over the matching source area. +fn resample(px: &[f32], w: usize, h: usize, tw: usize, th: usize) -> Vec { + let mut out = vec![0.0f32; tw * th * 3]; + for ty in 0..th { + let (y0, y1) = (ty * h / th, ((ty + 1) * h / th).max(ty * h / th + 1)); + for tx in 0..tw { + let (x0, x1) = (tx * w / tw, ((tx + 1) * w / tw).max(tx * w / tw + 1)); + let mut s = [0.0f32; 3]; + for y in y0..y1 { + for x in x0..x1 { + for k in 0..3 { + s[k] += px[(y * w + x) * 3 + k]; + } + } + } + let n = ((y1 - y0) * (x1 - x0)) as f32; + for k in 0..3 { + out[(ty * tw + tx) * 3 + k] = s[k] / n; + } + } + } + out +} + +fn lin(v: f32) -> f64 { + let v = f64::from(v); + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +/// Lab (D50) of display sRGB 0..1 (Bradford-adapted sRGB → XYZ D50). +fn lab(p: &[f32]) -> [f64; 3] { + let m = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]]; + let l = [lin(p[0]), lin(p[1]), lin(p[2])]; + let xyz: [f64; 3] = std::array::from_fn(|i| m[i][0] * l[0] + m[i][1] * l[1] + m[i][2] * l[2]); + let w = [0.9642, 1.0, 0.8249]; + let f = |t: f64| if t > 216.0 / 24389.0 { t.cbrt() } else { (24389.0 / 27.0 * t + 16.0) / 116.0 }; + let [fx, fy, fz] = [0, 1, 2].map(|k| f(xyz[k] / w[k])); + [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)] +} + +fn mean_de(a: &[f32], b: &[f32]) -> f64 { + let n = a.len() / 3; + a.as_chunks::<3>() + .0 + .iter() + .zip(b.as_chunks::<3>().0) + .map(|(p, q)| { + let (x, y) = (lab(p), lab(q)); + ((x[0] - y[0]).powi(2) + (x[1] - y[1]).powi(2) + (x[2] - y[2]).powi(2)).sqrt() + }) + .sum::() + / n as f64 +} + +/// Developed ProPhoto 16-bit → display sRGB 0..1. +fn to_srgb(rgb: &[u16]) -> Vec { + let t = Transform::new(Builtin::ProPhotoCompat.profile(), Builtin::Srgb.profile(), Intent::RelativeColorimetric, false).expect("transform"); + let mut out = vec![0u16; rgb.len()]; + t.convert_u16(rgb, 3, &mut out, 3, false); + out.iter().map(|v| f32::from(*v) / 65535.0).collect() +} + +fn write_png(path: &str, px: &[f32], w: usize, h: usize) { + let (s, sw, sh) = shrink(px, w, h, 1200); + let bytes: Vec = s.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8).collect(); + let img = Image::from_u8(sw as u32, sh as u32, ChannelLayout::Rgb, bytes).expect("image"); + std::fs::write(path, codecs::encode(&img, Format::Png, &EncodeOptions::default()).expect("png")).expect("write"); +} + +/// Times the fit on a synthetic 6034×4012 NEF-like raw with a 1632×1086 camera-style preview. +fn synthetic() { + use photocraft_raw::testgen::{TiffBuilder, Val, mosaic}; + let (w, h) = (6034usize, 4012usize); + let colours: Vec<[f32; 3]> = (0..96u32).map(|i| [0.1 + 0.05 * (i % 9) as f32, 0.1 + 0.04 * (i % 11) as f32, 0.1 + 0.06 * (i % 7) as f32]).collect(); + let at = |x: usize, y: usize| { + let ramp = 0.15 + 0.85 * ((x * 12) % w) as f32 / w as f32; + colours[(y * 8 / h) * 12 + x * 12 / w].map(|v| v * ramp) + }; + let cam: Vec<[f32; 3]> = (0..w * h).map(|i| at(i % w, i / w)).collect(); + let data = mosaic(&cam, w, [0, 1, 1, 2], 0, 4095); + drop(cam); + let (pw, ph) = (1632usize, 1086usize); + let px: Vec = (0..pw * ph) + .flat_map(|i| { + let c = at((i % pw) * w / pw, (i / pw) * h / ph); + c.map(|v| { + let v = (1.6 * v / (1.0 + 0.6 * v)).clamp(0.0, 1.0); + ((if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }) * 255.0).round() as u8 + }) + }) + .collect(); + let jpeg = + codecs::encode(&Image::from_u8(pw as u32, ph as u32, ChannelLayout::Rgb, px).expect("image"), Format::Jpeg, &EncodeOptions::default()).expect("jpeg"); + let mut t = TiffBuilder::default(); + let strip = t.blob(data.iter().flat_map(|v| v.to_le_bytes()).collect()); + let raw = t.ifd(vec![ + (256, Val::Long(vec![w as u32])), + (257, Val::Long(vec![h as u32])), + (258, Val::Short(vec![12])), + (259, Val::Short(vec![1])), + (262, Val::Short(vec![32803])), + (273, Val::Blobs(vec![strip])), + (277, Val::Short(vec![1])), + (278, Val::Long(vec![h as u32])), + (279, Val::Long(vec![(data.len() * 2) as u32])), + (33421, Val::Short(vec![2, 2])), + (33422, Val::Byte(vec![0, 1, 1, 2])), + ]); + let len = jpeg.len() as u32; + let jb = t.blob(jpeg); + let ifd0 = + t.ifd(vec![(271, Val::Ascii("NIKON CORPORATION".into())), (330, Val::Ifds(vec![raw])), (513, Val::Blobs(vec![jb])), (514, Val::Long(vec![len]))]); + t.chain = vec![ifd0]; + let bytes = t.build(); + let opts = DevelopOptions::default(); + let sensor = photocraft_raw::decode(&bytes, &opts.limits).expect("decode"); + let _ = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts); + let mut times: Vec = (0..7) + .map(|_| { + let t = Instant::now(); + let r = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts); + assert!(r.is_ok(), "{r:?}"); + t.elapsed().as_secs_f64() * 1e3 + }) + .collect(); + times.sort_by(f64::total_cmp); + let p = photocraft_raw::embedded_preview(&bytes).expect("preview"); + let t = Instant::now(); + let img = codecs::decode_as(Format::Jpeg, p.jpeg).expect("jpeg"); + let dec = t.elapsed().as_secs_f64() * 1e3; + let r = photocraft_raw::Reference { width: img.width(), height: img.height(), rgb: img.data() }; + let t = Instant::now(); + let _ = photocraft_raw::fit_look(&sensor, &opts, &r); + println!(" preview decode {dec:.1} ms, fit_look {:.1} ms", t.elapsed().as_secs_f64() * 1e3); + println!("synthetic {w}x{h}: preview decode + fit median {:.1} ms (min {:.1}, max {:.1})", times[3], times[0], times[6]); +} + +fn main() { + let mut args = std::env::args().skip(1); + let mut png: Option = None; + let mut files = Vec::new(); + while let Some(a) = args.next() { + match a.as_str() { + "--png" => png = args.next(), + "--synthetic" => { + synthetic(); + return; + } + _ => files.push(a), + } + } + println!("| file | fit | ΔE grid fallback → fit | ΔE full fallback → fit | fit ms | develop ms |"); + println!("|---|---|---|---|---|---|"); + for f in files { + let bytes = std::fs::read(&f).expect("read"); + let name = std::path::Path::new(&f).file_stem().and_then(|s| s.to_str()).unwrap_or("raw").to_string(); + let opts = DevelopOptions::default(); + let sensor = photocraft_raw::decode(&bytes, &opts.limits).expect("decode"); + // Warm up (thread pool), then time the fit. + let _ = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts); + let t = Instant::now(); + let fit = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts); + let fit_ms = t.elapsed().as_secs_f64() * 1e3; + let before = develop_sensor(&sensor, &opts).expect("develop"); + let t = Instant::now(); + let after = match &fit { + Ok(look) => Some(develop_sensor(&sensor, &DevelopOptions { camera_look: Some(look.clone()), ..opts.clone() }).expect("develop")), + Err(_) => None, + }; + let dev_ms = t.elapsed().as_secs_f64() * 1e3; + // Independent check against the largest preview. + let p = photocraft_raw::embedded_preview(&bytes).expect("preview"); + let raw_jpeg = codecs::decode_as_with(Format::Jpeg, p.jpeg, &codecs::DecodeOptions { keep_orientation: true, ..Default::default() }).expect("jpeg"); + let own = raw_jpeg.meta.exif.as_deref().map_or(1, codecs::exif_orientation); + let o = if own != 1 { own } else { codecs::exif_orientation(&bytes) }; + let jpeg = raw_jpeg.oriented(o).expect("orient").converted(ChannelLayout::Rgb, photocraft_codecs::SampleType::U8).into_owned(); + let (jw, jh) = (jpeg.width() as usize, jpeg.height() as usize); + let jpx: Vec = jpeg.data().iter().map(|v| f32::from(*v) / 255.0).collect(); + let (dw, dh) = (before.width as usize, before.height as usize); + let (gw, gh) = (300, (300 * dh).div_ceil(dw)); + let jref = resample(&jpx, jw, jh, gw, gh); + let b = to_srgb(&before.rgb); + let de_before = mean_de(&resample(&b, dw, dh, gw, gh), &jref); + let a = after.as_ref().map(|d| to_srgb(&d.rgb)); + let de_after = a.as_ref().map(|a| mean_de(&resample(a, dw, dh, gw, gh), &jref)); + let (verdict, grid) = match &fit { + Ok(l) => ("used".to_string(), format!("{:.1} → {:.1}", l.delta_e_fallback, l.delta_e)), + Err(e) => (format!("rejected: {e}"), "-".into()), + }; + println!("| {name} | {verdict} | {grid} | {de_before:.1} → {} | {fit_ms:.0} | {dev_ms:.0} |", de_after.map_or("-".into(), |v| format!("{v:.1}"))); + if let Ok(l) = &fit { + eprintln!("{name}: to_xyz {:?}\n tone {:?}", l.to_xyz, l.tone.as_ref().map(|t| t.knots())); + } + if let Some(dir) = &png { + write_png(&format!("{dir}/{name}-before.png"), &b, dw, dh); + if let Some(a) = &a { + write_png(&format!("{dir}/{name}-after.png"), a, dw, dh); + } + write_png(&format!("{dir}/{name}-camera-jpeg.png"), &jpx, jw, jh); + } + } +} diff --git a/crates/ui-egui/src/camera_raw_ui.rs b/crates/ui-egui/src/camera_raw_ui.rs index e4cfd61eb54..76c61e68006 100644 --- a/crates/ui-egui/src/camera_raw_ui.rs +++ b/crates/ui-egui/src/camera_raw_ui.rs @@ -858,7 +858,8 @@ pub fn opened_without_dialog(app: &mut PhotocraftApp, index: usize, name: &str, } let Some(document) = app.session.documents().get(index).map(|st| st.doc.id) else { return }; let method = photocraft_io::raw::developed_demosaic(warnings).unwrap_or_else(|| app.session.prefs().raw_defaults.demosaic.method()); - let raw = RawOpen { document, name: name.to_string(), path: path.map(str::to_string), bytes: None, developed_with: method, demosaic: method }; + let raw = + RawOpen { document, name: name.to_string(), path: path.map(str::to_string), bytes: None, decoded: None, developed_with: method, demosaic: method }; let mut params = CameraRaw::default(); let sidecar = path.and_then(read_sidecar).map(|(loaded, _, _)| loaded); if let Some(loaded) = &sidecar { From b6171972a06685df1404a5f4de4ca85dfbe9d145 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 21:59:08 +0100 Subject: [PATCH 10/65] perf(cms): compute the Gamut Warning mask in parallel GamutCheck gets a bulk mask_rgba that splits the pixels into 16K-pixel chunks on the rayon pool; gamut_mask in the engine calls it instead of a serial per-pixel loop. The per-pixel test is unchanged, so the mask is bit-identical. Fixes #9744 Co-Authored-By: Claude Sonnet 5.5 --- crates/cms/src/gamut.rs | 64 +++++++++++++++++++++++++++++++++ crates/engine/src/color_cmds.rs | 15 ++------ 2 files changed, 66 insertions(+), 13 deletions(-) diff --git a/crates/cms/src/gamut.rs b/crates/cms/src/gamut.rs index 8b1abe1dd38..8e85bf48609 100644 --- a/crates/cms/src/gamut.rs +++ b/crates/cms/src/gamut.rs @@ -9,6 +9,11 @@ use crate::{CmsError, Intent}; /// Default ΔE76 threshold above which a colour counts as out of gamut. pub const DEFAULT_THRESHOLD: f32 = 4.0; +#[cfg(not(target_arch = "wasm32"))] +const PAR_MIN_PIXELS: usize = 16 * 1024; +#[cfg(not(target_arch = "wasm32"))] +const PAR_CHUNK_PIXELS: usize = 16 * 1024; + /// Precomputed out-of-gamut test for colours of `src` against `proof`. /// /// A colour is out of gamut when sending it to the proof device (relative colorimetric, @@ -75,4 +80,63 @@ impl GamutCheck { pub fn out_of_gamut(&self, px: &[f32]) -> bool { self.delta_e(px) > self.threshold } + + /// Out-of-gamut mask for RGBA pixels: `255` where the pixel has alpha > 0 and its first + /// `inputs()` channels are out of gamut, `0` elsewhere. Returns the number of flagged + /// pixels. Only `min(px.len(), mask.len())` pixels are processed. Runs on the rayon pool + /// (not on wasm); the result is identical to calling [`Self::out_of_gamut`] per pixel. + pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> usize { + let n = px.len().min(mask.len()); + let (px, mask) = (&px[..n], &mut mask[..n]); + let run = |p: &[[f32; 4]], m: &mut [u8]| { + let mut count = 0; + for (p, m) in p.iter().zip(m.iter_mut()) { + let hit = p[3] > 0.0 && self.out_of_gamut(&p[..3]); + *m = if hit { 255 } else { 0 }; + count += usize::from(hit); + } + count + }; + #[cfg(not(target_arch = "wasm32"))] + if n >= PAR_MIN_PIXELS { + use rayon::prelude::*; + return px.par_chunks(PAR_CHUNK_PIXELS).zip(mask.par_chunks_mut(PAR_CHUNK_PIXELS)).map(|(p, m)| run(p, m)).sum(); + } + run(px, mask) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Builtin; + + fn image(n: usize) -> Vec<[f32; 4]> { + let mut s = 0x9E37_79B9u32; + let mut rnd = move || { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + (s >> 8) as f32 / (1u32 << 24) as f32 + }; + // Includes out-of-range values and zero alpha. + (0..n).map(|i| [rnd() * 1.2 - 0.1, rnd(), rnd(), if i % 7 == 0 { 0.0 } else { rnd() }]).collect() + } + + #[test] + fn mask_rgba_matches_per_pixel_check() { + let src = Builtin::Srgb.profile(); + // Sizes straddle the parallel threshold and the chunk size, odd ones included. + for (proof, threshold) in [(Builtin::CoatedCmyk, 4.0), (Builtin::CoatedCmyk, 1.5), (Builtin::GrayGamma22, 4.0), (Builtin::DisplayP3, 0.5)] { + let check = GamutCheck::new(src, proof.profile(), threshold).unwrap(); + for n in [0, 1, 1023, 16 * 1024 - 1, 16 * 1024, 16 * 1024 + 1, 50_001] { + let px = image(n); + let want: Vec = px.iter().map(|p| if p[3] > 0.0 && check.out_of_gamut(&p[..3]) { 255 } else { 0 }).collect(); + let mut got = vec![7u8; n]; + let count = check.mask_rgba(&px, &mut got); + assert_eq!(got, want, "{proof:?} threshold {threshold} n {n}"); + assert_eq!(count, want.iter().filter(|&&m| m == 255).count()); + } + } + } } diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rs index 9e9c0aafd35..6823e4183f6 100644 --- a/crates/engine/src/color_cmds.rs +++ b/crates/engine/src/color_cmds.rs @@ -900,19 +900,8 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result Result<(Vec, usize)> { let check = GamutCheck::new(&composite_profile(doc), &setup.profile, threshold).map_err(cms_err)?; let buf = photocraft_compose::flatten(doc); - let mut count = 0; - let mask = buf - .px - .iter() - .map(|p| { - if p[3] > 0.0 && check.out_of_gamut(&p[..3]) { - count += 1; - 255 - } else { - 0 - } - }) - .collect(); + let mut mask = vec![0u8; buf.px.len()]; + let count = check.mask_rgba(&buf.px, &mut mask); Ok((mask, count)) } From 58acaaf499adccfe0080afdc99d5c7ee3a337364 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 27 Oct 2026 19:40:53 +0100 Subject: [PATCH 11/65] fix(cms): reject non-RGB sources in GamutCheck::mask_rgba instead of panicking mask_rgba is fallible now and returns CmsError::Invalid when the check was not built from a 3-channel source profile; a CMYK source used to panic on the first alpha-positive pixel. Regression test added. Co-Authored-By: Claude Sonnet 5.5 --- crates/cms/src/gamut.rs | 36 +++++++++++++++++++++++++-------- crates/engine/src/color_cmds.rs | 2 +- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/crates/cms/src/gamut.rs b/crates/cms/src/gamut.rs index 8e85bf48609..aee5bb6dddd 100644 --- a/crates/cms/src/gamut.rs +++ b/crates/cms/src/gamut.rs @@ -81,11 +81,19 @@ impl GamutCheck { self.delta_e(px) > self.threshold } - /// Out-of-gamut mask for RGBA pixels: `255` where the pixel has alpha > 0 and its first - /// `inputs()` channels are out of gamut, `0` elsewhere. Returns the number of flagged - /// pixels. Only `min(px.len(), mask.len())` pixels are processed. Runs on the rayon pool - /// (not on wasm); the result is identical to calling [`Self::out_of_gamut`] per pixel. - pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> usize { + /// Out-of-gamut mask for RGBA pixels: `255` where the pixel has alpha > 0 and its RGB + /// channels are out of gamut, `0` elsewhere. Returns the number of flagged pixels. Only + /// `min(px.len(), mask.len())` pixels are processed. Runs on the rayon pool (not on wasm); + /// the result is identical to calling [`Self::out_of_gamut`] per pixel. + /// + /// # Errors + /// [`CmsError::Invalid`] when the check was not built from a three-channel (RGB) source + /// profile: an RGBA pixel carries only three colour channels, so it cannot be tested + /// against a CMYK or gray source. Nothing is written to `mask` in that case. + pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> Result { + if self.inputs != 3 { + return Err(CmsError::Invalid(format!("gamut mask needs a 3-channel (RGB) source profile, got {} channels", self.inputs))); + } let n = px.len().min(mask.len()); let (px, mask) = (&px[..n], &mut mask[..n]); let run = |p: &[[f32; 4]], m: &mut [u8]| { @@ -100,9 +108,9 @@ impl GamutCheck { #[cfg(not(target_arch = "wasm32"))] if n >= PAR_MIN_PIXELS { use rayon::prelude::*; - return px.par_chunks(PAR_CHUNK_PIXELS).zip(mask.par_chunks_mut(PAR_CHUNK_PIXELS)).map(|(p, m)| run(p, m)).sum(); + return Ok(px.par_chunks(PAR_CHUNK_PIXELS).zip(mask.par_chunks_mut(PAR_CHUNK_PIXELS)).map(|(p, m)| run(p, m)).sum()); } - run(px, mask) + Ok(run(px, mask)) } } @@ -133,10 +141,22 @@ mod tests { let px = image(n); let want: Vec = px.iter().map(|p| if p[3] > 0.0 && check.out_of_gamut(&p[..3]) { 255 } else { 0 }).collect(); let mut got = vec![7u8; n]; - let count = check.mask_rgba(&px, &mut got); + let count = check.mask_rgba(&px, &mut got).unwrap(); assert_eq!(got, want, "{proof:?} threshold {threshold} n {n}"); assert_eq!(count, want.iter().filter(|&&m| m == 255).count()); } } } + + #[test] + fn mask_rgba_rejects_non_rgb_source() { + // A CMYK (4-channel) and a gray (1-channel) source cannot be tested from RGBA pixels. + for src in [Builtin::CoatedCmyk, Builtin::GrayGamma22] { + let check = GamutCheck::new(src.profile(), Builtin::Srgb.profile(), 4.0).unwrap(); + let px = image(64); + let mut mask = vec![9u8; 64]; + assert!(matches!(check.mask_rgba(&px, &mut mask), Err(CmsError::Invalid(_))), "{src:?}"); + assert!(mask.iter().all(|&m| m == 9), "mask must stay untouched"); + } + } } diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rs index 6823e4183f6..9f3bfef167e 100644 --- a/crates/engine/src/color_cmds.rs +++ b/crates/engine/src/color_cmds.rs @@ -901,7 +901,7 @@ pub fn gamut_mask(doc: &Document, setup: &ProofSetup, threshold: f32) -> Result< let check = GamutCheck::new(&composite_profile(doc), &setup.profile, threshold).map_err(cms_err)?; let buf = photocraft_compose::flatten(doc); let mut mask = vec![0u8; buf.px.len()]; - let count = check.mask_rgba(&buf.px, &mut mask); + let count = check.mask_rgba(&buf.px, &mut mask).map_err(cms_err)?; Ok((mask, count)) } From ec55f4964c15f2c3b29b32dce0b646f3f94e88db Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 27 Oct 2026 23:32:24 +0100 Subject: [PATCH 12/65] Camera Raw tests: raw opens take turns so a parallel test cannot evict the kept decode Co-Authored-By: Claude Sonnet 5.5 --- .../ui-egui/src/dialogs/camera_raw_ui/tests.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs index be52e81e5de..262f3cf710f 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs @@ -310,9 +310,26 @@ fn dialog_drives_the_engine() { assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": "x"}}})).unwrap().is_err()); } +std::thread_local! { + /// Held by a test's thread from its first `raw_app` to the test's end. + static RAW_OPEN_TURN: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + /// An app whose importer is the real one, opening a synthetic DNG. +/// +/// Raw opens keep their decode in one process-wide list of two (`photocraft_io::raw`), so tests +/// that open raws take turns: a parallel test's open would otherwise evict the decode another +/// test is about to take. The turn is held until the test's thread ends (nextest runs each test +/// in its own process, where this costs nothing). fn raw_app() -> (PhotocraftApp, Vec) { use photocraft_raw::testgen::{DngSpec, mosaic, scene}; + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + RAW_OPEN_TURN.with(|held| { + let mut held = held.borrow_mut(); + if held.is_none() { + *held = Some(TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + } + }); let services = crate::Services { import: Some(Box::new(|name: &str, b: &[u8], opts: &photocraft_io::ImportOptions| { photocraft_io::import_with_options(name, b, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()) From d98b9ea17be9b1b96aa3e052fb33e981b36928b9 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 20:10:41 +0100 Subject: [PATCH 13/65] paint: stop a stroke past a dab-area budget and skip dabs outside the paintable area A stroke had no limit on its cost: a 500 px brush at 1 % spacing over a 200 000 px segment rasterized 40 000 dabs (tens of seconds, about 1.5 GB), almost all of them far off the canvas, with their coverage tiles allocated and never read. StrokeRenderer::with_clip skips dabs whose rectangle misses the clip (pixels inside are unchanged), and a budget of 2^31 dab-rectangle pixels per stroke ends painting past it. The engine passes the canvas plus the pixels the layer already holds. Refs #11136 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/brush_cmds.rs | 25 +++-- crates/engine/src/cmd/brush_cmds/tests.rs | 16 +++- crates/paint/src/lib.rs | 2 +- crates/paint/src/render.rs | 77 +++++++++++++++ crates/paint/src/render/budget_tests.rs | 110 ++++++++++++++++++++++ 5 files changed, 221 insertions(+), 9 deletions(-) create mode 100644 crates/paint/src/render/budget_tests.rs diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index e09ff2098ca..3e73d9341b4 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -12,7 +12,7 @@ use photocraft_paint::mixer::{MixerSettings, MixerState}; use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect}; use photocraft_paint::tile::PREVIEW_SIDE; use photocraft_paint::{ - BrushPreset, BrushSettings, GrayTile, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke, + BrushPreset, BrushSettings, GrayTile, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke_clipped, }; use photocraft_raster::Surface; use serde_json::{Value, json}; @@ -90,6 +90,12 @@ pub(crate) fn check_coords(pts: &[StrokePoint], cmd: &str) -> Result<()> { Ok(()) } +/// Where a stroke can change pixels: the canvas plus any pixels the layer already holds past its +/// edge (a moved layer keeps them, #5067). Dabs that reach neither are not rasterized. +fn paintable_area(canvas: Rect, surf: &Surface) -> Rect { + canvas.union(&surf.tile_bounds()) +} + /// Deep-merge `patch` into `base` (objects merge key by key; anything else replaces). fn merge(base: &mut Value, patch: &Value) { match (base, patch) { @@ -289,7 +295,9 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS } let sel = doc.selection.clone(); let table = crate::mode_cmds::paint_color_table(doc, p); + let canvas = doc.bounds(); let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; + let clip = paintable_area(canvas, surf); let mut brush = brush; erase_locked(&mut brush, lock, bg); if auto_erase { @@ -304,23 +312,23 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS .iter() .filter(|p| crate::symmetry_cmds::SymmetryAxis::has_distinct_mirror(&pts, p)) .map(|p| { - let mut renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom); + let mut renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip); renderer.push(p); renderer.finish(); renderer }) .collect(); if copies.is_empty() { - render_stroke(surf, &brush, &pts, sel.as_ref(), lock, zoom) + render_stroke_clipped(surf, &brush, &pts, sel.as_ref(), lock, zoom, Some(clip)) } else { let pre = surf.clone(); - let mut original = StrokeRenderer::new(&brush, Some(surf.format()), zoom); + let mut original = StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip); original.push(&pts); original.finish(); original.composite_union_many(&copies, &pre, surf, sel.as_ref(), lock) } } else { - render_stroke(surf, &brush, &pts, sel.as_ref(), lock, zoom) + render_stroke_clipped(surf, &brush, &pts, sel.as_ref(), lock, zoom, Some(clip)) }; if let (Some(table), Some(pre)) = (&table, &unpainted) { crate::mode_cmds::keep_in_color_table(table, pre, surf, damage); @@ -613,15 +621,18 @@ impl LiveStroke { let mut doc = (*st.doc).clone(); let sel = doc.selection.clone(); let table = crate::mode_cmds::paint_color_table(&doc, p); + let canvas = doc.bounds(); let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, layer, p)?; + let clip = paintable_area(canvas, surf); erase_locked(&mut brush, lock, s.tools.background); if pencil && flag(p, "autoErase", false) { let fg = table.as_ref().map_or(fg, |t| crate::mode_cmds::table_color(t, fg)); apply_auto_erase(&mut brush, surf, pts.first(), fg, s.tools.background); } - let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom); + let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip); let symmetry = s.active().and_then(|st| st.symmetry.clone()); - let mirrors: Vec<_> = (0..symmetry.as_ref().map_or(0, |s| s.mirror_count())).map(|_| StrokeRenderer::new(&brush, Some(surf.format()), zoom)).collect(); + let mirrors: Vec<_> = + (0..symmetry.as_ref().map_or(0, |s| s.mirror_count())).map(|_| StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip)).collect(); let mirror_distinct = vec![false; mirrors.len()]; let pre = surf.clone(); let mut live = Self { diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index c29d4c3146f..7c4859766d2 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -31,6 +31,18 @@ fn stroke_backwards_compatible() { assert!(rgba(&s, 30, 5)[3] > 0.9 && rgba(&s, 30, 8)[3] < 0.01); } +#[test] +fn a_stroke_from_far_off_the_canvas_paints_only_what_reaches_it() { + // Dabs that cannot reach the canvas are not rasterized (their coverage is never read). + let mut s = session(80, 80); + let r = s.execute("paint.stroke", json!({"points": [[-100_000, 20], [70, 20], [70, 60]], "size": 6, "color": "#0000ff", "brush": {"hardness": 0.5, "smoothing": {"amount": 0.0}}})).unwrap(); + assert!(rgba(&s, 40, 20)[3] > 0.9, "the part on the canvas is painted: {:?} {r}", rgba(&s, 40, 20)); + assert!(rgba(&s, 70, 50)[3] > 0.9); + assert_eq!(rgba(&s, 40, 40)[3], 0.0); + let d: Vec = r["damage"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); + assert!(d[0] > -100, "the damage does not span the off-canvas path: {r}"); +} + #[test] fn fill_fills_the_enclosed_region_not_the_outline() { // #3659: a closed gesture with `fill` paints the interior, not a ring. @@ -1157,7 +1169,9 @@ fn out_of_range_scatter_is_rejected_and_the_maximum_still_paints() { s.execute("tools.setBrush", json!({ "brush": patch })).unwrap(); let r = s.execute("paint.stroke", stroke.clone()).unwrap(); let d: Vec = r["damage"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); - assert!(d[0].abs() < 1000 && d[1].abs() < 1000 && d[2] > 0 && d[3] > 0, "{r}"); + // A dab scattered clear of the canvas is not rasterized, so its damage is empty. + let off_canvas = d[2] == 0 && d[3] == 0; + assert!(off_canvas || (d[0].abs() < 1000 && d[1].abs() < 1000 && d[2] > 0 && d[3] > 0), "{r}"); } // Control: 200 % scatter paints where it did before the cap (the soft default tip reaches a // little past its radius). diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index 214a28177d7..da2e67c834e 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -39,7 +39,7 @@ pub use brush::{ }; pub use curve::ResponseCurve; pub use mixer::MixerSettings; -pub use render::{BrushContext, StrokeRenderer, UnionLive, grid_center, grid_square, render_stroke}; +pub use render::{BrushContext, StrokeRenderer, UnionLive, grid_center, grid_square, render_stroke, render_stroke_clipped}; pub use tile::{GrayTile, StoredTile}; /// One input sample. Missing stylus data defaults to "mouse": full pressure, no tilt/rotation. diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index 83243bdafa1..de98e2e231b 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -740,6 +740,33 @@ pub struct StrokeRenderer { dual_buf: Vec, all_dabs: Option>, regions: RegionPool, + /// Dabs whose rectangle misses this one are not rasterized (see [`with_clip`](Self::with_clip)). + clip: Option, + /// Dab-rectangle pixels the stroke may still rasterize (see [`MAX_STROKE_DAB_AREA`]). + area_left: u64, +} + +/// Most dab-rectangle pixels one stroke rasterizes: past it the stroke stops painting, so a very +/// large brush at the finest spacing over a very long path costs bounded time and memory instead +/// of growing with path length times brush area. A soft round dab costs about 1.2 ns per pixel on +/// an idle four-thread machine, so the limit is a few seconds of work. 2^31 pixels is, for +/// example, 10 000 dabs of a 500 px brush (a 50 000 px path at 1 % spacing) or 50 000 dabs of a +/// 200 px brush; a 20 000 px scribble with a 500 px brush at 5 % spacing uses a fifth of it. +pub const MAX_STROKE_DAB_AREA: u64 = 1 << 31; + +/// Whether a dab with rectangle `rect` is painted: it reaches `clip` and fits `area_left`, which +/// it is charged against. An over-budget dab ends the stroke's painting for good. +fn admit(clip: Option, area_left: &mut u64, rect: Rect) -> bool { + if *area_left == 0 || rect.is_empty() || clip.is_some_and(|c| c.intersect(&rect).is_empty()) { + return false; + } + let area = u64::from(rect.width()) * u64::from(rect.height()); + if area > *area_left { + *area_left = 0; + return false; + } + *area_left -= area; + true } /// The tile buffers [`StrokeRenderer::composite`] works in, kept from one composite to the next: @@ -845,6 +872,8 @@ impl StrokeRenderer { dual_buf: Vec::new(), all_dabs: None, regions: RegionPool::default(), + clip: p.clip, + area_left: p.area_left, }) } Some(m) => { @@ -897,9 +926,30 @@ impl StrokeRenderer { dual_buf: Vec::new(), all_dabs: None, regions: RegionPool::default(), + clip: None, + area_left: MAX_STROKE_DAB_AREA, } } + /// Only paint where a dab can reach inside `clip` (the target's paintable area): a dab whose + /// rectangle misses it is counted but not rasterized, and allocates no coverage tiles. Pixels + /// inside `clip` come out exactly as without it. + pub fn with_clip(mut self, clip: Rect) -> Self { + self.clip = Some(clip); + self + } + + /// Override the dab-area budget ([`MAX_STROKE_DAB_AREA`]) for this stroke. + pub fn with_dab_area_budget(mut self, pixels: u64) -> Self { + self.area_left = pixels; + self + } + + /// Whether the stroke has stopped painting because it used up its dab-area budget. + pub fn budget_exhausted(&self) -> bool { + self.area_left == 0 + } + /// Keep a copy of every primary dab (for tests and sequential tools). pub fn record_dabs(mut self) -> Self { self.all_dabs = Some(Vec::new()); @@ -923,6 +973,9 @@ impl StrokeRenderer { let mut native = [0.0f32; 8]; for d in &dabs { let rect = self.ctx.dab_rect(d, false); + if !admit(self.clip, &mut self.area_left, rect) { + continue; + } // Wet Edges acts on the whole stroke (#2088): the dab records how deep it reaches each // pixel and the stroke darkens its own rim when composited, not every dab's. self.ctx.rasterize_into(d, false, rect, &mut self.scratch, wet.then_some(&mut self.depth_scratch)); @@ -940,6 +993,9 @@ impl StrokeRenderer { if let Some(dm) = self.dual.as_mut() { for d in &duals { let rect = self.ctx.dab_rect(d, true); + if !admit(self.clip, &mut self.area_left, rect) { + continue; + } self.ctx.rasterize(d, true, rect, &mut self.scratch); dm.accumulate(rect, &self.scratch, 1.0, None, None); } @@ -1028,6 +1084,8 @@ impl StrokeRenderer { dual_buf: duals, all_dabs: None, regions: RegionPool::default(), + clip: self.clip, + area_left: self.area_left, }; t.raster_pending(); // Tiles whose coverage the tail doesn't change still composite the same: redraw them all. @@ -1283,12 +1341,28 @@ pub fn render_stroke( selection: Option<&Surface>, lock_transparency: bool, zoom: f32, +) -> Rect { + render_stroke_clipped(target, brush, points, selection, lock_transparency, zoom, None) +} + +/// [`render_stroke`] that only rasterizes dabs reaching `clip` (see [`StrokeRenderer::with_clip`]). +pub fn render_stroke_clipped( + target: &mut Surface, + brush: &BrushSettings, + points: &[StrokePoint], + selection: Option<&Surface>, + lock_transparency: bool, + zoom: f32, + clip: Option, ) -> Rect { if points.is_empty() { return Rect::EMPTY; } let pre = target.clone(); let mut r = StrokeRenderer::new(brush, Some(target.format()), zoom); + if let Some(c) = clip { + r = r.with_clip(c); + } r.push(points); r.finish(); r.composite(&pre, target, selection, lock_transparency, true) @@ -1363,3 +1437,6 @@ mod reference; #[cfg(test)] mod coverage_tests; + +#[cfg(test)] +mod budget_tests; diff --git a/crates/paint/src/render/budget_tests.rs b/crates/paint/src/render/budget_tests.rs new file mode 100644 index 00000000000..be1f5121344 --- /dev/null +++ b/crates/paint/src/render/budget_tests.rs @@ -0,0 +1,110 @@ +//! Stroke cost limits: the clip rectangle and the dab-area budget. + +use super::*; + +fn brush(size: f32, spacing: f32) -> BrushSettings { + BrushSettings { size, spacing, hardness: 0.5, ..BrushSettings::default() } +} + +fn line(r: &mut StrokeRenderer, from: f64, to: f64) { + r.push(&[StrokePoint::new(from, 50.0, 1.0), StrokePoint::new(to, 50.0, 1.0)]); + r.finish(); +} + +#[test] +fn clip_skips_far_dabs_and_leaves_the_pixels_inside_unchanged() { + let b = brush(20.0, 0.25); + let clip = Rect::new(0, 0, 200, 100); + let mut plain = StrokeRenderer::new(&b, None, 1.0); + let mut clipped = StrokeRenderer::new(&b, None, 1.0).with_clip(clip); + // A path that runs 20000 px, almost all of it far outside the clip. + line(&mut plain, -100.0, 20_000.0); + line(&mut clipped, -100.0, 20_000.0); + assert_eq!(plain.dab_count(), clipped.dab_count()); + for y in clip.y0..clip.y1 { + for x in clip.x0..clip.x1 { + assert_eq!(plain.coverage_at(x, y).to_bits(), clipped.coverage_at(x, y).to_bits(), "({x},{y})"); + } + } + assert!(plain.cov.tiles.len() > 20 * clipped.cov.tiles.len(), "{} vs {}", plain.cov.tiles.len(), clipped.cov.tiles.len()); + assert_eq!(clipped.coverage_at(10_000, 50), 0.0); + assert!(clipped.bounds().x1 < 400, "{:?}", clipped.bounds()); +} + +#[test] +fn a_dab_that_straddles_the_clip_edge_is_painted_in_full_inside() { + let b = brush(40.0, 0.25); + let clip = Rect::new(0, 0, 100, 100); + let mut plain = StrokeRenderer::new(&b, None, 1.0); + let mut clipped = StrokeRenderer::new(&b, None, 1.0).with_clip(clip); + plain.push(&[StrokePoint::new(110.0, 50.0, 1.0)]); + clipped.push(&[StrokePoint::new(110.0, 50.0, 1.0)]); + plain.finish(); + clipped.finish(); + assert!(plain.coverage_at(95, 50) > 0.0); + assert_eq!(plain.coverage_at(95, 50).to_bits(), clipped.coverage_at(95, 50).to_bits()); +} + +#[test] +fn a_huge_brush_at_the_finest_spacing_over_a_long_path_stays_cheap_with_a_clip() { + // 500 px brush at the 1 % minimum spacing over 2e6 px: 400 000 dabs; only those that reach the + // clip are rasterized. + let b = brush(500.0, 0.0); + let mut r = StrokeRenderer::new(&b, None, 1.0).with_clip(Rect::new(0, 0, 256, 256)); + let t = std::time::Instant::now(); + line(&mut r, -1_000_000.0, 1_000_000.0); + assert!(r.dab_count() > 100_000, "{}", r.dab_count()); + assert!(r.cov.tiles.len() < 1000, "{}", r.cov.tiles.len()); + assert!(!r.budget_exhausted()); + assert!(t.elapsed().as_secs_f64() < 20.0, "{:?}", t.elapsed()); +} + +#[test] +fn the_budget_stops_painting_but_keeps_counting_dabs() { + let b = brush(20.0, 0.25); + // A 20 px brush has a dab rectangle of about 30x30; room for about ten of them. + let mut r = StrokeRenderer::new(&b, None, 1.0).with_dab_area_budget(10_000); + line(&mut r, 0.0, 2_000.0); + assert!(r.budget_exhausted()); + assert!(r.dab_count() > 300, "{}", r.dab_count()); + assert!(r.coverage_at(1_000, 50) == 0.0); + assert!(r.bounds().x1 < 200, "{:?}", r.bounds()); + // The first dabs did paint. + assert!(r.coverage_at(2, 50) > 0.0); + // Further input is ignored: no growth. + let tiles = r.cov.tiles.len(); + line(&mut r, 3_000.0, 4_000.0); + assert_eq!(r.cov.tiles.len(), tiles); +} + +#[test] +fn the_budget_is_charged_once_and_shared_with_the_dual_brush() { + let mut b = brush(20.0, 0.25); + b.dual_brush.enabled = true; + b.dual_brush.size = 10.0; + let mut r = StrokeRenderer::new(&b, None, 1.0); + line(&mut r, 0.0, 300.0); + assert!(MAX_STROKE_DAB_AREA - r.area_left > 0); + assert!(!r.budget_exhausted()); +} + +/// How much of the budget everyday strokes use, so a limit change is judged against numbers. +#[test] +fn everyday_strokes_use_a_small_part_of_the_budget() { + // (size, spacing, path length in px): a 100 px brush at 1 % spacing over 6000 px, a 500 px + // brush at 5 % over 20 000 px (a scribble across a large document), 20 px at 25 % over 1e6 px. + for (size, spacing, len) in [(100.0, 0.01, 6_000.0), (500.0, 0.05, 20_000.0), (20.0, 0.25, 1.0e6)] { + let b = brush(size, spacing); + // The clip rejects every dab, so this measures the generator and `dab_rect` only. + let mut r = StrokeRenderer::new(&b, None, 1.0).with_clip(Rect::new(0, 0, 1, 1)).record_dabs(); + r.push(&[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(len, 0.0, 1.0)]); + r.finish(); + let used: u64 = r.dabs().iter().map(|d| r.ctx.dab_rect(d, false)).map(|q| u64::from(q.width()) * u64::from(q.height())).sum(); + println!( + "size {size} spacing {spacing} len {len}: {} dabs, {used} px = {:.1} % of the budget", + r.dab_count(), + used as f64 * 100.0 / MAX_STROKE_DAB_AREA as f64 + ); + assert!(used < MAX_STROKE_DAB_AREA / 4, "{used}"); + } +} From efd725cc89aa0cea7844319d8a6561d914ec92cf Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 20:15:25 +0100 Subject: [PATCH 14/65] paint: charge the dual brush apart, skip (not end on) a dab that does not fit the budget Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/brush_cmds/tests.rs | 7 ++++- crates/paint/src/render.rs | 31 +++++++++++++++------ crates/paint/src/render/budget_tests.rs | 34 ++++++++++++++++++----- 3 files changed, 55 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 7c4859766d2..4342cee3e59 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -35,7 +35,12 @@ fn stroke_backwards_compatible() { fn a_stroke_from_far_off_the_canvas_paints_only_what_reaches_it() { // Dabs that cannot reach the canvas are not rasterized (their coverage is never read). let mut s = session(80, 80); - let r = s.execute("paint.stroke", json!({"points": [[-100_000, 20], [70, 20], [70, 60]], "size": 6, "color": "#0000ff", "brush": {"hardness": 0.5, "smoothing": {"amount": 0.0}}})).unwrap(); + let r = s + .execute( + "paint.stroke", + json!({"points": [[-100_000, 20], [70, 20], [70, 60]], "size": 6, "color": "#0000ff", "brush": {"hardness": 0.5, "smoothing": {"amount": 0.0}}}), + ) + .unwrap(); assert!(rgba(&s, 40, 20)[3] > 0.9, "the part on the canvas is painted: {:?} {r}", rgba(&s, 40, 20)); assert!(rgba(&s, 70, 50)[3] > 0.9); assert_eq!(rgba(&s, 40, 40)[3], 0.0); diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index de98e2e231b..549c92449cf 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -744,25 +744,31 @@ pub struct StrokeRenderer { clip: Option, /// Dab-rectangle pixels the stroke may still rasterize (see [`MAX_STROKE_DAB_AREA`]). area_left: u64, + /// The same budget for the Dual Brush's dabs, so primary and dual dabs are charged apart and + /// the result does not depend on how the input was chunked. + dual_area_left: u64, + /// A dab was left out for want of budget. + refused: bool, } /// Most dab-rectangle pixels one stroke rasterizes: past it the stroke stops painting, so a very /// large brush at the finest spacing over a very long path costs bounded time and memory instead /// of growing with path length times brush area. A soft round dab costs about 1.2 ns per pixel on /// an idle four-thread machine, so the limit is a few seconds of work. 2^31 pixels is, for -/// example, 10 000 dabs of a 500 px brush (a 50 000 px path at 1 % spacing) or 50 000 dabs of a +/// example, 8 000 dabs of a 500 px brush (about a 40 000 px path at 1 % spacing) or 50 000 dabs of a /// 200 px brush; a 20 000 px scribble with a 500 px brush at 5 % spacing uses a fifth of it. pub const MAX_STROKE_DAB_AREA: u64 = 1 << 31; /// Whether a dab with rectangle `rect` is painted: it reaches `clip` and fits `area_left`, which -/// it is charged against. An over-budget dab ends the stroke's painting for good. -fn admit(clip: Option, area_left: &mut u64, rect: Rect) -> bool { - if *area_left == 0 || rect.is_empty() || clip.is_some_and(|c| c.intersect(&rect).is_empty()) { +/// it is charged against. +fn admit(clip: Option, area_left: &mut u64, refused: &mut bool, rect: Rect) -> bool { + if rect.is_empty() || clip.is_some_and(|c| c.intersect(&rect).is_empty()) { return false; } let area = u64::from(rect.width()) * u64::from(rect.height()); + // A dab that does not fit is skipped; a smaller later one (pressure) may still fit. if area > *area_left { - *area_left = 0; + *refused = true; return false; } *area_left -= area; @@ -874,6 +880,8 @@ impl StrokeRenderer { regions: RegionPool::default(), clip: p.clip, area_left: p.area_left, + dual_area_left: p.dual_area_left, + refused: p.refused, }) } Some(m) => { @@ -928,6 +936,8 @@ impl StrokeRenderer { regions: RegionPool::default(), clip: None, area_left: MAX_STROKE_DAB_AREA, + dual_area_left: MAX_STROKE_DAB_AREA, + refused: false, } } @@ -942,12 +952,13 @@ impl StrokeRenderer { /// Override the dab-area budget ([`MAX_STROKE_DAB_AREA`]) for this stroke. pub fn with_dab_area_budget(mut self, pixels: u64) -> Self { self.area_left = pixels; + self.dual_area_left = pixels; self } - /// Whether the stroke has stopped painting because it used up its dab-area budget. + /// Whether a dab was left out because the stroke used up its dab-area budget. pub fn budget_exhausted(&self) -> bool { - self.area_left == 0 + self.refused } /// Keep a copy of every primary dab (for tests and sequential tools). @@ -973,7 +984,7 @@ impl StrokeRenderer { let mut native = [0.0f32; 8]; for d in &dabs { let rect = self.ctx.dab_rect(d, false); - if !admit(self.clip, &mut self.area_left, rect) { + if !admit(self.clip, &mut self.area_left, &mut self.refused, rect) { continue; } // Wet Edges acts on the whole stroke (#2088): the dab records how deep it reaches each @@ -993,7 +1004,7 @@ impl StrokeRenderer { if let Some(dm) = self.dual.as_mut() { for d in &duals { let rect = self.ctx.dab_rect(d, true); - if !admit(self.clip, &mut self.area_left, rect) { + if !admit(self.clip, &mut self.dual_area_left, &mut self.refused, rect) { continue; } self.ctx.rasterize(d, true, rect, &mut self.scratch); @@ -1086,6 +1097,8 @@ impl StrokeRenderer { regions: RegionPool::default(), clip: self.clip, area_left: self.area_left, + dual_area_left: self.dual_area_left, + refused: self.refused, }; t.raster_pending(); // Tiles whose coverage the tail doesn't change still composite the same: redraw them all. diff --git a/crates/paint/src/render/budget_tests.rs b/crates/paint/src/render/budget_tests.rs index be1f5121344..f14c0bec09b 100644 --- a/crates/paint/src/render/budget_tests.rs +++ b/crates/paint/src/render/budget_tests.rs @@ -51,12 +51,10 @@ fn a_huge_brush_at_the_finest_spacing_over_a_long_path_stays_cheap_with_a_clip() // clip are rasterized. let b = brush(500.0, 0.0); let mut r = StrokeRenderer::new(&b, None, 1.0).with_clip(Rect::new(0, 0, 256, 256)); - let t = std::time::Instant::now(); line(&mut r, -1_000_000.0, 1_000_000.0); assert!(r.dab_count() > 100_000, "{}", r.dab_count()); assert!(r.cov.tiles.len() < 1000, "{}", r.cov.tiles.len()); assert!(!r.budget_exhausted()); - assert!(t.elapsed().as_secs_f64() < 20.0, "{:?}", t.elapsed()); } #[test] @@ -78,14 +76,36 @@ fn the_budget_stops_painting_but_keeps_counting_dabs() { } #[test] -fn the_budget_is_charged_once_and_shared_with_the_dual_brush() { +fn dual_dabs_are_charged_apart_and_chunking_does_not_change_the_result() { let mut b = brush(20.0, 0.25); b.dual_brush.enabled = true; b.dual_brush.size = 10.0; - let mut r = StrokeRenderer::new(&b, None, 1.0); - line(&mut r, 0.0, 300.0); - assert!(MAX_STROKE_DAB_AREA - r.area_left > 0); - assert!(!r.budget_exhausted()); + let pts: Vec<_> = (0..200).map(|i| StrokePoint::new(f64::from(i) * 7.0, 50.0, 1.0)).collect(); + let run = |chunk: usize| { + let mut r = StrokeRenderer::new(&b, None, 1.0).with_dab_area_budget(20_000); + for c in pts.chunks(chunk) { + r.push(c); + } + r.finish(); + r + }; + let (whole, chunked) = (run(1000), run(3)); + assert!(whole.budget_exhausted()); + for x in 0..1400 { + assert_eq!(whole.coverage_at(x, 50).to_bits(), chunked.coverage_at(x, 50).to_bits(), "x {x}"); + assert_eq!(whole.dual.as_ref().unwrap().get(x, 50).to_bits(), chunked.dual.as_ref().unwrap().get(x, 50).to_bits(), "dual x {x}"); + } + assert!(whole.dual.as_ref().unwrap().get(2, 50) > 0.0); +} + +#[test] +fn a_dab_too_big_for_what_is_left_does_not_end_the_stroke() { + let (mut left, mut refused) = (1000, false); + assert!(!admit(None, &mut left, &mut refused, Rect::new(0, 0, 100, 100))); + assert!(refused); + assert_eq!(left, 1000); + assert!(admit(None, &mut left, &mut refused, Rect::new(0, 0, 10, 10))); + assert_eq!(left, 900); } /// How much of the budget everyday strokes use, so a limit change is judged against numbers. From 90cd7a78df19996af59184799befd7e93617923d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:18:52 +0100 Subject: [PATCH 15/65] paint: require damage for the dual-brush primary dab; document with_dab_area_budget CodeRabbit review points: the dual(10.0) case could pass through the off-canvas branch although its primary dab is on the canvas; with_dab_area_budget replaces what is left, so it is set before the first dab. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/brush_cmds/tests.rs | 7 ++++--- crates/paint/src/render.rs | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 4342cee3e59..a0e2b8506bf 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -1169,13 +1169,14 @@ fn out_of_range_scatter_is_rejected_and_the_maximum_still_paints() { assert!(s.execute("tools.setBrush", json!({ "brush": scatter(1e38) })).is_err()); assert!(s.execute("paint.stroke", stroke.clone()).is_ok()); // The maximum (1000 %) is accepted and paints a finite, well-formed dab. - for patch in [scatter(10.0), dual(10.0)] { + for (patch, primary_on_canvas) in [(scatter(10.0), false), (dual(10.0), true)] { let mut s = new(); s.execute("tools.setBrush", json!({ "brush": patch })).unwrap(); let r = s.execute("paint.stroke", stroke.clone()).unwrap(); let d: Vec = r["damage"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); - // A dab scattered clear of the canvas is not rasterized, so its damage is empty. - let off_canvas = d[2] == 0 && d[3] == 0; + // A dab scattered clear of the canvas is not rasterized, so its damage is empty. The dual + // brush scatters only its own tip: the primary dab stays on the canvas and always paints. + let off_canvas = !primary_on_canvas && d[2] == 0 && d[3] == 0; assert!(off_canvas || (d[0].abs() < 1000 && d[1].abs() < 1000 && d[2] > 0 && d[3] > 0), "{r}"); } // Control: 200 % scatter paints where it did before the cap (the soft default tip reaches a diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index 549c92449cf..11ad7cd8171 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -949,7 +949,8 @@ impl StrokeRenderer { self } - /// Override the dab-area budget ([`MAX_STROKE_DAB_AREA`]) for this stroke. + /// Override the dab-area budget ([`MAX_STROKE_DAB_AREA`]) for this stroke. Set it before the first + /// dab: it replaces what is left, so pixels already charged are not carried over. pub fn with_dab_area_budget(mut self, pixels: u64) -> Self { self.area_left = pixels; self.dual_area_left = pixels; From b4487ee599980917b0407a165c484fd003bba9db Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:53:23 -0600 Subject: [PATCH 16/65] fix(paint): a bucket fill clicked on transparency fills the transparency in full (#11311) --- crates/algo/src/paint.rs | 104 +++++++++++++++++++++- crates/engine/src/cmd/paint_cmds/tests.rs | 74 +++++++++++++++ 2 files changed, 174 insertions(+), 4 deletions(-) diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index 4862304786d..2070a59d42e 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -63,7 +63,23 @@ pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { } } -/// Composites `color(i)` over `area` of the surface with per-pixel coverage. +/// `o`, the pixel `d` with `c` composited at coverage `k`, with what is left of `d`'s transparency +/// filled by `c` up to coverage `full` (≥ `k`) as well, behind the colour already there: the +/// transparent part of the pixel takes the fill at `full` while its colour keeps the softer `k`. +fn fill_transparency(o: [f32; 4], d: [f32; 4], c: [f32; 4], k: f32, full: f32) -> [f32; 4] { + let add = ((full - k).max(0.0) * c[3].clamp(0.0, 1.0) * (1.0 - d[3]).max(0.0)).min((1.0 - o[3]).max(0.0)); + let a = o[3] + add; + if add.is_nan() || add <= 0.0 || a <= 0.0 { + return o; + } + let mix = |i: usize| (o[i] * o[3] + c[i] * add) / a; + [mix(0), mix(1), mix(2), a] +} + +/// Composites `color(i)` over `area` of the surface with per-pixel coverage. With `transparency`, +/// a covered pixel's transparency takes the fill at that coverage instead (see +/// [`fill_transparency`]); Lock Transparent Pixels and Clear ignore it. +#[allow(clippy::too_many_arguments)] fn composite_area( s: &mut Surface, area: Rect, @@ -72,6 +88,7 @@ fn composite_area( color: impl Fn(i32, i32) -> [f32; 4] + Sync, lock_transparency: bool, inks: Option<[f32; 4]>, + transparency: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>, ) { // Composite tile by tile (in parallel on native); tiles with zero coverage are left untouched, // so their copy-on-write storage (and GPU residency) survives. @@ -99,7 +116,11 @@ fn composite_area( let d = photocraft_raster::to_rgba(&fmt, px); let o = match mode { FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k), - FillMode::Blend(m) => blend::composite(m, d, color(x, y), k), + FillMode::Blend(m) => { + let c = color(x, y); + let o = blend::composite(m, d, c, k); + transparency.map_or(o, |full| fill_transparency(o, d, c, k, full(x, y))) + } // Locked transparency keeps the alpha, so Clear leaves the pixel as it is. FillMode::Clear if lock_transparency => d, FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))], @@ -165,6 +186,7 @@ pub fn paint_gradient( }, lock_transparency, None, + None, ); } @@ -227,8 +249,16 @@ pub fn bucket_fill_inks( } let img = crate::selection::rgba8_image(s, area); let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false }; + // Clicked on transparency: the flood fills empty pixels, and the empty part of the pixels + // along its anti-aliased edge (the soft rim a cleared selection leaves) is that same empty + // area, so it is filled in full rather than left as a semi-transparent ring (#11311). + let at_seed = usize::try_from(seed.1 - area.y0) + .ok() + .and_then(|y| y.checked_mul(area.width() as usize)) + .and_then(|row| row.checked_add(usize::try_from(seed.0 - area.x0).ok()?)); + let empty_seed = at_seed.and_then(|i| img.get(i)).is_some_and(|p| p[3] == 0); drop(img); - bucket_fill_region_inks(s, ®ion, opacity, selection, lock_transparency, src, inks, mode); + fill_region(s, ®ion, opacity, selection, lock_transparency, src, inks, mode, empty_seed); true } @@ -256,10 +286,31 @@ pub fn bucket_fill_region_inks( src: impl Fn(i32, i32) -> [f32; 4] + Sync, inks: Option<[f32; 4]>, mode: FillMode, +) { + fill_region(s, region, opacity, selection, lock_transparency, src, inks, mode, false); +} + +/// [`bucket_fill_region_inks`]; with `fill_empty`, the transparent part of every pixel the region +/// touches takes the fill at the full opacity and selection coverage, while the region's +/// anti-aliasing still softens the colour over what is already there. Opaque pixels come out +/// exactly as without it. +#[allow(clippy::too_many_arguments)] +fn fill_region( + s: &mut Surface, + region: &crate::selection::Region, + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + src: impl Fn(i32, i32) -> [f32; 4] + Sync, + inks: Option<[f32; 4]>, + mode: FillMode, + fill_empty: bool, ) { // Composite only over the filled region's box. let b = region.bbox; - composite_area(s, b, mode, |x, y| region.at(x, y) * opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)), src, lock_transparency, inks); + let strength = |x: i32, y: i32| opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)); + let empty: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if fill_empty { Some(&strength) } else { None }; + composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, empty); } #[cfg(test)] @@ -344,6 +395,51 @@ mod tests { assert_eq!(s.rgba(-4, 4), [0.0; 4], "outside the region"); } + /// #11311: flooding transparency with anti-aliasing fills the empty part of the region's edge + /// pixels at the fill's opacity, so the edge is no semi-transparent ring; opaque pixels the + /// anti-aliasing reaches blend exactly as before. + #[test] + fn bucket_on_transparency_fills_the_edge_pixels_in_full() { + let a = Rect::new(0, 0, 8, 1); + let white = |_, _| [1.0, 1.0, 1.0, 1.0]; + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + for (opaque, opacity) in [([1.0, 1.0, 1.0, 1.0], 1.0), ([1.0, 1.0, 1.0, 1.0], 0.5), ([1.0, 0.0, 0.0, 1.0], 1.0)] { + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(4, 0, 8, 1), &opaque); + // The same region filled without the rule: what the bucket used to do. + let mut before = s.clone(); + let img = crate::selection::rgba8_image(&before, a); + let region = crate::selection::wand_region(&img, a, (1, 0), 0.0, true, true).unwrap(); + bucket_fill_region_inks(&mut before, ®ion, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal)); + assert!(before.rgba(3, 0)[3] < opacity * 0.97, "{fmt:?}: the old edge was semi-transparent: {:?}", before.rgba(3, 0)); + + assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal))); + for x in 0..4 { + let p = s.rgba(x, 0); + assert!(p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3) && (p[3] - opacity).abs() < 3e-3, "{fmt:?} {opaque:?} at {x}: {p:?}"); + } + for x in 4..8 { + assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} {opaque:?} at {x}: opaque pixels blend as before"); + } + assert!(s.rgba(4, 0)[3] > 0.999); + } + } + } + + /// The rule is for a click on transparency only: from an opaque seed, a semi-transparent + /// neighbour along the edge keeps its own transparency (it belongs to another area). + #[test] + fn bucket_on_opaque_pixels_keeps_neighbouring_transparency() { + let a = Rect::new(0, 0, 8, 1); + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 4, 1), &[1.0, 1.0, 1.0, 0.5]); + s.fill_rect(Rect::new(4, 0, 8, 1), &[1.0, 1.0, 1.0, 1.0]); + assert!(bucket_fill_inks(&mut s, a, (6, 0), 0.0, true, true, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal))); + let edge = s.rgba(3, 0)[3]; + assert!(edge > 0.5 && edge < 0.6, "only the anti-aliased coverage lands: {edge}"); + assert!((s.rgba(1, 0)[3] - 0.5).abs() < 0.01, "outside the region"); + } + /// The Paint Bucket's Mode: Multiply darkens what's there, Clear erases it (half at 50 %). #[test] fn bucket_mode_blends_or_clears() { diff --git a/crates/engine/src/cmd/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs index ba30e9d7191..835e450d83b 100644 --- a/crates/engine/src/cmd/paint_cmds/tests.rs +++ b/crates/engine/src/cmd/paint_cmds/tests.rs @@ -328,3 +328,77 @@ fn bucket_and_gradient_reject_non_numeric_opacity_without_editing() { assert!((px(&s, 5, 5)[0] - 128.0 / 255.0).abs() < 0.01, "{cmd}: null opacity is 100%"); } } + +/// #11311: a white layer (the Background made a normal layer), a selection cleared to +/// transparency, Deselect, then the Paint Bucket clicked in the hole with white at 100 %. Returns +/// the session after the fill and the layer's pixels right after the clear. +fn clear_then_bucket(depth: u32, selection: Value, bucket_aa: bool) -> (Session, Vec<[f32; 4]>) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 120, "height": 100, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + s.execute("select.rect", selection).unwrap(); + s.execute("edit.clear", json!({})).unwrap(); + let cleared = layer_rgba(&s); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("paint.bucket", json!({"x": 60, "y": 50, "color": "#ffffff", "antiAlias": bucket_aa})).unwrap(); + (s, cleared) +} + +/// The active layer's pixels over the canvas, row by row. +fn layer_rgba(s: &Session) -> Vec<[f32; 4]> { + let d = s.active().unwrap(); + let surf = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap(); + let b = d.doc.bounds(); + (b.y0..b.y1).flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))).map(|(x, y)| surf.rgba(x, y)).collect() +} + +/// The first `n` pixels (as `x, y, rgba`) that aren't opaque white at 8 bits. +fn not_white(px: &[[f32; 4]], width: usize, n: usize) -> Vec<(usize, usize, [f32; 4])> { + let is_white = |p: &[f32; 4]| p.iter().all(|c| (c.clamp(0.0, 1.0) * 255.0).round() == 255.0); + px.iter().enumerate().filter(|(_, p)| !is_white(p)).take(n).map(|(i, p)| (i % width, i / width, *p)).collect() +} + +fn assert_all_white(s: &Session, what: &str) { + let doc = &s.active().unwrap().doc; + let width = doc.bounds().width() as usize; + let layer = layer_rgba(s); + assert_eq!(not_white(&layer, width, 8), vec![], "{what}: layer pixels left after the fill"); + let composite = photocraft_compose::render(doc, doc.bounds()).px.clone(); + assert_eq!(composite.len(), layer.len()); + assert_eq!(not_white(&composite, width, 8), vec![], "{what}: composite pixels left after the fill"); +} + +/// #11311: after clearing an anti-aliased selection and bucket-filling the hole white at 100 %, +/// every pixel of the layer and of the composite is opaque white. The clear itself is right: it +/// leaves a soft rim of white at partial alpha around a fully transparent hole. The bucket used to +/// leave that rim (and its own anti-aliased edge) semi-transparent: a grey ring over the checkerboard. +#[test] +fn bucket_after_clearing_an_antialiased_selection_leaves_no_ring() { + for depth in [8, 16, 32] { + let ellipse = json!({"x": 20, "y": 10, "width": 80, "height": 80, "ellipse": true, "antiAlias": true}); + let (s, cleared) = clear_then_bucket(depth, ellipse, true); + // A transparent hole (its RGB zeroed) inside a rim of straight white at partial alpha, + // which the bucket's similarity test (RGB 255 away from the hole's 0) leaves out. + assert_eq!(cleared[50 * 120 + 60], [0.0; 4], "depth {depth}: the hole is empty"); + let rim: Vec<&[f32; 4]> = cleared.iter().filter(|p| p[3] > 0.0 && p[3] < 1.0).collect(); + assert!(!rim.is_empty(), "depth {depth}: an anti-aliased clear leaves a soft rim"); + assert!(rim.iter().all(|p| p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3)), "depth {depth}: the rim keeps its white"); + assert_all_white(&s, &format!("depth {depth}, anti-aliased ellipse")); + } +} + +/// Controls for #11311: a hard-edged selection leaves no soft rim, but the bucket's own +/// anti-aliasing used to leave the hole's edge pixels partly transparent too, so hard edges end +/// white as well; with neither anti-aliased (the case that was always right) it stays white. +#[test] +fn bucket_after_clearing_a_hard_selection_leaves_no_ring() { + let hard_ellipse = json!({"x": 20, "y": 10, "width": 80, "height": 80, "ellipse": true, "antiAlias": false}); + let rect = json!({"x": 30, "y": 20, "width": 60, "height": 60}); + for depth in [8, 16, 32] { + for (selection, bucket_aa) in [(hard_ellipse.clone(), true), (rect.clone(), true), (rect.clone(), false)] { + let (s, cleared) = clear_then_bucket(depth, selection.clone(), bucket_aa); + assert!(cleared.iter().all(|p| p[3] == 0.0 || p[3] == 1.0), "depth {depth} {selection}: a hard clear leaves no rim"); + assert_all_white(&s, &format!("depth {depth} {selection}, bucket antiAlias {bucket_aa}")); + } + } +} From 87e6bf6bfac1594476594194b09a19cefc8d60f8 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:06:16 -0600 Subject: [PATCH 17/65] fix(paint): write the picked CMYK inks at a transparent fill's made-opaque edge (#11311) --- crates/algo/src/paint.rs | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index 2070a59d42e..d7a1139caf7 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -126,11 +126,14 @@ fn composite_area( FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))], }; from_rgba_into(&fmt, o, &mut enc); - // A colour picked as CMYK inks replaces fully covered pixels of a CMYK target as it is. + // A colour picked as CMYK inks replaces fully covered pixels of a CMYK target as it + // is — and pixels the fill made fully opaque out of transparency, whose colour is the + // fill alone even though their coverage is partial (the edge of a bucket fill on + // transparency, #11354 review). A pixel that held colour keeps its blended encoding. if let Some(i) = inks && fmt.mode == photocraft_color::ColorMode::Cmyk && mode == FillMode::Blend(BlendMode::Normal) - && k >= 1.0 + && (k >= 1.0 || (d[3] <= 0.0 && o[3] >= 1.0)) { enc[..4].copy_from_slice(&i); } @@ -426,6 +429,37 @@ mod tests { } } + /// #11354 review: on a CMYK target, the edge pixels a transparent-seed bucket makes + /// opaque take the picked inks like the fully covered interior — their colour is the + /// fill alone. A partially transparent destination the fill touches keeps the blended + /// colour it already had, so its inks stay the conversion of that blend. + #[test] + fn bucket_on_transparency_writes_the_picked_cmyk_inks_at_the_edge() { + let a = Rect::new(0, 0, 8, 1); + let inks = [1.0f32, 0.0, 0.0, 0.0]; + let rgb = photocraft_color::convert::cmyk_to_rgb(inks).map(|c| c.clamp(0.0, 1.0)); + let src = |_, _| [rgb[0], rgb[1], rgb[2], 1.0]; + let raw = |s: &Surface, x: i32| -> Vec { s.read_region(Rect::new(x, 0, x + 1, 1)).into_iter().take(4).collect() }; + let is_inks = |got: &[f32]| got.iter().zip(inks).all(|(a, b)| (a - b).abs() < 0.02); + + // Transparent run against opaque white: x=3 is the anti-aliased edge (coverage < 1). + let mut s = Surface::new(PixelFormat::CMYKA8); + s.fill_rect(Rect::new(4, 0, 8, 1), &[0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, 1.0, None, false, src, Some(inks), FillMode::Blend(BlendMode::Normal))); + assert!(is_inks(&raw(&s, 1)), "fully covered: {:?}", raw(&s, 1)); + assert!(is_inks(&raw(&s, 3)), "the made-opaque edge takes the picked inks: {:?}", raw(&s, 3)); + + // The edge pixel holds white at half alpha instead: the fill raises its alpha, + // but the colour is a blend, so the picked inks do not replace it. + let mut s = Surface::new(PixelFormat::CMYKA8); + s.fill_rect(Rect::new(3, 0, 4, 1), &[0.0, 0.0, 0.0, 0.0, 0.5]); + s.fill_rect(Rect::new(4, 0, 8, 1), &[0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, 1.0, None, false, src, Some(inks), FillMode::Blend(BlendMode::Normal))); + let edge = s.rgba(3, 0); + assert!(edge[3] > 0.5, "the fill raised the partial pixel's alpha: {edge:?}"); + assert!(!is_inks(&raw(&s, 3)), "a blended destination keeps its own encoding: {:?}", raw(&s, 3)); + } + /// The rule is for a click on transparency only: from an opaque seed, a semi-transparent /// neighbour along the edge keeps its own transparency (it belongs to another area). #[test] From 6b4d605f4e9fb019732a2dc6537afb66e84f7baa Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 5 Nov 2026 03:07:18 +0100 Subject: [PATCH 18/65] Smart-object Replace Color: refuse Lab bounds there, adapt the stage key to TileBytes Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/adjust_cmds/tests.rs | 11 +++++++++++ crates/engine/src/cmd/smart_cmds/stack_cache.rs | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index c5f4a583e42..5bc7d240ed7 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -668,6 +668,17 @@ fn replace_color_smart_filter_keeps_the_foreground_it_was_run_with() { assert_eq!(max_diff(&flatten(&s), &baked), 0.0, "changing the foreground leaves the filter unchanged"); } +/// Lab bounds edit pixels in place; a smart object keeps its pixels, so they are refused there. +#[test] +fn replace_color_lab_bounds_are_refused_on_a_smart_object() { + let mut s = smart_session(); + let before = flatten(&s); + let r = s.execute("image.adjustments.replaceColor", json!({"labMinimum": [0, -128, -128], "labMaximum": [100, 127, 127], "hue": 90})); + assert!(r.is_err(), "Lab bounds on a smart object must be refused"); + assert!(smart_filters_of(&s).is_empty()); + assert_eq!(max_diff(&flatten(&s), &before), 0.0); +} + /// #5335: Curves (⌘M) edits the targeted layer mask, saved channel or Quick Mask at every depth. #[test] fn curves_apply_to_non_colour_targets_at_every_depth() { diff --git a/crates/engine/src/cmd/smart_cmds/stack_cache.rs b/crates/engine/src/cmd/smart_cmds/stack_cache.rs index fe11c5bc7c2..69ee6515f0f 100644 --- a/crates/engine/src/cmd/smart_cmds/stack_cache.rs +++ b/crates/engine/src/cmd/smart_cmds/stack_cache.rs @@ -63,7 +63,7 @@ pub(super) fn filter_key(below: &StageKey, f: &SmartFilter, mask: Option<&photoc tiles.sort_by_key(|(coord, _)| **coord); for (coord, tile) in tiles { h.update(format!("{coord:?}").as_bytes()); - h.update(tile.bytes()); + h.update(&tile.bytes()); } } *h.finalize().as_bytes() From 064dcd7fa6b154f997debebc5a6a2ffc7e8ce1ed Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 7 Nov 2026 03:59:40 -0500 Subject: [PATCH 19/65] fix(engine): count markers keep their coordinates through Image Size, Canvas Size and Image Rotation (#11762) Count markers were mapped with the pixels by Image Size, Canvas Size and Image Rotation. In the reference application they keep their document coordinates, also where they end up off the canvas. These commands now put the count points back after mapping the rest of the geometry (keeping_count_points); notes, the ruler, paths, slices and guides still follow the image, and Crop (including its straighten turn), Perspective Crop, Trim, Reveal All and the artboard paths are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/canvas_geom.rs | 12 ++++ crates/engine/src/cmd.rs | 4 +- crates/engine/src/cmd/count_resize_tests.rs | 64 +++++++++++++++++++++ crates/engine/src/cmd/image_cmds.rs | 6 +- crates/engine/src/cmd/mode_cmds.rs | 12 +++- 5 files changed, 93 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/count_resize_tests.rs diff --git a/crates/engine/src/canvas_geom.rs b/crates/engine/src/canvas_geom.rs index 93bc4654b9e..33e1ad443a1 100644 --- a/crates/engine/src/canvas_geom.rs +++ b/crates/engine/src/canvas_geom.rs @@ -287,6 +287,18 @@ pub(crate) fn transform_doc_marks(doc: &mut Document, a: &Affine) { } } +/// Runs `f` (Image Size, Canvas Size, Image Rotation) and puts the count points back where they +/// were: they keep their document coordinates, also where they end up off the canvas, as in the +/// reference application (#11762). Other marks follow the map as `f` applies it. +pub(crate) fn keeping_count_points(doc: &mut Document, f: impl FnOnce(&mut Document) -> R) -> R { + let saved: Vec> = doc.measurement.count_groups.iter().map(|g| g.points.clone()).collect(); + let r = f(doc); + for (g, points) in doc.measurement.count_groups.iter_mut().zip(saved) { + g.points = points; + } + r +} + /// Applies `a` to all non-pixel geometry of the document (layers and document marks). pub(crate) fn transform_geometry(doc: &mut Document, a: &Affine) { let dpi = doc.resolution_dpi; diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4c911e6be01..63741f78083 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -37,7 +37,7 @@ fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + s.execute("count.add", json!({"x": POINT[0], "y": POINT[1]})).unwrap(); + s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap(); + s +} + +fn count_point(s: &Session) -> [f64; 2] { + s.active().unwrap().doc.measurement.count_groups[0].points[0] +} + +fn note(s: &Session) -> [f64; 2] { + s.active().unwrap().doc.notes[0].position +} + +#[test] +fn count_points_keep_their_coordinates() { + let steps: [(&str, Value); 8] = [ + ("image.imageSize", json!({"width": 300, "height": 200})), + ("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})), + ("image.imageRotation.90cw", json!({})), + ("image.imageRotation.90ccw", json!({})), + ("image.imageRotation.180", json!({})), + ("image.imageRotation.flipCanvasHorizontal", json!({})), + ("image.imageRotation.flipCanvasVertical", json!({})), + ("image.rotation.arbitrary", json!({"angle": 30})), + ]; + for (cmd, p) in steps { + let mut s = doc(); + let before = note(&s); + s.execute(cmd, p).unwrap(); + assert_eq!(count_point(&s), POINT, "{cmd}"); + assert_ne!(note(&s), before, "{cmd}: notes still follow the image"); + s.undo(); + assert_eq!((count_point(&s), note(&s)), (POINT, before), "{cmd}: undo"); + } +} + +#[test] +fn all_three_in_a_row_leave_the_point_where_it_was() { + let mut s = doc(); + s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap(); + s.execute("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})).unwrap(); + s.execute("image.imageRotation.90cw", json!({})).unwrap(); + assert_eq!(count_point(&s), POINT); +} + +#[test] +fn crop_still_moves_count_points() { + let mut s = doc(); + s.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap(); + assert_ne!(count_point(&s), POINT, "not measured: Crop keeps today's behaviour"); +} diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index fa6a50e0a1a..436935a5ec3 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -293,7 +293,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result { Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails, Method::Automatic => Resample::BicubicSharper, }; - resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles) + crate::canvas_geom::keeping_count_points(doc, |doc| resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles)) })?; // The size the document has now: without resampling `width`/`height` are ignored (#1815). let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; @@ -689,7 +689,7 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result { let ext = extension_color(s, p); s.set_sampler_map(photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy))); s.edit("Canvas Size", |doc, _| { - translate_doc(doc, "image.canvasSize", dx, dy)?; + crate::canvas_geom::keeping_count_points(doc, |doc| translate_doc(doc, "image.canvasSize", dx, dy))?; doc.size = Size::new(nw, nh); if nw > ow as u32 || nh > oh as u32 { drop_fill_caches(&mut doc.layers); @@ -1015,7 +1015,7 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar Ok(()) })?; } - crate::mode_cmds::rotate_arbitrary(s, &json!({"angle": angle, "direction": "ccw"}))?; + crate::mode_cmds::rotate_arbitrary_with(s, &json!({"angle": angle, "direction": "ccw"}), false)?; // Color Sampler points follow the crop's origin shift too (the rotation moved them above). s.set_sampler_map(crop_target.sampler_map(target)); let extension = s.tools.background; diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index ea6504f7a8c..320d87552d9 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -62,6 +62,12 @@ pub fn rotated_size(size: Size, deg: f64) -> Size { } pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { + rotate_arbitrary_with(s, p, true) +} + +/// [`rotate_arbitrary`]; `keep_counts` leaves the count points where they were (Image Rotation, +/// #11762). The Crop tool's straighten turn moves them with the image, as before. +pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, keep_counts: bool) -> Result { const CMD: &str = "image.rotation.arbitrary"; // At full precision: an f32 angle can grow the canvas 1 px past what `rotated_size` gives callers. let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(0.0); @@ -129,7 +135,11 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { // What Free Transform leaves alone: unlinked vector masks, gradient angles, artboards… crate::canvas_geom::transform_layer_geometry(l, &a, false, dpi); } - crate::canvas_geom::transform_doc_marks(doc, &a); + if keep_counts { + crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::transform_doc_marks(doc, &a)); + } else { + crate::canvas_geom::transform_doc_marks(doc, &a); + } for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { ch.surface = crate::transform_cmds::warp_gray(&ch.surface, &h, interp)?; } From d8b48faf4750f28c5ec2d7d72439777b1fe5cad8 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 13:15:00 +0100 Subject: [PATCH 20/65] Smart filters: Equalize honours cancellation like the other filters Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/smart_cmds/rendering.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs index 8c352c50265..733cf5346c0 100644 --- a/crates/engine/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -158,6 +158,7 @@ fn renders_in_object(f: &SmartFilter) -> bool { fn apply_smart_filter(f: &SmartFilter, cur: &Surface, canvas: Rect, extent: Rect, mask: Option<&photocraft_doc::LayerMask>, ctx: &JobCtx) -> Result { crate::jobs::authorize_render_command(&f.command, &f.params)?; let rendered = if f.command == "image.adjustments.equalize" { + ctx.check()?; crate::adjust_cmds::adjust_as_filter("equalize", &f.params, cur, mask) } else { crate::filters::apply_filter_to_surface_in(&f.command, &f.params, cur, canvas, None, extent, ctx)? From 8abea6ca27231e0a47adf5d36e9aa36bfd88bf59 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 7 Nov 2026 08:56:04 -0500 Subject: [PATCH 21/65] Ruler Straighten with crop turns count points with the image; the test checks each note position Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/analysis_cmds.rs | 3 +- crates/engine/src/cmd/count_resize_tests.rs | 36 ++++++++++++++------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index d9d7d1510c8..ed6dba0254f 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -728,7 +728,8 @@ fn straighten(s: &mut Session, p: &Value) -> Result { let (w0, h0) = (f64::from(d.size.width), f64::from(d.size.height)); compound(s, "Straighten", |s| { if crop { - s.execute("image.rotation.arbitrary", json!({"angle": rot, "direction": "cw"}))?; + // Count points turn with the image here, since the crop after it moves them too. + crate::mode_cmds::rotate_arbitrary_with(s, &json!({"angle": rot, "direction": "cw"}), false)?; let nd = doc(s)?; let (cw, ch) = inscribed(w0, h0, rot.to_radians()); let (nw, nh) = (f64::from(nd.size.width), f64::from(nd.size.height)); diff --git a/crates/engine/src/cmd/count_resize_tests.rs b/crates/engine/src/cmd/count_resize_tests.rs index 48b08db27ed..32f3562aa4a 100644 --- a/crates/engine/src/cmd/count_resize_tests.rs +++ b/crates/engine/src/cmd/count_resize_tests.rs @@ -26,22 +26,24 @@ fn note(s: &Session) -> [f64; 2] { #[test] fn count_points_keep_their_coordinates() { - let steps: [(&str, Value); 8] = [ - ("image.imageSize", json!({"width": 300, "height": 200})), - ("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})), - ("image.imageRotation.90cw", json!({})), - ("image.imageRotation.90ccw", json!({})), - ("image.imageRotation.180", json!({})), - ("image.imageRotation.flipCanvasHorizontal", json!({})), - ("image.imageRotation.flipCanvasVertical", json!({})), - ("image.rotation.arbitrary", json!({"angle": 30})), + // The note at [100, 100] on the 600×400 canvas, where each command moves it. + let steps: [(&str, Value, [f64; 2]); 8] = [ + ("image.imageSize", json!({"width": 300, "height": 200}), [50.0, 50.0]), + ("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"}), [0.0, 50.0]), + ("image.imageRotation.90cw", json!({}), [300.0, 100.0]), + ("image.imageRotation.90ccw", json!({}), [100.0, 500.0]), + ("image.imageRotation.180", json!({}), [500.0, 300.0]), + ("image.imageRotation.flipCanvasHorizontal", json!({}), [500.0, 100.0]), + ("image.imageRotation.flipCanvasVertical", json!({}), [100.0, 300.0]), + ("image.rotation.arbitrary", json!({"angle": 30}), [236.794_919_243_112_3, 136.897_459_621_556_2]), ]; - for (cmd, p) in steps { + for (cmd, p, moved) in steps { let mut s = doc(); let before = note(&s); s.execute(cmd, p).unwrap(); assert_eq!(count_point(&s), POINT, "{cmd}"); - assert_ne!(note(&s), before, "{cmd}: notes still follow the image"); + let n = note(&s); + assert!((n[0] - moved[0]).abs() < 1e-6 && (n[1] - moved[1]).abs() < 1e-6, "{cmd}: note at {n:?}, expected {moved:?}"); s.undo(); assert_eq!((count_point(&s), note(&s)), (POINT, before), "{cmd}: undo"); } @@ -62,3 +64,15 @@ fn crop_still_moves_count_points() { s.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap(); assert_ne!(count_point(&s), POINT, "not measured: Crop keeps today's behaviour"); } + +#[test] +fn ruler_straighten_with_crop_moves_count_points_with_the_image() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + s.execute("count.add", json!({"x": 250, "y": 150})).unwrap(); + s.execute("notes.add", json!({"x": 250, "y": 150})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); + s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap(); + let (c, n) = (count_point(&s), note(&s)); + assert!((c[0] - n[0]).abs() < 1e-6 && (c[1] - n[1]).abs() < 1e-6, "count {c:?} vs note {n:?}"); +} From 4b2fae426ff2cf183da2b609590334b33bcb5b41 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:24:02 +0100 Subject: [PATCH 22/65] gamut: mask_rgba refuses any non-RGB source profile, including Lab Co-Authored-By: Claude Sonnet 5.5 --- crates/cms/src/gamut.rs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/crates/cms/src/gamut.rs b/crates/cms/src/gamut.rs index aee5bb6dddd..94818dddb88 100644 --- a/crates/cms/src/gamut.rs +++ b/crates/cms/src/gamut.rs @@ -2,7 +2,7 @@ use crate::clut::Clut; use crate::pipeline::{Pipeline, Stage}; -use crate::profile::Profile; +use crate::profile::{ColorSpace, Profile}; use crate::transform::link_stages; use crate::{CmsError, Intent}; @@ -22,6 +22,7 @@ const PAR_CHUNK_PIXELS: usize = 16 * 1024; #[derive(Debug)] pub struct GamutCheck { inputs: usize, + source_space: ColorSpace, grid: Option, exact: (Pipeline, Pipeline), pub threshold: f32, @@ -49,7 +50,7 @@ impl GamutCheck { 4 => Some(Clut::sample(vec![17; 4], 1, de)), _ => None, }; - Ok(GamutCheck { inputs: n, grid, exact: (direct, via), threshold }) + Ok(GamutCheck { inputs: n, source_space: src.color_space, grid, exact: (direct, via), threshold }) } pub fn inputs(&self) -> usize { @@ -87,12 +88,12 @@ impl GamutCheck { /// the result is identical to calling [`Self::out_of_gamut`] per pixel. /// /// # Errors - /// [`CmsError::Invalid`] when the check was not built from a three-channel (RGB) source - /// profile: an RGBA pixel carries only three colour channels, so it cannot be tested - /// against a CMYK or gray source. Nothing is written to `mask` in that case. + /// [`CmsError::Invalid`] when the check was not built from an RGB source profile: an RGBA + /// pixel carries only RGB colour channels, so it cannot be tested against a CMYK, gray or + /// Lab source. Nothing is written to `mask` in that case. pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> Result { - if self.inputs != 3 { - return Err(CmsError::Invalid(format!("gamut mask needs a 3-channel (RGB) source profile, got {} channels", self.inputs))); + if self.source_space != ColorSpace::Rgb || self.inputs != 3 { + return Err(CmsError::Invalid(format!("gamut mask needs an RGB source profile, got {:?} with {} channels", self.source_space, self.inputs))); } let n = px.len().min(mask.len()); let (px, mask) = (&px[..n], &mut mask[..n]); @@ -150,8 +151,8 @@ mod tests { #[test] fn mask_rgba_rejects_non_rgb_source() { - // A CMYK (4-channel) and a gray (1-channel) source cannot be tested from RGBA pixels. - for src in [Builtin::CoatedCmyk, Builtin::GrayGamma22] { + // A CMYK (4-channel), gray (1-channel) and Lab (3-channel, not RGB) source cannot be tested from RGBA pixels. + for src in [Builtin::CoatedCmyk, Builtin::GrayGamma22, Builtin::LabD50] { let check = GamutCheck::new(src.profile(), Builtin::Srgb.profile(), 4.0).unwrap(); let px = image(64); let mut mask = vec![9u8; 64]; From 138af24a91be4411eb0d48121193da3465140bd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 7 Nov 2026 16:58:16 +0100 Subject: [PATCH 23/65] fix(engine): the magic eraser refuses Indexed and Bitmap documents `paint.magicEraser` checked the layer kind and the pixel lock but never the document's colour mode, so a click in an opened palette PNG (which opens in Indexed Color) erased it: the Background became "Layer 0" and a "Magic Eraser" step went into the History. The reference application answers that click with an alert instead, with one OK button, and leaves the document alone. The two measured alerts now come back from the command before anything is sampled or edited, so a refused click changes nothing at all: no pixel, no selection, no History step, and the Background stays a Background. Indexed Color and Bitmap are refused at every bit depth; Duotone and Multichannel are not measured and keep today's behaviour, as do RGB, Grayscale, CMYK and Lab at 8 bits and RGB at 16 and 32 bits. The Magic Eraser press shows the same text as a `DialogKind::Error` (the message and OK), like a refused Move press does, and asks the engine's own check for it rather than repeating the rule, so the press and the command cannot disagree. Background Eraser (#11912) and Mixer Brush (#11958) get their own alerts in their own items. Fixes #12032 --- crates/engine/src/cmd/eraser_cmds.rs | 38 +++++- .../magic_eraser_mode_refusal_tests.rs | 104 ++++++++++++++++ crates/ui-egui/src/tools/eraser_ui.rs | 111 +++++++++++++++++- 3 files changed, 251 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs diff --git a/crates/engine/src/cmd/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs index 1433498078b..c12c6673f68 100644 --- a/crates/engine/src/cmd/eraser_cmds.rs +++ b/crates/engine/src/cmd/eraser_cmds.rs @@ -6,8 +6,13 @@ //! Background can't hold transparency. The Magic Eraser paints the background colour on other //! layers with locked transparency; the Background Eraser refuses them. Both respect the selection, //! work in the layer's own colour model and depth, and are one undo step per click / stroke. +//! +//! The Magic Eraser refuses Indexed Color and Bitmap documents with the reference's alerts +//! ([`MAGIC_ERASER_INDEXED_ERROR`] and [`MAGIC_ERASER_BITMAP_ERROR`], #12032), before it samples +//! anything, so a refused click leaves the document exactly as it was. use photocraft_algo::selection as sel; +use photocraft_color::ColorMode; use photocraft_doc::{Document, Layer, LayerContent, LayerId}; use photocraft_geom::Rect; use photocraft_paint::Stroke; @@ -77,6 +82,28 @@ fn damage(s: &mut Session, dmg: Rect, erased: bool) -> Value { json!({ "erased": erased, "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] }) } +/// The reference's alert for a Magic Eraser click in an Indexed Color document (#12032), measured: +/// one alert with an OK button. The UI shows this text through `tl!` (English is the catalog +/// source); the command returns it as its error. +pub const MAGIC_ERASER_INDEXED_ERROR: &str = + "Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +/// The same alert for a Bitmap document (#12032), which points at Grayscale instead. +pub const MAGIC_ERASER_BITMAP_ERROR: &str = + "Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The alert `doc` gets instead of a Magic Eraser click, or `None` when the click may erase +/// (#12032). Indexed Color and Bitmap are the two measured refusals, at every bit depth; Duotone +/// and Multichannel are not measured and keep erasing, as do RGB, Grayscale, CMYK and Lab. +/// The text is exactly what `paint.magicEraser` answers with, so the tool can refuse the press with +/// what the command would refuse. +pub fn magic_eraser_refusal(doc: &Document) -> Option<&'static str> { + match doc.mode { + ColorMode::Indexed => Some(MAGIC_ERASER_INDEXED_ERROR), + ColorMode::Bitmap => Some(MAGIC_ERASER_BITMAP_ERROR), + _ => None, + } +} + /// `paint.magicEraser`: erase the wand region around `(x, y)`. fn magic_eraser(s: &mut Session, p: &Value) -> Result { const CMD: &str = "paint.magicEraser"; @@ -87,6 +114,13 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result { let tolerance = number(p, CMD, "tolerance", 32.0, 0.0..=255.0)? as f32; let opacity = number(p, CMD, "opacity", 100.0, 1.0..=100.0)? as f32 / 100.0; let (anti_alias, contiguous, sample_all) = (flag(p, "antiAlias", true), flag(p, "contiguous", true), flag(p, "sampleAllLayers", false)); + // #12032: an Indexed Color or a Bitmap document gets the reference's alert before anything is + // sampled or edited, so the click changes nothing: no pixels, no selection, no History step, + // and the Background stays a Background. The tool refuses the press with this same text + // (`eraser_ui::click`), which is why the check belongs to the command. + if let Some(msg) = s.active().and_then(|st| magic_eraser_refusal(&st.doc)) { + return Err(EngineError::Other(msg.into())); + } let id = active_pixel_layer(s, p, CMD)?; { let d = s.active().ok_or(EngineError::NoDocument)?; @@ -257,7 +291,7 @@ pub fn specs() -> Vec { label: "Magic Eraser", menu: &[], shortcut: None, - params: r##"{"x":px,"y":px,"tolerance":0..255=32,"antiAlias":bool=true,"contiguous":bool=true,"sampleAllLayers":bool=false,"opacity":1..100=100}"##, + params: r##"{"x":px,"y":px,"tolerance":0..255=32,"antiAlias":bool=true,"contiguous":bool=true,"sampleAllLayers":bool=false,"opacity":1..100=100} (one undo step; a click off the canvas erases nothing and records no step; refused with the tool's alert and nothing changes: an Indexed Color document answers "Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit).", a Bitmap document "Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; Duotone and Multichannel erase as before)"##, enabled: has_pixel_layer, run: magic_eraser, journal: true, @@ -275,5 +309,7 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +mod magic_eraser_mode_refusal_tests; #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs b/crates/engine/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs new file mode 100644 index 00000000000..b56d839310b --- /dev/null +++ b/crates/engine/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs @@ -0,0 +1,104 @@ +//! #12032: the Magic Eraser refuses Indexed Color and Bitmap documents with the reference's +//! alerts, and refuses them *before* it samples or edits anything: no History step, the Background +//! stays a Background, the pixels and the selection stay as they were. Duotone and Multichannel +//! are not measured, so they keep today's behaviour; the modes and depths the issue lists as +//! working (RGB, Grayscale, CMYK and Lab at 8 bits, RGB at 16 and 32 bits) still erase. + +use super::*; +use photocraft_doc::{Color, SampleType, Size}; + +/// The reference's alert for an Indexed Color document, measured (#12032); the alert has one OK +/// button. Spelled out here rather than taken from the command, so the test fails if the text the +/// app shows ever drifts from what was measured. +const INDEXED: &str = "Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +/// Its alert for a Bitmap document, measured (#12032). +const BITMAP: &str = "Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// A 64x48 document in `mode` at `depth`: a white Background - one flat colour, so a Magic Eraser +/// click on it would wipe the canvas out - with a live selection. Both must survive a refusal. +fn session(mode: photocraft_color::ColorMode, depth: SampleType) -> Session { + let d = Document::with_background("palette", Size::new(64, 48), mode, depth, Color::WHITE); + let mut s = Session::new(); + s.add_document(d, None); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 20, "height": 20, "antiAlias": false})).unwrap(); + s +} + +/// What a refused click must leave exactly as it was: the document itself, the History depth, one +/// pixel, and the selection. +fn snapshot(s: &Session) -> (std::sync::Arc, usize, Vec, Option) { + let st = s.active().unwrap(); + let pixels = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(2, 2).to_vec(); + (st.doc.clone(), st.history.past_len(), pixels, st.doc.selection.clone()) +} + +/// The text `paint.magicEraser` answers this click with, panicking with `case` in its message when +/// it erases or answers something else. +fn alert(s: &mut Session, case: &str, want: &str, p: Value) -> String { + match s.execute("paint.magicEraser", p.clone()) { + Err(e) if e.to_string() == want => e.to_string(), + Err(e) => panic!("{case}: refused with the wrong text: {e}"), + Ok(r) => panic!("{case}: the click erased instead of being refused: {r}"), + } +} + +#[test] +fn magic_eraser_refuses_indexed_and_bitmap_with_the_reference_alerts() { + for (case, mode, want) in [("Indexed", photocraft_color::ColorMode::Indexed, INDEXED), ("Bitmap", photocraft_color::ColorMode::Bitmap, BITMAP)] { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + // The refusal is the same whatever else the click asks for: sampling every layer or + // only this one, the whole canvas or one colour, inside the selection or not. + for p in [ + json!({"x": 2, "y": 2, "antiAlias": false}), + json!({"x": 12, "y": 12, "antiAlias": false}), + json!({"x": 2, "y": 2, "antiAlias": false, "sampleAllLayers": true}), + json!({"x": 2, "y": 2, "antiAlias": false, "contiguous": false, "tolerance": 255, "opacity": 1}), + ] { + let name = format!("{case} {depth:?} {p}"); + let mut s = session(mode, depth); + let (doc, steps, pixels, selection) = snapshot(&s); + let id = s.active().unwrap().active_layer.unwrap(); + assert_eq!(alert(&mut s, &name, want, p), want.to_string()); + let st = s.active().unwrap(); + // Nothing at all happened: not a History step, not a pixel, not the selection, and + // the Background is still a Background rather than the "Layer 0" the erase makes. + assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "{name}: the document is untouched"); + assert_eq!(st.history.past_len(), steps, "{name}: no History step"); + assert_eq!(st.doc.layer(id).unwrap().name, "Background", "{name}: the layer name"); + assert!(st.doc.is_background(id), "{name}: still a Background"); + assert_eq!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2).to_vec(), pixels, "{name}: pixels unchanged"); + assert_eq!(st.doc.selection, selection, "{name}: the selection is unchanged"); + } + } + } +} + +#[test] +fn magic_eraser_still_erases_the_measured_modes_and_depths() { + for (mode, depth) in [("rgb", 8), ("gray", 8), ("cmyk", 8), ("lab", 8), ("rgb", 16), ("rgb", 32)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "mode": mode, "depth": depth})).unwrap(); + let h = s.active().unwrap().history.past_len(); + let id = s.active().unwrap().active_layer.unwrap(); + let r = s.execute("paint.magicEraser", json!({"x": 2, "y": 2, "antiAlias": false})).unwrap(); + assert_eq!(r["erased"], true, "{mode} {depth}: still erases"); + assert_eq!(s.active().unwrap().history.past_len(), h + 1, "{mode} {depth}: one undo step"); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().name, "Layer 0", "{mode} {depth}: the Background became a layer"); + assert_eq!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2)[3], 0.0, "{mode} {depth}: erased to transparency"); + } +} + +/// Duotone and Multichannel are *not measured* (#12032), so they keep today's behaviour: the click +/// erases, and neither of the two alerts appears. +#[test] +fn duotone_and_multichannel_keep_todays_behaviour() { + for (case, mode) in [("Duotone", photocraft_color::ColorMode::Duotone), ("Multichannel", photocraft_color::ColorMode::Multichannel)] { + let mut s = session(mode, SampleType::U8); + let id = s.active().unwrap().active_layer.unwrap(); + let r = s.execute("paint.magicEraser", json!({"x": 2, "y": 2, "antiAlias": false})); + assert!(r.is_ok(), "{case}: keeps today's behaviour, answers {r:?}"); + assert_eq!(r.unwrap()["erased"], true, "{case}"); + assert_eq!(s.active().unwrap().doc.layer(id).unwrap().name, "Layer 0", "{case}"); + } +} diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index ac896eeb0b0..2f7f7b57b34 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -1,10 +1,14 @@ //! UI for the Eraser group's colour-aware tools: Magic Eraser (click → `paint.magicEraser`) and //! Background Eraser (stroke → `paint.backgroundEraser`), with their options bars. +//! +//! A Magic Eraser press in an Indexed Color or Bitmap document shows the reference's alert (message +//! + OK) and runs nothing: the document keeps its pixels and its History (#12032). +use photocraft_engine::eraser_cmds::{MAGIC_ERASER_BITMAP_ERROR, MAGIC_ERASER_INDEXED_ERROR}; use serde_json::{Value, json}; use crate::PhotocraftApp; -use crate::state::Tool; +use crate::state::{DialogKind, Tool}; use crate::theme::Tokens; use crate::{icons, widgets}; @@ -15,11 +19,36 @@ fn report(app: &mut PhotocraftApp, r: Result) { } } +/// The alert this document gets instead of a Magic Eraser click (#12032): `Some(text)` means the +/// click is refused. The check is the engine's, so the press and `paint.magicEraser` can never +/// disagree about what is erased. +fn document_alert(app: &PhotocraftApp) -> Option<&'static str> { + app.session.active().and_then(|st| photocraft_engine::eraser_cmds::magic_eraser_refusal(&st.doc)) +} + +/// A `paint.magicEraser` error as the alert it was meant to be (#12032), so a click that reaches +/// the command shows the same dialog the press shows rather than only the status bar. +fn error_alert(error: &str) -> Option<&'static str> { + [MAGIC_ERASER_INDEXED_ERROR, MAGIC_ERASER_BITMAP_ERROR].into_iter().find(|text| *text == error) +} + +/// Opens the alert: the message and one OK button, as a refused Move press does +/// (`move_lock::prompt`). +fn refuse(app: &mut PhotocraftApp, message: &str) { + app.ui.open_dialog(DialogKind::Error, json!({"message": tl!(message)}).as_object().cloned().unwrap_or_default()); +} + /// Magic Eraser click at document `(x, y)`. Returns false for other tools. pub fn click(app: &mut PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { if tool != Tool::MagicEraser { return false; } + // An Indexed Color or Bitmap document (#12032): the reference answers the click with its alert + // and erases nothing, so the command is never reached - and the document keeps its History. + if let Some(message) = document_alert(app) { + refuse(app, message); + return true; + } let o = &app.ui.tool_options; let p = json!({ "x": x.floor(), @@ -31,6 +60,11 @@ pub fn click(app: &mut PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { "opacity": o.magic_eraser_opacity, }); let r = app.run("paint.magicEraser", p); + if let Err(e) = &r + && let Some(message) = error_alert(e) + { + refuse(app, message); + } report(app, r); true } @@ -133,3 +167,78 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } true } + +#[cfg(test)] +mod tests { + use super::*; + use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; + + /// The message of every open error dialog, in the order they were opened. + fn alerts(app: &PhotocraftApp) -> Vec<&str> { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(|m| m.as_str())).collect() + } + + /// The app with a white 64x48 document in `mode` open and the Magic Eraser picked: a click on + /// it would wipe the flat canvas out. + fn app_in(mode: ColorMode) -> PhotocraftApp { + let mut s = photocraft_engine::Session::new(); + s.add_document(Document::with_background("p", Size::new(64, 48), mode, SampleType::U8, Color::WHITE), None); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.ui.tool = Tool::MagicEraser; + app + } + + /// #12032: the press in an Indexed Color or a Bitmap document shows the reference's alert - the + /// measured text and an OK button - and runs nothing: no History step, no erase, the Background + /// stays a Background, and the alert rather than the status bar carries the message. + #[test] + fn a_press_in_an_indexed_or_bitmap_document_shows_the_alert_and_erases_nothing() { + for (case, mode, want) in [("Indexed", ColorMode::Indexed, MAGIC_ERASER_INDEXED_ERROR), ("Bitmap", ColorMode::Bitmap, MAGIC_ERASER_BITMAP_ERROR)] { + let mut app = app_in(mode); + let st = app.session.active().unwrap(); + let (doc, steps) = (st.doc.clone(), st.history.past_len()); + let id = st.active_layer.unwrap(); + assert!(click(&mut app, Tool::MagicEraser, 2.0, 2.0), "{case}: the Magic Eraser takes the click"); + assert_eq!(alerts(&app), [want], "{case}: one alert with the reference's text"); + let st = app.session.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "{case}: the command never ran"); + assert_eq!(st.history.past_len(), steps, "{case}: no History step"); + assert_eq!(st.doc.layer(id).unwrap().name, "Background", "{case}: still a Background"); + assert!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2)[3] > 0.0, "{case}: nothing erased"); + assert!(!app.ui.status_error, "{case}: the alert is the answer, not the status bar"); + // OK closes it (`DialogKind::Error` asks for nothing else), and the next press answers + // the same way: the document is no more erasable than it was. + let open: Vec = app.ui.dialogs.iter().map(|d| d.id).collect(); + for dialog in open { + app.ui.close_dialog(dialog); + } + click(&mut app, Tool::MagicEraser, 10.0, 10.0); + assert_eq!(alerts(&app), [want], "{case}: the next press is refused too"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "{case}: still no History step"); + } + } + + /// #12032: the new press check leaves every document the tool can edit exactly as it was: the + /// click erases, no alert opens. + #[test] + fn a_press_in_an_editable_document_still_erases() { + for (case, mode) in [ + ("RGB", ColorMode::Rgb), + ("Grayscale", ColorMode::Grayscale), + ("CMYK", ColorMode::Cmyk), + ("Lab", ColorMode::Lab), + ("Duotone", ColorMode::Duotone), + ("Multichannel", ColorMode::Multichannel), + ] { + let mut app = app_in(mode); + let steps = app.session.active().unwrap().history.past_len(); + assert!(click(&mut app, Tool::MagicEraser, 2.0, 2.0), "{case}"); + assert!(app.ui.dialogs.iter().all(|d| d.kind != DialogKind::Error), "{case}: no alert"); + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + assert_eq!(st.doc.layer(id).unwrap().name, "Layer 0", "{case}: the Background became a layer"); + assert_eq!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2)[3], 0.0, "{case}: erased to transparency"); + assert_eq!(st.history.past_len(), steps + 1, "{case}: one undo step"); + } + } +} From 8c5467355d40f14a0ecd2e0321e1a49d00fc8105 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 18:27:44 +0100 Subject: [PATCH 24/65] Affinity import: charge shape caches by the compiled stroke bounds An acute miter reaches past the stroke width, so the cache could span tiles that were not charged to the import budget. Compile the shape once, charge its clipped bounds and render from the same compiled shape. Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/affinity.rs | 47 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index fb33fd8a848..3a52a60d220 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -478,12 +478,13 @@ impl Builder<'_> { // The pixel cache is optional (the shape renders from its path without it), so charge the // area it would cover to the import's pixel budget and go without it when that is spent: // geometry across a 300000 px canvas would otherwise be rasterized for every shape. - let reach = sh.stroke.as_ref().map_or(0, |s| (s.width.ceil() as i32).saturating_add(1)); - let area = frame.inflate(reach).intersect(&self.canvas); + // The compiled bounds are what `render` covers, an acute miter reaching past the stroke width included. + let compiled = photocraft_vector::CompiledShape::new(&sh, photocraft_vector::DEFAULT_TOLERANCE, self.canvas); + let area = compiled.bounds().map_or(Rect::default(), |b| b.intersect(&self.canvas)); // Whole tiles: even a 2x2 px shape keeps one, which 50 000 small shapes add up to gigabytes. let cost = crate::text_import::cache_bytes(area, self.format.bytes_per_pixel()); if charge(&mut self.cache_budget, cost) { - sh.cache = Some(photocraft_vector::render_shape(&sh, self.format, self.canvas)); + sh.cache = Some(compiled.render(self.format, self.canvas)); } else { self.uncached_shapes += 1; } @@ -814,6 +815,46 @@ mod tests { assert_eq!(b.pixel_budget, MAX_PIXEL_BYTES, "caches don't draw on the pool images need"); } + #[test] + fn an_acute_miter_is_charged_for_the_tiles_it_reaches() { + // A thin spike at x = 250 with a 4 px miter stroke reaches x = 270, into the next 256 px + // tile, though the stroke width alone would stay in the first. + let p = |x: f64, y: f64| af::Point { x, y }; + let sub = af::SubPath { + start: p(250.0, 100.0), + segments: [p(200.0, 95.0), p(200.0, 105.0), p(250.0, 100.0)].iter().map(|c| [*c; 3]).collect(), + closed: true, + }; + let mut d = page(vec![node(Kind::Shape { + path: af::Path { subpaths: vec![sub] }, + fills: Vec::new(), + strokes: vec![ap::Stroke { + paint: ap::Paint::Solid(ap::Color::Rgb { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }), + width: 4.0, + cap: Cap::Butt, + join: Join::Miter, + miter_limit: 20.0, + align: ap::Align::Center, + dash: None, + behind: false, + }], + even_odd: false, + })]); + d.spreads[0].bounds.x1 = 600.0; + d.spreads[0].bounds.y1 = 600.0; + let mut b = Builder::new("miter", &d).unwrap(); + let tile = crate::text_import::cache_bytes(Rect::new(0, 0, 1, 1), b.format.bytes_per_pixel()); + b.cache_budget = tile; + b.document(&d).unwrap(); + assert_eq!(b.uncached_shapes, 1, "two tiles do not fit a budget of one"); + assert_eq!(b.cache_budget, tile, "nothing was charged"); + let mut b2 = Builder::new("miter", &d).unwrap(); + b2.cache_budget = 2 * tile; + b2.document(&d).unwrap(); + assert_eq!(b2.uncached_shapes, 0); + assert_eq!(b2.cache_budget, 0, "charged for both tiles"); + } + #[test] fn a_cancelled_import_stops_building_layers() { let d = page((0..10).map(tiny_shape).collect()); From f38c1a54ca02443b0de1bb2acb688370bb1cfa71 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 01:25:16 +0100 Subject: [PATCH 25/65] Fix test RawOpen initializer after merge Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs index 024bf1f7f5f..760e6b95b05 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs @@ -757,7 +757,7 @@ fn auto_tone_of_a_never_shown_raw_matches_the_dialogs() { } } let method = photocraft_io::raw::Demosaic::Ahd; - let raw = RawOpen { document, name: "pattern.dng".into(), path: None, bytes: None, developed_with: method, demosaic: method }; + let raw = RawOpen { document, name: "pattern.dng".into(), path: None, bytes: None, decoded: None, developed_with: method, demosaic: method }; let (unshown, _) = filmstrip::first_settings(&app, &raw); open_raw(&mut app, &ctx, raw).unwrap(); let shown = &app.camera_raw.as_ref().unwrap().params; From d3fcccbe5e2fbc6afdbe93911e90b212e9ed216d Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:40:49 +0100 Subject: [PATCH 26/65] =?UTF-8?q?Actions:=20map=20Layer=20=E2=80=BA=20New?= =?UTF-8?q?=20=E2=80=BA=20Frame=20from=20Layers=20(#10723)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Make of class `framedGroupSection` with `From` = a layer by name loads as `layer.new.frameFromLayers` on that layer. The recorded descriptor, session ids included, saves back byte for byte while the step still frames the same layer with the same name; native steps write the measured keys without the session ids. frameFromLayers sized the frame from the selected layers even when given a `layer`, while the grouping it runs takes in only that layer; the frame now fits the given layer. --- crates/engine/src/cmd/atn_cmds.rs | 4 + crates/engine/src/cmd/atn_cmds/events.rs | 1 + .../src/cmd/atn_cmds/frame_section_tests.rs | 238 ++++++++++++++++++ .../src/cmd/atn_cmds/steps_frame_section.rs | 121 +++++++++ crates/engine/src/cmd/atn_cmds/steps_make.rs | 7 + crates/engine/src/cmd/atn_cmds/tests.rs | 1 + crates/engine/src/cmd/frame_cmds.rs | 5 +- docs/atn.md | 16 +- 8 files changed, 391 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/atn_cmds/frame_section_tests.rs create mode 100644 crates/engine/src/cmd/atn_cmds/steps_frame_section.rs diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 0e90e5d3dc8..22e859ebd75 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -43,6 +43,7 @@ mod steps_direct_adjustments; mod steps_distort; mod steps_doc; mod steps_droplet; +mod steps_frame_section; mod steps_gallery; mod steps_gradient; mod steps_image; @@ -193,5 +194,8 @@ mod selection_tests; #[cfg(test)] mod render_tests; +#[cfg(test)] +mod frame_section_tests; + #[cfg(test)] mod recorded_tools_tests; diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 2736c87b943..43d520df6ef 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -855,6 +855,7 @@ pub(super) const EVENTS: &[Event] = &[ "image.calculations", "type.convertToShape", "type.createWorkPath", + super::steps_frame_section::COMMAND, "layer.new.layer", "layer.layerStyle.createLayer", "layer.new.group", diff --git a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs new file mode 100644 index 00000000000..396ba420a87 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs @@ -0,0 +1,238 @@ +//! #10723: Layer › New › Frame from Layers, recorded as a Make of class `framedGroupSection` +//! (`docs/atn.md`, "Recorded through the menus"). + +use super::*; +use photocraft_doc::{Layer, LayerId}; +use photocraft_geom::Rect; + +const FRAME: &str = "layer.new.frameFromLayers"; +const SOURCE: &str = "_atnFrameSectionDescriptor"; + +/// `From`: the layer `name`, by name. +fn by_name(name: &str) -> D { + D::Reference(vec![ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul(name) }]) +} + +/// The measured step, session ids included, built here independently of the converter. +fn recorded(from: D, name: &str) -> Descriptor { + Descriptor::new("null") + .with("null", D::Reference(vec![ReferenceItem::Class(class("framedGroupSection"))])) + .with("From", from) + .with("layerSectionStart", D::Integer(4)) + .with("layerSectionEnd", D::Integer(5)) + .with("Nm ", D::Text(UnicodeString::new_nul(name))) +} + +/// `d` without the keys `drop`. +fn without(mut d: Descriptor, drop: &[&str]) -> Descriptor { + d.items.retain(|(k, _)| !drop.iter().any(|key| k.is(key))); + d +} + +/// The step PhotoCraft writes: the measured keys without the session ids. +fn canonical(from: D, name: Option<&str>) -> Descriptor { + let d = without(recorded(from, name.unwrap_or("")), &["layerSectionStart", "layerSectionEnd"]); + if name.is_some() { d } else { without(d, &["Nm "]) } +} + +/// The target layer, the `From` of a step recorded in PhotoCraft without a layer of its own. +fn target_layer() -> D { + D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Trgt") }]) +} + +/// Load the Make steps holding `ds` as action "A" through `actions.load`. +fn load(ds: Vec) -> (Session, Value) { + let items = ds.into_iter().map(|d| AtnItem { event: AtnEvent::Code(*b"Mk "), dictionary: b"Make".to_vec(), descriptor: Some(d), ..Default::default() }); + let file = AtnFile { + name: UnicodeString::new_nul("Frames"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: items.collect(), ..Default::default() }], + ..Default::default() + }; + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&atn::write(&file).unwrap())})).unwrap(); + (s, r) +} + +/// The descriptor of the first step of action "A" as `actions.save` writes it. +fn saved(s: &mut Session) -> Option> { + let r = s.execute("actions.save", json!({"action": "A"})).unwrap(); + assert_eq!(r["skipped"], json!([]), "{r}"); + let mut items = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap().actions.remove(0).items; + assert_eq!(items[0].event, AtnEvent::Code(*b"Mk ")); + items.remove(0).descriptor.as_ref().map(Descriptor::to_bytes) +} + +/// The descriptor a native Frame from Layers step with `p` saves as, if it saves. +fn exported(p: &Value) -> Option { + export_item(FRAME, p, "S").and_then(|item| item.descriptor) +} + +/// A 100 × 80 document with "Photo" (pixels at (10, 15)–(40, 45)) under "Other" (pixels at +/// (60, 5)–(90, 25)), "Other" selected. +fn two_layers(s: &mut Session) -> (LayerId, LayerId) { + s.execute("file.new", json!({"width": 100, "height": 80})).unwrap(); + let mut add = |name: &str, r: Rect| { + s.edit(name, |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster(name, fmt); + l.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(id) + }) + .unwrap() + }; + let photo = add("Photo", Rect::new(10, 15, 40, 45)); + let other = add("Other", Rect::new(60, 5, 90, 25)); + s.execute("layer.select", json!({"layer": other.0, "mode": "replace"})).unwrap(); + (photo, other) +} + +/// The frame layers named `name`, as (group id, frame `[x, y, w, h]`). +fn frames(s: &Session, name: &str) -> Vec<(LayerId, [f64; 4])> { + let doc = &s.active().unwrap().doc; + doc.walk() + .into_iter() + .filter(|(_, _, l)| l.name == name) + .filter_map(|(_, _, l)| l.frame.as_ref().map(|f| (l.id, [f.transform.m[4], f.transform.m[5], f.transform.m[0], f.transform.m[3]]))) + .collect() +} + +/// Recorded steps load with the exact layer and name and save back byte for byte: the measured +/// form, another key order, no session ids, no name, and the target-layer form. +#[test] +fn recorded_steps_load_and_save_back_unchanged() { + let mut reordered = recorded(by_name("Photo"), "Frame 1"); + reordered.items.reverse(); + let cases = [ + (recorded(by_name("Photo"), "Frame 1"), json!({"layer": "Photo", "name": "Frame 1"})), + (reordered, json!({"layer": "Photo", "name": "Frame 1"})), + (without(recorded(by_name("Ébène"), "Cadre"), &["layerSectionStart", "layerSectionEnd"]), json!({"layer": "Ébène", "name": "Cadre"})), + (without(recorded(by_name("Photo"), ""), &["Nm "]), json!({"layer": "Photo"})), + (recorded(by_name("Photo"), ""), json!({"layer": "Photo", "name": ""})), + (canonical(target_layer(), Some("Frame 1")), json!({"name": "Frame 1"})), + ]; + for (d, params) in cases { + let (mut s, r) = load(vec![d.clone()]); + assert_eq!(r["unsupported"], json!([]), "{r}"); + let (id, p) = &s.actions.list[0].steps[0]; + let mut p = p.clone(); + p.as_object_mut().unwrap().remove(SOURCE); + assert_eq!((id.as_str(), &p), (FRAME, ¶ms)); + assert_eq!(saved(&mut s), Some(d.to_bytes())); + } +} + +/// A loaded step frames the layer it names, not the selected one: the frame fits that layer's +/// pixels, the other layer stays where it was, and one Undo takes the frame back. +#[test] +fn a_loaded_step_frames_the_named_layer_and_undoes() { + let (mut s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); + let (photo, other) = two_layers(&mut s); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[10.0, 15.0, 30.0, 30.0]]); + let doc = &s.active().unwrap().doc; + assert!(doc.layer(photo).is_none(), "Photo went into the frame"); + assert!(doc.layers.iter().any(|l| l.id == other), "Other stays a top-level layer"); + s.execute("history.undo", json!({})).unwrap(); + assert!(frames(&s, "Frame 1").is_empty()); + let doc = &s.active().unwrap().doc; + assert!(doc.layers.iter().any(|l| l.id == photo) && doc.layers.iter().any(|l| l.id == other)); +} + +/// Without a layer of its own the command still frames the selected layers. +#[test] +fn without_a_layer_the_selected_layers_are_framed() { + let mut s = Session::new(); + let (photo, other) = two_layers(&mut s); + s.execute(FRAME, json!({"name": "Frame 1"})).unwrap(); + assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[60.0, 5.0, 30.0, 20.0]]); + let doc = &s.active().unwrap().doc; + assert!(doc.layer(other).is_none() && doc.layers.iter().any(|l| l.id == photo)); +} + +/// A step recorded in PhotoCraft writes the measured keys without the session ids: the layer by +/// name (the target layer without one) and `Nm ` for a name that isn't blank. It loads back to +/// the same settings. +#[test] +fn native_steps_save_the_measured_keys() { + for (p, d, back) in [ + (json!({"layer": "Photo", "name": "Frame 1"}), canonical(by_name("Photo"), Some("Frame 1")), json!({"layer": "Photo", "name": "Frame 1"})), + (json!({"layer": "Photo"}), canonical(by_name("Photo"), None), json!({"layer": "Photo"})), + (json!({"name": "Frame 1"}), canonical(target_layer(), Some("Frame 1")), json!({"name": "Frame 1"})), + (json!({"name": " ", "layer": null}), canonical(target_layer(), None), json!({})), + (json!({}), canonical(target_layer(), None), json!({})), + ] { + assert_eq!(exported(&p), Some(d.clone()), "{p}"); + let (s, _) = load(vec![d]); + assert_eq!(s.actions.list[0].steps[0], (FRAME.to_string(), back), "{p}"); + } +} + +/// A native step the event can't hold is refused: a layer by id or selector, a name that isn't +/// text, or the group options the command passes on (colour, mode, opacity), which the step +/// doesn't record. +#[test] +fn settings_the_event_cannot_hold_are_refused() { + for p in [ + json!({"layer": 3}), + json!({"layer": {"index": 2}}), + json!({"layer": {"background": true}}), + json!({"name": 4}), + json!({"name": "Frame 1", "color": "red"}), + json!({"mode": "multiply"}), + json!({"opacity": 50}), + json!({"name": "Frame 1", "width": 200}), + ] { + assert!(exported(&p).is_none(), "{p}"); + } +} + +/// Any other form keeps the reference step: no `From`, another `From`, a repeated or extra key, +/// values of another type, or another `null`. +#[test] +fn other_forms_keep_the_photoshop_step() { + let measured = recorded(by_name("Photo"), "Frame 1"); + let replaced = |key: &str, v: D| { + let mut d = measured.clone(); + d.items.iter_mut().filter(|(k, _)| k.is(key)).for_each(|slot| slot.1 = v.clone()); + d + }; + let forms = [ + without(measured.clone(), &["From"]), + replaced("From", D::Reference(vec![ReferenceItem::Index { class: class("Lyr "), index: 2 }])), + replaced("From", D::Reference(vec![ReferenceItem::Name { class: class("Chnl"), name: UnicodeString::new_nul("Photo") }])), + replaced("From", D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Al ") }])), + replaced("From", D::Text(UnicodeString::new_nul("Photo"))), + replaced("Nm ", D::Integer(1)), + replaced("layerSectionEnd", D::Double(5.0)), + replaced("null", D::Reference(vec![ReferenceItem::Class(class("frame"))])), + measured.clone().with("Nm ", D::Text(UnicodeString::new_nul("Again"))), + measured.clone().with("From", by_name("Other")), + measured.clone().with("Wdth", D::UnitFloat { unit: PX, value: 200.0 }), + ]; + for d in forms { + let (mut s, r) = load(vec![d.clone()]); + assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}"); + assert_eq!(s.actions.list[0].steps[0].0, PHOTOSHOP_STEP, "{d:?}"); + assert_eq!(saved(&mut s), Some(d.to_bytes())); + } +} + +/// A loaded step whose layer or name was changed saves the new settings, not the stale +/// recording; one whose recording is damaged still saves its settings. +#[test] +fn changed_or_damaged_steps_save_their_settings() { + let (s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); + let mut p = s.actions.list[0].steps[0].1.clone(); + assert!(p.get(SOURCE).is_some(), "{p}"); + p["layer"] = json!("Other"); + assert_eq!(exported(&p), Some(canonical(by_name("Other"), Some("Frame 1")))); + p["layer"] = json!("Photo"); + p["name"] = json!(" "); + assert_eq!(exported(&p), Some(canonical(by_name("Photo"), None))); + p["name"] = json!("Frame 1"); + p[SOURCE] = json!("not base64!"); + assert_eq!(exported(&p), Some(canonical(by_name("Photo"), Some("Frame 1")))); +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_frame_section.rs b/crates/engine/src/cmd/atn_cmds/steps_frame_section.rs new file mode 100644 index 00000000000..e2340988e69 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_frame_section.rs @@ -0,0 +1,121 @@ +//! Layer › New › Frame from Layers, recorded as a Make of class `framedGroupSection`, as +//! `docs/atn.md` ("Recorded through the menus") measures it (#10723): `From` = the layer **by +//! name**, `layerSectionStart`, `layerSectionEnd` (longs) and `Nm ` (text). The dialog's width +//! and height are not in the step. +//! +//! `layerSectionStart` and `layerSectionEnd` are ids of the recording session, so they are not +//! settings: a loaded step keeps them only inside its recorded descriptor. + +use super::descriptors::{class_ref, desc, jstr, name_ref, target_ref, text}; +use super::fields::{Mapped, step}; +use super::{D, Descriptor, ReferenceItem, Value, json}; + +/// The native command the step plays as. +pub(super) const COMMAND: &str = "layer.new.frameFromLayers"; +/// The recorded descriptor, kept when it differs from the one [`to`] would write (session ids, +/// key order), so a load and save keeps the step unchanged. +const SOURCE: &str = "_atnFrameSectionDescriptor"; + +/// The settings a step holds: the layer it frames (`None`: the selected layers) and the frame's +/// name (`None`: no `Nm `, so the frame takes the command's default name). +#[derive(Debug, PartialEq)] +struct Settings { + layer: Option, + name: Option, +} + +/// Text without the trailing NUL the format may carry. +fn plain(t: &super::UnicodeString) -> Option { + String::from_utf16(t.0.strip_suffix(&[0]).unwrap_or(&t.0)).ok() +} + +/// `From`: a layer by name, or the target layer (`Lyr ` `Ordn.Trgt`), the form a step recorded +/// in PhotoCraft without a layer of its own writes. +fn source_layer(v: &D) -> Option> { + let D::Reference(r) = v else { return None }; + match r.as_slice() { + [ReferenceItem::Name { class, name }] if class.class_id.is("Lyr ") => Some(Some(plain(name)?)), + [ReferenceItem::Enumerated { class, type_id, value }] if class.class_id.is("Lyr ") && type_id.is("Ordn") && value.is("Trgt") => Some(None), + _ => None, + } +} + +/// The measured form only: `null` = class `framedGroupSection`, `From`, optional session ids +/// (longs) and an optional `Nm `, each key at most once and nothing else. +fn recorded(d: &Descriptor) -> Option { + const KEYS: [&str; 5] = ["null", "From", "layerSectionStart", "layerSectionEnd", "Nm "]; + let once = |key: &str| d.items.iter().filter(|(k, _)| k.is(key)).count() <= 1; + if d.items.iter().any(|(k, _)| !KEYS.iter().any(|key| k.is(key))) || !KEYS.iter().all(|key| once(key)) { + return None; + } + let section = matches!(d.get("null")?, D::Reference(r) if matches!(r.as_slice(), [ReferenceItem::Class(c)] if c.class_id.is("framedGroupSection"))); + if !section || ["layerSectionStart", "layerSectionEnd"].iter().any(|key| d.get(key).is_some_and(|v| !matches!(v, D::Integer(_)))) { + return None; + } + let name = match d.get("Nm ") { + None => None, + Some(D::Text(t)) => Some(plain(t)?), + Some(_) => return None, + }; + Some(Settings { layer: source_layer(d.get("From")?)?, name }) +} + +/// The descriptor a step recorded in PhotoCraft saves as: the measured keys without the session +/// ids, `Nm ` only for a name of the step's own (not blank). +fn canonical(settings: &Settings) -> Descriptor { + let from = settings.layer.as_deref().map_or_else(|| target_ref("Lyr "), |layer| name_ref("Lyr ", layer)); + let d = desc("null").with("null", class_ref("framedGroupSection")).with("From", from); + match &settings.name { + Some(name) => d.with("Nm ", text(name)), + None => d, + } +} + +/// Map the measured form; any other stays a complete kept step. +pub(super) fn from(d: &Descriptor) -> Mapped { + let Some(settings) = recorded(d) else { return Mapped::Unsupported { harmless: false } }; + let mut p = json!({}); + if let Some(layer) = &settings.layer { + p["layer"] = layer.as_str().into(); + } + if let Some(name) = &settings.name { + p["name"] = name.as_str().into(); + } + if *d != canonical(&settings) { + p[SOURCE] = photocraft_paint::tile::b64_encode(&d.to_bytes()).into(); + } + step(COMMAND, p) +} + +/// A native step the event holds: the selected layers or a layer by name, and a name. A layer by +/// id (meaningless in another document) and the group options the command passes on to the +/// group it frames (colour, mode, opacity) refuse export: the step records none of them. +fn native(p: &Value) -> Option { + let m = p.as_object()?; + if m.keys().any(|key| !["layer", "name", SOURCE].contains(&key.as_str())) { + return None; + } + let layer = match m.get("layer") { + None | Some(Value::Null) => None, + Some(Value::String(layer)) => Some(layer.clone()), + Some(_) => return None, + }; + let name = match m.get("name") { + None | Some(Value::Null) => None, + // A blank name is no name to the command either. + Some(Value::String(n)) => Some(n.clone()).filter(|n| !n.trim().is_empty()), + Some(_) => return None, + }; + Some(Settings { layer, name }) +} + +/// Save the recorded descriptor while the step still frames the same layer with the same name, +/// otherwise the canonical form of the step's settings. +pub(super) fn to(p: &Value) -> Option { + let settings = native(p)?; + let source = jstr(p, SOURCE) + .and_then(photocraft_paint::tile::b64_decode) + .and_then(|bytes| Descriptor::from_bytes(&bytes).ok()) + .filter(|d| recorded(d).is_some_and(|r| r.layer == settings.layer && r.name.filter(|n| !n.trim().is_empty()) == settings.name)); + Some(source.unwrap_or_else(|| canonical(&settings))) +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index c331d1c585c..6a5eb6dea71 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -552,6 +552,10 @@ pub(super) fn make_from(d: &Descriptor) -> Mapped { if let Some(mapped) = super::steps_layer_style::create_from_descriptor(d) { return mapped; } + // Layer › New › Frame from Layers (#10723). + if get_ref(d, "null").and_then(ref_class).as_deref() == Some("framedGroupSection") { + return super::steps_frame_section::from(d); + } if d.items == type_shape_descriptor().items { return none("type.convertToShape"); } @@ -720,6 +724,9 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option { if id == super::steps_layer_style::CREATE { return super::steps_layer_style::style_to(id, p); } + if id == super::steps_frame_section::COMMAND { + return super::steps_frame_section::to(p); + } if id == "type.convertToShape" { return p.as_object().filter(|p| p.is_empty()).map(|_| type_shape_descriptor()); } diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index ab152eddac4..da45f9c2ff0 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -691,6 +691,7 @@ fn every_mapped_command_exports_and_imports_back() { "rotationAdaptation":"none","scale":true,"mirror":false,"output":"new"}), ), ("edit.fade", json!({"opacity":50,"mode":"Multiply"})), + ("layer.new.frameFromLayers", json!({"layer": "Photo", "name": "Frame 1"})), ("layer.linkLayers", json!({})), ("layer.smartObjects.stackMode.range", json!({})), ("layer.smartObjects.stackMode.entropy", json!({})), diff --git a/crates/engine/src/cmd/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs index 8e2ea786b50..c88177cc972 100644 --- a/crates/engine/src/cmd/frame_cmds.rs +++ b/crates/engine/src/cmd/frame_cmds.rs @@ -135,8 +135,11 @@ fn new_frame(s: &mut Session, p: &Value) -> Result { Ok(result) } fn frame_from_layers(s: &mut Session, p: &Value) -> Result { + // A `layer` of its own (a recorded step names its layer) is what the grouping below takes + // in, so the frame fits that layer, not whatever is selected. + let explicit = crate::commands::explicit_layer(s, p)?; let st = s.active().ok_or(EngineError::NoDocument)?; - let ids = st.selected_layers(); + let ids = explicit.map_or_else(|| st.selected_layers(), |id| vec![id]); let bounds = ids .iter() .filter_map(|id| st.doc.layer(*id)) diff --git a/docs/atn.md b/docs/atn.md index be7eca3787e..33a476396f8 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -147,7 +147,7 @@ row; the action still adds only one Undo entry. | `CtTL` | cutToLayer | Layer Via Cut | `layer.new.layerViaCut` | | `LnsF` | lensFlare | Lens Flare | `filter.render.lensFlare` | | `Lvls` | levels | Levels | `image.adjustments.levels`, `image.autoTone`, `image.autoContrast` | -| `Mk ` | make | Make | `image.calculations`, `layer.layerStyle.createLayer`, `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newFillLayer.gradient`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot`, `type.convertToShape`, `type.createWorkPath` | +| `Mk ` | make | Make | `image.calculations`, `layer.layerStyle.createLayer`, `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.new.frameFromLayers` (Layer › New › Frame from Layers), `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newFillLayer.gradient`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot`, `type.convertToShape`, `type.createWorkPath` | | (string ID only) | animationFramesFromLayers | Make Frames from Layers | | | (string ID only) | matchColor | Match Color | `image.adjustments.matchColor` | | `Mxm ` | maximum | Maximum | `filter.other.maximum` | @@ -272,6 +272,20 @@ options are refused on export. Playback uses the native command's preconditions and current state. Isolate Layers toggles the panel view; type defaults remain session settings; Record Measurements uses the current measurement configuration. +Layer › New › Frame from Layers is a Make with `null` = the class +`framedGroupSection`, `From` = the layer by name and `Nm ` = the frame's name. It +plays as `layer.new.frameFromLayers` on that layer, and the frame fits that +layer's bounds whatever is selected. The dialog's width and height are not in the +step. `layerSectionStart` and `layerSectionEnd` are ids of the recording session: +a loaded step saves back its recorded descriptor, session ids included, while it +still frames the same layer with the same name, and a step recorded in PhotoCraft +writes `null`, `From` and `Nm ` (only for a name that isn't blank) without them. A +native step without a layer of its own frames the selected layers and writes +`From` = the target layer, a form the recordings don't show. Another `From`, a +repeated or extra key, or a value of another type stays a kept step; a native step +with a layer by id, or with the group options the command passes on (colour, mode, +opacity), refuses export. + Link Layers plays as the toggle the reference application performs (played twice on the same layers it links, then unlinks them; see the measurements below). Unlink is explicit and idempotent: it keeps an already unlinked selection unlinked and clears singleton link groups. From c82594d1ebbc31a6f1cb82f25ecb55bcf5959f24 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:38:58 +0100 Subject: [PATCH 27/65] Frame from Layers: admit a step on the layer it names (#10723) The spec didn't declare `layer`, so admission checked the selection: with no layer selected a step naming an existing layer failed with "select a layer". --- .../engine/src/cmd/atn_cmds/frame_section_tests.rs | 12 ++++++++++++ crates/engine/src/cmd/frame_cmds.rs | 5 ++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs index 396ba420a87..dec64be796c 100644 --- a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs +++ b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs @@ -141,6 +141,18 @@ fn a_loaded_step_frames_the_named_layer_and_undoes() { assert!(doc.layers.iter().any(|l| l.id == photo) && doc.layers.iter().any(|l| l.id == other)); } +/// A step that names its layer plays with no layer selected: the command is admitted on the +/// named layer, not the (empty) selection. +#[test] +fn a_loaded_step_plays_with_no_layer_selected() { + let (mut s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); + two_layers(&mut s); + s.execute("select.deselectLayers", json!({})).unwrap(); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[10.0, 15.0, 30.0, 30.0]]); +} + /// Without a layer of its own the command still frames the selected layers. #[test] fn without_a_layer_the_selected_layers_are_framed() { diff --git a/crates/engine/src/cmd/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs index c88177cc972..e48f3372461 100644 --- a/crates/engine/src/cmd/frame_cmds.rs +++ b/crates/engine/src/cmd/frame_cmds.rs @@ -362,7 +362,10 @@ pub fn specs() -> Vec { has_doc, new_frame, ), - CommandSpec { menu: &["Layer", "New"], ..spec("layer.new.frameFromLayers", "Frame from Layers", r#"{name?:str}"#, has_layer, frame_from_layers) }, + CommandSpec { + menu: &["Layer", "New"], + ..spec("layer.new.frameFromLayers", "Frame from Layers", r#"{"layer":id?,"name":str?}"#, has_layer, frame_from_layers) + }, spec("layer.frame.set", "Frame Properties", r#"{"layer":id?,"transform":[a,b,c,d,x,y]?,"stroke":object|null?,"name":str?}"#, has_doc, set), CommandSpec { journal: false, ..spec("layer.frame.info", "Frame Info", r#"{"layer":id?}"#, has_doc, query) }, spec("layer.frame.convert", "Convert to Frame", r#"{"layer":id?,"name":str?,"width":px?,"height":px?}"#, has_doc, convert), From 3dc0a8dd1cecf071668c54173da0b03c9ca80d44 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 9 Nov 2026 14:25:36 +0100 Subject: [PATCH 28/65] Frame from Layers: the no-selection test checks which layer was framed (#10723) --- crates/engine/src/cmd/atn_cmds/frame_section_tests.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs index dec64be796c..873ace66273 100644 --- a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs +++ b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs @@ -146,11 +146,15 @@ fn a_loaded_step_frames_the_named_layer_and_undoes() { #[test] fn a_loaded_step_plays_with_no_layer_selected() { let (mut s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); - two_layers(&mut s); + let (photo, other) = two_layers(&mut s); s.execute("select.deselectLayers", json!({})).unwrap(); let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); assert_eq!(played["ran"], 1, "{played}"); assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[10.0, 15.0, 30.0, 30.0]]); + // The frame took in Photo, not Other. + let doc = &s.active().unwrap().doc; + assert!(doc.layer(photo).is_none(), "Photo went into the frame"); + assert!(doc.layers.iter().any(|l| l.id == other), "Other stays a top-level layer"); } /// Without a layer of its own the command still frames the selected layers. From dc78b558209b1e9e83961a6036cbcd4891ff12a4 Mon Sep 17 00:00:00 2001 From: "Eng. Mahmoud Bek ElNemer" Date: Tue, 10 Nov 2026 02:41:13 +0200 Subject: [PATCH 29/65] fix(memory): detect unmounted cgroup sandboxes with empty /sys/fs/cgroup or empty mount source (#12426) Linux sandboxes such as Flatpak/bubblewrap can leave an empty `/sys/fs/cgroup` mount-point directory exposed through `sysfs` without mounting `cgroup`/`cgroup2`, and emit `tmpfs` mountinfo entries with an empty mount source (`- tmpfs rw,...`). Both caused `cgroup_limits` to fail closed as `Unreadable`, reporting 0 B system memory. Treat a readable empty `/sys/fs/cgroup` directory the same as `NotFound` when `/proc/self/mountinfo` parses cleanly with no cgroup mounts, and accept empty mount sources in `parse_mountinfo` while keeping missing, empty, truncated, cgroup-mounted, non-empty, or unreadable states strictly fail-closed. Fixes #12426 --- crates/raster/src/memory/system.rs | 154 ++++++++++++++++++++++++++--- 1 file changed, 138 insertions(+), 16 deletions(-) diff --git a/crates/raster/src/memory/system.rs b/crates/raster/src/memory/system.rs index 998720b8b52..5ad4ebf5e52 100644 --- a/crates/raster/src/memory/system.rs +++ b/crates/raster/src/memory/system.rs @@ -127,12 +127,12 @@ pub(super) mod linux { } #[derive(Clone, Debug, PartialEq, Eq)] - struct Mount { - root: String, - mount_point: String, - fstype: String, - options: String, - super_options: String, + pub(super) struct Mount { + pub(super) root: String, + pub(super) mount_point: String, + pub(super) fstype: String, + pub(super) options: String, + pub(super) super_options: String, } /// Measures available RAM and free swap from `/proc/meminfo`, capped by the process's memory @@ -206,14 +206,14 @@ pub(super) mod linux { MembershipParse::Malformed => return CgroupLimits::Unreadable, }; let mountinfo = std::fs::read_to_string(proc_root.join("self/mountinfo")).ok(); - // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) - // shows the process its membership path but no interface files, so no limit is - // observable. Failing closed there reported 0 bytes free and refused every PSD on a - // machine with tens of GB. A present directory still takes the guarded path below. - // Only a confirmed NotFound counts as absent: a stat that fails for another reason - // (permissions) leaves the directory possibly present, so that case stays fail-closed. - let sys_root_absent = matches!(std::fs::metadata(sys_root), Err(e) if e.kind() == std::io::ErrorKind::NotFound); - if sys_root_absent && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { + // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) or + // only an empty mount-point directory left by `sysfs` shows the process its membership path + // but no interface files, so no limit is observable. Failing closed there reported 0 bytes + // free and refused every PSD on a machine with tens of GB. Only a present non-empty or + // unreadable directory takes the guarded path below: a stat or read_dir that fails for + // another reason (permissions, non-directory) leaves a mounted hierarchy possibly present, + // so that case stays fail-closed. + if sys_root_absent_or_empty(sys_root) && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { return CgroupLimits::NotConstrained; } @@ -273,16 +273,34 @@ pub(super) mod linux { MembershipParse::Parsed(membership) } + /// Whether `/sys/fs/cgroup` is absent (`ErrorKind::NotFound`) or a readable empty directory. + /// + /// Permission errors, non-directory paths, and unreadable directories return `false` and stay + /// fail-closed. + pub(super) fn sys_root_absent_or_empty(sys_root: &Path) -> bool { + match std::fs::metadata(sys_root) { + Err(e) => e.kind() == std::io::ErrorKind::NotFound, + Ok(meta) => meta.is_dir() && std::fs::read_dir(sys_root).is_ok_and(|mut entries| entries.next().is_none()), + } + } + /// Parses `/proc/self/mountinfo` into the mount fields used to locate a cgroup hierarchy. /// /// Malformed lines are skipped; callers fail closed when no matching mount is found. - fn parse_mountinfo(text: &str) -> Vec { + pub(super) fn parse_mountinfo(text: &str) -> Vec { let mut mounts = Vec::new(); for line in text.lines() { let fields: Vec<&str> = line.split_whitespace().collect(); let Some(separator) = fields.iter().position(|f| *f == "-") else { continue }; + let super_options = fields.get(separator + 3).copied().or_else(|| { + // `show_mountinfo` writes ` `; an empty source + // (e.g. a bubblewrap tmpfs mount) leaves two spaces between `fstype` and options. + let after = line.split_once(" - ")?.1.trim_start(); + let fstype = fields.get(separator + 1).copied()?; + after.strip_prefix(fstype)?.starts_with(" ").then(|| fields.get(separator + 2).copied()).flatten() + }); let (Some(root), Some(point), Some(fstype), Some(super_options)) = - (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), fields.get(separator + 3).copied()) + (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), super_options) else { continue; }; @@ -966,6 +984,23 @@ mod tests { assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // Isolated case 1: a readable empty `/sys/fs/cgroup` mount-point directory with normal + // non-cgroup `mountinfo` also reports `NotConstrained`. + let (proc, sys) = fixture("empty-cgroup-mountpoint"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // Isolated case 2: absent `/sys/fs/cgroup` with a bubblewrap empty-source non-cgroup mount + // (`- tmpfs rw,...`) parses cleanly and reports `NotConstrained`. + let (proc, _) = fixture("absent-cgroup-empty-source"); + let sys = proc.parent().unwrap().join("absent-sys"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // A truncated mount line may be the cgroup mount: with /sys/fs/cgroup absent, fail closed. let (proc, _) = fixture("truncated-mountinfo-line"); let sys = proc.parent().unwrap().join("absent-sys"); @@ -1269,4 +1304,91 @@ mod tests { assert_eq!(linux::available_at(&proc, &sys), Some((4 << 30) + (512 << 20)), "legacy helper keeps RAM + swap"); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); } + + #[cfg(target_os = "linux")] + #[test] + fn linux_parse_mountinfo_handles_empty_mount_source() { + let tmpfs = "26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev,size=65536k\n"; + let cg2 = "30 20 0:26 /user.slice /sys/fs/cg\\0402 rw,relatime - cgroup2 rw,nsdelegate\n"; + let truncated = "31 20 0:27 / /sys/fs/cgroup rw - cgroup2 rw\n"; + let mounts = linux::parse_mountinfo(&format!("{tmpfs}{cg2}{truncated}")); + assert_eq!(mounts.len(), 2, "single-space line missing super_options is skipped"); + let m0 = &mounts[0]; + assert_eq!((&m0.root[..], &m0.mount_point[..], &m0.fstype[..]), ("/", "/tmp", "tmpfs")); + assert_eq!((&m0.options[..], &m0.super_options[..]), ("rw,nosuid,nodev", "rw,nosuid,nodev,size=65536k")); + let m1 = &mounts[1]; + assert_eq!((&m1.root[..], &m1.mount_point[..], &m1.fstype[..]), ("/user.slice", "/sys/fs/cg 2", "cgroup2")); + assert_eq!((&m1.options[..], &m1.super_options[..]), ("rw,relatime", "rw,nsdelegate")); + } + + /// An empty `/sys/fs/cgroup` directory only reports `NotConstrained` when `mountinfo` parses + /// cleanly with no cgroup mount; cgroup mounts (including empty-source lines), missing/empty/ + /// truncated `mountinfo`, non-empty directories, files, and unreadable directories fail closed. + #[cfg(target_os = "linux")] + #[test] + fn linux_empty_or_invalid_sys_root_fails_closed_unless_proven_unmounted() { + use std::os::unix::fs::PermissionsExt; + + let bad_mountinfo: [(&str, Option<&str>); 6] = [ + ("empty-sys-missing-mountinfo", None), + ("empty-sys-empty-mountinfo", Some("")), + ("empty-sys-garbage-mountinfo", Some("not a mountinfo line\n")), + ("empty-sys-truncated-mountinfo", Some("25 20 0:23 / /proc rw - proc proc rw\n30 20 0:26 / /sys/fs/cgroup rw - cgroup2\n")), + ("empty-sys-cgroup2-mount", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n")), + ("empty-sys-empty-source-cgroup2", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 rw\n")), + ]; + for (name, mountinfo) in bad_mountinfo { + let (proc, sys) = fixture(name); + write(&proc.join("self/cgroup"), "0::/app\n"); + if let Some(text) = mountinfo { + write(&proc.join("self/mountinfo"), text); + } + assert!(linux::sys_root_absent_or_empty(&sys), "{name}"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "{name}"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + // Empty `/sys/fs/cgroup` with a v1 memory mount in `mountinfo` also fails closed. + let (proc, sys) = fixture("empty-sys-cgroup-v1-mount"); + write(&proc.join("self/cgroup"), "4:memory:/app\n"); + write(&proc.join("self/mountinfo"), "31 24 0:26 / /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // A non-empty `/sys/fs/cgroup` directory is not treated as unmounted even with non-cgroup mountinfo. + let (proc, sys) = fixture("non-empty-sys-root"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + write(&sys.join("memory.max"), "1073741824\n"); + assert!(!linux::sys_root_absent_or_empty(&sys)); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // `sys_root` as a regular file and a `NotADirectory` path component return false and fail closed. + let (proc, _) = fixture("file-sys-root"); + let file_sys = proc.parent().unwrap().join("sys-as-file"); + write(&file_sys, ""); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + for path in [&file_sys, &file_sys.join("cgroup")] { + assert!(!linux::sys_root_absent_or_empty(path)); + assert_eq!(linux::cgroup_limits(&proc, path), linux::CgroupLimits::Unreadable); + } + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // An unreadable `/sys/fs/cgroup` directory (`read_dir` error) returns false and fails closed. + let (proc, sys) = fixture("unreadable-sys-root"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o000)).unwrap(); + let read_blocked = std::fs::read_dir(&sys).is_err(); + let absent = linux::sys_root_absent_or_empty(&sys); + let limits = linux::cgroup_limits(&proc, &sys); + std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + if read_blocked { + assert!(!absent); + assert_eq!(limits, linux::CgroupLimits::Unreadable); + } + } } From c29a960956abb6283e7d93015746b3798586ce3a Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Tue, 10 Nov 2026 05:11:36 -0600 Subject: [PATCH 30/65] fix(paint): raise the rim around a transparent fill partly instead of to full opacity --- crates/algo/src/paint.rs | 91 +++++++++++++++++------ crates/engine/src/cmd/paint_cmds/tests.rs | 32 ++++++-- 2 files changed, 96 insertions(+), 27 deletions(-) diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index d7a1139caf7..5ad909d9352 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -63,22 +63,37 @@ pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { } } -/// `o`, the pixel `d` with `c` composited at coverage `k`, with what is left of `d`'s transparency -/// filled by `c` up to coverage `full` (≥ `k`) as well, behind the colour already there: the -/// transparent part of the pixel takes the fill at `full` while its colour keeps the softer `k`. -fn fill_transparency(o: [f32; 4], d: [f32; 4], c: [f32; 4], k: f32, full: f32) -> [f32; 4] { - let add = ((full - k).max(0.0) * c[3].clamp(0.0, 1.0) * (1.0 - d[3]).max(0.0)).min((1.0 - o[3]).max(0.0)); - let a = o[3] + add; - if add.is_nan() || add <= 0.0 || a <= 0.0 { +/// The pixel `d` filled with `c` (mode `m`) by a bucket clicked on transparency. The colour `d` +/// holds blends with `c` at the region's coverage `k`, as on any fill. The transparent part of the +/// pixel (`1 − αd`) takes the fill at strength `full × (1 − αd)` instead of `k`: the emptier the +/// pixel, the more of its emptiness is filled. So the result's alpha is +/// `αd + (1 − αd)² × full × αc` whatever `k` is (#11354 review): +/// - empty pixels (the hole and the hole's anti-aliased edge) fill to `full`; +/// - the soft rim a Clear leaves rises only partly, so a faint rim stays (α 187 → 205, 56 → 211, +/// 3 → 252 at 8 bits; the reference application gives 204, 211, 253); +/// - opaque pixels come out bit-identical to a plain composite at `k`. +fn fill_transparency(m: BlendMode, d: [f32; 4], c: [f32; 4], k: f32, full: f32) -> [f32; 4] { + let o = blend::composite(m, d, c, k); + let held = d[3].clamp(0.0, 1.0); + if held >= 1.0 || !full.is_finite() || !held.is_finite() { return o; } - let mix = |i: usize| (o[i] * o[3] + c[i] * add) / a; + let empty = 1.0 - held; + let add = full.clamp(0.0, 1.0) * c[3].clamp(0.0, 1.0) * empty * empty; + let a = held + add; + if a <= 0.0 { + return o; + } + // The colour `d` holds, blended at `k` as if it were all there; then the new part is `c`. + let soft = blend::composite(m, [d[0], d[1], d[2], 1.0], c, k); + let mix = |i: usize| (soft[i] * held + c[i] * add) / a; [mix(0), mix(1), mix(2), a] } /// Composites `color(i)` over `area` of the surface with per-pixel coverage. With `transparency`, -/// a covered pixel's transparency takes the fill at that coverage instead (see -/// [`fill_transparency`]); Lock Transparent Pixels and Clear ignore it. +/// a covered pixel's transparency takes the fill at a strength set by that value and by how empty +/// the pixel is, instead of by the coverage (see [`fill_transparency`]); Lock Transparent Pixels +/// and Clear ignore it. #[allow(clippy::too_many_arguments)] fn composite_area( s: &mut Surface, @@ -116,11 +131,10 @@ fn composite_area( let d = photocraft_raster::to_rgba(&fmt, px); let o = match mode { FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k), - FillMode::Blend(m) => { - let c = color(x, y); - let o = blend::composite(m, d, c, k); - transparency.map_or(o, |full| fill_transparency(o, d, c, k, full(x, y))) - } + FillMode::Blend(m) => match transparency { + Some(full) => fill_transparency(m, d, color(x, y), k, full(x, y)), + None => blend::composite(m, d, color(x, y), k), + }, // Locked transparency keeps the alpha, so Clear leaves the pixel as it is. FillMode::Clear if lock_transparency => d, FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))], @@ -252,9 +266,10 @@ pub fn bucket_fill_inks( } let img = crate::selection::rgba8_image(s, area); let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false }; - // Clicked on transparency: the flood fills empty pixels, and the empty part of the pixels - // along its anti-aliased edge (the soft rim a cleared selection leaves) is that same empty - // area, so it is filled in full rather than left as a semi-transparent ring (#11311). + // Clicked on transparency: the flood fills empty pixels, and the empty pixels along its + // anti-aliased edge are that same empty area, so they fill in full rather than being left as + // a semi-transparent ring (#11311). The soft rim a cleared selection leaves rises only by how + // empty each pixel is, so a faint rim stays (#11354 review; see `fill_transparency`). let at_seed = usize::try_from(seed.1 - area.y0) .ok() .and_then(|y| y.checked_mul(area.width() as usize)) @@ -294,9 +309,10 @@ pub fn bucket_fill_region_inks( } /// [`bucket_fill_region_inks`]; with `fill_empty`, the transparent part of every pixel the region -/// touches takes the fill at the full opacity and selection coverage, while the region's -/// anti-aliasing still softens the colour over what is already there. Opaque pixels come out -/// exactly as without it. +/// touches takes the fill at the opacity and selection coverage scaled by how transparent the +/// pixel is (empty pixels fill in full, a partly transparent rim rises partly), while the +/// region's anti-aliasing still softens the colour over what is already there. Opaque pixels come +/// out exactly as without it. #[allow(clippy::too_many_arguments)] fn fill_region( s: &mut Surface, @@ -460,6 +476,39 @@ mod tests { assert!(!is_inks(&raw(&s, 3)), "a blended destination keeps its own encoding: {:?}", raw(&s, 3)); } + /// #11354 review: the soft rim a Clear leaves rises only partly. The reference application + /// takes rim alphas 187, 56 and 3 to 204, 211 and 253; the rule here, `α + (1 − α)²`, gives + /// 205, 211 and 252, each within one level of it (fit in PR #11354's review round). The rim pixel + /// sits on the bucket's anti-aliased fringe; the hole beside it fills in full and the opaque + /// art behind it is untouched by the rule. + #[test] + fn bucket_on_transparency_raises_the_cleared_rim_partly() { + let a = Rect::new(0, 0, 8, 1); + let white = |_, _| [1.0, 1.0, 1.0, 1.0]; + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + // (rim alpha after the Clear, the reference application's result, ours) + for (rim, reference, ours) in [(187, 204, 205), (56, 211, 211), (3, 253, 252)] { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + let mut s = Surface::new(fmt); + // The cleared hole is [0, 0, 0, 0] (Clear zeroes its RGB), the rim straight white. + s.fill_rect(Rect::new(4, 0, 5, 1), &[1.0, 1.0, 1.0, rim as f32 / 255.0]); + s.fill_rect(Rect::new(5, 0, 8, 1), &[1.0, 1.0, 1.0, 1.0]); + let before = s.clone(); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 32.0, true, true, 1.0, None, false, white, None, FillMode::Blend(BlendMode::Normal))); + let p = s.rgba(4, 0); + assert_eq!(level(p[3]), ours, "{fmt:?}: rim {rim} -> {p:?}"); + assert!((ours - reference).abs() <= 1, "rim {rim}: ours {ours}, reference {reference}"); + assert!(p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3), "{fmt:?}: the rim stays white: {p:?}"); + for x in 0..4 { + assert_eq!(level(s.rgba(x, 0)[3]), 255, "{fmt:?} rim {rim}: the hole and its edge fill in full at {x}"); + } + for x in 5..8 { + assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} rim {rim}: opaque art at {x}"); + } + } + } + } + /// The rule is for a click on transparency only: from an opaque seed, a semi-transparent /// neighbour along the edge keeps its own transparency (it belongs to another area). #[test] diff --git a/crates/engine/src/cmd/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs index 835e450d83b..8a1c81c90c5 100644 --- a/crates/engine/src/cmd/paint_cmds/tests.rs +++ b/crates/engine/src/cmd/paint_cmds/tests.rs @@ -368,12 +368,15 @@ fn assert_all_white(s: &Session, what: &str) { assert_eq!(not_white(&composite, width, 8), vec![], "{what}: composite pixels left after the fill"); } -/// #11311: after clearing an anti-aliased selection and bucket-filling the hole white at 100 %, -/// every pixel of the layer and of the composite is opaque white. The clear itself is right: it -/// leaves a soft rim of white at partial alpha around a fully transparent hole. The bucket used to -/// leave that rim (and its own anti-aliased edge) semi-transparent: a grey ring over the checkerboard. +/// #11311 / #11354 review: after clearing an anti-aliased selection and bucket-filling the hole +/// white at 100 %, the hole and the hole's edge are opaque white and the opaque art is untouched. +/// The soft rim the Clear left (straight white at partial alpha) rises only partly, as in the +/// reference application: a pixel the fill reaches at alpha `α` ends at `α + (1 − α)²`, so a faint +/// rim stays. Before the first round the hole's own edge stayed semi-transparent (a grey ring); +/// the first round filled the rim to 255 too, which the reference does not do. #[test] -fn bucket_after_clearing_an_antialiased_selection_leaves_no_ring() { +fn bucket_after_clearing_an_antialiased_selection_fills_the_hole_and_raises_the_rim_partly() { + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; for depth in [8, 16, 32] { let ellipse = json!({"x": 20, "y": 10, "width": 80, "height": 80, "ellipse": true, "antiAlias": true}); let (s, cleared) = clear_then_bucket(depth, ellipse, true); @@ -383,7 +386,24 @@ fn bucket_after_clearing_an_antialiased_selection_leaves_no_ring() { let rim: Vec<&[f32; 4]> = cleared.iter().filter(|p| p[3] > 0.0 && p[3] < 1.0).collect(); assert!(!rim.is_empty(), "depth {depth}: an anti-aliased clear leaves a soft rim"); assert!(rim.iter().all(|p| p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3)), "depth {depth}: the rim keeps its white"); - assert_all_white(&s, &format!("depth {depth}, anti-aliased ellipse")); + + let after = layer_rgba(&s); + let mut raised = 0; + for (i, (was, now)) in cleared.iter().zip(&after).enumerate() { + let at = (i % 120, i / 120); + if was[3] <= 0.0 || was[3] >= 1.0 { + assert_eq!(level(now[3]), 255, "depth {depth} at {at:?}: hole, hole edge and opaque art end opaque: {now:?}"); + } else if now[3] > was[3] { + raised += 1; + let want = was[3] + (1.0 - was[3]).powi(2); + assert!((now[3] - want).abs() < 1.5 / 255.0, "depth {depth} at {at:?}: rim {was:?} -> {now:?}, want alpha {want}"); + } else { + assert_eq!(now, was, "depth {depth} at {at:?}: a rim pixel the fill does not reach stays"); + } + assert!(now[..3].iter().all(|c| (c - 1.0).abs() < 1e-3), "depth {depth} at {at:?}: white: {now:?}"); + } + assert!(raised > 0, "depth {depth}: the fill reaches the rim"); + assert!(after.iter().any(|p| level(p[3]) < 255), "depth {depth}: a faint rim stays, as in the reference"); } } From 0f6715519cc0ab3d38cc8c6b07c1598e671595bb Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Tue, 10 Nov 2026 17:11:14 +0000 Subject: [PATCH 31/65] fix(ui): Reset Tool gives the Smudge tool a 13 px soft tip at 25 % spacing (#12964) --- crates/ui-egui/src/canvas/paint_mouse.rs | 14 ++-- crates/ui-egui/src/lib.rs | 2 + .../ui-egui/src/smudge_default_tip_tests.rs | 84 +++++++++++++++++++ 3 files changed, 95 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/src/smudge_default_tip_tests.rs diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index 0bcec596d3b..dc93d1a7219 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -41,10 +41,10 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // in Normal mode: each tool's Mode starts at Normal, so a Multiply Brush doesn't make the // first Pattern Stamp stroke multiply (or give Healing a mode its menu doesn't have). // The Art History Brush also starts at full opacity (#10263): its Opacity is its own. - // The Background Eraser, the Healing Brush, the Burn tool and the Clone Stamp start with - // their own measured tips instead, as the whole brush Reset Tool gives them (#11911, - // #12099, #12671, #12601). - None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::CloneStamp) => fresh_brush(tool, ¤t), + // The Background Eraser, the Healing Brush, the Burn tool, the Clone Stamp and the Smudge + // tool start with their own measured tips instead, as the whole brush Reset Tool gives + // them (#11911, #12099, #12671, #12601, #12964). + None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::CloneStamp | Tool::Smudge) => fresh_brush(tool, ¤t), None => { let opacity = if tool == Tool::ArtHistoryBrush { BrushSettings::default().opacity } else { current.opacity }; BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, opacity, ..current } @@ -82,12 +82,15 @@ const HEALING_BRUSH_TIP: (f32, f32, f32) = (19.0, 1.0, 0.25); const BURN_TOOL_TIP: (f32, f32, f32) = (65.0, 0.0, 0.25); /// The Clone Stamp's tip after Reset Tool (#12601): a 21 px soft round at 25 % spacing. const CLONE_STAMP_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25); +/// The Smudge tool's tip after Reset Tool (#12964): a 13 px soft round at 25 % spacing. +const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); /// `tool`'s brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's /// smoothing, with the session's own fields of `current`. The Brush tool's tip is /// [`BRUSH_TOOL_TIP`], the Background Eraser's [`BACKGROUND_ERASER_TIP`], the Healing Brush's /// [`HEALING_BRUSH_TIP`], the Burn tool's [`BURN_TOOL_TIP`], the Clone Stamp's -/// [`CLONE_STAMP_TIP`] with no smoothing; the other tools keep the default tip. +/// [`CLONE_STAMP_TIP`] with no smoothing, the Smudge tool's [`SMUDGE_TOOL_TIP`]; the other tools +/// keep the default tip. pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings { let mut brush = BrushSettings { smoothing: first_smoothing(), ..BrushSettings::default() }; match tool { @@ -95,6 +98,7 @@ pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings Tool::BackgroundEraser => (brush.size, brush.hardness, brush.spacing) = BACKGROUND_ERASER_TIP, Tool::Healing => (brush.size, brush.hardness, brush.spacing) = HEALING_BRUSH_TIP, Tool::Burn => (brush.size, brush.hardness, brush.spacing) = BURN_TOOL_TIP, + Tool::Smudge => (brush.size, brush.hardness, brush.spacing) = SMUDGE_TOOL_TIP, Tool::CloneStamp => { (brush.size, brush.hardness, brush.spacing) = CLONE_STAMP_TIP; brush.smoothing.amount = 0.0; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 52768f36802..867053fb644 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1076,3 +1076,5 @@ mod background_eraser_digit_keys_tests; #[cfg(test)] mod clone_stamp_reset_tip_tests; +#[cfg(test)] +mod smudge_default_tip_tests; diff --git a/crates/ui-egui/src/smudge_default_tip_tests.rs b/crates/ui-egui/src/smudge_default_tip_tests.rs new file mode 100644 index 00000000000..3086f524677 --- /dev/null +++ b/crates/ui-egui/src/smudge_default_tip_tests.rs @@ -0,0 +1,84 @@ +//! #12964: the Smudge tool starts, and comes back after Reset Tool, with the reference +//! application's tip: a 13 px soft round (hardness 0 %, angle 0°, roundness 100 %) at 25 % +//! spacing. Other tools' starting tips are unchanged. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::burn_default_tip_tests::{app, invoke, pick}; +use crate::state::Tool; + +/// Size, hardness, spacing, angle and roundness of the live brush, as `brush.get` reports them. +fn tip(app: &mut PhotocraftApp) -> [f64; 5] { + let b = app.run("brush.get", json!({})).unwrap(); + ["size", "hardness", "spacing", "angle", "roundness"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4) +} + +/// A tip that is no tool's starting tip, so a reset has something to undo. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness) = (57.0, 0.4, 0.6, 30.0, 0.5); +} + +const SMUDGE_TIP: [f64; 5] = [13.0, 0.0, 0.25, 0.0, 1.0]; +const DEFAULT_TIP: [f64; 5] = [20.0, 1.0, 0.1, 0.0, 1.0]; + +#[test] +fn reset_tool_gives_the_smudge_tool_a_13_px_soft_tip() { + let mut app = app(); + pick(&mut app, Tool::Smudge); + scramble(&mut app); + invoke(&mut app, "tool.reset", json!({})); + assert_eq!(tip(&mut app), SMUDGE_TIP); + // The options-bar brush chip reads the live brush's rounded size. + assert_eq!(app.session.tools.brush.size.round(), 13.0); +} + +#[test] +fn a_first_use_starts_with_the_tip() { + // No stored tool brushes, as on a fresh install: the Smudge tool's first pick, after another + // tool's tip. + let mut app = app(); + pick(&mut app, Tool::Pencil); + scramble(&mut app); + pick(&mut app, Tool::Smudge); + assert_eq!(tip(&mut app), SMUDGE_TIP); + // Its own tip is then kept across tool switches. + app.session.tools.brush.size = 42.0; + pick(&mut app, Tool::Pencil); + pick(&mut app, Tool::Smudge); + assert_eq!(tip(&mut app)[0], 42.0); +} + +#[test] +fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { + let mut app = app(); + pick(&mut app, Tool::Smudge); + scramble(&mut app); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + assert_eq!(tip(&mut app), SMUDGE_TIP, "active"); + let mut app = self::app(); + pick(&mut app, Tool::Smudge); + scramble(&mut app); + pick(&mut app, Tool::Pencil); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + pick(&mut app, Tool::Smudge); + assert_eq!(tip(&mut app), SMUDGE_TIP, "picked after the reset"); +} + +#[test] +fn blur_and_sharpen_keep_their_tips() { + for tool in [Tool::Blur, Tool::Sharpen] { + let mut a = app(); + pick(&mut a, tool); + scramble(&mut a); + invoke(&mut a, "tool.reset", json!({})); + assert_eq!(tip(&mut a), DEFAULT_TIP, "{tool:?}"); + // A first use still takes the current tip, as before. + let mut a = app(); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + pick(&mut a, tool); + assert_eq!(tip(&mut a)[0], 57.0, "{tool:?}, first use"); + } +} From 442d1e5a6e09912c43af019a221b0f2d6fbe2b24 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 10 Nov 2026 21:41:17 +0100 Subject: [PATCH 32/65] Camera Raw open: sensor decode keeps the caller's limits (#9432) Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/raw.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rs index 07a28c6da38..c75556b60c1 100644 --- a/crates/io/src/raw.rs +++ b/crates/io/src/raw.rs @@ -197,7 +197,7 @@ impl std::fmt::Debug for RawDecode { impl RawDecode { /// Decodes `bytes` and fits its look, as a default open does. pub fn new(bytes: &[u8]) -> Result { - let sensor = decode_sensor(bytes)?; + let sensor = decode_sensor(bytes, &limits())?; let look = default_look(bytes, &sensor); Ok(RawDecode::from_parts(bytes, sensor, look)) } @@ -221,10 +221,10 @@ impl RawDecode { } } -/// The sensor data of `bytes` under the shared limits. -fn decode_sensor(bytes: &[u8]) -> Result { +/// The sensor data of `bytes` under `limits`. +fn decode_sensor(bytes: &[u8], limits: &Limits) -> Result { DECODES.with(|n| n.set(n.get() + 1)); - photocraft_raw::decode(bytes, &limits()).map_err(IoError::Raw) + photocraft_raw::decode(bytes, limits).map_err(IoError::Raw) } thread_local! { @@ -405,7 +405,7 @@ type Kept = (Sensor, Option); /// With `keep`, also hands back the sensor and the look it fitted (the default look, when /// `opts` named none) instead of freeing them. fn develop_fitted(bytes: &[u8], opts: &DevelopOptions, keep: bool) -> Result<(photocraft_raw::Developed, Option), RawError> { - let sensor = decode_sensor(bytes).map_err(|e| match e { + let sensor = decode_sensor(bytes, &opts.limits).map_err(|e| match e { IoError::Raw(e) => e, e => RawError::Malformed(e.to_string()), })?; @@ -507,6 +507,18 @@ fn jxl_preview_image(raw: &[u8], p: photocraft_raw::DecodedPreview) -> Result Date: Tue, 10 Nov 2026 21:43:05 +0100 Subject: [PATCH 33/65] Fix clippy in the new limits test Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/raw.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rs index c75556b60c1..30fa9446d06 100644 --- a/crates/io/src/raw.rs +++ b/crates/io/src/raw.rs @@ -514,8 +514,7 @@ mod tests { let (w, h) = (40, 24); let bytes = DngSpec::cfa(w, h, mosaic(&scene(w, h), w, [0, 1, 1, 2], 0, 65535)).build(); assert!(import_raw_with("a.dng", &bytes, &DevelopOptions::default()).is_ok()); - let mut tight = DevelopOptions::default(); - tight.limits = Limits { max_width: 8, max_height: 8, max_pixels: 64, max_alloc: 1 << 20 }; + let tight = DevelopOptions { limits: Limits { max_width: 8, max_height: 8, max_pixels: 64, max_alloc: 1 << 20 }, ..DevelopOptions::default() }; assert!(matches!(import_raw_with("a.dng", &bytes, &tight), Err(IoError::Raw(RawError::LimitExceeded(_))))); } From 5a2e891e8488bd75b6496086d33a9a29ec91d8fc Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 10 Nov 2026 22:17:30 +0100 Subject: [PATCH 34/65] Affinity import: skip compiling shapes once no cache tile fits Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/affinity.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index 3a52a60d220..90e473fafeb 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -478,7 +478,18 @@ impl Builder<'_> { // The pixel cache is optional (the shape renders from its path without it), so charge the // area it would cover to the import's pixel budget and go without it when that is spent: // geometry across a 300000 px canvas would otherwise be rasterized for every shape. + // Once not even one tile is left nothing can be charged, so skip compiling the shape + // (flattening and stroking its path) just to throw the result away. + let tile = crate::text_import::cache_bytes(Rect::new(0, 0, 1, 1), self.format.bytes_per_pixel()); + if self.cache_budget < tile { + if !sh.path.subpaths.is_empty() { + self.uncached_shapes += 1; + } + return sh; + } // The compiled bounds are what `render` covers, an acute miter reaching past the stroke width included. + #[cfg(test)] + COMPILED_SHAPES.with(|n| n.set(n.get() + 1)); let compiled = photocraft_vector::CompiledShape::new(&sh, photocraft_vector::DEFAULT_TOLERANCE, self.canvas); let area = compiled.bounds().map_or(Rect::default(), |b| b.intersect(&self.canvas)); // Whole tiles: even a 2x2 px shape keeps one, which 50 000 small shapes add up to gigabytes. @@ -690,6 +701,12 @@ fn color(c: ap::Color) -> Color { } } +#[cfg(test)] +thread_local! { + /// How many shapes this thread compiled for a pixel cache (for the exhausted-budget test). + static COMPILED_SHAPES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + #[cfg(test)] mod tests { use super::*; @@ -815,6 +832,19 @@ mod tests { assert_eq!(b.pixel_budget, MAX_PIXEL_BYTES, "caches don't draw on the pool images need"); } + #[test] + fn shapes_are_not_compiled_once_no_cache_tile_fits() { + // Three tiles pay for the first three shapes; the other 27 must not even be compiled. + let d = page((0..30).map(tiny_shape).collect()); + let mut b = Builder::new("shapes", &d).unwrap(); + b.cache_budget = 3 * 256 * 256 * 4; + COMPILED_SHAPES.with(|n| n.set(0)); + b.document(&d).unwrap(); + assert_eq!(COMPILED_SHAPES.with(std::cell::Cell::get), 3); + assert_eq!(b.uncached_shapes, 27, "the skipped-cache warning still counts them"); + assert_eq!(b.doc.layers.len(), 30, "every shape still imports"); + } + #[test] fn an_acute_miter_is_charged_for_the_tiles_it_reaches() { // A thin spike at x = 250 with a 4 px miter stroke reaches x = 270, into the next 256 px From 1c0048e1f1a7c77ffdcd8820188d3b19a2f5d55b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 10 Nov 2026 22:23:19 +0100 Subject: [PATCH 35/65] Smart-object adjustments: restrict the resolved pixel target; refuse Equalize Entire Image with a selection Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/cmd/adjust_cmds.rs | 25 +++++++++----- crates/engine/src/cmd/adjust_cmds/tests.rs | 40 ++++++++++++++++++++++ crates/engine/src/cmd/extra_cmds.rs | 8 +++++ 3 files changed, 64 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index a1771ea4689..a3e82a10490 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -331,20 +331,25 @@ pub(crate) fn has_adjustable(s: &Session) -> std::result::Result<(), String> { } } +/// The smart object an adjustment's pixels would go to: the layer the params resolve to (the +/// active one by default), when the command edits its pixels and that layer is a smart object. +/// `None` for a mask or channel target, or a layer that is not a smart object. +pub(crate) fn smart_pixel_target(s: &Session, p: &Value) -> Result> { + if crate::commands::is_mask_target(p) || crate::channel_cmds::is_channel_target(p) || crate::color_channels::target(s, p)?.is_some() { + return Ok(None); + } + let Ok(id) = crate::commands::layer_param(s, p) else { return Ok(None) }; + let smart = s.active().is_some_and(|d| matches!(d.doc.layer(id).map(|l| &l.content), Some(LayerContent::Smart(_)))); + Ok(smart.then_some(id)) +} + /// Image › Adjustments on a smart object record `image.adjustments.` as a smart filter /// (Photoshop): the adjustment re-runs from the source whenever the object re-renders, through /// [`adjust_as_filter`]. `Ok(true)` when it was recorded (one history step, the selection becomes /// the filter mask); `Ok(false)` when the command should edit pixels instead (a mask or channel /// target, or the active layer is not a smart object). pub(crate) fn adjust_as_smart_filter(s: &mut Session, kind: &str, label: &str, p: &Value) -> Result { - if crate::commands::is_mask_target(p) || crate::channel_cmds::is_channel_target(p) || crate::color_channels::target(s, p)?.is_some() { - return Ok(false); - } - let Ok(id) = crate::commands::layer_param(s, p) else { return Ok(false) }; - let smart = s.active().is_some_and(|d| matches!(d.doc.layer(id).map(|l| &l.content), Some(LayerContent::Smart(_)))); - if !smart { - return Ok(false); - } + let Some(id) = smart_pixel_target(s, p)? else { return Ok(false) }; // A pixel or full lock refuses the smart filter, as for `filter.*` on a smart object. crate::commands::check_pixels_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?; // The recorded params are the command's own, minus the engine's private `__kind` key. @@ -453,7 +458,9 @@ fn replace_color_params(cmd: &str, p: &Value, default_color: [f32; 4]) -> Result fn replace_color(s: &mut Session, p: &Value) -> Result { const CMD: &str = "image.adjustments.replaceColor"; let localized_requested = p.get("localized").and_then(Value::as_bool).unwrap_or(false); - let on_smart = s.active().is_some_and(|d| matches!(d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content), Some(LayerContent::Smart(_)))); + // Only the smart object's own pixels are restricted: a mask, alpha channel or Quick Mask over + // it edits as for any layer. + let on_smart = smart_pixel_target(s, p)?.is_some(); // Recorded Lab bounds use native profile matching and edit pixels in place; ordinary RGB // samples keep their existing path. A smart object has no pixels to edit that way. if on_smart && (p.get("labMinimum").is_some() || p.get("labMaximum").is_some()) { diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index 744d6ce45d6..9155d5a8e11 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -605,6 +605,46 @@ fn multi_sample_replace_color_is_refused_on_a_smart_object() { assert_eq!(s.active().unwrap().history.past_len(), steps, "no history step"); } +/// Localized Replace Color is refused only for the smart object's own pixels: an alpha channel, +/// or an explicit `layer` that is not a smart object, edits as usual while a smart object is active. +#[test] +fn localized_replace_color_is_refused_only_for_the_smart_objects_pixels() { + let mut s = smart_session(); + let (filters, steps) = (smart_filters_of(&s).len(), s.active().unwrap().history.past_len()); + let own = json!({"localized": true, "points": [[3, 3]]}); + let e = s.execute("image.adjustments.replaceColor", own).unwrap_err(); + assert!(e.to_string().contains("smart filter"), "{e}"); + assert_eq!(smart_filters_of(&s).len(), filters); + s.execute("channel.new", json!({"name": "Alpha", "fill": "white"})).unwrap(); + let channel = json!({"localized": true, "points": [[3, 3]], "target": {"channel": 0}}); + s.execute("image.adjustments.replaceColor", channel).expect("a channel under a smart object is not refused"); + assert_eq!(smart_filters_of(&s).len(), filters, "no smart filter for a channel edit"); + assert!(s.active().unwrap().history.past_len() > steps); + // The smart object is active, but the command names the Background. + let background = doc(&s).layers.iter().find(|l| !matches!(l.content, LayerContent::Smart(_))).unwrap().id; + let other = json!({"localized": true, "points": [[3, 3]], "layer": background.0}); + s.execute("image.adjustments.replaceColor", other).expect("an explicit pixel layer is not refused"); + assert_eq!(smart_filters_of(&s).len(), filters); +} + +/// Equalize Entire Image Based On Selected Area needs the selection for the histogram only, which +/// a smart filter's output mask cannot express: refused rather than recorded as "selected area only". +#[test] +fn equalize_entire_image_is_refused_on_a_smart_object_with_a_selection() { + let mut s = smart_session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 24, "height": 32})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + let e = s.execute("image.adjustments.equalize", json!({"selectedAreaOnly": false})).unwrap_err(); + assert!(e.to_string().contains("smart object"), "{e}"); + assert!(smart_filters_of(&s).is_empty(), "nothing recorded"); + assert_eq!(s.active().unwrap().history.past_len(), steps); + s.execute("image.adjustments.equalize", json!({"selectedAreaOnly": true})).unwrap(); + assert_eq!(smart_filters_of(&s).len(), 1, "the selected area itself still records a filter"); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.adjustments.equalize", json!({"selectedAreaOnly": false})).unwrap(); + assert_eq!(smart_filters_of(&s).len(), 2, "without a selection it is plain Equalize"); +} + /// #780: a targeted mask enables Invert (and filters) on layers without pixels, such as an /// adjustment layer; viewing the mask (⌥-click) targets it too. #[test] diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index 3937142883e..186ef104d57 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -245,6 +245,14 @@ fn equalize(s: &mut Session, p: &Value) -> Result { Some(Value::Bool(only)) => !only, Some(_) => return Err(EngineError::BadParams { cmd: "image.adjustments.equalize".into(), msg: "selectedAreaOnly must be true or false".into() }), }; + // A smart filter's selection is its output mask, so it cannot also stand for "histogram from + // the selection, applied to everything": refuse instead of quietly leaving the rest unchanged. + if whole && s.active().is_some_and(|d| d.doc.selection.is_some()) && crate::adjust_cmds::smart_pixel_target(s, p)?.is_some() { + return Err(EngineError::BadParams { + cmd: "image.adjustments.equalize".into(), + msg: "Equalize Entire Image Based On Selected Area is not available on a smart object yet".into(), + }); + } if crate::adjust_cmds::adjust_as_smart_filter(s, "equalize", "Equalize", p)? { return Ok(Value::Null); } From 612afbff218004eb01c8e28f2079e486ab55c5a8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:45:21 +0100 Subject: [PATCH 36/65] #11871: Ruler Straighten with crop asks an untrusted session's gate for its nested Image Rotation, now called directly Co-Authored-By: DuBearte Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/analysis_cmds.rs | 8 +++++++- crates/engine/src/cmd/count_resize_tests.rs | 12 ++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index 4b6f0f83179..41585c3360a 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -796,7 +796,13 @@ fn straighten(s: &mut Session, p: &Value) -> Result { compound(s, "Straighten", |s| { if crop { // Count points turn with the image here, since the crop after it moves them too. - crate::mode_cmds::rotate_arbitrary_with(s, &json!({"angle": rot, "direction": "cw"}), false)?; + // Called directly rather than through `execute`, so an untrusted session's gate is + // asked here, as dispatch would have asked it for the nested rotation. + let rotation = json!({"angle": rot, "direction": "cw"}); + if let Some(gate) = s.authorize { + gate("image.rotation.arbitrary", &rotation)?; + } + crate::mode_cmds::rotate_arbitrary_with(s, &rotation, false)?; let nd = doc(s)?; let (cw, ch) = inscribed(w0, h0, rot.to_radians()); let (nw, nh) = (f64::from(nd.size.width), f64::from(nd.size.height)); diff --git a/crates/engine/src/cmd/count_resize_tests.rs b/crates/engine/src/cmd/count_resize_tests.rs index 32f3562aa4a..ccc4adad099 100644 --- a/crates/engine/src/cmd/count_resize_tests.rs +++ b/crates/engine/src/cmd/count_resize_tests.rs @@ -76,3 +76,15 @@ fn ruler_straighten_with_crop_moves_count_points_with_the_image() { let (c, n) = (count_point(&s), note(&s)); assert!((c[0] - n[0]).abs() < 1e-6 && (c[1] - n[1]).abs() < 1e-6, "count {c:?} vs note {n:?}"); } + +#[test] +fn ruler_straighten_with_crop_asks_the_gate_for_its_rotation() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); + let size = s.active().unwrap().doc.size; + s.authorize = Some(|id, _| if id == "image.rotation.arbitrary" { Err(crate::EngineError::Other("denied".into())) } else { Ok(()) }); + assert!(s.execute("image.analysis.straightenLayer", json!({"crop": true})).is_err(), "the nested rotation is denied"); + s.authorize = None; + assert_eq!(s.active().unwrap().doc.size, size, "nothing turned"); +} From da1bf121abf26311de92515f42ba272d328e6e7a Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:46:17 +0100 Subject: [PATCH 37/65] #12097: literal translation keys for the Magic Eraser alerts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tl!(message) hid both alerts from the translation report. Both texts are now literal tl! keys; a test keeps them equal to the engine's texts. Co-Authored-By: Hartmut Nörenberg Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/tools/eraser_ui.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index fa61e45791c..3a88440a526 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -35,7 +35,21 @@ fn error_alert(error: &str) -> Option<&'static str> { /// Opens the alert: the message and one OK button, as a refused Move press does /// (`move_lock::prompt`). fn refuse(app: &mut PhotocraftApp, message: &str) { - app.ui.open_dialog(DialogKind::Error, json!({"message": tl!(message)}).as_object().cloned().unwrap_or_default()); + app.ui.open_dialog(DialogKind::Error, json!({"message": alert_text(message)}).as_object().cloned().unwrap_or_default()); +} + +/// The alert in the UI language. Literal keys, so the translation report lists both alerts for the +/// translators; `alert_keys_match_the_engine_texts` keeps them equal to the engine's texts. +fn alert_text(message: &str) -> &str { + match message { + MAGIC_ERASER_INDEXED_ERROR => { + tl!("Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit).") + } + MAGIC_ERASER_BITMAP_ERROR => { + tl!("Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit).") + } + other => tl!(other), + } } /// Magic Eraser click at document `(x, y)`. Returns false for other tools. @@ -367,6 +381,17 @@ mod tests { use super::*; use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; + /// #12032: the literal translation keys are the engine's alert texts, so an English UI shows + /// exactly what `paint.magicEraser` answers and the catalogs translate the right string. + #[test] + fn alert_keys_match_the_engine_texts() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + for text in [MAGIC_ERASER_INDEXED_ERROR, MAGIC_ERASER_BITMAP_ERROR] { + assert_eq!(alert_text(text), text); + } + }); + } + /// The message of every open error dialog, in the order they were opened. fn alerts(app: &PhotocraftApp) -> Vec<&str> { app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(|m| m.as_str())).collect() From 40a8891077069d794efddc43b765ec42ffda3870 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 15:22:48 +0100 Subject: [PATCH 38/65] #11871: the Straighten tests run on a pixel layer, since main turns Straighten Layer off for the Background (#12033) Co-Authored-By: DuBearte Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/count_resize_tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/engine/src/cmd/count_resize_tests.rs b/crates/engine/src/cmd/count_resize_tests.rs index ccc4adad099..7648ed00514 100644 --- a/crates/engine/src/cmd/count_resize_tests.rs +++ b/crates/engine/src/cmd/count_resize_tests.rs @@ -71,6 +71,8 @@ fn ruler_straighten_with_crop_moves_count_points_with_the_image() { s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); s.execute("count.add", json!({"x": 250, "y": 150})).unwrap(); s.execute("notes.add", json!({"x": 250, "y": 150})).unwrap(); + // Straighten Layer is off for the Background (#12033). + s.execute("layer.new.layer", json!({})).unwrap(); s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap(); let (c, n) = (count_point(&s), note(&s)); @@ -81,6 +83,8 @@ fn ruler_straighten_with_crop_moves_count_points_with_the_image() { fn ruler_straighten_with_crop_asks_the_gate_for_its_rotation() { let mut s = Session::new(); s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + // Straighten Layer is off for the Background (#12033). + s.execute("layer.new.layer", json!({})).unwrap(); s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); let size = s.active().unwrap().doc.size; s.authorize = Some(|id, _| if id == "image.rotation.arbitrary" { Err(crate::EngineError::Other("denied".into())) } else { Ok(()) }); From 8a73ffc14371478d66ca4582278177990caff146 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 13:10:08 -0500 Subject: [PATCH 39/65] Add Anchor Point: the pen with "+" only over a segment, a black arrow elsewhere (#12729) The Add Anchor Point cursor now shows what a click would do. Over a segment of the targeted path it stays the pen with "+"; over an anchor, a handle end, empty canvas, with no path targeted, and over a locked shape layer's segments it is a new black arrow. Ctrl shows the arrow, Alt and the Precise crosshair are unchanged. The arrow is PhotoCraft's own polygon drawing (tool_cursor/arrow.rs, Shape::Arrow, tip at the hotspot, bitmap cropped so the hotspot is (1,1)); #12746 and #12709 can reuse it. A read-only anchor_tools::adds_anchor_at, built on `target`, drives both the cursor and the badge. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/ui-egui/src/canvas.rs | 10 ++ crates/ui-egui/src/canvas/tool_cursor.rs | 34 +++- .../tool_cursor/add_anchor_cursor_tests.rs | 158 ++++++++++++++++++ .../ui-egui/src/canvas/tool_cursor/arrow.rs | 60 +++++++ crates/ui-egui/src/canvas/tool_feedback.rs | 9 +- crates/ui-egui/src/caps_lock_tests.rs | 2 +- crates/ui-egui/src/tools/anchor_tools.rs | 7 + .../ui-egui/src/tools/anchor_tools/tests.rs | 8 +- 8 files changed, 281 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs create mode 100644 crates/ui-egui/src/canvas/tool_cursor/arrow.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index dbe4bca522c..0c006141275 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1993,6 +1993,16 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & { crate::tool_cursor::continue_path(painter, p) } + // Add Anchor Point: the pen with "+" only over a segment a click would split, else the + // black arrow (#12729); ⌘ is Direct Selection's arrow. ⌥ and Precise stay as they were. + Tool::AddAnchorPoint + if !precise_other_cursor(app) && { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + !mods.alt && (mods.command || !crate::anchor_tools::adds_anchor_at(app, tool, xf.to_doc(p))) + } => + { + crate::tool_cursor::arrow(ui.ctx(), p) + } // The pen tools: their own icon with its nib on the point, or the crosshair for // precise Other Cursors (#4639). Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => { diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index 42b3e622dfb..f3e39ceb1da 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -12,6 +12,7 @@ use egui::{CursorIcon, CustomCursorImage, Painter, Pos2, Stroke, Vec2, vec2}; use crate::canvas::ViewXform; use crate::state::Tool; +mod arrow; mod bucket; mod hand; mod pen; @@ -30,9 +31,11 @@ const MAX_SIDE: u16 = if cfg!(any(target_os = "windows", target_os = "macos")) { /// What a bitmap cursor shows. `Hand` is the Hand tool's open hand, or its fist while it drags; /// `Zoom` is the Zoom tool's magnifier, with a minus when it zooms out. `Outline` is a brush tip -/// outline: closed rings of logical-point offsets from the hotspot. +/// outline: closed rings of logical-point offsets from the hotspot. `Arrow` is the black arrow +/// pointer, its tip on the hotspot. #[derive(Clone, Debug, PartialEq)] enum Shape { + Arrow, Circle { radius: f32, centre: bool }, Crosshair { length: f32, gap: f32 }, Hand { closed: bool }, @@ -379,6 +382,20 @@ fn hand_with(ctx: &egui::Context, closed: bool, bitmap: bool) -> CursorIcon { if closed { CursorIcon::Grabbing } else { CursorIcon::Grab } } +/// The black arrow pointer, its tip on the pointer (`_at`): an OS cursor bitmap on every platform +/// that takes one, the system arrow where none can be set. +pub(crate) fn arrow(ctx: &egui::Context, _at: Pos2) -> CursorIcon { + arrow_with(ctx, native(ctx)) +} + +fn arrow_with(ctx: &egui::Context, bitmap: bool) -> CursorIcon { + if bitmap && let Some(image) = cached_image(ctx, &Shape::Arrow, native_scale(ctx)) { + ctx.set_cursor_image(Some(image)); + return CursorIcon::None; + } + CursorIcon::Default +} + /// The bitmap [`hand`] hands Windows, for tests that check the Hand's pointer on every platform. #[cfg(test)] pub(crate) fn hand_bitmap(ctx: &egui::Context, closed: bool) -> Option { @@ -563,7 +580,7 @@ fn paint(painter: &Painter, at: Pos2, shape: &Shape) -> bool { } } // Only ever a bitmap: without one the OS draws its own grab cursors. - Shape::Hand { .. } | Shape::Zoom { .. } | Shape::Pipette => {} + Shape::Arrow | Shape::Hand { .. } | Shape::Zoom { .. } | Shape::Pipette => {} } } true @@ -612,6 +629,7 @@ fn extent(shape: &Shape) -> Option { } if *centre { e.max(3.0) } else { e } } + Shape::Arrow => arrow::REACH, Shape::Hand { .. } => hand::HALF, Shape::Zoom { .. } => zoom::HALF, // The 24-unit SVG extends at most 22 units from (2, 22). This extra unit plus @@ -665,6 +683,10 @@ fn coverage(shape: &Shape, dx: f32, dy: f32, scale: f32) -> (f32, f32) { let (lx, ly) = (dx / scale, dy / scale); silhouette(zoom::shape(lx, ly), zoom::glyph(*out, lx, ly), 0.75, scale) } + Shape::Arrow => { + let (lx, ly) = (dx / scale, dy / scale); + silhouette(arrow::shape(lx, ly), f32::MAX, 0.0, scale) + } Shape::Pipette => (0.0, 0.0), // SVG rasterization supplies these pixels. } } @@ -778,7 +800,7 @@ fn rasterize(shape: &Shape, scale: f32) -> Option { let hotf = f32::from(hot); let mut put = |col: usize, row: usize, cov: (f32, f32)| { if let Some(px) = row.checked_mul(n).and_then(|i| i.checked_add(col)).and_then(|i| rgba.get_mut(i * 4..i * 4 + 4)) { - px.copy_from_slice(&stroke_pixel(cov, dark, light)); + px.copy_from_slice(&if matches!(shape, Shape::Arrow) { arrow::pixel(cov) } else { stroke_pixel(cov, dark, light) }); } }; if let Shape::Outline { rings, centre } = shape { @@ -830,7 +852,8 @@ fn rasterize(shape: &Shape, scale: f32) -> Option { } } } - Some(CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }) + let image = CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }; + if matches!(shape, Shape::Arrow) { arrow::crop(image) } else { Some(image) } } /// Use the toolbar's actual SVG, with its lower-left tip (2, 22) at the hotspot. @@ -872,3 +895,6 @@ mod tests; #[cfg(test)] mod count_tests; + +#[cfg(test)] +mod add_anchor_cursor_tests; diff --git a/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs b/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs new file mode 100644 index 00000000000..27b746d7c80 --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs @@ -0,0 +1,158 @@ +//! #12729: Add Anchor Point's cursor says what a click would do. Over a segment of the targeted path +//! it is the pen with "+"; over an anchor, a handle end, empty canvas, with no path targeted and +//! over a locked shape layer's segments it is the black arrow. ⌘ keeps Direct Selection's arrow, +//! ⌥ and the Precise "Other Cursors" crosshair stay as they were. The tests drive the real canvas +//! (`document_area`) and compare the OS cursor bitmap it hands the platform with the arrow's and +//! the pen's. + +use egui::{CursorIcon, Modifiers, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use super::{PenVariant, Shape, rasterize}; +use crate::PhotocraftApp; +use crate::anchor_tools::delete_anchor_targeted_path_tests::{select_layer, select_saved_path, setup}; +use crate::state::Tool; + +/// Path 1 is the square (50,450)-(150,550); the shape layer is the rectangle (450,100)-(650,250). +const SQUARE_TOP: [f32; 2] = [100.0, 450.0]; +const SQUARE_CORNER: [f32; 2] = [50.0, 450.0]; +const SQUARE_MIDDLE: [f32; 2] = [100.0, 500.0]; +const SHAPE_TOP: [f32; 2] = [550.0, 100.0]; + +/// The canvas at 100 % over `app`, the view centred on `view` (a document point). +fn harness(app: PhotocraftApp, view: [f32; 2]) -> Harness<'static, PhotocraftApp> { + let mut app = app; + app.sync_views(); + app.ui.extras.rulers = false; + let mut h = Harness::builder().with_size(vec2(900.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = view; + v.fit_pending = false; + h.run_steps(2); + h +} + +/// Hover the document point `at` with `mods` held. +fn hover(h: &mut Harness<'static, PhotocraftApp>, at: [f32; 2], view: [f32; 2], mods: Modifiers) { + h.event(egui::Event::ModifiersChanged(mods)); + let p: Pos2 = h.state().last_canvas_rect.center() + vec2(at[0] - view[0], at[1] - view[1]); + h.hover_at(p); + h.run_steps(3); +} + +#[derive(Debug, PartialEq)] +enum Shown { + Arrow, + Pen, + Crosshair, + Other, +} + +/// Which cursor the last frame asked the platform for. +fn shown(h: &Harness<'static, PhotocraftApp>) -> Shown { + let out = &h.output().platform_output; + let scale = super::native_scale(&h.ctx); + let same = + |a: &egui::CustomCursorImage, b: Option| b.is_some_and(|b| a.size == b.size && a.hotspot == b.hotspot && a.rgba == b.rgba); + match &out.cursor_image { + Some(i) if same(i, rasterize(&Shape::Arrow, scale)) => Shown::Arrow, + Some(i) if same(i, PenVariant::from_tool(Tool::AddAnchorPoint).and_then(|v| super::pen::rasterize(v, scale))) => Shown::Pen, + Some(i) if same(i, rasterize(&super::STANDARD_CROSSHAIR, scale)) => Shown::Crosshair, + _ => Shown::Other, + } +} + +/// The square's Path 1 targeted, the pointer at `at` on it. +fn on_path_one(at: [f32; 2], mods: Modifiers) -> Shown { + let (mut app, _) = setup(Tool::AddAnchorPoint); + select_saved_path(&mut app); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, at, SQUARE_MIDDLE, mods); + shown(&h) +} + +#[test] +fn over_a_segment_of_the_targeted_path_it_is_the_pen_with_plus() { + assert_eq!(on_path_one(SQUARE_TOP, Modifiers::NONE), Shown::Pen); +} + +#[test] +fn over_an_anchor_a_handle_end_or_empty_canvas_it_is_the_black_arrow() { + assert_eq!(on_path_one(SQUARE_CORNER, Modifiers::NONE), Shown::Arrow); + assert_eq!(on_path_one(SQUARE_MIDDLE, Modifiers::NONE), Shown::Arrow); + // A handle end: a curved top edge's out-handle ends in empty canvas, off every segment. + let (mut app, _) = setup(Tool::AddAnchorPoint); + let path = json!({"subpaths": [{"closed": true, "knots": [{"anchor": [50, 450], "in": [50, 450], "out": [50, 400]}, [150, 450], [150, 550], [50, 550]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, [50.0, 400.0], SQUARE_MIDDLE, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow); +} + +#[test] +fn with_no_path_targeted_it_is_the_black_arrow_everywhere() { + // The active layer is the pixel layer "Red": no path is targeted, whatever lies under the pointer. + for at in [SHAPE_TOP, [450.0, 100.0], [550.0, 175.0], [300.0, 150.0]] { + let (app, _) = setup(Tool::AddAnchorPoint); + let mut h = harness(app, SHAPE_TOP); + hover(&mut h, at, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow, "{at:?}"); + } +} + +#[test] +fn over_a_segment_of_a_locked_shape_layers_mask_it_is_the_black_arrow() { + let (mut app, shape) = setup(Tool::AddAnchorPoint); + select_layer(&mut app, shape); + let mut h = harness(app, SHAPE_TOP); + hover(&mut h, SHAPE_TOP, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Pen, "unlocked, the same point is a segment"); + h.state_mut().run("layer.lockLayers", json!({"position": true})).unwrap(); + hover(&mut h, SHAPE_TOP, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow); +} + +#[test] +fn with_ctrl_held_it_is_the_black_arrow_even_over_a_segment() { + assert_eq!(on_path_one(SQUARE_TOP, Modifiers::COMMAND), Shown::Arrow); +} + +#[test] +fn with_alt_held_it_stays_the_pen_over_empty_canvas() { + assert_eq!(on_path_one(SQUARE_MIDDLE, Modifiers::ALT), Shown::Pen); +} + +#[test] +fn the_precise_other_cursors_crosshair_keeps_working() { + for at in [SQUARE_TOP, SQUARE_MIDDLE] { + let (mut app, _) = setup(Tool::AddAnchorPoint); + select_saved_path(&mut app); + app.run("prefs.set", json!({"path": "cursors.other", "value": "precise"})).unwrap(); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, at, SQUARE_MIDDLE, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Crosshair, "{at:?}"); + } +} + +#[test] +fn the_arrow_bitmap_is_not_empty_and_its_hotspot_is_the_tip_at_1_1() { + let image = rasterize(&Shape::Arrow, 1.0).unwrap(); + assert_eq!(image.hotspot, [1, 1]); + let alpha = |x: usize, y: usize| image.rgba[(y * usize::from(image.size[0]) + x) * 4 + 3]; + assert!(image.rgba.chunks(4).any(|p| p[3] == 255 && p[0] == 0), "a solid black body"); + assert!(image.rgba.chunks(4).any(|p| p[3] > 0 && p[0] == 255), "a white edge"); + assert!(alpha(1, 1) > 0, "the tip pixel is covered"); + assert_eq!(super::arrow_with(&egui::Context::default(), false), CursorIcon::Default); +} diff --git a/crates/ui-egui/src/canvas/tool_cursor/arrow.rs b/crates/ui-egui/src/canvas/tool_cursor/arrow.rs new file mode 100644 index 00000000000..b99cd208869 --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/arrow.rs @@ -0,0 +1,60 @@ +//! The black arrow pointer: a filled black arrow with a white edge, PhotoCraft's own drawing from +//! one polygon (tip at the top left, body down to the right, a short tail), as a signed distance +//! field (negative inside) in logical pixels from the tip with y pointing down. The hotspot is the +//! tip; the bitmap is cropped to the arrow so the tip sits one pixel in from its top left corner, +//! at (1, 1) at 100 %. Windows' stock arrow is white, so every platform gets this bitmap. + +use std::sync::Arc; + +use egui::CustomCursorImage; + +use super::hand::capsule; + +/// How far the polygon reaches from the tip, outline excluded. +pub(super) const REACH: f32 = 20.0; + +/// The arrow's corners, clockwise from the tip. +const OUTLINE: [[f32; 2]; 7] = [[0.0, 0.0], [11.5, 11.8], [6.7, 11.8], [9.2, 17.4], [6.6, 18.6], [4.0, 12.8], [0.0, 16.5]]; + +/// The arrow's silhouette: negative inside it. +pub(super) fn shape(x: f32, y: f32) -> f32 { + let mut distance = f32::MAX; + let mut inside = false; + for (&a, &b) in OUTLINE.iter().zip(OUTLINE.iter().cycle().skip(1)) { + distance = distance.min(capsule(x, y, a, b, 0.0)); + // Even-odd rule: a ray towards +x crossing this edge flips the answer. + if (a[1] > y) != (b[1] > y) && x < a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) { + inside = !inside; + } + } + if inside { -distance } else { distance } +} + +/// One bitmap pixel in straight RGBA: black `fill` over a white edge, `outline` being the coverage +/// of the whole arrow (edge included), each 0 to 1. No coverage is `[0; 4]`. +pub(super) fn pixel((fill, outline): (f32, f32)) -> [u8; 4] { + let edge = outline * (1.0 - fill); + let alpha = fill + edge; + let white = if alpha > 0.0 { (255.0 * edge / alpha).round() as u8 } else { 0 }; + [white, white, white, (255.0 * alpha).round() as u8] +} + +/// Crop `image` (the arrow centred on its hotspot) to the pixels it covers, the hotspot moving +/// with them. `None` when nothing is covered. +pub(super) fn crop(image: CustomCursorImage) -> Option { + let [w, h] = image.size.map(usize::from); + let covered = |col: usize, row: usize| image.rgba.get((row * w + col) * 4 + 3).is_some_and(|&a| a > 0); + let cols: Vec = (0..w).filter(|&c| (0..h).any(|r| covered(c, r))).collect(); + let rows: Vec = (0..h).filter(|&r| (0..w).any(|c| covered(c, r))).collect(); + let (&c0, &c1) = (cols.first()?, cols.last()?); + let (&r0, &r1) = (rows.first()?, rows.last()?); + let mut rgba = Vec::with_capacity((c1 - c0 + 1) * (r1 - r0 + 1) * 4); + for row in r0..=r1 { + rgba.extend_from_slice(image.rgba.get((row * w + c0) * 4..(row * w + c1 + 1) * 4)?); + } + Some(CustomCursorImage { + rgba: Arc::from(rgba), + size: [u16::try_from(c1 - c0 + 1).ok()?, u16::try_from(r1 - r0 + 1).ok()?], + hotspot: [image.hotspot[0].checked_sub(u16::try_from(c0).ok()?)?, image.hotspot[1].checked_sub(u16::try_from(r0).ok()?)?], + }) +} diff --git a/crates/ui-egui/src/canvas/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs index 88aec042e57..21608f1ead6 100644 --- a/crates/ui-egui/src/canvas/tool_feedback.rs +++ b/crates/ui-egui/src/canvas/tool_feedback.rs @@ -109,7 +109,14 @@ pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option Option<(PathRef, Path } } +/// Whether a click at `p` with Add Anchor Point (`tool`) would add an anchor: the pointer is over +/// a segment of the targeted path that the tool may edit. Read-only; the cursor and its badge +/// (#12729) ask it, so they show the pen with "+" only where a click does something. +pub(crate) fn adds_anchor_at(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> bool { + tool == Tool::AddAnchorPoint && target(app, tool, p).is_some() +} + /// The Pen's Auto Add/Delete (#4144): what a Pen click at `p` does to the active path instead of /// starting a new one, as the anchor tool that does it (Add Anchor Point on a segment, Delete /// Anchor Point on an anchor), the path and the hit. While a path is being drawn it edits that diff --git a/crates/ui-egui/src/tools/anchor_tools/tests.rs b/crates/ui-egui/src/tools/anchor_tools/tests.rs index d04b5aa1a2d..1303c650461 100644 --- a/crates/ui-egui/src/tools/anchor_tools/tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/tests.rs @@ -144,7 +144,13 @@ fn shape_layer_paths_are_edited_and_the_added_anchor_replaces_the_selection() { #[test] fn the_cursor_shows_plus_or_minus() { use crate::tool_feedback::{Badge, badge}; - let app = app(Tool::AddAnchorPoint); + let mut app = app(Tool::AddAnchorPoint); + assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), None, "no path targeted, no segment under the pointer (#12729)"); + with_path(&mut app); + app.ui.selected_path = Some("work".into()); + app.hover_doc = Some([80.0, 80.0]); + assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), None, "off the path's segments"); + app.hover_doc = Some([80.0, 120.0]); assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), Some(Badge::Add)); assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::ALT), Some(Badge::Subtract)); assert_eq!(badge(&app, Tool::DeleteAnchorPoint, Modifiers::NONE), Some(Badge::Subtract)); From 3a23cf3e6b10283637e927e4c6923eb3804d3a56 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 20:28:37 +0100 Subject: [PATCH 40/65] fix(paint): raise only the ring next to a transparent flood, at coverage 1 - alpha (#11354) Since main's wand fringe gives a transparent seed no fringe coverage (#11776), the PR's rim rule never ran after the merge. The rim now has its own reach: with Anti-alias on, each pixel 8-adjacent to the flood takes a plain composite of the fill at coverage (1 - alpha) x opacity x selection. That gives the measured alpha alpha + (1 - alpha)^2 for a white rim, and also the reference colours for a black edge filled green (#12528: alpha 40 -> (0,248,0,221), 112 -> (0,190,0,192), 197 -> (0,70,0,210), 253 -> (0,2,0,253)), which the earlier colour mix missed. Pixels further out keep their alpha, and Anti-alias off leaves the ring alone, both as measured. The flood itself is fully covered on main, so the CMYK inks rule is back to "fully covered". Co-Authored-By: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/algo/src/paint.rs | 184 ++++++++++++++-------- crates/engine/src/cmd/paint_cmds/tests.rs | 14 +- 2 files changed, 131 insertions(+), 67 deletions(-) diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index 2ba5ddb7365..5d40e81d93c 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -63,37 +63,10 @@ pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { } } -/// The pixel `d` filled with `c` (mode `m`) by a bucket clicked on transparency. The colour `d` -/// holds blends with `c` at the region's coverage `k`, as on any fill. The transparent part of the -/// pixel (`1 − αd`) takes the fill at strength `full × (1 − αd)` instead of `k`: the emptier the -/// pixel, the more of its emptiness is filled. So the result's alpha is -/// `αd + (1 − αd)² × full × αc` whatever `k` is (#11354 review): -/// - empty pixels (the hole and the hole's anti-aliased edge) fill to `full`; -/// - the soft rim a Clear leaves rises only partly, so a faint rim stays (α 187 → 205, 56 → 211, -/// 3 → 252 at 8 bits; the reference application gives 204, 211, 253); -/// - opaque pixels come out bit-identical to a plain composite at `k`. -fn fill_transparency(m: BlendMode, d: [f32; 4], c: [f32; 4], k: f32, full: f32) -> [f32; 4] { - let o = blend::composite(m, d, c, k); - let held = d[3].clamp(0.0, 1.0); - if held >= 1.0 || !full.is_finite() || !held.is_finite() { - return o; - } - let empty = 1.0 - held; - let add = full.clamp(0.0, 1.0) * c[3].clamp(0.0, 1.0) * empty * empty; - let a = held + add; - if a <= 0.0 { - return o; - } - // The colour `d` holds, blended at `k` as if it were all there; then the new part is `c`. - let soft = blend::composite(m, [d[0], d[1], d[2], 1.0], c, k); - let mix = |i: usize| (soft[i] * held + c[i] * add) / a; - [mix(0), mix(1), mix(2), a] -} - -/// Composites `color(i)` over `area` of the surface with per-pixel coverage. With `transparency`, -/// a covered pixel's transparency takes the fill at a strength set by that value and by how empty -/// the pixel is, instead of by the coverage (see [`fill_transparency`]); Lock Transparent Pixels -/// and Clear ignore it. +/// Composites `color(i)` over `area` of the surface with per-pixel coverage. Where the coverage is +/// zero, `rim(x, y)` (when given) is the strength of a bucket's transparent-seed fringe there: the +/// pixel takes the fill at coverage `rim × (1 − α)`, its own transparency (#11354 review; see +/// [`bucket_fill_inks`]). Lock Transparent Pixels and Clear ignore it. #[allow(clippy::too_many_arguments)] fn composite_area( s: &mut Surface, @@ -103,7 +76,7 @@ fn composite_area( color: impl Fn(i32, i32) -> [f32; 4] + Sync, lock_transparency: bool, inks: Option<[f32; 4]>, - transparency: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>, + rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>, ) { // Composite tile by tile (in parallel on native); tiles with zero coverage are left untouched, // so their copy-on-write storage (and GPU residency) survives. @@ -118,8 +91,12 @@ fn composite_area( let mut enc = [0.0f32; 8]; for y in r.y0..r.y1 { for x in r.x0..r.x1 { - let k = coverage(x, y); - if k <= 0.0 { + let mut k = coverage(x, y); + let on_rim = match rim { + Some(rim) if k <= 0.0 && !lock_transparency && matches!(mode, FillMode::Blend(_)) => rim(x, y), + _ => 0.0, + }; + if k <= 0.0 && on_rim <= 0.0 { continue; } if !any { @@ -129,25 +106,26 @@ fn composite_area( let i = ((y - r.y0) as usize * w + (x - r.x0) as usize) * n; let px = &mut region[i..i + n]; let d = photocraft_raster::to_rgba(&fmt, px); + if k <= 0.0 { + // A rim pixel: only its transparency takes the fill, so opaque art stays as it is. + k = on_rim * (1.0 - d[3].clamp(0.0, 1.0)); + if k.is_nan() || k <= 0.0 { + continue; + } + } let o = match mode { FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k), - FillMode::Blend(m) => match transparency { - Some(full) => fill_transparency(m, d, color(x, y), k, full(x, y)), - None => blend::composite(m, d, color(x, y), k), - }, + FillMode::Blend(m) => blend::composite(m, d, color(x, y), k), // Locked transparency keeps the alpha, so Clear leaves the pixel as it is. FillMode::Clear if lock_transparency => d, FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))], }; from_rgba_into(&fmt, o, &mut enc); - // A colour picked as CMYK inks replaces fully covered pixels of a CMYK target as it - // is — and pixels the fill made fully opaque out of transparency, whose colour is the - // fill alone even though their coverage is partial (the edge of a bucket fill on - // transparency, #11354 review). A pixel that held colour keeps its blended encoding. + // A colour picked as CMYK inks replaces fully covered pixels of a CMYK target as it is. if let Some(i) = inks && fmt.mode == photocraft_color::ColorMode::Cmyk && mode == FillMode::Blend(BlendMode::Normal) - && (k >= 1.0 || (d[3] <= 0.0 && o[3] >= 1.0)) + && k >= 1.0 { enc[..4].copy_from_slice(&i); } @@ -267,15 +245,18 @@ pub fn bucket_fill_inks( } let img = crate::selection::rgba8_image(s, area); let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false }; - // Clicked on transparency: the flood fills empty pixels, and the empty pixels along its - // anti-aliased edge are that same empty area, so they fill in full rather than being left as - // a semi-transparent ring (#11311). The soft rim a cleared selection leaves rises only by how - // empty each pixel is, so a faint rim stays (#11354 review; see `fill_transparency`). + // Clicked on transparency with Anti-alias on: the wand's fringe gives the partly transparent + // pixels around the flood no coverage (their alpha is measured against the seed's 0), but the + // reference application fills each pixel 8-adjacent to the flood at coverage `1 − α`, so the + // soft rim a cleared selection leaves rises partly (α 187 → 205, 56 → 211, 3 → 252; the + // reference gives 204, 211, 253) and a black edge pixel of alpha 40 filled green becomes + // (0, 248, 0, 221) (#11311, #12528, #11354 review). Pixels further out stay as they are; with + // Anti-alias off nothing outside the flood changes. let at_seed = usize::try_from(seed.1 - area.y0) .ok() .and_then(|y| y.checked_mul(area.width() as usize)) .and_then(|row| row.checked_add(usize::try_from(seed.0 - area.x0).ok()?)); - let empty_seed = at_seed.and_then(|i| img.get(i)).is_some_and(|p| p[3] == 0); + let empty_seed = anti_alias && at_seed.and_then(|i| img.get(i)).is_some_and(|p| p[3] == 0); drop(img); fill_region(s, ®ion, opacity, selection, lock_transparency, src, inks, mode, empty_seed); true @@ -309,11 +290,9 @@ pub fn bucket_fill_region_inks( fill_region(s, region, opacity, selection, lock_transparency, src, inks, mode, false); } -/// [`bucket_fill_region_inks`]; with `fill_empty`, the transparent part of every pixel the region -/// touches takes the fill at the opacity and selection coverage scaled by how transparent the -/// pixel is (empty pixels fill in full, a partly transparent rim rises partly), while the -/// region's anti-aliasing still softens the colour over what is already there. Opaque pixels come -/// out exactly as without it. +/// [`bucket_fill_region_inks`]; with `rim`, the pixels 8-adjacent to the region's fully covered +/// pixels that the region itself leaves uncovered take the fill at coverage `1 − α` (see +/// [`composite_area`]). Fully covered pixels and pixels further out are filled as without it. #[allow(clippy::too_many_arguments)] fn fill_region( s: &mut Surface, @@ -324,13 +303,35 @@ fn fill_region( src: impl Fn(i32, i32) -> [f32; 4] + Sync, inks: Option<[f32; 4]>, mode: FillMode, - fill_empty: bool, + rim: bool, ) { - // Composite only over the filled region's box. + // Composite only over the filled region's box (with Anti-alias on it already holds the + // one-pixel ring around the flood). let b = region.bbox; let strength = |x: i32, y: i32| opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)); - let empty: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if fill_empty { Some(&strength) } else { None }; - composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, empty); + let ring = if rim { rim_ring(region) } else { Vec::new() }; + let on_ring = |x: i32, y: i32| { + let at = usize::try_from(y - b.y0).ok().zip(usize::try_from(x - b.x0).ok()).filter(|_| b.contains(x, y)); + let hit = at.and_then(|(yy, xx)| yy.checked_mul(b.width() as usize)?.checked_add(xx)).and_then(|i| ring.get(i)); + if hit == Some(&true) { strength(x, y) } else { 0.0 } + }; + let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if rim { Some(&on_ring) } else { None }; + composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, rim); +} + +/// Over `region.bbox` (row-major): the pixels the region leaves uncovered that touch one of its +/// fully covered pixels, diagonals included. +fn rim_ring(region: &crate::selection::Region) -> Vec { + let (w, h) = (region.bbox.width() as usize, region.bbox.height() as usize); + let full = |x: usize, y: usize| y.checked_mul(w).and_then(|r| r.checked_add(x)).and_then(|i| region.mask.get(i)) == Some(&255); + let n = w.saturating_mul(h).min(region.mask.len()); + (0..n) + .map(|i| { + let (x, y) = (i % w, i / w); + region.mask.get(i) == Some(&0) + && (y.saturating_sub(1)..=(y + 1).min(h - 1)).any(|ny| (x.saturating_sub(1)..=(x + 1).min(w - 1)).any(|nx| (nx, ny) != (x, y) && full(nx, ny))) + }) + .collect() } #[cfg(test)] @@ -435,7 +436,6 @@ mod tests { let img = crate::selection::rgba8_image(&before, a); let region = crate::selection::wand_region(&img, a, (1, 0), 0.0, true, true).unwrap(); bucket_fill_region_inks(&mut before, ®ion, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal)); - assert!(before.rgba(3, 0)[3] < opacity * 0.97, "{fmt:?}: the old edge was semi-transparent: {:?}", before.rgba(3, 0)); assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal))); for x in 0..4 { @@ -514,20 +514,80 @@ mod tests { } } - /// The rule is for a click on transparency only: from an opaque seed, a semi-transparent - /// neighbour along the edge keeps its own transparency (it belongs to another area). + /// The rule is for a click on transparency only: from an opaque seed the fill is exactly the + /// wand region's own fill, fringe included. #[test] fn bucket_on_opaque_pixels_keeps_neighbouring_transparency() { let a = Rect::new(0, 0, 8, 1); let mut s = Surface::new(PixelFormat::RGBA8); s.fill_rect(Rect::new(0, 0, 4, 1), &[1.0, 1.0, 1.0, 0.5]); s.fill_rect(Rect::new(4, 0, 8, 1), &[1.0, 1.0, 1.0, 1.0]); + let mut plain = s.clone(); + let img = crate::selection::rgba8_image(&plain, a); + let region = crate::selection::wand_region(&img, a, (6, 0), 0.0, true, true).unwrap(); + bucket_fill_region_inks(&mut plain, ®ion, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal)); assert!(bucket_fill_inks(&mut s, a, (6, 0), 0.0, true, true, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal))); - let edge = s.rgba(3, 0)[3]; - assert!(edge > 0.5 && edge < 0.6, "only the anti-aliased coverage lands: {edge}"); + for x in 0..8 { + assert_eq!(s.rgba(x, 0), plain.rgba(x, 0), "at {x}"); + } assert!((s.rgba(1, 0)[3] - 0.5).abs() < 0.01, "outside the region"); } + /// #12528 (reference application, transparent seed, Tolerance 32, Anti-alias on): a black + /// edge pixel bordering the filled area takes the green fill at coverage `1 − α`, so its + /// colour as well as its alpha follow the reference within two levels; with Anti-alias off it + /// stays as it was. + #[test] + fn bucket_on_transparency_blends_into_the_edge_at_its_transparency() { + let a = Rect::new(0, 0, 8, 1); + let green = |_, _| [0.0, 1.0, 0.0, 1.0]; + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + // (edge alpha, the reference application's result) + for (alpha, reference) in [(40, [0, 248, 0, 221]), (112, [0, 190, 0, 192]), (197, [0, 70, 0, 210]), (253, [0, 2, 0, 253])] { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + for anti_alias in [true, false] { + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(4, 0, 5, 1), &[0.0, 0.0, 0.0, alpha as f32 / 255.0]); + s.fill_rect(Rect::new(5, 0, 8, 1), &[0.0, 0.0, 0.0, 1.0]); + let before = s.clone(); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 32.0, true, anti_alias, 1.0, None, false, green, None, FillMode::Blend(BlendMode::Normal))); + let got = s.rgba(4, 0).map(level); + if anti_alias { + assert!(got.iter().zip(reference).all(|(g, r)| (g - r).abs() <= 2), "{fmt:?} alpha {alpha}: {got:?}, reference {reference:?}"); + } else { + assert_eq!(s.rgba(4, 0), before.rgba(4, 0), "{fmt:?} alpha {alpha}: Anti-alias off leaves the edge"); + } + for x in 5..8 { + assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} alpha {alpha}: opaque art at {x}"); + } + } + } + } + } + + /// #11354 review (measured in the reference application with a 4 px feathered rim): only the + /// one-pixel ring 8-adjacent to the flood rises, diagonals included; pixels further out keep + /// their alpha exactly. + #[test] + fn bucket_on_transparency_raises_only_the_ring_next_to_the_flood() { + let a = Rect::new(0, 0, 7, 7); + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(a, &[1.0, 1.0, 1.0, 100.0 / 255.0]); + s.fill_rect(Rect::new(3, 3, 4, 4), &[0.0; 4]); + let before = s.clone(); + assert!(bucket_fill_inks(&mut s, a, (3, 3), 32.0, true, true, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal))); + for y in 0..7 { + for x in 0..7 { + let (p, was) = (s.rgba(x, y), before.rgba(x, y)); + match ((x - 3).abs(), (y - 3).abs()) { + (0, 0) => assert!(p[3] > 0.999, "the flood at ({x},{y}): {p:?}"), + (dx, dy) if dx <= 1 && dy <= 1 => assert!(p[3] > was[3] + 0.1, "the ring at ({x},{y}) rises: {p:?}"), + _ => assert_eq!(p, was, "beyond the ring at ({x},{y})"), + } + } + } + } + /// The Paint Bucket's Mode: Multiply darkens what's there, Clear erases it (half at 50 %). #[test] fn bucket_mode_blends_or_clears() { diff --git a/crates/engine/src/cmd/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs index e915eceef9c..70433735809 100644 --- a/crates/engine/src/cmd/paint_cmds/tests.rs +++ b/crates/engine/src/cmd/paint_cmds/tests.rs @@ -372,8 +372,8 @@ fn assert_all_white(s: &Session, what: &str) { /// #11311 / #11354 review: after clearing an anti-aliased selection and bucket-filling the hole /// white at 100 %, the hole and the hole's edge are opaque white and the opaque art is untouched. /// The soft rim the Clear left (straight white at partial alpha) rises only partly, as in the -/// reference application: a pixel the fill reaches at alpha `α` ends at `α + (1 − α)²`, so a faint -/// rim stays. Before the first round the hole's own edge stayed semi-transparent (a grey ring); +/// reference application: a pixel of the one-pixel ring 8-adjacent to the flood, at alpha `α`, +/// ends at `α + (1 − α)²`, and pixels further out keep their alpha, so a faint rim stays. Before the first round the hole's own edge stayed semi-transparent (a grey ring); /// the first round filled the rim to 255 too, which the reference does not do. #[test] fn bucket_after_clearing_an_antialiased_selection_fills_the_hole_and_raises_the_rim_partly() { @@ -389,17 +389,21 @@ fn bucket_after_clearing_an_antialiased_selection_fills_the_hole_and_raises_the_ assert!(rim.iter().all(|p| p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3)), "depth {depth}: the rim keeps its white"); let after = layer_rgba(&s); + // The flood is every pixel the 8-bit wand sees as empty; the ring is the pixels 8-adjacent to it. + let empty = |x: i64, y: i64| (0..120).contains(&x) && (0..100).contains(&y) && level(cleared[(y * 120 + x) as usize][3]) == 0; let mut raised = 0; for (i, (was, now)) in cleared.iter().zip(&after).enumerate() { let at = (i % 120, i / 120); - if was[3] <= 0.0 || was[3] >= 1.0 { + let (x, y) = (at.0 as i64, at.1 as i64); + let next_to_flood = (-1..=1).any(|dy| (-1..=1).any(|dx| (dx, dy) != (0, 0) && empty(x + dx, y + dy))); + if level(was[3]) == 0 || was[3] >= 1.0 { assert_eq!(level(now[3]), 255, "depth {depth} at {at:?}: hole, hole edge and opaque art end opaque: {now:?}"); - } else if now[3] > was[3] { + } else if next_to_flood { raised += 1; let want = was[3] + (1.0 - was[3]).powi(2); assert!((now[3] - want).abs() < 1.5 / 255.0, "depth {depth} at {at:?}: rim {was:?} -> {now:?}, want alpha {want}"); } else { - assert_eq!(now, was, "depth {depth} at {at:?}: a rim pixel the fill does not reach stays"); + assert_eq!(now, was, "depth {depth} at {at:?}: a rim pixel beyond the ring next to the flood stays"); } assert!(now[..3].iter().all(|c| (c - 1.0).abs() < 1e-3), "depth {depth} at {at:?}: white: {now:?}"); } From 23a66cb159bda97106dd9e74dd7936c80ee0be34 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:14:01 +0100 Subject: [PATCH 41/65] Triangle tool: shape layers are named Triangle N, not Polygon N (#13353) The Triangle tool and Create Triangle send `shape.create` with `kind: "triangle"`. The engine builds it as a 3-sided live polygon, the same as before, and names the layer from the default base name "Triangle". Polygon N stays for polygons, and each base name is counted separately. An explicit `name` still wins. --- crates/engine/src/cmd/vector_cmds/shape.rs | 26 ++++++- .../vector_cmds/triangle_layer_name_tests.rs | 70 +++++++++++++++++++ crates/ui-egui/src/dialogs/shape_dialog.rs | 2 +- crates/ui-egui/src/tools/vector_ui/shapes.rs | 2 +- 4 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/cmd/vector_cmds/triangle_layer_name_tests.rs diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index 547ad47eca5..a191e238493 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -6,6 +6,7 @@ use super::{ Affine, Color, Document, EngineError, Fill, FillRule, Layer, LayerContent, LayerId, LiveShape, Path, PathOp, Point, Result, SHAPE_BLOCKS, Session, ShapeLayer, Value, bad, json, sel, vector, }; +use std::borrow::Cow; fn active_shape(s: &Session) -> std::result::Result<&ShapeLayer, String> { let d = s.active().ok_or("no document open")?; @@ -70,7 +71,22 @@ pub(super) fn paste_shape_stroke(s: &mut Session, p: &Value) -> Result { /// The path `shape.create` draws for live-shape params `p` (the Shape tools preview it while dragging). pub fn shape_path(p: &Value) -> Result { let kind = p.get("kind").and_then(Value::as_str).unwrap_or("rect"); - Ok(vector::shapes::live_path(&live_from_params("shape.create", kind, p, None)?)) + let (kind, p) = triangle_as_polygon(kind, p); + Ok(vector::shapes::live_path(&live_from_params("shape.create", kind, &p, None)?)) +} + +/// `kind: "triangle"` (the Triangle tool, Create Triangle) is a 3-sided polygon: the live-shape +/// kind and params to build it from. Its own kind only names the new layer (Triangle N). +fn triangle_as_polygon<'a>(kind: &'a str, p: &'a Value) -> (&'a str, Cow<'a, Value>) { + if kind != "triangle" { + return (kind, Cow::Borrowed(p)); + } + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.insert("sides".into(), json!(3)); + o.remove("starRatio"); + } + ("polygon", Cow::Owned(q)) } fn live_kind(l: &LiveShape) -> &'static str { @@ -426,6 +442,7 @@ fn default_name(kind: &str) -> &'static str { "roundedRect" | "roundRect" => "Rounded Rectangle", "ellipse" => "Ellipse", "polygon" => "Polygon", + "triangle" => "Triangle", "star" => "Star", "line" => "Line", _ => "Shape", @@ -442,7 +459,8 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result { let v = p.get("path").ok_or_else(|| bad(CMD, "kind \"path\" needs `path`"))?; (parse_path(v).map_err(|e| bad(CMD, e))?, None) } else { - let l = live_from_params(CMD, kind, p, None)?; + let (live_kind, q) = triangle_as_polygon(kind, p); + let l = live_from_params(CMD, live_kind, &q, None)?; (vector::shapes::live_path(&l), Some(l)) }; let (fill, stroke) = new_fill_stroke(s, CMD, p)?; @@ -782,6 +800,10 @@ pub(super) fn selection_to_shape(s: &mut Session, p: &Value) -> Result { shape_create(s, &q) } +#[cfg(test)] +#[path = "triangle_layer_name_tests.rs"] +mod triangle_layer_name_tests; + #[cfg(test)] mod arrow_affine_regression_tests { use super::*; diff --git a/crates/engine/src/cmd/vector_cmds/triangle_layer_name_tests.rs b/crates/engine/src/cmd/vector_cmds/triangle_layer_name_tests.rs new file mode 100644 index 00000000000..5cfddca5ba6 --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/triangle_layer_name_tests.rs @@ -0,0 +1,70 @@ +//! The Triangle tool and Create Triangle name their shape layers Triangle N, not Polygon N (#13353). + +use serde_json::{Value, json}; + +use super::super::{LayerContent, LayerId, LiveShape, shape_path}; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 160, "background": "white"})).unwrap(); + s +} + +/// The params the Triangle tool's drag and Create Triangle's OK send. +fn triangle(rect: [f64; 4]) -> Value { + json!({"kind": "triangle", "rect": rect}) +} + +fn name(info: &Value) -> &str { + info["name"].as_str().unwrap() +} + +#[test] +fn triangles_are_named_triangle_n() { + let mut s = session(); + let first = s.execute("shape.create", triangle([20.0, 20.0, 60.0, 40.0])).unwrap(); + let second = s.execute("shape.create", triangle([90.0, 30.0, 50.0, 50.0])).unwrap(); + assert_eq!((name(&first), name(&second)), ("Triangle 1", "Triangle 2")); +} + +#[test] +fn a_triangle_is_a_live_three_sided_polygon() { + let mut s = session(); + // Any `sides` or `starRatio` sent along is ignored: a triangle has 3 sides and no star. + let p = json!({"kind": "triangle", "rect": [20, 20, 60, 40], "sides": 7, "starRatio": 0.3, "cornerRadius": 4}); + let id = s.execute("shape.create", p.clone()).unwrap()["layer"].as_u64().unwrap(); + let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content else { panic!("not a shape layer") }; + assert_eq!(sh.live, Some(LiveShape::Polygon { rect: [20.0, 20.0, 60.0, 40.0], sides: 3, star_ratio: 1.0, corner_radius: 4.0 })); + // The drag's preview and Path mode draw the same outline. + let polygon = json!({"kind": "polygon", "rect": [20, 20, 60, 40], "sides": 3, "cornerRadius": 4}); + assert_eq!(shape_path(&p).unwrap(), shape_path(&polygon).unwrap()); + assert_eq!(sh.path, shape_path(&polygon).unwrap()); +} + +#[test] +fn polygons_and_triangles_count_on_their_own() { + let mut s = session(); + let tri = s.execute("shape.create", triangle([20.0, 20.0, 60.0, 40.0])).unwrap(); + let poly = s.execute("shape.create", json!({"kind": "polygon", "rect": [90, 30, 50, 50], "sides": 5})).unwrap(); + let three = s.execute("shape.create", json!({"kind": "polygon", "rect": [90, 90, 50, 50], "sides": 3})).unwrap(); + assert_eq!((name(&tri), name(&poly), name(&three)), ("Triangle 1", "Polygon 1", "Polygon 2")); +} + +#[test] +fn an_explicit_name_wins() { + let mut s = session(); + let info = s.execute("shape.create", json!({"kind": "triangle", "rect": [20, 20, 60, 40], "name": "Roof"})).unwrap(); + assert_eq!(name(&info), "Roof"); +} + +#[test] +fn a_triangle_without_a_rect_is_refused() { + let mut s = session(); + let history = s.active().unwrap().history.past_len(); + for p in [json!({"kind": "triangle"}), json!({"kind": "triangle", "rect": "x"})] { + assert!(s.execute("shape.create", p.clone()).is_err(), "{p}"); + } + assert!(shape_path(&json!({"kind": "triangle"})).is_err()); + assert_eq!(s.active().unwrap().history.past_len(), history); +} diff --git a/crates/ui-egui/src/dialogs/shape_dialog.rs b/crates/ui-egui/src/dialogs/shape_dialog.rs index fc9a3e9ea67..95180b8ec05 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog.rs @@ -124,7 +124,7 @@ pub fn geometry(f: &Map) -> Result { if radii.iter().any(|r| *r > 0.0) { json!({"kind": "roundedRect", "rect": rect, "radii": radii}) } else { json!({"kind": "rect", "rect": rect}) } } "ellipse" => json!({"kind": "ellipse", "rect": rect}), - "triangle" => json!({"kind": "polygon", "rect": rect, "sides": 3}), + "triangle" => json!({"kind": "triangle", "rect": rect}), "polygon" => { let sides = num(f, "sides").map_or(5.0, |s| s.round().clamp(3.0, 100.0)); let ratio = num(f, "starRatio").map_or(100.0, |r| r.clamp(1.0, 100.0)); diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 0776227d04b..9c2028919f7 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -116,7 +116,7 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: Tool::Rectangle if o.corner_radius > 0.0 => json!({"kind": "roundedRect", "rect": rect, "radii": vec![o.corner_radius; 4]}), Tool::Rectangle | Tool::CustomShape => json!({"kind": "rect", "rect": rect}), Tool::EllipseShape => json!({"kind": "ellipse", "rect": rect}), - Tool::Triangle => json!({"kind": "polygon", "rect": rect, "sides": 3}), + Tool::Triangle => json!({"kind": "triangle", "rect": rect}), // PhotoCraft's star defaults; the Star Tool's own options are not measured yet (#11377). Tool::Star => json!({"kind": "star", "rect": rect, "sides": 5, "starRatio": 0.5}), _ => json!({"kind": "polygon", "rect": rect, "sides": o.polygon_sides.max(3)}), From 4acc542584f42ec463ea6ca4a011b7d049f91dab Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 22:16:31 +0100 Subject: [PATCH 42/65] PR #12989: pin the spacing in the Smudge replay timing test The Smudge tool now starts with its own 13 px soft tip at 25 % spacing (#12964), so pressure_sized_smudge_release_matches_replay_and_undo_redo compared a 25 % live brush with the replay session's 10 % default. The setup now sets the spacing as well, as the Dodge change did for the sequential-dab test. Co-Authored-By: NaufalDzz Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/stroke_timing_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index ee9461f6fde..d569f73f111 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -545,8 +545,10 @@ fn a_shift_click_dodge_line_commits_its_live_pixels_unsmoothed() { fn pressure_sized_smudge_release_matches_replay_and_undo_redo() { use crate::stylus::PenSample; + // The spacing is set too: the Smudge tool starts with its own tip (#12964), the replay's + // fresh session with the default brush. let setup = |run: &mut dyn FnMut(&str, Value)| { - run("tools.setBrush", json!({"brush": {"size":40,"hardness":0.7,"pressureSize":true,"smoothing":{"amount":0.4}}})); + run("tools.setBrush", json!({"brush": {"size":40,"hardness":0.7,"spacing":0.1,"pressureSize":true,"smoothing":{"amount":0.4}}})); run("paint.stroke", json!({"points":[[10,20],[190,80]],"size":30,"color":"#2060c0"})); }; let mut h = harness(); From bf550d8fcb0f33a57d800974f7a37cd3eb5a2c84 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:29:47 -0600 Subject: [PATCH 43/65] perf(paint): only build the rim ring when an unlocked Blend fill can read it (#11354) --- crates/algo/src/paint.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index 5d40e81d93c..0a5b113c5cf 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -309,13 +309,17 @@ fn fill_region( // one-pixel ring around the flood). let b = region.bbox; let strength = |x: i32, y: i32| opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)); - let ring = if rim { rim_ring(region) } else { Vec::new() }; + // The ring is only ever read for an unlocked Blend fill (see composite_area), and it is + // empty when the region covers every pixel, so do not build it in those cases: on a large + // canvas it is a bool per pixel plus a full scan of the mask. + let use_rim = rim && !lock_transparency && matches!(mode, FillMode::Blend(_)) && region.mask.contains(&0); + let ring = if use_rim { rim_ring(region) } else { Vec::new() }; let on_ring = |x: i32, y: i32| { let at = usize::try_from(y - b.y0).ok().zip(usize::try_from(x - b.x0).ok()).filter(|_| b.contains(x, y)); let hit = at.and_then(|(yy, xx)| yy.checked_mul(b.width() as usize)?.checked_add(xx)).and_then(|i| ring.get(i)); if hit == Some(&true) { strength(x, y) } else { 0.0 } }; - let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if rim { Some(&on_ring) } else { None }; + let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if use_rim { Some(&on_ring) } else { None }; composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, rim); } From f25e2ce9c63071241420b4d79dbb8d5dddf865aa Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 22:32:42 +0000 Subject: [PATCH 44/65] Keep Create Rectangle closed inside the active live rectangle --- crates/ui-egui/src/canvas/gesture.rs | 10 +- .../canvas/rectangle_click_in_shape_tests.rs | 113 ++++++++++++++++++ crates/ui-egui/src/dialogs/shape_dialog.rs | 33 ++++- 3 files changed, 153 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index 1b82804e3da..c30bcf1694f 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -6,6 +6,10 @@ use super::strokes::{ use super::textures::shown_as_document; use super::{PhotocraftApp, Tool, json}; +#[cfg(test)] +#[path = "rectangle_click_in_shape_tests.rs"] +mod rectangle_click_in_shape_tests; + pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { finish(app, d, None); } @@ -110,8 +114,10 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option) { // mode a click adds nothing: the dialog makes a shape layer, which Path mode never draws, // and the click's few pixels of travel would add a speck of a subpath to the work path. t if crate::vector_ui::is_shape_tool(t) - && crate::shape_dialog::is_click(d.start, &d.points, app.point_zoom()) - && (crate::vector_ui::draws_path(&app.ui.tool_options) || crate::shape_dialog::open(app, t, d.start).is_some()) => {} + && crate::shape_dialog::is_tool_click(t, &app.ui.tool_options, d.start, &d.points, app.point_zoom()) + && (crate::vector_ui::draws_path(&app.ui.tool_options) + || crate::shape_dialog::click_inside_active_rectangle(app, t, d.start) + || crate::shape_dialog::open(app, t, d.start).is_some()) => {} t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.live), Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]), Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]), diff --git a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs new file mode 100644 index 00000000000..05063f06332 --- /dev/null +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -0,0 +1,113 @@ +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; +use serde_json::json; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.ui.tool = Tool::Rectangle; + app.sync_views(); + app +} + +fn shape(app: &mut PhotocraftApp, kind: &str, radius: f64) { + app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": radius, "fill": "#ff0000"})).unwrap(); +} + +fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: end_x, y: end_y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, mods); +} + +fn state(app: &PhotocraftApp) -> (usize, usize) { + let active = app.session.active().unwrap(); + (active.doc.layer_count(), active.history.past_len()) +} + +fn assert_create_rectangle(app: &PhotocraftApp) { + let [dialog] = app.ui.dialogs.as_slice() else { panic!("expected one Create Rectangle dialog") }; + assert_eq!(dialog.fields["__label"], "Create Rectangle"); + assert_eq!(dialog.fields["width"], 100.0); + assert_eq!(dialog.fields["height"], 100.0); + assert_eq!(dialog.fields["fromCenter"], false); +} + +#[test] +fn inside_the_active_live_rectangle_is_a_no_op() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + let center = [500.0, 350.0]; + for end in [center, [501.0, 350.0]] { + gesture(&mut app, center, end); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), before); + } +} + +#[test] +fn outside_the_rectangle_and_on_the_pasteboard_open_create_rectangle() { + for point in [[100.0, 500.0], [-20.0, 500.0]] { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + gesture(&mut app, point, point); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); + } +} + +#[test] +fn a_pixel_layer_or_non_rectangle_shape_leaves_the_dialog_available() { + let point = [500.0, 350.0]; + for other_shape in [false, true] { + let mut app = app(); + shape(&mut app, "rect", 0.0); + if other_shape { + shape(&mut app, "ellipse", 0.0); + } else { + app.run("layer.new", json!({"name": "Pixels"})).unwrap(); + } + let before = state(&app); + gesture(&mut app, point, point); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); + } +} + +#[test] +fn rounded_corners_use_the_outline_and_other_modes_keep_their_click_behavior() { + let mut app = app(); + shape(&mut app, "roundedRect", 30.0); + let before = state(&app); + let center = [500.0, 350.0]; + gesture(&mut app, center, center); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), before); + let corner = [401.0, 301.0]; + gesture(&mut app, corner, corner); + assert_create_rectangle(&app); + app.ui.dialogs.clear(); + + app.ui.tool_options.shape_mode = "path".into(); + gesture(&mut app, center, center); + assert!(app.ui.dialogs.is_empty()); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + app.ui.tool_options.shape_mode = "pixels".into(); + gesture(&mut app, center, center); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); +} + +#[test] +fn more_than_one_pixel_of_travel_still_draws_a_shape() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let (layers, history) = state(&app); + gesture(&mut app, [500.0, 350.0], [502.0, 351.0]); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), (layers + 1, history + 1)); +} diff --git a/crates/ui-egui/src/dialogs/shape_dialog.rs b/crates/ui-egui/src/dialogs/shape_dialog.rs index fc9a3e9ea67..1fae4717508 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog.rs @@ -47,10 +47,41 @@ fn valid(key: &str, v: &Value) -> bool { /// True for a press and release that never left `start` by more than a few screen pixels. pub fn is_click(start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool { - let slop = 3.0 / f64::from(zoom.max(0.01)); + within_click_slop(start, points, zoom, 3.0) +} + +pub(crate) fn is_tool_click(tool: Tool, options: &crate::state::ToolOptions, start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool { + if tool == Tool::Rectangle && options.shape_mode == "shape" { within_click_slop(start, points, zoom, 1.0) } else { is_click(start, points, zoom) } +} + +fn within_click_slop(start: [f64; 2], points: &[[f64; 3]], zoom: f32, pixels: f64) -> bool { + let slop = pixels / f64::from(zoom.max(0.01)); points.iter().all(|p| (p[0] - start[0]).hypot(p[1] - start[1]) <= slop) } +/// A Shape-mode Rectangle click inside the active live rectangle leaves the shape alone (#13340). +pub(crate) fn click_inside_active_rectangle(app: &PhotocraftApp, tool: Tool, at: [f64; 2]) -> bool { + use photocraft_doc::{LayerContent, LiveShape}; + + if tool != Tool::Rectangle || app.ui.tool_options.shape_mode != "shape" { + return false; + } + let Some(layer) = app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) else { return false }; + let LayerContent::Shape(shape) = &layer.content else { return false }; + let Some(LiveShape::Rect { rect: [x, y, w, h], radii }) = shape.live else { return false }; + let (left, top) = (x.min(x + w), y.min(y + h)); + let (right, bottom) = (x.max(x + w), y.max(y + h)); + let [px, py] = at; + if !((left..=right).contains(&px) && (top..=bottom).contains(&py)) { + return false; + } + let (l, r, t, b) = (px - left, right - px, py - top, bottom - py); + [(l, t), (r, t), (r, b), (l, b)] + .into_iter() + .zip(photocraft_vector::shapes::clamp_radii(w.abs(), h.abs(), radii)) + .all(|((dx, dy), radius)| dx >= radius || dy >= radius || (radius - dx).hypot(radius - dy) <= radius) +} + /// Open the creation dialog of `tool` for a click at `at` (document px). `None` for a tool without /// one (Line, Custom Shape). pub fn open(app: &mut PhotocraftApp, tool: Tool, at: [f64; 2]) -> Option { From d7b001a147446dd04507093287f7bc33d23668b9 Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 22:34:36 +0000 Subject: [PATCH 45/65] Use the registered pixel-layer command in the regression test --- crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs index 05063f06332..e772826f3da 100644 --- a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -69,7 +69,7 @@ fn a_pixel_layer_or_non_rectangle_shape_leaves_the_dialog_available() { if other_shape { shape(&mut app, "ellipse", 0.0); } else { - app.run("layer.new", json!({"name": "Pixels"})).unwrap(); + app.run("layer.new.layer", json!({"name": "Pixels"})).unwrap(); } let before = state(&app); gesture(&mut app, point, point); From 3c971cfc371bfc5f0d7396fc011bffb8f4e9f3e0 Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 22:41:24 +0000 Subject: [PATCH 46/65] Separate rectangle geometry checks from snapping and tool overlays --- .../canvas/rectangle_click_in_shape_tests.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs index e772826f3da..faf81a9374f 100644 --- a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -7,12 +7,13 @@ fn app() -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); app.ui.tool = Tool::Rectangle; + app.ui.extras.snap = false; app.sync_views(); app } fn shape(app: &mut PhotocraftApp, kind: &str, radius: f64) { - app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": radius, "fill": "#ff0000"})).unwrap(); + app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": [radius; 4], "fill": "#ff0000"})).unwrap(); } fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { @@ -79,7 +80,7 @@ fn a_pixel_layer_or_non_rectangle_shape_leaves_the_dialog_available() { } #[test] -fn rounded_corners_use_the_outline_and_other_modes_keep_their_click_behavior() { +fn rounded_corners_use_the_outline() { let mut app = app(); shape(&mut app, "roundedRect", 30.0); let before = state(&app); @@ -88,16 +89,22 @@ fn rounded_corners_use_the_outline_and_other_modes_keep_their_click_behavior() { assert!(app.ui.dialogs.is_empty()); assert_eq!(state(&app), before); let corner = [401.0, 301.0]; - gesture(&mut app, corner, corner); + super::finish_gesture(&mut app, super::Drag::new(Tool::Rectangle, corner, vec![[corner[0], corner[1], 1.0]], egui::Modifiers::NONE, false)); assert_create_rectangle(&app); - app.ui.dialogs.clear(); +} +#[test] +fn other_modes_keep_their_click_behavior() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + let center = [500.0, 350.0]; app.ui.tool_options.shape_mode = "path".into(); gesture(&mut app, center, center); assert!(app.ui.dialogs.is_empty()); assert!(app.session.active().unwrap().doc.work_path.is_none()); app.ui.tool_options.shape_mode = "pixels".into(); - gesture(&mut app, center, center); + super::finish_gesture(&mut app, super::Drag::new(Tool::Rectangle, center, vec![[center[0], center[1], 1.0]], egui::Modifiers::NONE, false)); assert_create_rectangle(&app); assert_eq!(state(&app), before); } From eb46134f80e64f50ec29dc81f96074542d4a6dbd Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 22:46:10 +0000 Subject: [PATCH 47/65] Serialize the rounded rectangle test radii as a Rust array --- crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs index faf81a9374f..ec3c180e7f9 100644 --- a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -13,7 +13,8 @@ fn app() -> PhotocraftApp { } fn shape(app: &mut PhotocraftApp, kind: &str, radius: f64) { - app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": [radius; 4], "fill": "#ff0000"})).unwrap(); + let radii = [radius; 4]; + app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": radii, "fill": "#ff0000"})).unwrap(); } fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { From 7a0c3bfca6c0a66d86c30ec136282e3e3b5b967b Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Wed, 11 Nov 2026 17:47:28 -0500 Subject: [PATCH 48/65] Add Anchor Point cursor: the pen tools' cursor choice in its own function (#12729) draw_default_tool_cursor went over clippy's cognitive complexity limit (31/30) once main's latest arms met this PR's guarded Add Anchor Point arm. The pen tools' arm now calls pen_tool_cursor, which holds the Precise crosshair, the Add Anchor Point arrow and the pen icon; no behaviour change. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4120297802f..a44f7dfc460 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1863,6 +1863,22 @@ fn pencil_outline_cursor(painter: &egui::Painter, xf: &ViewXform, p: Pos2, size: egui::CursorIcon::None } +/// A pen tool's cursor at screen point `p` (document point `doc`): the crosshair for precise Other +/// Cursors (#4639), the black arrow for Add Anchor Point unless a click would split a segment +/// (#12729; ⌘ is Direct Selection's arrow, ⌥ keeps the pen), else the tool's own pen icon. +fn pen_tool_cursor(app: &PhotocraftApp, ui: &egui::Ui, tool: Tool, doc: [f64; 2], p: Pos2) -> egui::CursorIcon { + if precise_other_cursor(app) { + return egui::CursorIcon::Crosshair; + } + if tool == Tool::AddAnchorPoint { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + if !mods.alt && (mods.command || !crate::anchor_tools::adds_anchor_at(app, tool, doc)) { + return crate::tool_cursor::arrow(ui.ctx(), p); + } + } + pen_cursor(ui.ctx(), tool, p) +} + fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &CanvasOverlayInput<'_>, resizing: bool, p: Pos2) { let painter = input.painter; let xf = input.xf; @@ -1998,18 +2014,10 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & } // Add Anchor Point: the pen with "+" only over a segment a click would split, else the // black arrow (#12729); ⌘ is Direct Selection's arrow. ⌥ and Precise stay as they were. - Tool::AddAnchorPoint - if !precise_other_cursor(app) && { - let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); - !mods.alt && (mods.command || !crate::anchor_tools::adds_anchor_at(app, tool, xf.to_doc(p))) - } => - { - crate::tool_cursor::arrow(ui.ctx(), p) - } // The pen tools: their own icon with its nib on the point, or the crosshair for - // precise Other Cursors (#4639). + // precise Other Cursors (#4639); Add Anchor Point the black arrow off a segment (#12729). Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => { - if precise_other_cursor(app) { egui::CursorIcon::Crosshair } else { pen_cursor(ui.ctx(), tool, p) } + pen_tool_cursor(app, ui, tool, xf.to_doc(p), p) } // Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool. Tool::Move if crate::move_mods::copying(app, alt) => egui::CursorIcon::Copy, From 490009277dc6da6db3e49c4979ebc1c17affc4dc Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 11 Nov 2026 22:49:14 +0000 Subject: [PATCH 49/65] Keep dialog regressions within the new Rectangle click rules --- crates/ui-egui/src/dialogs/shape_dialog/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/shape_dialog/tests.rs b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs index 1ca5de28f72..03f65d743d1 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs @@ -174,7 +174,7 @@ fn a_click_with_jitter_opens_the_dialog_on_hidpi() { let i = app.session.active_index().unwrap(); app.ui.views[i].zoom = 1.0; let before = layers(&app); - press(&mut app, Tool::Rectangle, [20.0, 30.0], [24.0, 30.0]); + press(&mut app, Tool::Rectangle, [20.0, 30.0], [22.0, 30.0]); only_dialog(&app); assert_eq!(layers(&app), before, "a jittery click draws nothing"); } @@ -347,7 +347,7 @@ fn right_click_picks_the_unit_of_that_field_only_and_it_is_not_remembered() { set(&mut app, id, json!({"widthUnit": "mm", "width": 50})); crate::dialogs::confirm(&mut app, id).unwrap(); app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "cm"})).unwrap(); - press(&mut app, Tool::Rectangle, [40.0, 40.0], [40.0, 40.0]); + press(&mut app, Tool::Rectangle, [140.0, 140.0], [140.0, 140.0]); let id = only_dialog(&app); let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); assert_eq!((f.get("widthUnit"), f["width"].as_f64()), (None, Some(50.0)), "the size is remembered, the unit isn't"); From 3b118ec008308c258fecd6697cbff045adb27f54 Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Thu, 12 Nov 2026 04:14:22 +0000 Subject: [PATCH 50/65] Path Selection: a drag on a shape moves it, not the targeted saved path (#13270) --- crates/ui-egui/src/canvas/tool_input.rs | 1 + crates/ui-egui/src/tools.rs | 2 + crates/ui-egui/src/tools/path_components.rs | 11 +++ ...h_selection_shape_over_saved_path_tests.rs | 70 +++++++++++++++++++ 4 files changed, 84 insertions(+) create mode 100644 crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index b3b4c425443..5c453dae143 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -602,6 +602,7 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods: if let Some(st) = app.session.active() && let Some(id) = crate::vector_ui::pick_shape_at(&st.doc, [x, y], tol) { + crate::path_components::untarget_saved_path_off(app, [x, y], tol); let _ = app.run("layer.select", json!({"layer": id.0})); } // The component pressed is selected, so the drag moves it (and the others selected). diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 684c8dbc326..4bc64c59ae6 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -73,6 +73,8 @@ mod gradient_options_bar_mode_tests; mod gradient_refusal_messages_tests; #[cfg(test)] mod line_tool_defaults_tests; +#[cfg(test)] +mod path_selection_shape_over_saved_path_tests; #[cfg(test)] mod remove_default_size_tests; diff --git a/crates/ui-egui/src/tools/path_components.rs b/crates/ui-egui/src/tools/path_components.rs index 74f866c6247..a82ccededd3 100644 --- a/crates/ui-egui/src/tools/path_components.rs +++ b/crates/ui-egui/src/tools/path_components.rs @@ -32,6 +32,17 @@ fn target(app: &PhotocraftApp) -> Option<(PathRef, Path)> { active_paths(app).into_iter().next() } +/// A Path Selection press on a shape layer, off every component of the targeted saved path: +/// the saved path is no longer the target, so the press and drag act on the shape (#13270). +/// A press on one of the saved path's components keeps it targeted. +pub(crate) fn untarget_saved_path_off(app: &mut PhotocraftApp, at: [f64; 2], tol: f64) { + if let Some((PathRef::Saved(_), path)) = target(app) + && component_at(&path, at, tol).is_none() + { + app.ui.selected_path = None; + } +} + /// The selected components: their path and the first subpath of each, in order. `None` with /// nothing selected, a selection on a path that is not an active one any more, or a tool other /// than Path Selection (the only one that shows it, so the only one that acts on it). diff --git a/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs b/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs new file mode 100644 index 00000000000..4590657480c --- /dev/null +++ b/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs @@ -0,0 +1,70 @@ +//! #13270: with a saved path targeted in the Paths panel, a Path Selection drag on a shape layer +//! targets and moves the shape, as in the reference application; the saved path keeps its points. +//! A drag on a component of the saved path still moves that component. + +use egui::Modifiers; +use photocraft_doc::{LayerContent, LayerId, Path}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const SAVED: &str = "Path 1"; + +/// A rectangle shape at 500,100–700,200, a pixel layer "Red" above it, active, and the saved +/// path "Path 1" (a square 100,300–200,400) selected in the Paths panel, with Path Selection. +fn setup() -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [500, 100, 200, 100], "fill": "#2050c0"})).unwrap(); + let shape = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({"name": "Red"})).unwrap(); + let square = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [200, 300], [200, 400], [100, 400]]}]}); + app.run("path.set", json!({"name": SAVED, "path": square})).unwrap(); + app.ui.selected_path = Some(SAVED.into()); + app.ui.tool = Tool::PathSelection; + (app, shape) +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, Modifiers::NONE); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, Modifiers::NONE); +} + +fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == SAVED).unwrap().path.clone() +} + +fn shape_bounds(app: &PhotocraftApp, id: LayerId) -> Option<(f64, f64, f64, f64)> { + let doc = &app.session.active().unwrap().doc; + doc.walk().iter().find(|(_, _, l)| l.id == id).and_then(|(_, _, l)| match &l.content { + LayerContent::Shape(sh) => sh.path.control_bounds(), + _ => None, + }) +} + +#[test] +fn a_drag_on_a_shape_moves_the_shape_not_the_targeted_saved_path() { + let (mut app, shape) = setup(); + let (path_before, shape_before) = (saved(&app), shape_bounds(&app, shape).unwrap()); + drag(&mut app, [600.0, 150.0], [650.0, 200.0]); + assert_eq!(app.session.active().unwrap().active_layer, Some(shape), "the shape is the active layer"); + assert_eq!(saved(&app), path_before, "the saved path keeps its points"); + let (x0, y0, x1, y1) = shape_before; + assert_eq!(shape_bounds(&app, shape), Some((x0 + 50.0, y0 + 50.0, x1 + 50.0, y1 + 50.0)), "the shape moved by the drag"); + assert_eq!(app.ui.selected_path, None, "the saved path is no longer the target"); +} + +#[test] +fn a_drag_on_a_component_of_the_saved_path_still_moves_it() { + let (mut app, shape) = setup(); + let shape_before = shape_bounds(&app, shape); + drag(&mut app, [150.0, 350.0], [180.0, 370.0]); + assert_eq!(saved(&app).control_bounds(), Some((130.0, 320.0, 230.0, 420.0)), "the saved path moved"); + assert_eq!(shape_bounds(&app, shape), shape_before, "the shape stays"); + assert_eq!(app.ui.selected_path.as_deref(), Some(SAVED)); +} From e54921b2972a20e6254194402b11ab2afa95a5f4 Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 12 Nov 2026 07:53:06 +0000 Subject: [PATCH 51/65] Retry CI after the Type options bar test flake From ec55bed7b0e553cf2a18131ba967dcc50f753f1b Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:55:36 +0100 Subject: [PATCH 52/65] algo, engine, ui: Perspective Crop commits a quad mirrored on one axis (#12489) `convex_quad` accepts a quad only when it is wound clockwise on screen, so a Perspective Crop box flipped on one axis (an Alt+corner drag past the opposite corner along x only), which is convex but wound counter-clockwise, was drawn red and refused by `image.perspectiveCrop` and `quad_to_rect`. The reference application commits it mirrored, each corner mapped as it lies. Add `convex_quad_any_winding` (the same angle and area limits, either winding; self-crossing, degenerate and non-finite quads stay invalid) and use it for Perspective Crop only: the `corners` check and its error text, `quad_to_rect`, and the overlay's validity check. The homography already maps each corner onto its own rectangle corner, so the crop comes out mirrored. Perspective Warp steps keep the clockwise-only `convex_quad`; clicked corners are still sorted clockwise and commit upright; a box turned 180 degrees still commits upside down. Tests: algo (a counter-clockwise quad maps corner to corner; bow ties, collinear, sliver and non-finite quads stay refused), and the new perspective_crop_mirrored_tests.rs (the measured Alt-drag case commits mirrored and is drawn valid, the command takes counter-clockwise corners, clicks commit upright, 180 degrees upside down, invalid quads stay red). The mirrored cases fail without the fix. Fixes #12489 --- crates/algo/src/transform.rs | 14 +- crates/algo/src/transform/tests.rs | 28 +++- .../engine/src/cmd/perspective_crop_cmds.rs | 11 +- .../tools/perspective_crop_mirrored_tests.rs | 138 ++++++++++++++++++ .../ui-egui/src/tools/perspective_crop_ui.rs | 13 +- 5 files changed, 191 insertions(+), 13 deletions(-) create mode 100644 crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index 5a46b472e9e..5dabbd2a0cc 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -210,6 +210,15 @@ pub fn convex_quad(q: &[[f64; 2]; 4]) -> bool { area2.is_finite() && area2 >= 2.0 } +/// Is `q` (TL, TR, BR, BL) a usable Perspective Crop quad in either winding: a [`convex_quad`], +/// or one wound counter-clockwise on screen (a box flipped on one axis, which crops mirrored, +/// #12489) with the same corner angle and area limits? Self-crossing, degenerate and non-finite +/// quads are not. The Perspective Warp steps keep the clockwise-only [`convex_quad`]. +pub fn convex_quad_any_winding(q: &[[f64; 2]; 4]) -> bool { + let [tl, tr, br, bl] = *q; + convex_quad(q) || convex_quad(&[tl, bl, br, tr]) +} + /// The output size a Perspective Crop of `q` (TL, TR, BR, BL) takes when none is given: the mean /// length of the top and bottom edges by the mean length of the left and right edges. pub fn quad_size(q: &[[f64; 2]; 4]) -> (f64, f64) { @@ -287,9 +296,10 @@ fn perspective_estimate(q: &[[f64; 2]; 4], [cx, cy]: [f64; 2]) -> Option<(f64, f /// The homography taking the quad `q` (TL, TR, BR, BL) onto the rectangle (0, 0)–(`w`, `h`), corner /// to corner: the inverse of the unit-square-to-quad map (Heckbert, "Fundamentals of Texture /// Mapping and Image Warping", 1989, §2.2.3) scaled to the rectangle. `None` when `q` isn't a -/// [`convex_quad`] or the size isn't positive. +/// [`convex_quad_any_winding`] or the size isn't positive. A quad wound counter-clockwise maps +/// mirrored, each corner onto its own rectangle corner. pub fn quad_to_rect(q: &[[f64; 2]; 4], w: f64, h: f64) -> Option { - if !(convex_quad(q) && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + if !(convex_quad_any_winding(q) && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { return None; } Homography::rect_to_quad([0.0, 0.0, w, h], *q)?.inverse() diff --git a/crates/algo/src/transform/tests.rs b/crates/algo/src/transform/tests.rs index b70bc74c3d4..af6e81b615e 100644 --- a/crates/algo/src/transform/tests.rs +++ b/crates/algo/src/transform/tests.rs @@ -61,7 +61,7 @@ fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { } /// Perspective Crop's map lands each quad corner exactly on its rectangle corner; degenerate, -/// self-crossing, counter-clockwise and non-finite quads have none. +/// self-crossing and non-finite quads have none. #[test] fn quad_to_rect_maps_corners_and_refuses_bad_quads() { let q = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; @@ -75,7 +75,7 @@ fn quad_to_rect_maps_corners_and_refuses_bad_quads() { for bad in [ [[0.0, 0.0], [50.0, 0.0], [100.0, 0.0], [0.0, 50.0]], [[0.0, 0.0], [50.0, 50.0], [50.0, 0.0], [0.0, 50.0]], - [[0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0]], + [[0.0, 0.0], [50.0, 50.0], [0.0, 50.0], [50.0, 0.0]], [[0.0, 0.0], [f64::NAN, 0.0], [50.0, 50.0], [0.0, 50.0]], [[0.0, 0.0]; 4], ] { @@ -84,6 +84,30 @@ fn quad_to_rect_maps_corners_and_refuses_bad_quads() { assert!(quad_to_rect(&q, 0.0, 10.0).is_none()); } +/// #12489: a quad wound counter-clockwise (a box flipped on one axis) maps mirrored, each corner +/// onto its own rectangle corner. Perspective Warp's clockwise-only check still refuses it. +#[test] +fn quad_to_rect_maps_a_counter_clockwise_quad_mirrored() { + let q = [[140.0, 25.0], [30.0, 12.0], [14.0, 95.0], [128.0, 110.0]]; + assert!(!convex_quad(&q) && convex_quad_any_winding(&q)); + let h = quad_to_rect(&q, 100.0, 80.0).unwrap(); + for (c, want) in q.iter().zip([[0.0, 0.0], [100.0, 0.0], [100.0, 80.0], [0.0, 80.0]]) { + let (x, y) = h.apply(c[0], c[1]); + assert!((x - want[0]).abs() < 1e-9 && (y - want[1]).abs() < 1e-9, "{c:?} -> ({x}, {y})"); + } + // Self-crossing in either winding, three corners on a line, and a sliver stay refused. + for bad in [ + [[0.0, 0.0], [50.0, 0.0], [0.0, 50.0], [50.0, 50.0]], + [[50.0, 0.0], [0.0, 0.0], [50.0, 50.0], [0.0, 50.0]], + [[50.0, 0.0], [25.0, 0.0], [0.0, 0.0], [50.0, 50.0]], + [[50.0, 0.0], [0.0, 0.0], [0.0, 0.01], [50.0, 0.01]], + [[50.0, 0.0], [0.0, f64::INFINITY], [0.0, 50.0], [50.0, 50.0]], + ] { + assert!(!convex_quad_any_winding(&bad), "{bad:?}"); + assert!(quad_to_rect(&bad, 10.0, 10.0).is_none(), "{bad:?}"); + } +} + fn rgba() -> Surface { Surface::new(PixelFormat::RGBA8) } diff --git a/crates/engine/src/cmd/perspective_crop_cmds.rs b/crates/engine/src/cmd/perspective_crop_cmds.rs index d5d4db24f57..161fa35e704 100644 --- a/crates/engine/src/cmd/perspective_crop_cmds.rs +++ b/crates/engine/src/cmd/perspective_crop_cmds.rs @@ -12,7 +12,7 @@ //! editable equivalent for them. Vector masks, paths, notes, slices and guides follow the affine //! map closest to the homography (exact when the quad is a parallelogram). -use photocraft_algo::transform::{Homography, Interp, convex_quad, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; +use photocraft_algo::transform::{Homography, Interp, convex_quad_any_winding, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; use photocraft_color::PixelFormat; use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size}; use photocraft_geom::{Affine, Rect}; @@ -39,7 +39,8 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } -/// `corners`: four `[x, y]` points, TL, TR, BR, BL, forming a convex quad clockwise on screen. +/// `corners`: four `[x, y]` points, TL, TR, BR, BL, forming a convex quad. Wound counter-clockwise +/// on screen (a box flipped on one axis) it crops mirrored, each corner as it lies (#12489). fn corners(p: &Value) -> Result<[[f64; 2]; 4]> { let shape = || bad("`corners` must be four [x, y] points: top-left, top-right, bottom-right, bottom-left"); let list = p.get("corners").and_then(Value::as_array).filter(|a| a.len() == 4).ok_or_else(shape)?; @@ -52,9 +53,9 @@ fn corners(p: &Value) -> Result<[[f64; 2]; 4]> { } *slot = [x, y]; } - if !convex_quad(&q) { + if !convex_quad_any_winding(&q) { return Err(bad( - "the corners must form a convex quadrilateral at least 1 px in area, in order top-left, top-right, bottom-right, bottom-left (clockwise on screen)", + "the corners must form a convex quadrilateral at least 1 px in area, in order top-left, top-right, bottom-right, bottom-left (counter-clockwise on screen crops mirrored)", )); } Ok(q) @@ -387,7 +388,7 @@ mod tests { json!({"corners": [[0, 0], [10, 0], [10, 10]]}), json!({"corners": [[0, 0], [50, 0], [100, 0], [0, 50]]}), json!({"corners": [[0, 0], [50, 50], [50, 0], [0, 50]]}), - json!({"corners": [[0, 0], [0, 50], [50, 50], [50, 0]]}), + json!({"corners": [[50, 0], [0, 0], [50, 50], [0, 50]]}), json!({"corners": [[0, 0], [0.5, 0], [0.5, 0.5], [0, 0.5]]}), json!({"corners": [[0, 0], [1e300, 0], [50, 50], [0, 50]]}), json!({"corners": [[0, 0], ["a", 0], [50, 50], [0, 50]]}), diff --git a/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs b/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs new file mode 100644 index 00000000000..e01e64387c0 --- /dev/null +++ b/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs @@ -0,0 +1,138 @@ +//! #12489: a Perspective Crop box flipped on one axis (⌥ dragging a corner past the opposite one +//! along x only) is wound counter-clockwise. It is drawn valid and commits mirrored, each corner +//! mapped as it lies, as in the reference application; `image.perspectiveCrop` takes the same +//! corners. Clicked corners still commit upright, a box turned 180° still commits upside down, and +//! self-crossing and degenerate quads stay invalid. + +use std::sync::Arc; + +use egui::{Modifiers, Pos2, Rect, vec2}; +use serde_json::json; + +use super::*; + +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const YELLOW: [f32; 4] = [1.0, 1.0, 0.0, 1.0]; + +/// The measured test document: 800 x 500, red (top left), green (top right), blue (bottom left) +/// and yellow (bottom right) quadrants with a black square in the middle; the Perspective Crop tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 500})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + let surf = Arc::make_mut(&mut app.session.active_mut().unwrap().doc).layers[0].surface_mut().unwrap(); + for (x, y, c) in [(0, 0, RED), (400, 0, GREEN), (0, 250, BLUE), (400, 250, YELLOW)] { + surf.fill_rect(photocraft_geom::Rect::from_xywh(x, y, 400, 250), &c); + } + surf.fill_rect(photocraft_geom::Rect::from_xywh(395, 245, 10, 10), &[0.0, 0.0, 0.0, 1.0]); + app +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + assert!(pointer(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods)); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + assert!(pointer(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Up { x: to[0], y: to[1] }, mods)); +} + +fn click(app: &mut PhotocraftApp, p: [f64; 2]) { + drag(app, p, p, Modifiers::NONE); +} + +/// The overlay `draw_overlay` paints: (shield polygons, whether the frame is red). +fn overlay(app: &PhotocraftApp) -> (usize, bool) { + let ctx = egui::Context::default(); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)), zoom: 1.0, center: [400.0, 250.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut o = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf)); + o.textures_delta.clear(); + let shield = o.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Path(p) if p.fill == SHIELD)).count(); + let red = Color32::from_rgb(0xe5, 0x3e, 0x3e); + let frame_red = o.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Path(p) if p.closed && p.stroke.color == egui::epaint::ColorMode::Solid(red))); + (shield, frame_red) +} + +/// The committed canvas's size and the colours at its four corners (TL, TR, BL, BR). +fn corners(app: &PhotocraftApp) -> ((u32, u32), [[f32; 4]; 4]) { + let doc = &app.session.active().unwrap().doc; + let (w, h) = (doc.size.width as i32, doc.size.height as i32); + let surf = doc.layers[0].surface().unwrap(); + ((doc.size.width, doc.size.height), [surf.rgba(3, 3), surf.rgba(w - 4, 3), surf.rgba(3, h - 4), surf.rgba(w - 4, h - 4)]) +} + +#[test] +fn alt_corner_drag_past_the_opposite_corner_on_one_axis_commits_mirrored() { + let mut app = app(); + // A fresh 100 x 100 box, its bottom right corner ⌥ dragged past the fixed top left one on x only. + drag(&mut app, [450.0, 220.0], [550.0, 320.0], Modifiers::NONE); + drag(&mut app, [550.0, 320.0], [350.0, 300.0], Modifiers::ALT); + assert_eq!(app.ui.perspective_crop, Some([[450.0, 220.0], [350.0, 220.0], [350.0, 300.0], [450.0, 300.0]]), "flipped left to right"); + let (shield, red) = overlay(&app); + assert!(shield > 0 && !red, "drawn as a valid quad: accent frame and shield, not red"); + commit(&mut app); + assert!(app.ui.perspective_crop.is_none(), "committed"); + let (size, [tl, tr, bl, br]) = corners(&app); + assert_eq!(size, (100, 80)); + assert_eq!([tl, tr, bl, br], [GREEN, RED, YELLOW, BLUE], "mirrored left to right, top stays on top"); +} + +#[test] +fn the_command_takes_counter_clockwise_corners_and_mirrors() { + let mut app = app(); + let r = app.run("image.perspectiveCrop", json!({"corners": [[450, 220], [350, 220], [350, 300], [450, 300]]})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(100), Some(80))); + assert_eq!(corners(&app).1, [GREEN, RED, YELLOW, BLUE]); + // Mirrored top to bottom the other way round. + let mut app = self::app(); + app.run("image.perspectiveCrop", json!({"corners": [[350, 300], [450, 300], [450, 220], [350, 220]]})).unwrap(); + assert_eq!(corners(&app).1, [BLUE, YELLOW, RED, GREEN]); +} + +#[test] +fn clicked_corners_commit_upright_in_any_order() { + let mut app = app(); + // Counter-clockwise clicks from the top left. + for p in [[350.0, 220.0], [350.0, 300.0], [450.0, 300.0], [450.0, 220.0]] { + click(&mut app, p); + } + assert_eq!(app.ui.perspective_crop, Some([[350.0, 220.0], [450.0, 220.0], [450.0, 300.0], [350.0, 300.0]]), "sorted clockwise"); + commit(&mut app); + assert_eq!(corners(&app), ((100, 80), [RED, GREEN, BLUE, YELLOW])); +} + +#[test] +fn a_box_turned_180_degrees_commits_upside_down() { + let mut app = app(); + drag(&mut app, [450.0, 300.0], [550.0, 400.0], Modifiers::NONE); + drag(&mut app, [550.0, 400.0], [350.0, 200.0], Modifiers::ALT); + assert_eq!(app.ui.perspective_crop, Some([[450.0, 300.0], [350.0, 300.0], [350.0, 200.0], [450.0, 200.0]])); + commit(&mut app); + assert_eq!(corners(&app), ((100, 100), [YELLOW, BLUE, GREEN, RED])); +} + +#[test] +fn self_crossing_and_degenerate_quads_stay_invalid() { + for q in [ + // Self-crossing (a bow tie), each way round. + [[350.0, 220.0], [450.0, 220.0], [350.0, 300.0], [450.0, 300.0]], + [[450.0, 220.0], [350.0, 220.0], [450.0, 300.0], [350.0, 300.0]], + // Three corners on a line, and no area. + [[350.0, 220.0], [400.0, 220.0], [450.0, 220.0], [350.0, 300.0]], + [[400.0, 250.0]; 4], + ] { + let mut app = app(); + app.ui.perspective_crop = Some(q); + let (shield, red) = overlay(&app); + assert!(shield == 0 && red, "{q:?} is drawn red without the shield"); + assert!(app.run("image.perspectiveCrop", json!({ "corners": q })).is_err(), "{q:?}"); + commit(&mut app); + assert_eq!(app.ui.perspective_crop, Some(q), "{q:?} stays for fixing"); + assert_eq!(app.session.active().unwrap().doc.size.width, 800); + } + let mut app = app(); + assert!(app.run("image.perspectiveCrop", json!({"corners": [[350, 220], [f64::NAN, 220], [450, 300], [350, 300]]})).is_err()); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index bf0d491fb06..5a47aebe50f 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -4,8 +4,8 @@ //! BL in document px; clicked corners are put in that order); //! - drag a corner to move it alone, onto an edge of a skewed object (a photographed page, a //! facade); drag inside the quad to move it; -//! - the quad shows its perspective grid (Show Grid) and turns red while it isn't a convex quad -//! wound like its box, which can't be committed; +//! - the quad shows its perspective grid (Show Grid) and turns red while it isn't a convex quad, +//! which can't be committed; one flipped on one axis (wound the other way) commits mirrored; //! - ↵ (or ✓) commits: `image.perspectiveCrop` maps the quad onto an upright rectangle, the whole //! document in one undo step. Its size comes from the options bar's W x H (and the resolution), //! which are the Crop tool's fields (`crop_size`), or with them empty from the rectangle the @@ -14,7 +14,7 @@ //! A pending quad belongs to the document it was drawn on, like the Crop tool's frame. use egui::{Color32, Pos2, Stroke}; -use photocraft_algo::transform::{Homography, convex_quad}; +use photocraft_algo::transform::{Homography, convex_quad, convex_quad_any_winding}; use photocraft_engine::prefs::Unit; use serde_json::{Value, json}; @@ -393,7 +393,8 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform _ => app.ui.perspective_crop, }; if let Some(q) = quad.filter(|q| q.iter().flatten().all(|v| v.is_finite())) { - let ok = convex_quad(&q); + // A quad flipped on one axis is wound counter-clockwise and commits mirrored (#12489). + let ok = convex_quad_any_winding(&q); let color = if ok { accent } else { Color32::from_rgb(0xe5, 0x3e, 0x3e) }; // The image outside the quad is dimmed (#11972), following the quad while it is dragged. if ok && let Some(size) = app.session.active().map(|d| d.doc.size) { @@ -521,6 +522,10 @@ mod perspective_crop_shield_tests; #[path = "perspective_crop_deselect_tests.rs"] mod perspective_crop_deselect_tests; +#[cfg(test)] +#[path = "perspective_crop_mirrored_tests.rs"] +mod perspective_crop_mirrored_tests; + #[cfg(test)] mod tests { use super::*; From b374e27b9dfa0c636fb053800851119873aa9f1e Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:25:19 +0100 Subject: [PATCH 53/65] engine: Pencil Auto Erase probes a CMYK pick with the picked inks (#13060) In a CMYK layer the stroke renderer paints a foreground picked as CMYK as those exact inks (`StrokeRenderer::composite`, #4344), but `apply_auto_erase` built its probe from the foreground's RGB stand-in converted back to CMYK. For a rich black (or any ink mix the RGB doesn't round-trip to) the probe never matched the stroke's own pixels, so a stroke starting on them painted the foreground again instead of the background. The probe now puts the picked inks in, under the same condition the renderer uses (CMYK target, inks picked for this foreground). Commit and live stroke share `apply_auto_erase`, so both are fixed. Test: a rich-black pencil line in a CMYK document, then an Auto Erase stroke starting on it paints the background, live and committed. It fails without the fix. Fixes #13060 --- crates/engine/src/cmd/brush_cmds.rs | 17 ++++++++++--- crates/engine/src/cmd/brush_cmds/tests.rs | 29 +++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 0a410926799..6a3164c07a2 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -341,12 +341,23 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS /// Pencil Auto Erase: a stroke that starts on a pixel of the foreground colour paints the /// background colour instead (Photoshop). The match is exact (#11966): the foreground as the /// layer would store it (its mode and depth) against the pixel, its alpha aside, so one level -/// off paints the foreground. +/// off paints the foreground. In a CMYK layer a foreground picked as CMYK is probed as the inks +/// the stroke paints (#13060), not as its RGB stand-in converted back. fn apply_auto_erase(brush: &mut BrushSettings, surf: &Surface, start: Option<&StrokePoint>, fg: [f32; 4], bg: [f32; 4]) { let Some(p0) = start else { return }; let c = surf.rgba(p0.x.floor() as i32, p0.y.floor() as i32); - let mut probe = Surface::new(surf.format()); - probe.write_pixel(0, 0, &photocraft_raster::from_rgba(&surf.format(), [fg[0], fg[1], fg[2], 1.0])); + let format = surf.format(); + let mut px = photocraft_raster::from_rgba(&format, [fg[0], fg[1], fg[2], 1.0]); + // The renderer's condition for painting the picked inks (`StrokeRenderer::composite`), keyed + // on the foreground being probed. + if let (photocraft_color::ColorMode::Cmyk, Some((rgb, inks))) = (format.mode, brush.color_cmyk) + && rgb == [fg[0], fg[1], fg[2]] + && let Some(channels) = px.get_mut(..4) + { + channels.copy_from_slice(&inks); + } + let mut probe = Surface::new(format); + probe.write_pixel(0, 0, &px); let stored = probe.rgba(0, 0); // Far below one 8-bit level: only the float noise of the conversion. if c[3] > 0.0 && (0..3).all(|i| (c[i] - stored[i]).abs() < 1e-5) { diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 7a424e2f03b..5d67b14b468 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -212,6 +212,35 @@ fn pencil_is_aliased_and_auto_erases() { assert_eq!(rgba(&s, 40, 26), [0.0, 0.0, 0.0, 1.0]); } +/// #13060: in a CMYK document a foreground picked as CMYK inks (a rich black, which its sRGB +/// stand-in does not convert back to) is painted as those inks, and Pencil Auto Erase recognises +/// them: a stroke that starts on it paints the background colour, live and committed. +#[test] +fn pencil_auto_erase_probes_a_cmyk_pick_with_the_picked_inks() { + let rich_black = [0.6f32, 0.4, 0.4, 1.0]; + let rgb = photocraft_color::convert::cmyk_to_rgb(rich_black).map(|c| c.clamp(0.0, 1.0)); + let mut s = session(40, 20); + s.execute("image.mode.cmyk", json!({})).unwrap(); + s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": rich_black, "background": "#ffffff"})).unwrap(); + s.execute("paint.pencil", json!({"points": [[5, 10], [35, 10]], "size": 5})).unwrap(); + let pixel = |s: &Session, x: i32, y: i32| -> Vec { surface(s).read_region(Rect::new(x, y, x + 1, y + 1)).into_iter().take(4).collect() }; + let painted = pixel(&s, 20, 10); + assert!(painted.iter().zip(rich_black).all(|(a, b)| (a - b).abs() < 0.01), "the stroke paints the picked inks: {painted:?}"); + let white = [1.0f32, 1.0, 1.0, 1.0]; + + // Live: the stroke that starts on the rich black paints the background. + let p = json!({"points": [[12, 10]], "autoErase": true, "smoothing": 0.0}); + let mut live = LiveStroke::begin_with(&s, "paint.pencil", &p).unwrap(); + live.push(&[StrokePoint::new(12.0, 18.0, 1.0)]).unwrap(); + let shown = live.doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(12, 17); + assert!(shown.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-3), "live: {shown:?}"); + + // Committed: the same. + s.execute("paint.pencil", json!({"points": [[20, 10], [20, 18]], "size": 3, "autoErase": true})).unwrap(); + let erased = rgba(&s, 20, 17); + assert!(erased.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-3), "committed: {erased:?}"); +} + #[test] fn mixer_brush_reservoir_and_cleaning() { let mut s = session(200, 30); From 8943be1f4fae5b689e68c1826aff56f6ec179e3f Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:12:26 +0100 Subject: [PATCH 54/65] engine, ui: Burn, Sponge, Blur and Smudge refuse Indexed Color and Bitmap (#12673, #13033, #12656, #12967) The colour-mode check `mode_refusal` in retouch_cmds/dab.rs only knew paint.dodge and paint.sharpen, so the other dab tools painted into Indexed Color and Bitmap documents, where the reference application refuses with an alert. Add their arms (both `dab_cmd` and the live stroke `LiveDab::begin` call it, so nothing is previewed either), and name the tools in the canvas `mode_tool_name` so a press opens the same alert with OK. Multichannel and Duotone were not measured and keep today's behaviour. Tests: one engine file per tool (refusal text from the command and the live stroke, pixels and History unchanged; RGB/Gray/CMYK/Lab at 8/16/32 bits, Multichannel and Duotone keep working) and a canvas alert test for all four. The engine refusal tests fail without the fix. Fixes #12673 Fixes #13033 Fixes #12656 Fixes #12967 --- .../blur_refuses_indexed_tests.rs | 57 +++++++++++++++++++ .../burn_refuses_indexed_tests.rs | 48 ++++++++++++++++ crates/engine/src/cmd/retouch_cmds/dab.rs | 27 ++++++++- .../smudge_refuses_indexed_tests.rs | 57 +++++++++++++++++++ .../sponge_refuses_indexed_tests.rs | 49 ++++++++++++++++ .../src/retouch_mode_refusal_alert_tests.rs | 41 +++++++++++++ crates/ui-egui/src/tools/brush_refusal.rs | 14 ++++- 7 files changed, 287 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs create mode 100644 crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs create mode 100644 crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs create mode 100644 crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs create mode 100644 crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs diff --git a/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs new file mode 100644 index 00000000000..16e430f6508 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs @@ -0,0 +1,57 @@ +//! #12656: the Blur tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the blur tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the blur tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The grey document with its left half black: an edge for the stroke to work on. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = session(mode, depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "strength": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = edged(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.blur", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.blur", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = edged(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.blur", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.blur", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs new file mode 100644 index 00000000000..d278633555e --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs @@ -0,0 +1,48 @@ +//! #12673: the Burn tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the burn tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the burn tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "range": "midtones", "exposure": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = session(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.burn", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.burn", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = session(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.burn", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.burn", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index 082fa9a28e2..2a89e5527e5 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -280,13 +280,18 @@ impl DabTool { } } -/// The reference application refuses a Dodge or Sharpen stroke in Indexed Color and Bitmap -/// documents, with its alert's words (#12686, #12953); other modes (Multichannel and Duotone were -/// not measured) paint as before. The live stroke checks this too, so it previews nothing there. +/// The reference application refuses a Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke in +/// Indexed Color and Bitmap documents, with its alert's words (#12686, #12673, #13033, #12656, +/// #12953, #12967); other modes (Multichannel and Duotone were not measured) paint as before. The +/// live stroke checks this too, so it previews nothing there. fn mode_refusal(s: &Session, cmd: &str) -> Result<()> { let tool = match cmd { "paint.dodge" => "dodge tool", + "paint.burn" => "burn tool", + "paint.sponge" => "sponge tool", + "paint.blur" => "blur tool", "paint.sharpen" => "sharpen tool", + "paint.smudge" => "smudge tool", _ => return Ok(()), }; let why = match s.active().map(|st| st.doc.mode) { @@ -717,6 +722,22 @@ mod dodge_refuses_indexed_tests; #[path = "sharpen_refuses_indexed_tests.rs"] mod sharpen_refuses_indexed_tests; +#[cfg(test)] +#[path = "burn_refuses_indexed_tests.rs"] +mod burn_refuses_indexed_tests; + +#[cfg(test)] +#[path = "sponge_refuses_indexed_tests.rs"] +mod sponge_refuses_indexed_tests; + +#[cfg(test)] +#[path = "blur_refuses_indexed_tests.rs"] +mod blur_refuses_indexed_tests; + +#[cfg(test)] +#[path = "smudge_refuses_indexed_tests.rs"] +mod smudge_refuses_indexed_tests; + #[cfg(test)] #[path = "smudge_mode_tests.rs"] mod smudge_mode_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs new file mode 100644 index 00000000000..4a621b27c3f --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs @@ -0,0 +1,57 @@ +//! #12967: the Smudge tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the smudge tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the smudge tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The grey document with its left half black: an edge for the stroke to work on. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = session(mode, depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "strength": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = edged(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.smudge", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.smudge", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = edged(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.smudge", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.smudge", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs new file mode 100644 index 00000000000..61dd03901c3 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs @@ -0,0 +1,49 @@ +//! #13033: the Sponge tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the sponge tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the sponge tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "mode": "desaturate"}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = session(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.sponge", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.sponge", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +/// +/// The grey document has no saturation to take away, so this checks that the stroke runs and +/// records its History step, not that pixels change. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = session(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.sponge", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + s.execute("paint.sponge", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs b/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs new file mode 100644 index 00000000000..eba8c7bce4b --- /dev/null +++ b/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs @@ -0,0 +1,41 @@ +//! #12673, #13033, #12656, #12967: a press with the Burn, Sponge, Blur or Smudge tool in an Indexed +//! Color or Bitmap document opens the reference application's colour-mode alert with OK, once, and +//! paints nothing; in RGB the same press still paints. + +use serde_json::json; + +use super::brush_refusal_alert_tests::{alerts, app, refused, steps, stroke}; +use super::*; + +const TOOLS: [(Tool, &str); 4] = [(Tool::Burn, "burn tool"), (Tool::Sponge, "sponge tool"), (Tool::Blur, "blur tool"), (Tool::Smudge, "smudge tool")]; + +#[test] +fn indexed_color_documents_get_the_mode_alert() { + for (tool, name) in TOOLS { + let mut app = app(tool); + app.run("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + refused(&mut app, &format!("Could not use the {name} because it does not work with Indexed Color images (convert image to RGB Color mode to edit).")); + } +} + +#[test] +fn bitmap_documents_get_the_mode_alert() { + for (tool, name) in TOOLS { + let mut app = app(tool); + app.run("image.mode.grayscale", json!({})).unwrap(); + app.run("image.mode.bitmap", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Bitmap); + refused(&mut app, &format!("Could not use the {name} because it does not work with Bitmap images (convert image to Grayscale mode to edit).")); + } +} + +#[test] +fn rgb_documents_keep_painting() { + for (tool, _) in TOOLS { + let mut app = app(tool); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{tool:?}: no alert"); + assert_eq!(steps(&app), before + 1, "{tool:?}: the stroke was applied"); + } +} diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index bfa63bb3abc..0fa245f0b53 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -22,13 +22,17 @@ pub const REMOVE_LOCKED: &str = "Can't use the tool because the layer is locked. pub const INDEXED: &str = "Could not use the {tool} because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; pub const BITMAP: &str = "Could not use the {tool} because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; -/// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge -/// and Sharpen tools. Kept apart from [`tool_name`]: the layer alerts aren't wired for the Dodge -/// tool yet (#12685). +/// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge, +/// Burn, Sponge, Blur, Sharpen and Smudge tools. Kept apart from [`tool_name`]: the layer alerts +/// aren't wired for all of them yet (#12685). fn mode_tool_name(tool: Tool) -> Option<&'static str> { match tool { Tool::Dodge => Some(tl!("dodge tool")), + Tool::Burn => Some(tl!("burn tool")), + Tool::Sponge => Some(tl!("sponge tool")), + Tool::Blur => Some(tl!("blur tool")), Tool::Sharpen => Some(tl!("sharpen tool")), + Tool::Smudge => Some(tl!("smudge tool")), _ => None, } } @@ -110,6 +114,10 @@ mod sharpen_refusal_alert_tests; #[path = "../sponge_refusal_alert_tests.rs"] mod sponge_refusal_alert_tests; +#[cfg(test)] +#[path = "../retouch_mode_refusal_alert_tests.rs"] +mod retouch_mode_refusal_alert_tests; + #[cfg(test)] #[path = "../bucket_bitmap_alert_tests.rs"] mod bucket_bitmap_alert_tests; From 16c8e5c4d182e73578890b71b206af88b138dd21 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:41:55 +0100 Subject: [PATCH 55/65] Freeform Pen: anchors on the trace's turning points, rounded joins (#12838) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fit_trace places the Freeform Pen's anchors as the reference application does on the issue's sample strokes: corners only at turns sharper than 80°, each run fitted one segment at a time as far as one cubic follows the trace, ending on the first turning point in x or y within reach, with the segment's turn bounded by Curve Fit (75° per px, at most 150°). The end handle of each piece is fitted, not estimated. A closed trace keeps its release point as an anchor. Make Work Path keeps its fitting. Curve Fit 2: sine 6 anchors on the peaks, circle 5, open circle 4, vee 4 smooth, line unchanged; 0.5 and 1 px give more anchors. --- crates/vector/src/trace.rs | 308 +++++++++++++++++- .../vector/src/trace_freeform_anchor_tests.rs | 131 ++++++++ 2 files changed, 421 insertions(+), 18 deletions(-) create mode 100644 crates/vector/src/trace_freeform_anchor_tests.rs diff --git a/crates/vector/src/trace.rs b/crates/vector/src/trace.rs index 1557af863df..655b83022d5 100644 --- a/crates/vector/src/trace.rs +++ b/crates/vector/src/trace.rs @@ -10,8 +10,10 @@ //! Contours are emitted as subpaths: the first combines, the rest *exclude*, which is the //! even-odd area for nested, non-crossing contours regardless of their orientation. //! -//! [`fit_trace`] runs steps 2 and 3 on a freehand pointer trace (the Freeform Pen), open or -//! closed, with a corner window that grows with the tolerance. +//! [`fit_trace`] fits a freehand pointer trace (the Freeform Pen), open or closed, the way the +//! reference application places its anchors: corners only at turns sharper than 80°, then each +//! run segment by segment, every segment as long as one cubic follows the trace, ending on a +//! turning point in x or y (a wave's peak, a circle's top) where one is in reach. use std::collections::HashMap; @@ -190,14 +192,14 @@ fn walk(lp: &[P], i: usize, window: f64, fwd: bool, closed: bool) -> P { lp[cur] } -/// Indices of corner points: where the direction over ±`window` px turns by more than 60°. The -/// ends of an open polyline are never corners. -fn corners(lp: &[P], window: f64, closed: bool) -> Vec { +/// Indices of corner points: where the direction over ±`window` px turns by more than +/// `turn_deg`. The ends of an open polyline are never corners. +fn corners(lp: &[P], window: f64, closed: bool, turn_deg: f64) -> Vec { let n = lp.len(); if n < 3 || !window.is_finite() || lp.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) { return Vec::new(); } - let cos_thresh = (60f64).to_radians().cos(); + let cos_thresh = turn_deg.to_radians().cos(); let turn: Vec = (0..n) .map(|i| { if !closed && (i == 0 || i + 1 == n) { @@ -280,7 +282,7 @@ fn fit_closed(lp: &[P], tol: f64, window: f64) -> Subpath { if n < 3 || lp.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) { return Subpath { closed: true, knots: Vec::new(), op: PathOp::Combine }; } - let cs = corners(lp, window, true); + let cs = corners(lp, window, true, MASK_CORNER_TURN); let mut segs: Vec<[P; 4]> = Vec::new(); let mut corner_at_start: Vec = Vec::new(); if cs.is_empty() { @@ -329,9 +331,10 @@ pub const MAX_TRACE_POINTS: usize = 4096; /// Fits a freehand pointer trace (the Freeform Pen's drag) with cubic Béziers that stay within /// `tolerance` px of every sample: Photoshop's Curve Fit, clamped to 0.1–100 px (2 px when not -/// finite). Turns sharper than 60° over ±2 × `tolerance` become corner anchors, the other inner -/// anchors are smooth. A `closed` trace becomes a closed subpath. Non-finite samples are skipped; -/// `None` when fewer than two distinct points remain (three when `closed`). +/// finite). Turns sharper than 80° over ±2 × `tolerance` become corner anchors; the other inner +/// anchors are smooth and sit on the trace's turning points in x and y where they can. A `closed` +/// trace becomes a closed subpath whose release point stays an anchor. Non-finite samples are +/// skipped; `None` when fewer than two distinct points remain (three when `closed`). pub fn fit_trace(points: &[[f64; 2]], tolerance: f64, closed: bool) -> Option { let tol = if tolerance.is_finite() { tolerance.clamp(0.1, 100.0) } else { 2.0 }; let window = (2.0 * tol).max(1.5); @@ -359,16 +362,64 @@ pub fn fit_trace(points: &[[f64; 2]], tolerance: f64, closed: bool) -> Option 3 && lp.last().zip(lp.first()).is_some_and(|(a, b)| len(sub(*a, *b)) < min_step) { lp.pop(); } - return (lp.len() >= 3).then(|| fit_closed(&lp, tol, window)); + return (lp.len() >= 3).then(|| close_trace(&lp, fit_open(&lp, tol, window), window)); } (lp.len() >= 2).then(|| fit_open(&lp, tol, window)) } +/// Corners of [`trace_mask`]'s contours: turns sharper than this many degrees. +const MASK_CORNER_TURN: f64 = 60.0; + +/// Corners of a freehand trace: turns sharper than this many degrees. The reference application +/// rounds a 67° vee with two smooth anchors (#12838); a right angle stays a corner. +const FREEFORM_CORNER_TURN: f64 = 80.0; + +/// Most a freehand segment turns, in degrees per px of Curve Fit, up to [`MAX_SEGMENT_TURN`]. A +/// smooth stroke fits within any Curve Fit with few anchors, yet the reference application adds +/// anchors as Curve Fit goes down (its 324° arc: 12 segments at 0.5 px, 5 at 1 px, 3 at 2 px, +/// #12838). 75° per px reaches the cap at the default 2 px. +const SEGMENT_TURN_PER_PX: f64 = 75.0; + +/// Most a freehand segment turns, in degrees: a longer arc gets another anchor. A 180° arc fits +/// one cubic within 2 px, but the reference application gives a whole circle five anchors and +/// 324° of it four (#12838). +const MAX_SEGMENT_TURN: f64 = 150.0; + +/// Closes an open fit of a closed trace: the release point stays an anchor, and a segment joins it +/// to the first one, smooth unless the trace has a corner there. +fn close_trace(lp: &[P], mut sp: Subpath, window: f64) -> Subpath { + sp.closed = true; + let n = lp.len(); + let seam = corners(lp, window, true, FREEFORM_CORNER_TURN); + let corner = seam.first() == Some(&0) || seam.last() == Some(&(n - 1)); + let m = sp.knots.len(); + let (Some(first), Some(last)) = (sp.knots.first().copied(), sp.knots.last().copied()) else { return sp }; + if m < 2 { + return sp; + } + let (f, l) = ((first.anchor.x, first.anchor.y), (last.anchor.x, last.anchor.y)); + let third = len(sub(f, l)) / 3.0; + let (t_out, t_in) = if corner { + (norm(sub(f, l)), norm(sub(f, l))) + } else { + // Leave the release point as the trace arrived at it, reach the start as the trace left it. + let arrive = norm(sub(l, (last.in_ctrl.x, last.in_ctrl.y))); + let leave = norm(sub((first.out_ctrl.x, first.out_ctrl.y), f)); + (if len(arrive) > 0.0 { arrive } else { norm(sub(l, lp[n - 2])) }, if len(leave) > 0.0 { leave } else { norm(sub(lp[1], f)) }) + }; + let pt = |p: P| Point::new(p.0, p.1); + sp.knots[m - 1].out_ctrl = pt(add(l, mul(t_out, third))); + sp.knots[m - 1].smooth = !corner; + sp.knots[0].in_ctrl = pt(sub(f, mul(t_in, third))); + sp.knots[0].smooth = !corner; + sp +} + /// Fits an open polyline with cubic Béziers, one run between consecutive corners at a time. fn fit_open(lp: &[P], tol: f64, window: f64) -> Subpath { let n = lp.len(); let mut cuts = vec![0]; - cuts.extend(corners(lp, window, false)); + cuts.extend(corners(lp, window, false, FREEFORM_CORNER_TURN)); cuts.push(n - 1); cuts.dedup(); let mut segs: Vec<[P; 4]> = Vec::new(); @@ -387,11 +438,7 @@ fn fit_open(lp: &[P], tol: f64, window: f64) -> Subpath { let third = mul(sub(b, a), 1.0 / 3.0); segs.push([a, add(a, third), sub(b, third), b]); } else { - // End tangents over a stretch of the trace, not the first jittery sample. - let reach = (2.0 * window).min(len(sub(b, a)) / 3.0).max(window); - let t1 = norm(sub(walk(pts, 0, reach, true, false), a)); - let t2 = norm(sub(walk(pts, m - 1, reach, false, false), b)); - fit_cubic(pts, t1, t2, tol * tol, &mut segs, 0); + fit_run(pts, tol, window, &mut segs); } corner_at_start.extend((before..segs.len()).map(|k| k == before)); } @@ -407,6 +454,227 @@ fn fit_open(lp: &[P], tol: f64, window: f64) -> Subpath { Subpath { closed: false, knots, op: PathOp::Combine } } +/// Fits one freehand run (no corner inside) from its first sample to its last, a segment at a +/// time: each reaches as far along the trace as one cubic stays within `tol` and turns at most +/// [`SEGMENT_TURN_PER_PX`] × `tol` (up to [`MAX_SEGMENT_TURN`]), and ends on the first turning +/// point of the trace in x or y inside that reach (a wave's peak, a circle's top) when there is +/// one, as the reference application places its anchors (#12838); with the next turning point +/// just out of reach, halfway to it. Consecutive segments share their tangent, so inner anchors +/// are smooth. +fn fit_run(pts: &[P], tol: f64, window: f64, out: &mut Vec<[P; 4]>) { + let m = pts.len(); + if m < 2 { + return; + } + let max_turn = (SEGMENT_TURN_PER_PX * tol).min(MAX_SEGMENT_TURN); + let turns = turning_points(pts, tol); + let arc: Vec = pts + .iter() + .scan((0.0, pts[0]), |(acc, prev), &q| { + *acc += len(sub(q, *prev)); + *prev = q; + Some(*acc) + }) + .collect(); + // The first segment leaves as the trace does; the others continue the one before. + let mut t1: Option

= None; + // An anchor on a turning point leaves a segment of at least this length behind it. + let min_gap = 3.0 * window; + let mut a = 0; + while a + 1 < m { + let fit = |b: usize| fit_piece(pts.get(a..=b)?, t1, tol, max_turn); + // Farthest end that fits: doubling steps, then halving the gap to the first failure. + let mut good = a + 1; + let mut bad = m; + let mut step = 2; + while bad == m { + let b = (a + step).min(m - 1); + if b <= good { + break; + } + if fit(b).is_some() { + good = b; + if b == m - 1 { + break; + } + step = step.saturating_mul(2); + } else { + bad = b; + } + } + while bad < m && bad - good > 1 { + let mid = good + (bad - good) / 2; + if fit(mid).is_some() { + good = mid; + } else { + bad = mid; + } + } + let end = if good + 1 == m { + good + } else { + let mut ahead = turns.iter().copied().filter(|&t| t > a && arc[t] - arc[a] >= min_gap); + let inside = ahead.clone().take_while(|&t| t <= good).take(4).find(|&t| fit(t).is_some()); + // A turning point within two reaches: halfway there, so no sliver is left before it. + let halfway = ahead.find(|&t| t > good).filter(|&t| arc[t] - arc[a] <= 2.0 * (arc[good] - arc[a])).and_then(|t| { + let mid = arc.partition_point(|&s| s < (arc[a] + arc[t]) / 2.0).clamp(a + 1, good); + fit(mid).map(|_| mid) + }); + inside.or(halfway).unwrap_or(good) + }; + // Two samples always fit; the chord stands in should a degenerate piece not. + let seg = fit(end).unwrap_or_else(|| thirds(pts[a], pts[end], t1)); + let into = sub(seg[3], seg[2]); + t1 = Some(if len(into) > 1e-12 { norm(into) } else { norm(sub(seg[3], seg[0])) }); + out.push(seg); + a = end; + } +} + +/// Indices where the trace turns back in x or in y by more than `tol` (a wave's peaks, a circle's +/// top, bottom and sides), in order. Jitter smaller than `tol` makes none. +fn turning_points(pts: &[P], tol: f64) -> Vec { + let mut out = Vec::new(); + for axis in 0..2 { + let v = |i: usize| if axis == 0 { pts[i].0 } else { pts[i].1 }; + // Direction of travel along the axis: 0 until the trace has moved by more than `tol`. + let mut dir = 0i8; + let (mut hi, mut lo) = (0usize, 0usize); + for i in 1..pts.len() { + if v(i) >= v(hi) { + hi = i; + } + if v(i) <= v(lo) { + lo = i; + } + if dir >= 0 && v(i) < v(hi) - tol { + if dir > 0 { + out.push(hi); + } + dir = -1; + lo = i; + } else if dir <= 0 && v(i) > v(lo) + tol { + if dir < 0 { + out.push(lo); + } + dir = 1; + hi = i; + } + } + } + out.sort_unstable(); + out.dedup(); + out +} + +/// One cubic from the first sample of `pts` to the last, leaving along `t1` when given, that stays +/// within `tol` of every sample and turns at most `max_turn` degrees. +fn fit_piece(pts: &[P], t1: Option

, tol: f64, max_turn: f64) -> Option<[P; 4]> { + let n = pts.len(); + if n < 2 { + return None; + } + let (p0, p3) = (pts[0], pts[n - 1]); + if n == 2 { + return Some(thirds(p0, p3, t1)); + } + let seg = len(sub(p3, p0)); + // A handle longer than the chord loops (a few samples leave least squares free to); even a + // 150° arc's handles are about half its chord. + let tame = |b: Option<[P; 4]>| match b { + Some(b) if len(sub(b[1], b[0])) <= seg && len(sub(b[2], b[3])) <= seg => b, + _ => thirds(p0, p3, t1), + }; + let err2 = tol * tol; + let mut u = chord_params(pts); + let mut b = tame(generate_free(pts, &u, t1)); + let mut e = max_error(pts, &b, &u).0; + for _ in 0..6 { + if e <= err2 { + break; + } + u = reparam(pts, &u, &b); + b = tame(generate_free(pts, &u, t1)); + e = max_error(pts, &b, &u).0; + } + (e <= err2 && turn_deg(&b) <= max_turn).then_some(b) +} + +/// A cubic from `p0` to `p3` with handles a third of the chord: leaving along `t1` when given, +/// otherwise along the chord, and arriving along the chord. +fn thirds(p0: P, p3: P, t1: Option

) -> [P; 4] { + let chord = sub(p3, p0); + let d = len(chord) / 3.0; + let c = norm(chord); + [p0, add(p0, mul(t1.unwrap_or(c), d)), sub(p3, mul(c, d)), p3] +} + +/// Least-squares control points through `pts` at parameters `u`. The second handle is free, so +/// how the piece arrives at its end comes from the whole piece, not from a direction estimated +/// from a few jittery samples there; the first lies along `t1` when given (a smooth join to the +/// segment before), and is free too otherwise. `None` when the samples cannot pin them down. +fn generate_free(pts: &[P], u: &[f64], t1: Option

) -> Option<[P; 4]> { + let (p0, p3) = (*pts.first()?, *pts.last()?); + let (mut a11, mut a12, mut a22) = (0.0, 0.0, 0.0); + let (mut r1, mut r2) = ((0.0, 0.0), (0.0, 0.0)); + for (q, &t) in pts.iter().zip(u) { + let mt = 1.0 - t; + let (b0, b1, b2, b3) = (mt * mt * mt, 3.0 * mt * mt * t, 3.0 * mt * t * t, t * t * t); + let res = sub(*q, add(mul(p0, b0), mul(p3, b3))); + (a11, a12, a22) = (a11 + b1 * b1, a12 + b1 * b2, a22 + b2 * b2); + r1 = add(r1, mul(res, b1)); + r2 = add(r2, mul(res, b2)); + } + if let ([_, q, _], [_, s, _], None) = (pts, u, t1) { + // One inner sample cannot pin down two free handles: the parabola through all three. + let ms = 1.0 - s; + let k = 2.0 * s * ms; + if k <= 1e-9 { + return None; + } + let c = mul(sub(*q, add(mul(p0, ms * ms), mul(p3, s * s))), 1.0 / k); + return Some([p0, add(p0, mul(sub(c, p0), 2.0 / 3.0)), add(p3, mul(sub(c, p3), 2.0 / 3.0)), p3]); + } + // b1·P1 + b2·P2 ≈ res, by least squares. + let det = a11 * a22 - a12 * a12; + if !det.is_finite() || det <= 1e-12 * a11 * a22 { + return None; + } + let Some(t) = t1 else { + let p1 = mul(sub(mul(r1, a22), mul(r2, a12)), 1.0 / det); + let p2 = mul(sub(mul(r2, a11), mul(r1, a12)), 1.0 / det); + return Some([p0, p1, p2, p3]); + }; + // P1 = P0 + α·t: solve for α and P2. + let (r1, r2) = (sub(r1, mul(p0, a11)), sub(r2, mul(p0, a12))); + let alpha = (dot(t, r1) * a22 - a12 * dot(t, r2)) / det; + if !alpha.is_finite() { + return None; + } + // A handle pointing back would cusp: the shortest that keeps the join smooth instead. + let alpha = alpha.max(1e-3 * len(sub(p3, p0))); + let p2 = mul(sub(r2, mul(t, a12 * alpha)), 1.0 / a22); + Some([p0, add(p0, mul(t, alpha)), p2, p3]) +} + +/// How far a cubic's direction turns along it, in degrees (both ways add up). +fn turn_deg(b: &[P; 4]) -> f64 { + const STEPS: usize = 32; + let mut total = 0.0; + let mut prev: Option

= None; + for k in 0..=STEPS { + let d = bezier_d1(b, k as f64 / STEPS as f64); + if len(d) < 1e-9 { + continue; + } + if let Some(p) = prev { + total += (p.0 * d.1 - p.1 * d.0).atan2(dot(p, d)).abs(); + } + prev = Some(d); + } + total.to_degrees() +} + /// Distance from `q` to the segment `a`–`b`. fn segment_distance(q: P, a: P, b: P) -> f64 { let ab = sub(b, a); @@ -662,7 +930,7 @@ mod tests { #[test] fn corners_have_bounded_work_for_many_tiny_segments() { let points: Vec

= (0..20_000).map(|i| (i as f64 * 0.01, if i % 2 == 0 { 0.0 } else { 1e-5 })).collect(); - let selected = corners(&points, 100.0, false); + let selected = corners(&points, 100.0, false, MASK_CORNER_TURN); assert!(selected.len() <= points.len()); } @@ -694,3 +962,7 @@ mod tests { } } } + +#[cfg(test)] +#[path = "trace_freeform_anchor_tests.rs"] +mod trace_freeform_anchor_tests; diff --git a/crates/vector/src/trace_freeform_anchor_tests.rs b/crates/vector/src/trace_freeform_anchor_tests.rs new file mode 100644 index 00000000000..79896a2bcff --- /dev/null +++ b/crates/vector/src/trace_freeform_anchor_tests.rs @@ -0,0 +1,131 @@ +//! Freeform Pen anchors against the reference application's sample strokes (#12838): mouse moves +//! in document coordinates, fitted at Curve Fit 2 px unless said otherwise. + +use std::f64::consts::TAU; + +use super::*; + +/// (100,400) to (500,400) in 4 px steps. +fn line() -> Vec<[f64; 2]> { + (0..=100).map(|i| [100.0 + 4.0 * i as f64, 400.0]).collect() +} + +/// x from 100 to 500 in 4 px steps, y = 400 + 60·sin(2π(x − 100)/200): two periods. +fn sine() -> Vec<[f64; 2]> { + (0..=100).map(|i| 100.0 + 4.0 * i as f64).map(|x| [x, 400.0 + 60.0 * ((x - 100.0) / 200.0 * TAU).sin()]).collect() +} + +/// Centre (600,300), radius 100, `steps` of 60 around from (700,300): 60 is the whole circle +/// back to the start, 54 the open one. +fn circle(steps: usize) -> Vec<[f64; 2]> { + (0..=steps).map(|i| i as f64 * TAU / 60.0).map(|a| [600.0 + 100.0 * a.cos(), 300.0 + 100.0 * a.sin()]).collect() +} + +/// (100,450) to (250,550) to (400,450), 45 steps a leg. +fn vee() -> Vec<[f64; 2]> { + let legs = [[100.0, 450.0], [250.0, 550.0], [400.0, 450.0]]; + legs.windows(2) + .flat_map(|w| (0..45).map(move |k| k as f64 / 45.0).map(move |t| [w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t])) + .chain([legs[2]]) + .collect() +} + +/// The five strokes, with whether the drag ends on its start (closes). +fn strokes() -> [(&'static str, Vec<[f64; 2]>, bool); 5] { + [("line", line(), false), ("sine", sine(), false), ("circle", circle(60), true), ("circle-open", circle(54), false), ("vee", vee(), false)] +} + +fn fit(points: &[[f64; 2]], curve_fit: f64, closed: bool) -> Subpath { + let sp = fit_trace(points, curve_fit, closed); + assert!(sp.is_some(), "the stroke fits"); + sp.unwrap_or_else(|| Subpath { closed, knots: Vec::new(), op: PathOp::Combine }) +} + +fn anchors(sp: &Subpath) -> Vec<[f64; 2]> { + sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect() +} + +/// Largest distance from a sample to the fitted subpath (each segment densely sampled). +fn max_deviation(sp: &Subpath, samples: &[[f64; 2]]) -> f64 { + let curve: Vec

= sp + .segments() + .iter() + .flat_map(|s| { + let b = [(s[0].x, s[0].y), (s[1].x, s[1].y), (s[2].x, s[2].y), (s[3].x, s[3].y)]; + (0..=1000).map(move |k| bezier(&b, k as f64 / 1000.0)) + }) + .collect(); + samples.iter().map(|q| curve.iter().map(|c| len(sub(*c, (q[0], q[1])))).fold(f64::MAX, f64::min)).fold(0.0, f64::max) +} + +#[test] +fn sine_anchors_sit_on_the_four_peaks() { + let samples = sine(); + let sp = fit(&samples, 2.0, false); + let got = anchors(&sp); + assert_eq!(got.len(), 6, "{got:?}"); + assert_eq!((got.first(), got.last()), (samples.first(), samples.last()), "press and release are anchors"); + for (a, peak) in got[1..5].iter().zip([[150.0, 460.0], [250.0, 340.0], [350.0, 460.0], [450.0, 340.0]]) { + assert!((a[0] - peak[0]).hypot(a[1] - peak[1]) <= 3.0, "{a:?} is not on the peak {peak:?}: {got:?}"); + } + assert!(sp.knots[1..5].iter().all(|k| k.smooth)); +} + +#[test] +fn closed_circle_has_five_anchors_and_the_open_one_four() { + let sp = fit(&circle(60), 2.0, true); + assert!(sp.closed); + assert_eq!(sp.knots.len(), 5, "{:?}", anchors(&sp)); + assert!(sp.knots.iter().all(|k| k.smooth), "a circle has no corners"); + let sp = fit(&circle(54), 2.0, false); + assert!(!sp.closed); + assert_eq!(sp.knots.len(), 4, "{:?}", anchors(&sp)); + assert!(sp.knots[1..3].iter().all(|k| k.smooth)); +} + +#[test] +fn vee_turns_with_a_rounded_join_not_a_cusp() { + let sp = fit(&vee(), 2.0, false); + let got = anchors(&sp); + assert_eq!(got.len(), 4, "{got:?}"); + assert_eq!((got[0], got[3]), ([100.0, 450.0], [400.0, 450.0])); + assert!(sp.knots[1..3].iter().all(|k| k.smooth), "no corner anchor: {got:?}"); + // Both inner anchors are near the turn, not along the legs. + assert!(got[1..3].iter().all(|a| (a[0] - 250.0).hypot(a[1] - 550.0) < 60.0), "{got:?}"); +} + +#[test] +fn line_is_unchanged_one_segment_with_handles_at_a_third() { + let sp = fit(&line(), 2.0, false); + assert_eq!(anchors(&sp), [[100.0, 400.0], [500.0, 400.0]]); + let (a, b) = (&sp.knots[0], &sp.knots[1]); + assert!((a.out_ctrl.x - (100.0 + 400.0 / 3.0)).abs() < 1e-9 && a.out_ctrl.y == 400.0); + assert!((b.in_ctrl.x - (500.0 - 400.0 / 3.0)).abs() < 1e-9 && b.in_ctrl.y == 400.0); +} + +#[test] +fn a_lower_curve_fit_gives_more_anchors() { + for (name, points, closed) in [("sine", sine(), false), ("circle-open", circle(54), false)] { + let at_2 = fit(&points, 2.0, closed).knots.len(); + for curve_fit in [0.5, 1.0] { + let n = fit(&points, curve_fit, closed).knots.len(); + assert!(n > at_2, "{name}: {n} anchors at Curve Fit {curve_fit}, {at_2} at 2"); + } + } +} + +/// Today's guarantee: the path stays within Curve Fit of every sample, on the strokes as given +/// and on the whole pixels a mouse delivers. +#[test] +fn every_sample_stays_within_curve_fit() { + for (name, points, closed) in strokes() { + let pixels: Vec<[f64; 2]> = points.iter().map(|p| [p[0].round(), p[1].round()]).collect(); + for samples in [points, pixels] { + for curve_fit in [0.5, 1.0, 2.0, 5.0, 10.0] { + let sp = fit(&samples, curve_fit, closed); + let d = max_deviation(&sp, &samples); + assert!(d <= curve_fit + 0.05, "{name} at Curve Fit {curve_fit}: a sample {d:.3} px away"); + } + } + } +} From 4d1cc4b6e50397a79e40c703b1c6d1dd770186e8 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:42:38 +0100 Subject: [PATCH 56/65] Freeform Pen: a failed short fit no longer stops the reach (#12838) A few samples can fit worse than more, so a failed doubling step looks one step further before it stops. On whole-pixel samples the vee now gets the reference application's four anchors at Curve Fit 2 (was five); the Curve Fit 2 tests run on both the given and the whole-pixel strokes. --- crates/vector/src/trace.rs | 15 +++-- .../vector/src/trace_freeform_anchor_tests.rs | 66 ++++++++++++------- 2 files changed, 52 insertions(+), 29 deletions(-) diff --git a/crates/vector/src/trace.rs b/crates/vector/src/trace.rs index 655b83022d5..38883d12528 100644 --- a/crates/vector/src/trace.rs +++ b/crates/vector/src/trace.rs @@ -483,7 +483,9 @@ fn fit_run(pts: &[P], tol: f64, window: f64, out: &mut Vec<[P; 4]>) { let mut a = 0; while a + 1 < m { let fit = |b: usize| fit_piece(pts.get(a..=b)?, t1, tol, max_turn); - // Farthest end that fits: doubling steps, then halving the gap to the first failure. + // Farthest end that fits: doubling steps, then halving the gap to the first failure. The + // error does not always grow with the length (a few samples can fit worse than more), so + // a failed step looks one step further before it stops the doubling. let mut good = a + 1; let mut bad = m; let mut step = 2; @@ -492,15 +494,20 @@ fn fit_run(pts: &[P], tol: f64, window: f64, out: &mut Vec<[P; 4]>) { if b <= good { break; } + let ahead = (a + step.saturating_mul(2)).min(m - 1); if fit(b).is_some() { good = b; - if b == m - 1 { - break; - } + } else if ahead > b && fit(ahead).is_some() { + good = ahead; step = step.saturating_mul(2); } else { bad = b; + continue; } + if good == m - 1 { + break; + } + step = step.saturating_mul(2); } while bad < m && bad - good > 1 { let mid = good + (bad - good) / 2; diff --git a/crates/vector/src/trace_freeform_anchor_tests.rs b/crates/vector/src/trace_freeform_anchor_tests.rs index 79896a2bcff..83105442d69 100644 --- a/crates/vector/src/trace_freeform_anchor_tests.rs +++ b/crates/vector/src/trace_freeform_anchor_tests.rs @@ -35,6 +35,12 @@ fn strokes() -> [(&'static str, Vec<[f64; 2]>, bool); 5] { [("line", line(), false), ("sine", sine(), false), ("circle", circle(60), true), ("circle-open", circle(54), false), ("vee", vee(), false)] } +/// The stroke as given and on the whole pixels a mouse delivers at 100 % zoom. +fn as_given_and_in_pixels(points: Vec<[f64; 2]>) -> [Vec<[f64; 2]>; 2] { + let pixels = points.iter().map(|p| [p[0].round(), p[1].round()]).collect(); + [points, pixels] +} + fn fit(points: &[[f64; 2]], curve_fit: f64, closed: bool) -> Subpath { let sp = fit_trace(points, curve_fit, closed); assert!(sp.is_some(), "the stroke fits"); @@ -60,38 +66,49 @@ fn max_deviation(sp: &Subpath, samples: &[[f64; 2]]) -> f64 { #[test] fn sine_anchors_sit_on_the_four_peaks() { - let samples = sine(); - let sp = fit(&samples, 2.0, false); - let got = anchors(&sp); - assert_eq!(got.len(), 6, "{got:?}"); - assert_eq!((got.first(), got.last()), (samples.first(), samples.last()), "press and release are anchors"); - for (a, peak) in got[1..5].iter().zip([[150.0, 460.0], [250.0, 340.0], [350.0, 460.0], [450.0, 340.0]]) { - assert!((a[0] - peak[0]).hypot(a[1] - peak[1]) <= 3.0, "{a:?} is not on the peak {peak:?}: {got:?}"); + for samples in as_given_and_in_pixels(sine()) { + let sp = fit(&samples, 2.0, false); + let got = anchors(&sp); + assert_eq!(got.len(), 6, "{got:?}"); + assert_eq!((got.first(), got.last()), (samples.first(), samples.last()), "press and release are anchors"); + for (a, peak) in got[1..5].iter().zip([[150.0, 460.0], [250.0, 340.0], [350.0, 460.0], [450.0, 340.0]]) { + assert!((a[0] - peak[0]).hypot(a[1] - peak[1]) <= 3.0, "{a:?} is not on the peak {peak:?}: {got:?}"); + } + assert!(sp.knots[1..5].iter().all(|k| k.smooth)); } - assert!(sp.knots[1..5].iter().all(|k| k.smooth)); } #[test] fn closed_circle_has_five_anchors_and_the_open_one_four() { - let sp = fit(&circle(60), 2.0, true); - assert!(sp.closed); - assert_eq!(sp.knots.len(), 5, "{:?}", anchors(&sp)); - assert!(sp.knots.iter().all(|k| k.smooth), "a circle has no corners"); - let sp = fit(&circle(54), 2.0, false); - assert!(!sp.closed); - assert_eq!(sp.knots.len(), 4, "{:?}", anchors(&sp)); - assert!(sp.knots[1..3].iter().all(|k| k.smooth)); + for samples in as_given_and_in_pixels(circle(60)) { + let sp = fit(&samples, 2.0, true); + assert!(sp.closed); + assert_eq!(sp.knots.len(), 5, "{:?}", anchors(&sp)); + assert!(sp.knots.iter().all(|k| k.smooth), "a circle has no corners"); + } + for samples in as_given_and_in_pixels(circle(54)) { + let sp = fit(&samples, 2.0, false); + assert!(!sp.closed); + assert_eq!(sp.knots.len(), 4, "{:?}", anchors(&sp)); + assert!(sp.knots[1..3].iter().all(|k| k.smooth)); + } } +/// On whole pixels the first segment past the turn fits worse over a few samples than over many; +/// the fit still reaches past them to the reference application's four anchors. #[test] fn vee_turns_with_a_rounded_join_not_a_cusp() { - let sp = fit(&vee(), 2.0, false); - let got = anchors(&sp); - assert_eq!(got.len(), 4, "{got:?}"); - assert_eq!((got[0], got[3]), ([100.0, 450.0], [400.0, 450.0])); - assert!(sp.knots[1..3].iter().all(|k| k.smooth), "no corner anchor: {got:?}"); - // Both inner anchors are near the turn, not along the legs. - assert!(got[1..3].iter().all(|a| (a[0] - 250.0).hypot(a[1] - 550.0) < 60.0), "{got:?}"); + for (i, samples) in as_given_and_in_pixels(vee()).into_iter().enumerate() { + let sp = fit(&samples, 2.0, false); + let got = anchors(&sp); + assert_eq!(got.len(), 4, "{got:?}"); + assert_eq!((got[0], got[3]), ([100.0, 450.0], [400.0, 450.0])); + assert!(sp.knots[1..3].iter().all(|k| k.smooth), "no corner anchor: {got:?}"); + if i == 0 { + // As measured, both inner anchors are near the turn, not along the legs. + assert!(got[1..3].iter().all(|a| (a[0] - 250.0).hypot(a[1] - 550.0) < 60.0), "{got:?}"); + } + } } #[test] @@ -119,8 +136,7 @@ fn a_lower_curve_fit_gives_more_anchors() { #[test] fn every_sample_stays_within_curve_fit() { for (name, points, closed) in strokes() { - let pixels: Vec<[f64; 2]> = points.iter().map(|p| [p[0].round(), p[1].round()]).collect(); - for samples in [points, pixels] { + for samples in as_given_and_in_pixels(points) { for curve_fit in [0.5, 1.0, 2.0, 5.0, 10.0] { let sp = fit(&samples, curve_fit, closed); let d = max_deviation(&sp, &samples); From 28d68162788023013ab9da661029dbbaf86073ca Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Thu, 12 Nov 2026 12:53:59 -0500 Subject: [PATCH 57/65] Rectangle tool: the Radius field sets the next rectangle, not the active shape (#13338) The Rectangle tool's options-bar Radius field showed the active shape's first radius and, when changed, ran shape.edit on it (a History state). It now shows and sets only the tool's own radius, which the next drawn rectangle takes. The Properties panel and the on-canvas corner widgets still edit the active shape, and the Path Selection / Direct Selection Radius field is unchanged. Tests in rectangle_radius_target_tests.rs: the field leaves the active shape alone (no History state), the next rectangle takes the typed radius, the field shows the tool's radius, and the Path Selection / Direct Selection field still edits the active shape. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Fable 5.2 queued; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- .../tools/rectangle_radius_target_tests.rs | 111 ++++++++++++++++++ crates/ui-egui/src/tools/shape_options.rs | 12 +- 2 files changed, 117 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/tools/rectangle_radius_target_tests.rs diff --git a/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs b/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs new file mode 100644 index 00000000000..9c9a5bf46d3 --- /dev/null +++ b/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs @@ -0,0 +1,111 @@ +//! #13338: the Rectangle tool's options-bar Radius sets the next rectangle, not the active shape. +//! It shows the tool's own radius. The Path Selection / Direct Selection Radius still edits the +//! active shape. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LiveShape}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// A document with Rectangle 1 (radius 20) as the active layer, and `tool` current. +fn bar_with(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.create", json!({"kind": "roundedRect", "rect": [10, 10, 80, 60], "radii": [20, 20, 20, 20], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn type_radius(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn history_len(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +/// The first radius of every rectangle shape layer, bottom to top. +fn radii(h: &Harness<'static, PhotocraftApp>) -> Vec { + let st = h.state().session.active().unwrap(); + st.doc + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Shape(sh) => match &sh.live { + Some(LiveShape::Rect { radii, .. }) => Some(radii[0]), + _ => None, + }, + _ => None, + }) + .collect() +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +#[test] +fn the_rectangle_tools_radius_field_leaves_the_active_shape_alone() { + let mut h = bar_with(Tool::Rectangle); + let before = history_len(&h); + type_radius(&mut h, "5000"); + assert_eq!(radii(&h), vec![20.0], "Rectangle 1 keeps its radius"); + assert_eq!(history_len(&h), before, "no History state"); + assert_eq!(h.state().ui.tool_options.corner_radius, 5000.0); +} + +#[test] +fn the_next_rectangle_takes_the_typed_radius() { + let mut h = bar_with(Tool::Rectangle); + type_radius(&mut h, "5000"); + drag(h.state_mut(), [100.0, 100.0], [180.0, 170.0]); + let all = radii(&h); + assert_eq!(all.len(), 2, "a second rectangle was drawn: {all:?}"); + assert_eq!(all[0], 20.0); + assert_eq!(all[1], 5000.0); +} + +#[test] +fn the_rectangle_tools_radius_field_shows_the_tools_radius() { + let mut h = bar_with(Tool::Rectangle); + h.state_mut().ui.tool_options.corner_radius = 0.0; + h.run_steps(3); + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field"); + let shown = field + .accesskit_node() + .numeric_value() + .map(|v| v as f32) + .or_else(|| field.accesskit_node().value().and_then(|v| v.trim_end_matches(" px").trim().parse().ok())); + assert_eq!(shown, Some(0.0), "the tool's radius, not the shape's 20"); +} + +#[test] +fn the_path_selection_radius_field_still_edits_the_active_shape() { + for tool in [Tool::PathSelection, Tool::DirectSelection] { + let mut h = bar_with(tool); + let before = history_len(&h); + type_radius(&mut h, "30"); + assert_eq!(radii(&h), vec![30.0], "{tool:?}: the active shape takes it"); + assert_eq!(history_len(&h), before + 1, "{tool:?}: one History state"); + } +} diff --git a/crates/ui-egui/src/tools/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs index d0f7e3c5a8e..966fdff212b 100644 --- a/crates/ui-egui/src/tools/shape_options.rs +++ b/crates/ui-egui/src/tools/shape_options.rs @@ -107,16 +107,12 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool crate::widgets::vline(ui, 22.0); let label = tl!("Radius:"); lbl(ui, label); - let mut r = match target.as_ref().and_then(|s| s.live.as_ref()) { - Some(photocraft_doc::LiveShape::Rect { radii, .. }) => radii[0] as f32, - _ => o.corner_radius, - }; + // The tool's own radius for the next rectangle (#13338); the active shape is not touched. + let mut r = o.corner_radius; let (resp, out_of_range) = crate::widgets::value_field_alerting(ui, label, &mut r, RADIUS_RANGE, "px", 62.0); radius_alert = out_of_range; if resp.changed() { o.corner_radius = r; - let rf = r as f64; - edit = Some(json!({"radii": [rf, rf, rf, rf], "coalesce": key("radius")})); } } Tool::Polygon => { @@ -225,6 +221,10 @@ fn radius_range_alert(app: &mut PhotocraftApp, owed: bool) { #[path = "rectangle_radius_range_tests.rs"] mod rectangle_radius_range_tests; +#[cfg(test)] +#[path = "rectangle_radius_target_tests.rs"] +mod rectangle_radius_target_tests; + /// Tool-bar paint changes affect the next shape; Properties edits the selected shape instead. pub(crate) fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: PaintChange) -> Result<(), String> { // A colour takes the place of a gradient; No Color keeps it for when the paint comes back. From 667a16dd475fbaccdbc17163da63a398070d27dc Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:22:20 +0100 Subject: [PATCH 58/65] Actions: keep make_from under the cognitive-complexity limit The Frame from Layers branch pushed make_from to 31/30 once main's Artboard mapping was merged in. Move the Make events another module maps (type path, artboard, layer style, frame) into delegated_make_from, tried in the same order as before. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/steps_make.rs | 30 ++++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index c3ea88ab58c..0e16f09c8f8 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -540,26 +540,32 @@ fn type_shape_descriptor() -> Descriptor { desc("null").with("null", class_ref("contentLayer")).with("Usng", target_ref("textLayer")) } +/// Make events another module maps: a type path, an artboard, a layer style or a frame, +/// tried in that order. +fn delegated_make_from(d: &Descriptor) -> Option { + let class = get_ref(d, "null").and_then(ref_class); + match class.as_deref() { + Some("Path") => return Some(super::steps_type_path::from(d)), + // Layer › New › Artboard and Artboard from Layers (#10723). + Some("artboardSection") => return Some(super::steps_artboard_section::from(d)), + _ => {} + } + if let Some(mapped) = super::steps_layer_style::create_from_descriptor(d) { + return Some(mapped); + } + // Layer › New › Frame from Layers (#10723). + (class.as_deref() == Some("framedGroupSection")).then(|| super::steps_frame_section::from(d)) +} + /// Import Make events only when their geometry and options can be represented faithfully, /// including the exact target-text-to-content-layer references. pub(super) fn make_from(d: &Descriptor) -> Mapped { if let Some(mapped) = super::steps_calculations::from_descriptor(d) { return mapped; } - if get_ref(d, "null").and_then(ref_class).as_deref() == Some("Path") { - return super::steps_type_path::from(d); - } - // Layer › New › Artboard and Artboard from Layers (#10723). - if get_ref(d, "null").and_then(ref_class).as_deref() == Some("artboardSection") { - return super::steps_artboard_section::from(d); - } - if let Some(mapped) = super::steps_layer_style::create_from_descriptor(d) { + if let Some(mapped) = delegated_make_from(d) { return mapped; } - // Layer › New › Frame from Layers (#10723). - if get_ref(d, "null").and_then(ref_class).as_deref() == Some("framedGroupSection") { - return super::steps_frame_section::from(d); - } if d.items == type_shape_descriptor().items { return none("type.convertToShape"); } From 169e10d9b09102b9778da3f83a6776bb28ea7ffb Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:38:30 +0300 Subject: [PATCH 59/65] Object Selection menu: the reference rows with and without a selection With a selection, Distort and Perspective leave the menu and Delete and Fill Selection follows Content-Aware Fill. With nothing selected over a pixel layer the menu is the layer menu: Blending Options, the layer rows, Free Transform, then Color Range, Load Selection and Reselect. Only that case was measured, so the Background and other layer kinds keep today's menu. The other selection tools keep their menus. --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index d600445e757..76e2ce80fae 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -518,8 +518,9 @@ pub const NO_SELECTION_MENU: &[Row] = &[ ]; /// Photoshop's generic layer menu, in its order for a pixel layer without a selection: the Count -/// tool's canvas menu on a marker or off one (#11772), and the Red Eye tool's without a selection. Each row is enabled as the Layers panel -/// menu enables it for the active layer (`menus::is_enabled`) and runs like the menu item. +/// tool's canvas menu on a marker or off one (#11772), and the Red Eye and Object Selection +/// (#12866) tools' without a selection. Each row is enabled as the Layers panel menu enables it +/// for the active layer (`menus::is_enabled`) and runs like the menu item. pub const COUNT_MENU: &[Row] = &[ Some(("Blending Options…", "layer.layerStyle.blendingOptions")), None, @@ -543,8 +544,9 @@ pub const COUNT_MENU: &[Row] = &[ /// Right-click with the Content-Aware Move tool inside an active selection (#12194). pub const CAM_INSIDE_SELECTION_MENU: &[Row] = &[Some(("Color Range…", "select.colorRange")), Some(("Load Selection…", "select.loadSelection"))]; -/// The selection menu as measured in the reference application with the Red Eye tool (#12577): -/// no Distort or Perspective, and Delete and Fill Selection after the fills. +/// The selection menu as measured in the reference application with the Red Eye tool (#12577) and +/// the Object Selection tool (#12866): no Distort or Perspective, and Delete and Fill Selection +/// after the fills. pub const MEASURED_SELECTION_MENU: &[Row] = selection_menu![ None, Some(("Fill…", "edit.fill")), @@ -851,7 +853,7 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { SAMPLER_MENU } else if menu.tool == Tool::Count { COUNT_MENU - } else if menu.tool == Tool::RedEye { + } else if matches!(menu.tool, Tool::RedEye | Tool::ObjectSelection) { if menu.has_selection { MEASURED_SELECTION_MENU } else { COUNT_MENU } } else if menu.tool == Tool::Eyedropper { EYEDROPPER_MENU From bb5671079488bacdaa74dac4cca6dc7c8f1fd440 Mon Sep 17 00:00:00 2001 From: rmsff <17902130+rmsff@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:38:30 +0300 Subject: [PATCH 60/65] Test the Object Selection canvas menus Without the fix the two tests of the new menus and the unmeasured-layers test fail; the others guard the unchanged menus. --- crates/ui-egui/src/canvas/canvas_tool_menu.rs | 3 + .../object_selection_menu_tests.rs | 175 ++++++++++++++++++ .../src/canvas/canvas_tool_menu/tests.rs | 2 +- 3 files changed, 179 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 76e2ce80fae..bfad6a57b8b 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -1840,3 +1840,6 @@ mod delete_anchor_menu_tests; #[cfg(test)] mod convert_point_menu_tests; + +#[cfg(test)] +mod object_selection_menu_tests; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs new file mode 100644 index 00000000000..103478739d5 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs @@ -0,0 +1,175 @@ +//! #12866: the Object Selection tool's canvas menu lists the reference application's rows: with a +//! selection, no Distort or Perspective and Delete and Fill Selection after the fills; with none, +//! the layer menu, its rows greyed as measured over the Background, a type and a shape layer. The +//! marquees', lassos' and Magic Wand's menus are unchanged. + +use egui::{Context, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; + +use super::tests::{app, harness, labels, right_click}; +use super::{COUNT_MENU, NO_SELECTION_MENU, SELECTION_MENU, available, open, rows}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// A pixel layer filled red, active, with `select` run first when given. +fn pixel_layer(select: &[(&str, Value)]) -> PhotocraftApp { + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + for (id, params) in select { + app.run(id, params.clone()).unwrap(); + } + app.ui.tool = Tool::ObjectSelection; + app +} + +/// Right-click the middle of the canvas: the open menu's entries as `ui.inspect` lists them. +fn right_click_entries(h: &mut Harness<'static, PhotocraftApp>) -> Vec { + let center = h.state().last_canvas_rect.center(); + right_click(h, center, Modifiers::NONE); + let inspected = crate::control::inspect(h.state(), &h.ctx); + assert_eq!(inspected["canvasToolMenu"]["tool"], json!("ObjectSelection")); + inspected["canvasToolMenu"]["entries"].as_array().cloned().unwrap_or_default() +} + +/// The entries' labels, a separator as `None`. +fn shown(entries: &[Value]) -> Vec> { + entries.iter().map(|e| if e["separator"] == json!(true) { None } else { e["label"].as_str().map(String::from) }).collect() +} + +/// The issue's notation: rows joined by " · ", separators written " ― ". +fn menu(spec: &str) -> Vec> { + spec.split(" ― ") + .enumerate() + .flat_map(|(i, group)| (i > 0).then_some(None).into_iter().chain(group.split(" · ").map(|label| Some(label.to_owned())))) + .collect() +} + +#[test] +fn with_a_selection_the_menu_lists_the_reference_rows() { + let mut h = harness(pixel_layer(&[("select.rect", json!({"x": 4, "y": 4, "width": 24, "height": 24}))])); + let entries = right_click_entries(&mut h); + assert_eq!( + shown(&entries), + menu( + "Deselect · Select Inverse · Feather… · Select and Mask… ― Save Selection… · Make Work Path… ― Layer Via Copy · Layer Via Cut · \ + New Layer… ― Free Transform · Transform Selection ― Fill… · Stroke… · Content-Aware Fill… · Delete and Fill Selection ― \ + Last Filter ― Fade…" + ) + ); + // A row the menu had before runs its command, as before. + let before = h.state().session.journal.len(); + h.get_by_label("Select Inverse").click(); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none()); + assert!(h.state().session.journal[before..].iter().any(|(id, _)| id == "select.inverse")); +} + +#[test] +fn with_no_selection_the_menu_lists_the_layer_rows() { + let mut h = harness(pixel_layer(&[("select.rect", json!({"x": 4, "y": 4, "width": 24, "height": 24})), ("select.deselect", json!({}))])); + let entries = right_click_entries(&mut h); + assert_eq!( + shown(&entries), + menu( + "Blending Options… ― Duplicate Layer… · Delete Layer · Group from Layers… ― Convert to Smart Object · Convert to Layers ― \ + Rasterize Layer · Rasterize Layer Style ― Free Transform ― Color Range… · Load Selection… · Reselect" + ) + ); + // Over a plain pixel layer these have nothing to act on and grey out. + for label in ["Convert to Layers", "Rasterize Layer", "Rasterize Layer Style"] { + let entry = entries.iter().find(|e| e["label"] == json!(label)); + assert_eq!(entry.map(|e| &e["enabled"]), Some(&json!(false)), "{label} is greyed out"); + } + h.get_by_label("Reselect").click(); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none()); + assert!(h.state().session.active().unwrap().doc.selection.is_some(), "Reselect brings the selection back"); + assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("select.reselect")); +} + +/// The rows greyed without a selection, as measured over each layer kind (#12866). Load +/// Selection… and Reselect follow the document, not the layer, and are left out. The reference +/// also greys Group from Layers… over the Background; here it stays on, because the engine's +/// `layer.new.groupFromLayers` groups the Background, which this item does not change. +const GREYED: [(&str, &[&str]); 3] = [ + ("Background", &["Blending Options…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform"]), + ("Type", &["Convert to Layers", "Rasterize Layer Style"]), + ("Shape", &["Convert to Layers", "Rasterize Layer Style"]), +]; + +#[test] +fn background_type_and_shape_layers_get_the_layer_menu_greyed_as_measured() { + for (kind, greyed) in GREYED { + let mut app = app(); + // The Background stays active under a second layer, so Delete Layer has one to keep. + let background = app.session.active().and_then(|st| st.active_layer).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + match kind { + "Background" => app.session.set_active_layer(Some(background)), + "Type" => { + app.run("type.create", json!({"x": 4, "y": 20, "text": "A", "size": 12})).unwrap(); + } + _ => { + app.run("shape.create", json!({"kind": "rect", "rect": [4, 4, 20, 20], "fill": "#ff0000"})).unwrap(); + } + } + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert_eq!(if st.doc.is_background(layer.id) { "Background" } else { layer.content.kind_name() }, kind); + app.ui.tool = Tool::ObjectSelection; + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0]), "{kind}"); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert_eq!(labels(rows(&menu)), labels(COUNT_MENU), "{kind}"); + let wrong: Vec<_> = rows(&menu) + .iter() + .flatten() + .filter(|(label, id)| !matches!(*label, "Load Selection…" | "Reselect") && available(&app, &menu, id) == greyed.contains(label)) + .map(|(label, _)| *label) + .collect(); + assert!(wrong.is_empty(), "{kind}: enabled or greyed unlike the reference: {wrong:?}"); + } +} + +#[test] +fn every_object_selection_row_runs_a_known_command() { + let mut app = pixel_layer(&[]); + let items = crate::menus::menu_items(&app); + // Selected first, then deselected. + for id in ["select.all", "select.deselect"] { + app.run(id, json!({})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for (label, id) in rows(&menu).iter().flatten() { + assert!(items.iter().any(|i| i.id == *id) || photocraft_engine::commands::find(id).is_some(), "{label}: unknown command {id}"); + } + } +} + +#[test] +fn the_other_selection_tools_keep_their_menus() { + let tools = [ + Tool::RectMarquee, + Tool::EllipseMarquee, + Tool::SingleRowMarquee, + Tool::SingleColumnMarquee, + Tool::Lasso, + Tool::PolygonLasso, + Tool::MagneticLasso, + Tool::MagicWand, + ]; + for tool in tools { + for (selection, menu) in [(true, SELECTION_MENU), (false, NO_SELECTION_MENU)] { + let mut app = app(); + if selection { + app.run("select.all", json!({})).unwrap(); + } + app.ui.tool = tool; + assert!(open(&mut app, &Context::default(), tool, [10.0, 10.0]), "{tool:?}"); + let open_rows = rows(app.ui.canvas_tool_menu.as_ref().unwrap()); + assert_eq!(labels(open_rows), labels(menu), "{tool:?}, selection {selection}"); + } + } +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs index 6a3c5075c52..debcd8aee48 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -387,7 +387,7 @@ fn transform_menu_follows_photoshop_order() { } } -fn labels(rows: &[Row]) -> Vec> { +pub(super) fn labels(rows: &[Row]) -> Vec> { rows.iter().map(|row| row.map(|(label, _)| label)).collect() } From caf17e354f95d5e8a1592c07c522948ded76508d Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 12 Nov 2026 13:01:20 +0100 Subject: [PATCH 61/65] Grey Group from Layers over the Background (PR #13005) The reference application refuses Group from Layers whenever the Background is among the selected layers, also beside an active pixel layer (measured). The Object Selection, Red Eye and Count canvas menus and the menu bar left it on. It now greys like its twin, and the tests pin the measured state. Co-Authored-By: rmsff <17902130+rmsff@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- .../object_selection_menu_tests.rs | 25 ++++++++++++++++--- crates/ui-egui/src/menus/enable_rules.rs | 9 ++++++- .../ui-egui/src/red_eye_context_menu_tests.rs | 7 +++--- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs index 103478739d5..a1f722a626e 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs @@ -91,11 +91,9 @@ fn with_no_selection_the_menu_lists_the_layer_rows() { } /// The rows greyed without a selection, as measured over each layer kind (#12866). Load -/// Selection… and Reselect follow the document, not the layer, and are left out. The reference -/// also greys Group from Layers… over the Background; here it stays on, because the engine's -/// `layer.new.groupFromLayers` groups the Background, which this item does not change. +/// Selection… and Reselect follow the document, not the layer, and are left out. const GREYED: [(&str, &[&str]); 3] = [ - ("Background", &["Blending Options…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform"]), + ("Background", &["Blending Options…", "Group from Layers…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform"]), ("Type", &["Convert to Layers", "Rasterize Layer Style"]), ("Shape", &["Convert to Layers", "Rasterize Layer Style"]), ]; @@ -133,6 +131,25 @@ fn background_type_and_shape_layers_get_the_layer_menu_greyed_as_measured() { } } +/// The reference application greys Group from Layers… whenever the Background is selected, also +/// beside a pixel layer that is the active one. +#[test] +fn group_from_layers_is_greyed_with_the_background_among_the_selected_layers() { + let mut app = pixel_layer(&[]); + let st = app.session.active().unwrap(); + let pixel = st.active_layer.unwrap(); + let background = st.doc.layers.iter().map(|l| l.id).find(|id| st.doc.is_background(*id)).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(available(&app, &menu, "layer.new.groupFromLayers"), "a pixel layer alone can be grouped"); + app.run("layer.select", json!({"layer": background.0, "mode": "add"})).unwrap(); + app.session.set_active_layer(Some(pixel)); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!available(&app, &menu, "layer.new.groupFromLayers"), "the Background is selected too"); +} + #[test] fn every_object_selection_row_runs_a_known_command() { let mut app = pixel_layer(&[]); diff --git a/crates/ui-egui/src/menus/enable_rules.rs b/crates/ui-egui/src/menus/enable_rules.rs index 3da894ccf73..dfe898d2981 100644 --- a/crates/ui-egui/src/menus/enable_rules.rs +++ b/crates/ui-egui/src/menus/enable_rules.rs @@ -27,6 +27,8 @@ fn background_blocks(id: &str, has_selection: bool) -> bool { "layer.createClippingMask" | "layer.releaseClippingMask" | "layer.mergeDown" + // The Background can't go into a group (#12866, measured on the canvas menu). + | "layer.new.groupFromLayers" | "layer.lockLayers" | "layer.maskAllObjects" | "edit.puppetWarp" @@ -104,6 +106,11 @@ fn selection_targets(id: &str) -> Option { /// runs on all of them is greyed only when none of them can take it (the active layer alone must /// not decide). Everything else, and a single selected layer, is judged by the active layer. pub fn disabled_for_selection(doc: &Document, selected: &[LayerId], active: Option<&Layer>, id: &str) -> bool { + // The reference application refuses Group from Layers whenever the Background is among the + // selected layers, not only when it is the active one. + if id == "layer.new.groupFromLayers" && selected.iter().filter_map(|l| doc.layer(*l)).any(|l| crate::doc_props_ui::is_background(doc, l)) { + return true; + } let Some(rule) = selection_targets(id).filter(|_| selected.len() > 1) else { return disabled_for(doc, active, id) }; let layers = selected.iter().filter_map(|l| doc.layer(*l)); let can = |l: &Layer| !disabled_for(doc, Some(l), id) && (!matches!(rule, Targets::WithoutMask) || l.mask.is_none()); @@ -186,7 +193,7 @@ pub fn disabled(app: &crate::PhotocraftApp, id: &str) -> bool { return true; } // Only these commands depend on the selection; skip walking the layers for the rest. - if selection_targets(id).is_some() { + if selection_targets(id).is_some() || id == "layer.new.groupFromLayers" { return disabled_for_selection(&st.doc, &st.selected_layers(), active, id); } disabled_for(&st.doc, active, id) diff --git a/crates/ui-egui/src/red_eye_context_menu_tests.rs b/crates/ui-egui/src/red_eye_context_menu_tests.rs index a7a5a209333..277eac21070 100644 --- a/crates/ui-egui/src/red_eye_context_menu_tests.rs +++ b/crates/ui-egui/src/red_eye_context_menu_tests.rs @@ -63,9 +63,10 @@ const NO_SELECTION: [&str; 17] = [ "Reselect", ]; -/// The reference also greys Group from Layers… and Load Selection…, but their menu-bar twins are -/// live here (as in the Count tool's menu), and the rows follow the twins. -const NO_SELECTION_GREY: [&str; 5] = ["Blending Options…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform"]; +/// The reference also greys Load Selection…, but its menu-bar twin is live here (as in the Count +/// tool's menu), and the row follows the twin. +const NO_SELECTION_GREY: [&str; 6] = + ["Blending Options…", "Group from Layers…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform"]; const IN_SELECTION: [&str; 23] = [ "Deselect", From cbcd62c8d1f304927a2f62e13ca69b741f98f8b4 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Thu, 12 Nov 2026 21:09:18 +0100 Subject: [PATCH 62/65] ci: let Cargo handle oversized Windows rustc commands --- .github/workflows/ci.yml | 26 ++++++-------------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1282fc662c9..cf927388b63 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -174,8 +174,8 @@ jobs: # Windows tests run as two legs in parallel: the unit tests and the integration tests. As one job # they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting the integration # tests over a third runner (nextest --partition) saved ~2 min of wall time but cost ~7 - # runner-minutes and one more Windows slot per PR. They stay outside the shared gate for sccache, - # which needs its own action step. + # runner-minutes and one more Windows slot per PR. Moving these legs into the shared gate is + # tracked by storytold/craft-common-actions#212. windows: needs: platforms if: needs.platforms.outputs.windows == 'true' @@ -187,6 +187,10 @@ jobs: matrix: part: [unit, integration] env: + # Released sccache expands Cargo's response files and exceeds Windows' rustc spawn limit + # (#13543). Let Cargo handle long commands until a release includes mozilla/sccache#3026. + # The dependency rust-cache below stays enabled; only compiler caching is disabled. + RUSTC_WRAPPER: "" # No debuginfo on Windows: writing PDBs for ~200 test binaries cost 2.2 of ~21 build minutes. # A panic still names its file and line; only backtrace frames lose theirs (Linux keeps # line-tables-only, so a backtrace with lines is one OS away). @@ -236,24 +240,6 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' && matrix.part == 'integration' }} cache-on-failure: true - # sccache caches the workspace crates' compiled libraries, which rust-cache leaves out: - # warm, each Windows leg built 4.5 min faster. Like rust-cache, only main writes (PRs read - # main's entries); a full set is ~90 MB, so it barely touches the 10 GB budget (#2688). - # Test executables can't be cached, so a PR still links its tests. - - name: Install sccache - uses: step-security/sccache-action@ae2d64c53dbae979f387673f0aae7ebb52087f6b # v0.0.11 - with: - version: v0.18.0 - - - name: Use sccache - env: - MAIN: ${{ github.ref == 'refs/heads/main' }} - run: | - echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV" - echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV" - if [ "$MAIN" != true ]; then echo "SCCACHE_GHA_RW_MODE=READ_ONLY" >> "$GITHUB_ENV"; fi - shell: bash - - name: Clippy if: matrix.part == 'integration' run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings From e660b4906bc809cfdf58e936d015e252f6811981 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Thu, 12 Nov 2026 21:56:57 +0100 Subject: [PATCH 63/65] Clear the clippy 1.100 lints that fail the gate on main (#13531) (#13535) * Clear the clippy 1.100 lints that fail the gate on main (#13531) Clippy 1.100.0 flags needless_range_loop in cms synth.rs (the gate failure on main), algo photo_util.rs and an engine multichannel test, and, on Windows only, needless_bool in format noreplace.rs, where the cfg(unix) branch compiles away. Each loop now iterates the slice it indexed, with the same values in the same order. * Clear the Linux-only clippy 1.100 needless_bool lints (#13531) paths_match in ui-egui and is_redirect in the app ended with a cfg(not(windows)) branch that is just `false`, which clippy 1.100 flags on Linux. Each platform's branch now returns the whole comparison: the same results, in the same order. --- apps/photocraft/src/external_svg.rs | 7 ++----- crates/algo/src/photo_util.rs | 4 ++-- crates/cms/src/synth.rs | 4 ++-- crates/engine/src/cmd/multichannel_cmds/tests.rs | 4 ++-- crates/format/src/noreplace.rs | 5 +---- crates/ui-egui/src/home_recent_ui.rs | 9 ++------- 6 files changed, 11 insertions(+), 22 deletions(-) diff --git a/apps/photocraft/src/external_svg.rs b/apps/photocraft/src/external_svg.rs index 1d4f5525734..c34dd88bd03 100644 --- a/apps/photocraft/src/external_svg.rs +++ b/apps/photocraft/src/external_svg.rs @@ -627,17 +627,14 @@ mod native { /// True for a symlink, or on Windows any reparse point, whose target could be swapped. /// Expects `symlink_metadata`, which describes the link itself rather than its target. fn is_redirect(metadata: &Metadata) -> bool { - if metadata.file_type().is_symlink() { - return true; - } #[cfg(windows)] { use std::os::windows::fs::MetadataExt; - metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT + metadata.file_type().is_symlink() || metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT } #[cfg(not(windows))] { - false + metadata.file_type().is_symlink() } } diff --git a/crates/algo/src/photo_util.rs b/crates/algo/src/photo_util.rs index 96c6f7b434c..8f1e436d533 100644 --- a/crates/algo/src/photo_util.rs +++ b/crates/algo/src/photo_util.rs @@ -167,8 +167,8 @@ impl BandChol { let n = a.diag.len(); let mut p = 0; for i in 0..n { - for k in a.rows[i]..a.rows[i + 1] { - p = p.max(i.abs_diff(a.cols[k])); + for &j in &a.cols[a.rows[i]..a.rows[i + 1]] { + p = p.max(i.abs_diff(j)); } } if n.saturating_mul(p + 1) > 40_000_000 { diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index 390e509dce3..c86bedc9bd9 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -119,7 +119,7 @@ impl CmykModel { (v + 4.0 * self.tvi[i] * v * (1.0 - v)).clamp(0.0, 1.0) }); let mut s = [0.0; 3]; - for m in 0..16 { + for (m, prim) in self.prim_n.iter().enumerate() { let mut w = 1.0; for (i, ai) in a.iter().enumerate() { w *= if m & (1 << i) != 0 { *ai } else { 1.0 - ai }; @@ -127,7 +127,7 @@ impl CmykModel { if w == 0.0 { continue; } - for (acc, p) in s.iter_mut().zip(&self.prim_n[m]) { + for (acc, p) in s.iter_mut().zip(prim) { *acc += w * p; } } diff --git a/crates/engine/src/cmd/multichannel_cmds/tests.rs b/crates/engine/src/cmd/multichannel_cmds/tests.rs index fc3cfd1cd63..99ad72d6733 100644 --- a/crates/engine/src/cmd/multichannel_cmds/tests.rs +++ b/crates/engine/src/cmd/multichannel_cmds/tests.rs @@ -110,8 +110,8 @@ fn flattens_layers_and_keeps_alpha_channels() { assert_eq!(d.channels.len(), 4); assert!(d.channels[3].spot.is_none(), "the saved selection stays an alpha channel"); // The black fill on the upper layer is solid ink in all three plates. - for k in 0..3 { - assert!(d.channels[k].surface.pixel(1, 1)[0] > 0.99); + for c in &d.channels[..3] { + assert!(c.surface.pixel(1, 1)[0] > 0.99); } // Back to RGB: the alpha channel survives, the inks become colour channels. s.execute("image.mode.rgb", json!({})).unwrap(); diff --git a/crates/format/src/noreplace.rs b/crates/format/src/noreplace.rs index 75a54350c5c..60d74d29c85 100644 --- a/crates/format/src/noreplace.rs +++ b/crates/format/src/noreplace.rs @@ -107,14 +107,11 @@ pub fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> { /// Use fallback only when the exclusive rename primitive itself is unsupported. fn unsupported_rename(error: &io::Error) -> bool { - if error.kind() == io::ErrorKind::Unsupported { - return true; - } #[cfg(unix)] if matches!(error.raw_os_error(), Some(code) if code == rustix::io::Errno::INVAL.raw_os_error() || code == rustix::io::Errno::NOSYS.raw_os_error()) { return true; } - false + error.kind() == io::ErrorKind::Unsupported } /// Linking claims an absent destination atomically; a later unlink failure is already published. diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 2cd4d5d2b48..e8f25a1e724 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -82,18 +82,13 @@ impl ThumbnailCache { /// Check if two path strings match, tolerating slash direction and Windows case differences. fn paths_match(a: &str, b: &str) -> bool { - if a == b { - return true; - } #[cfg(windows)] { - let a_norm = a.replace('\\', "/"); - let b_norm = b.replace('\\', "/"); - a_norm.eq_ignore_ascii_case(&b_norm) + a == b || a.replace('\\', "/").eq_ignore_ascii_case(&b.replace('\\', "/")) } #[cfg(not(windows))] { - false + a == b } } From 0c4eccefb2087c1ef78dd8bea13462394c8bb99b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Fri, 13 Nov 2026 00:14:41 +0100 Subject: [PATCH 64/65] test(io): size the Affinity shape-cache test's pixel budget in whole tiles Co-Authored-By: Claude Sonnet 5.5 --- crates/io/src/affinity.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index ef35c622143..927fa142d66 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -934,7 +934,7 @@ mod tests { let d = page(nodes); let mut b = Builder::new("mixed", &d).unwrap(); b.cache_budget = 4 * 256 * 256 * 4; - b.pixel_budget = 64 * 64 * 4; + b.pixel_budget = 256 * 256 * 4; // one whole tile for the image b.document(&d).unwrap(); assert_eq!(b.uncached_shapes, 60); assert!(b.doc.layers.iter().any(|l| matches!(l.content, LayerContent::Smart(_) | LayerContent::Raster(_))), "the image must import"); From 8631a921785429670f322bf67dacf9fd5a066799 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:16:51 +0100 Subject: [PATCH 65/65] Rasterize: undo the layers already converted when a later step fails (#4974) (#5073) * Rasterize: undo the layers already converted when a later step fails (#4974) * Rasterize: roll back through the shared compound helper when a later layer fails (#4974) * Test that a failed Rasterize keeps a clean document clean (#4974) * Rasterize: undo the layers already converted when a later step fails, and refuse before a step starts when there is nothing to do (#4974) * Format the rasterize rollback tests * Rasterize: cover the All Layers and Layer Style refusals through the real commands * Rasterize: name the history step after the variant, and test the rollback through the real commands (#4974) --------- Co-authored-by: skylar --- crates/engine/src/cmd/extra_cmds.rs | 94 +++++++++--- crates/engine/src/cmd/extra_cmds/tests.rs | 52 +++++++ crates/engine/src/cmd/rasterize_style_cmds.rs | 31 ++-- .../src/cmd/rasterize_style_cmds/tests.rs | 55 +++++++ .../tests/it/rasterize_selected_layers.rs | 140 +++++++++++++++++- 5 files changed, 339 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index 96ac6d88c36..4d8e1106896 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -727,11 +727,20 @@ pub(crate) fn kind_of(s: &Session, id: LayerId) -> Option<&'static str> { }) } +fn has_vector_mask(s: &Session, id: LayerId, only: Option<&str>) -> bool { + only.is_none() && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some()) +} + +/// Whether `rasterize_one` has something to do for this layer. +fn has_rasterize_work(s: &Session, id: LayerId, only: Option<&str>) -> bool { + kind_of(s, id).is_some_and(|k| only.is_none_or(|o| o == k)) || has_vector_mask(s, id, only) +} + /// Rasterize one layer; `only` restricts it to one kind. Without `only` (Rasterize › Layer / All /// Layers: "all vector data") a vector mask becomes a pixel mask too; layer effects stay live, as /// in Photoshop (Rasterize › Layer Style bakes them). Returns false when there was nothing to do. pub(crate) fn rasterize_one(s: &mut Session, id: LayerId, only: Option<&str>, key: &str) -> Result { - let vector_mask = only.is_none() && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some()); + let vector_mask = has_vector_mask(s, id, only); let content = rasterize_content(s, id, only, key)?; if vector_mask { s.execute("layer.rasterize.vectorMask", json!({"layer": id.0, "coalesce": key}))?; @@ -800,36 +809,75 @@ fn rasterize_content(s: &mut Session, id: LayerId, only: Option<&str>, key: &str /// rasterize"), every selected layer the command applies to, in one history step. pub(crate) fn rasterize(s: &mut Session, p: &Value, only: Option<&'static str>) -> Result { let ids = crate::layer_multi_cmds::targets(s, p)?; - let many = ids.len() > 1; - let key = step_key(s, "rasterize"); - let mut done = Vec::new(); - for id in ids { - if rasterize_one(s, id, only, &key)? { - done.push(id.0); - } + rasterize_layers(s, ids, only, rasterize_one) +} + +/// The history label of a Rasterize step: the kind it was limited to, or plain "Rasterize". +fn rasterize_label(only: Option<&str>) -> &'static str { + match only { + Some("type") => "Rasterize Type", + Some("shape") => "Rasterize Shape", + Some("fill") => "Rasterize Fill Content", + Some("smart") => "Rasterize Smart Object", + _ => "Rasterize", } - let Some(&first) = done.first() else { - return Err(EngineError::Other(match (only, many) { - (Some(k), false) => format!("the layer is not a {k} layer"), - (Some(k), true) => format!("none of the selected layers is a {k} layer"), - (None, false) => "the layer has nothing to rasterize".into(), - (None, true) => "none of the selected layers has anything to rasterize".into(), - })); - }; +} + +fn nothing_to_rasterize(only: Option<&str>, many: bool) -> EngineError { + EngineError::Other(match (only, many) { + (Some(k), false) => format!("the layer is not a {k} layer"), + (Some(k), true) => format!("none of the selected layers is a {k} layer"), + (None, false) => "the layer has nothing to rasterize".into(), + (None, true) => "none of the selected layers has anything to rasterize".into(), + }) +} + +/// Convert `ids` with `convert` as one history step; a layer that fails takes back the ones +/// converted before it (#4974). +fn rasterize_layers( + s: &mut Session, + ids: Vec, + only: Option<&str>, + convert: impl Fn(&mut Session, LayerId, Option<&str>, &str) -> Result, +) -> Result { + let many = ids.len() > 1; + // Refused before a step starts: a failed `compound` still moves the revision, and a command + // that changes nothing must leave it alone. + if !ids.iter().any(|&id| has_rasterize_work(s, id, only)) { + return Err(nothing_to_rasterize(only, many)); + } + let key = step_key(s, "rasterize"); + let (first, done) = crate::analysis_cmds::compound(s, rasterize_label(only), |s| { + let mut done = Vec::new(); + for id in ids { + if convert(s, id, only, &key)? { + done.push(id.0); + } + } + let Some(&first) = done.first() else { return Err(nothing_to_rasterize(only, many)) }; + Ok((first, done)) + })?; let active = s.active().and_then(|d| d.active_layer).map(|id| id.0).filter(|id| done.contains(id)); Ok(json!({"layer": active.unwrap_or(first), "layers": done})) } pub(crate) fn rasterize_all(s: &mut Session) -> Result { let ids: Vec = s.active().map(|d| d.doc.walk().into_iter().map(|(_, _, l)| l.id).collect()).unwrap_or_default(); - let key = step_key(s, "rasterizeAll"); - let mut n = 0; - for id in ids { - // Every sub-step shares one history entry via the coalescing key. - if rasterize_one(s, id, None, &key)? { - n += 1; - } + let ids: Vec = ids.into_iter().filter(|&id| has_rasterize_work(s, id, None)).collect(); + if ids.is_empty() { + return Ok(json!({"rasterized": 0})); } + let key = step_key(s, "rasterizeAll"); + let n = crate::analysis_cmds::compound(s, "Rasterize All Layers", |s| { + let mut n = 0; + for id in ids { + // Every sub-step shares one history entry via the coalescing key. + if rasterize_one(s, id, None, &key)? { + n += 1; + } + } + Ok(n) + })?; Ok(json!({"rasterized": n})) } diff --git a/crates/engine/src/cmd/extra_cmds/tests.rs b/crates/engine/src/cmd/extra_cmds/tests.rs index 647a585a23f..d85e7c95850 100644 --- a/crates/engine/src/cmd/extra_cmds/tests.rs +++ b/crates/engine/src/cmd/extra_cmds/tests.rs @@ -94,6 +94,10 @@ fn active(s: &Session) -> &Layer { d.doc.layer(d.active_layer.unwrap()).unwrap() } +fn layer_of(s: &Session, id: u64) -> &Layer { + doc(s).layer(LayerId(id)).unwrap() +} + fn pixel(s: &Session, x: i32, y: i32) -> Vec { active(s).surface().unwrap().pixel(x, y) } @@ -1165,6 +1169,54 @@ fn rasterize_fill_and_all_in_one_step() { assert!(doc(&s).walk().iter().all(|(_, _, l)| !matches!(l.content, LayerContent::Fill(_)))); } +/// #4974: Rasterize converts its layers as one step, so a layer that fails after another was +/// converted leaves the document, history, journal and dirty state as they were. +#[test] +fn a_later_layer_failing_takes_back_the_rasterized_ones() { + let mut s = session(8); + let a = s.execute("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap()["layer"].as_u64().unwrap(); + let b = s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap()["layer"].as_u64().unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); + let journal = s.journal.len(); + + let ids = vec![LayerId(a), LayerId(b)]; + let r = rasterize_layers(&mut s, ids.clone(), None, |s, id, only, key| { + if id.0 == b { Err(EngineError::Other("second layer failed".into())) } else { rasterize_one(s, id, only, key) } + }); + assert!(r.is_err()); + assert!(matches!(layer_of(&s, a).content, LayerContent::Fill(_))); + assert!(matches!(layer_of(&s, b).content, LayerContent::Fill(_))); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().history.can_redo()); + assert_eq!(s.journal.len(), journal); + assert!(!s.active().unwrap().is_dirty()); + + // Without the failure both are converted in a single step. + rasterize_layers(&mut s, ids, None, rasterize_one).unwrap(); + assert!(matches!(layer_of(&s, a).content, LayerContent::Raster(_))); + assert!(matches!(layer_of(&s, b).content, LayerContent::Raster(_))); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); +} + +/// A refused Rasterize starts no step: the revision and the saved state do not move. +#[test] +fn rasterize_with_nothing_to_convert_changes_nothing() { + let mut s = session(8); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let (revision, steps) = (s.active().unwrap().revision, s.active().unwrap().history.past_len()); + assert!(s.execute("layer.rasterize.layer", json!({})).is_err()); + assert!(s.execute("layer.rasterize.type", json!({})).is_err()); + assert_eq!(s.execute("layer.rasterize.allLayers", json!({})).unwrap()["rasterized"], 0); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().is_dirty()); +} + #[test] fn rasterize_smart_object_layer() { let mut s = session(8); diff --git a/crates/engine/src/cmd/rasterize_style_cmds.rs b/crates/engine/src/cmd/rasterize_style_cmds.rs index 55a637d5cbc..5c8210852b7 100644 --- a/crates/engine/src/cmd/rasterize_style_cmds.rs +++ b/crates/engine/src/cmd/rasterize_style_cmds.rs @@ -106,17 +106,30 @@ fn bake_one(s: &mut Session, id: LayerId, key: &str) -> Result { /// one history step. fn rasterize_layer_style(s: &mut Session, p: &Value) -> Result { let ids = crate::layer_multi_cmds::targets(s, p)?; + bake_layers(s, ids, bake_one) +} + +/// Bake `ids` with `bake` as one history step; a layer that fails takes back the ones baked before +/// it (#4974). +fn bake_layers(s: &mut Session, ids: Vec, bake: impl Fn(&mut Session, LayerId, &str) -> Result) -> Result { let many = ids.len() > 1; - let key = crate::extra_cmds::step_key(s, "rasterizeLayerStyle"); - let mut done = Vec::new(); - for id in ids { - if bake_one(s, id, &key)? { - done.push(id.0); - } + let nothing = || EngineError::Other(if many { "none of the selected layers has layer effects" } else { "the layer has no layer effects" }.into()); + // Refused before a step starts: a failed `compound` still moves the revision, and a command + // that changes nothing must leave it alone. + if !ids.iter().any(|&id| s.active().and_then(|d| d.doc.layer(id)).is_some_and(can_bake)) { + return Err(nothing()); } - let Some(&first) = done.first() else { - return Err(EngineError::Other(if many { "none of the selected layers has layer effects" } else { "the layer has no layer effects" }.into())); - }; + let key = crate::extra_cmds::step_key(s, "rasterizeLayerStyle"); + let (first, done) = crate::analysis_cmds::compound(s, "Rasterize Layer Style", |s| { + let mut done = Vec::new(); + for id in ids { + if bake(s, id, &key)? { + done.push(id.0); + } + } + let Some(&first) = done.first() else { return Err(nothing()) }; + Ok((first, done)) + })?; let active = s.active().and_then(|d| d.active_layer).map(|id| id.0).filter(|id| done.contains(id)); Ok(json!({"layer": active.unwrap_or(first), "layers": done})) } diff --git a/crates/engine/src/cmd/rasterize_style_cmds/tests.rs b/crates/engine/src/cmd/rasterize_style_cmds/tests.rs index b4391cb6f22..285ef60d97f 100644 --- a/crates/engine/src/cmd/rasterize_style_cmds/tests.rs +++ b/crates/engine/src/cmd/rasterize_style_cmds/tests.rs @@ -162,3 +162,58 @@ fn disabled_and_bad_params_fail_gracefully() { s.execute("layer.layerStyle.stroke", json!({"layer": g})).unwrap(); assert!(s.execute(ID, json!({"layer": g})).is_err(), "group styles are not baked"); } + +/// #4974: a layer that fails to bake takes back the ones baked before it. +#[test] +fn a_later_layer_failing_takes_back_the_baked_ones() { + let (mut s, id) = scene(8); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); + let journal = s.journal.len(); + let calls = std::cell::Cell::new(0); + let r = bake_layers(&mut s, vec![LayerId(id), LayerId(id)], |s, id, key| { + calls.set(calls.get() + 1); + if calls.get() == 1 { bake_one(s, id, key) } else { Err(EngineError::Other("second layer failed".into())) } + }); + assert!(r.is_err()); + assert_eq!(calls.get(), 2); + assert_eq!(layer(&s, id).effects.items.len(), 5); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().history.can_redo()); + assert_eq!(s.journal.len(), journal); + assert!(!s.active().unwrap().is_dirty()); +} + +/// A layer with no effects is refused before a step starts: the revision does not move. +#[test] +fn a_layer_without_effects_changes_nothing() { + let (mut s, _) = scene(8); + let plain = s.execute("layer.new.layer", json!({"name": "plain"})).unwrap()["layer"].as_u64().unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let (revision, steps) = (s.active().unwrap().revision, s.active().unwrap().history.past_len()); + let err = bake_layers(&mut s, vec![LayerId(plain)], bake_one).unwrap_err().to_string(); + assert!(err.contains("no layer effects"), "{err}"); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().is_dirty()); +} + +/// Through the command itself: a layer without effects is refused and nothing moves. +#[test] +fn rasterize_layer_style_on_a_layer_without_effects_changes_nothing() { + let (mut s, _) = scene(8); + s.execute("layer.new.layer", json!({"name": "plain"})).unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let (revision, steps, journal) = (s.active().unwrap().revision, s.active().unwrap().history.past_len(), s.journal.len()); + let err = s.execute(ID, json!({})).unwrap_err().to_string(); + assert!(err.contains("no selected layer has layer effects"), "{err}"); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert_eq!(s.journal.len(), journal); + assert!(!s.active().unwrap().is_dirty()); +} diff --git a/crates/engine/tests/it/rasterize_selected_layers.rs b/crates/engine/tests/it/rasterize_selected_layers.rs index a738b51681b..265af588943 100644 --- a/crates/engine/tests/it/rasterize_selected_layers.rs +++ b/crates/engine/tests/it/rasterize_selected_layers.rs @@ -3,7 +3,7 @@ //! only on the one that was clicked. An explicit `layer` param still targets exactly that layer. use photocraft_doc::{LayerContent, LayerId}; -use photocraft_engine::Session; +use photocraft_engine::{EngineError, Session}; use serde_json::{Value, json}; fn kind(s: &Session, id: LayerId) -> &'static str { @@ -143,3 +143,141 @@ fn bad_targets_fail_gracefully() { assert!(sc.s.execute(id, json!({"layer": u64::MAX})).is_err(), "{id}: no such layer"); } } + +fn deny(denied: &'static str, id: &str) -> photocraft_engine::Result<()> { + if id == denied { Err(EngineError::Other("denied".into())) } else { Ok(()) } +} + +fn deny_shape_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> { + deny("layer.rasterize.shape", id) +} + +fn deny_vector_mask_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> { + deny("layer.rasterize.vectorMask", id) +} + +fn deny_type_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> { + deny("type.rasterize", id) +} + +/// Everything a refused Rasterize has to leave as it was (#4974). +struct Snapshot { + doc: std::sync::Arc, + steps: usize, + journal: usize, + selection: Vec, +} + +impl Snapshot { + fn of(s: &mut Session) -> Snapshot { + // A clean document, and a redo entry that a step recorded by mistake would drop. + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let st = s.active().unwrap(); + assert!(st.history.can_redo(), "the test needs a redo entry"); + Snapshot { doc: st.doc.clone(), steps: st.history.past_len(), journal: s.journal.len(), selection: st.selected_layers() } + } + + fn assert_restored(&self, s: &Session) { + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &self.doc), "the document is the one from before"); + assert_eq!(st.history.past_len(), self.steps); + assert!(st.history.can_redo(), "the redo entry survives"); + assert_eq!(s.journal.len(), self.journal); + assert!(!st.is_dirty()); + assert_eq!(st.selected_layers(), self.selection); + } +} + +impl Scene { + /// Leave a redo entry behind: a layer that was made, then undone. + fn make_redo_entry(&mut self) { + self.s.execute("layer.new.layer", json!({})).unwrap(); + assert!(self.s.undo()); + assert!(self.s.active().unwrap().history.can_redo()); + } +} + +#[test] +fn rasterize_layer_takes_back_a_converted_layer_when_a_later_one_is_refused() { + let mut sc = scene(); + // The type layer is lower, so it is converted first; the shape layer's step is then denied. + sc.select(&[sc.text, sc.shape]); + sc.make_redo_entry(); + let before = Snapshot::of(&mut sc.s); + sc.s.authorize = Some(deny_shape_rasterize); + assert!(sc.s.execute("layer.rasterize.layer", json!({})).is_err()); + assert_eq!(kinds(&sc.s, &[sc.text, sc.shape]), ["type", "shape"]); + before.assert_restored(&sc.s); + // Allowed again, the same command converts both in one step. + sc.s.authorize = None; + sc.s.execute("layer.rasterize.layer", json!({})).unwrap(); + assert_eq!(kinds(&sc.s, &[sc.text, sc.shape]), ["raster", "raster"]); + assert_eq!(sc.s.active().unwrap().history.past_len(), before.steps + 1); +} + +#[test] +fn rasterize_layer_takes_back_the_content_when_its_vector_mask_step_is_refused() { + let mut sc = scene(); + let square = json!({"subpaths": [{"closed": true, "knots": [[4, 4], [40, 4], [40, 30], [4, 30]]}]}); + sc.s.execute("layer.vectorMask.add", json!({"layer": sc.text.0, "path": square})).unwrap(); + sc.select(&[sc.text]); + sc.make_redo_entry(); + let before = Snapshot::of(&mut sc.s); + // The type content converts, then the mask step is denied. + sc.s.authorize = Some(deny_vector_mask_rasterize); + assert!(sc.s.execute("layer.rasterize.layer", json!({})).is_err()); + assert_eq!(kind(&sc.s, sc.text), "type"); + assert!(sc.s.active().unwrap().doc.layer(sc.text).unwrap().vector_mask.is_some()); + before.assert_restored(&sc.s); +} + +#[test] +fn rasterize_layer_style_takes_back_a_baked_layer_when_a_later_one_is_refused() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let pixels = id_of(s.execute("layer.new.layer", json!({"name": "Pixels"})).unwrap()); + s.execute("paint.stroke", json!({"points": [[20, 20]], "size": 12})).unwrap(); + let shadow = json!({"blend": "normal", "distance": 4, "size": 2, "color": "#102040"}); + s.execute("layer.layerStyle.dropShadow", shadow.clone()).unwrap(); + let text = id_of(s.execute("type.create", json!({"text": "Hi", "size": 24, "x": 4, "y": 30})).unwrap()); + s.execute("layer.layerStyle.dropShadow", shadow).unwrap(); + let mut sc = Scene { s, text, shape: pixels, smart: pixels, fill: pixels, bystander: pixels }; + // The pixel layer is lower, so it is baked first; the type layer's content step is then denied. + sc.select(&[pixels, text]); + sc.make_redo_entry(); + let before = Snapshot::of(&mut sc.s); + sc.s.authorize = Some(deny_type_rasterize); + assert!(sc.s.execute("layer.rasterize.layerStyle", json!({})).is_err()); + let st = sc.s.active().unwrap(); + assert!(!st.doc.layer(pixels).unwrap().effects.items.is_empty(), "the baked layer has its effects back"); + assert_eq!(kind(&sc.s, text), "type"); + before.assert_restored(&sc.s); + sc.s.authorize = None; + sc.s.execute("layer.rasterize.layerStyle", json!({})).unwrap(); + assert!(sc.s.active().unwrap().doc.layer(pixels).unwrap().effects.items.is_empty()); + assert_eq!(kind(&sc.s, text), "raster"); +} + +#[test] +fn each_rasterize_command_names_its_history_step() { + let cases = [ + ("layer.rasterize.layer", "text", "Rasterize"), + ("layer.rasterize.type", "text", "Rasterize Type"), + ("layer.rasterize.shape", "shape", "Rasterize Shape"), + ("layer.rasterize.fillContent", "fill", "Rasterize Fill Content"), + ("layer.rasterize.smartObject", "smart", "Rasterize Smart Object"), + ]; + for (cmd, which, label) in cases { + let mut sc = scene(); + let id = match which { + "text" => sc.text, + "shape" => sc.shape, + "fill" => sc.fill, + _ => sc.smart, + }; + sc.select(&[id]); + sc.s.execute(cmd, json!({})).unwrap(); + assert_eq!(sc.s.active().unwrap().history.undo_label(), Some(label), "{cmd}"); + } +}