diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 70531586132..4164e43cdf3 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -270,3 +270,5 @@ mod satin_size_one_tests; #[cfg(test)] mod inner_glow_size_one_tests; +#[cfg(test)] +mod stroke_partial_alpha_tests; diff --git a/crates/compose/src/effects/composite.rs b/crates/compose/src/effects/composite.rs index 3d638c8a4ea..f7f82fce130 100644 --- a/crates/compose/src/effects/composite.rs +++ b/crates/compose/src/effects/composite.rs @@ -1,5 +1,5 @@ use super::bevel::{BevelPaint, TextureCtx, bevel_geom, bevel_maps, satin_map}; -use super::distance::{INSIDE_EPS, Metric, dist_inside_by, dist_outside_by, local_coverage, stroke_outside_exact}; +use super::distance::{INSIDE_EPS, Metric, dist_outside_by, local_coverage, stroke_inside_distance, stroke_outside_exact}; use super::paint::{dissolves_in, glow_map, paint_color, paint_fx, paint_glow, paint_pattern, rgb, shadow_map}; use super::{ Bevel, BevelStyle, BlendMode, Buffer, Effect, FxMaps, FxPaint, GlobalLight, Layer, MAX_REACH, Map, PREPARED_PATTERN_BYTES, Pattern, Placement, @@ -110,7 +110,7 @@ pub(crate) fn build_maps_prepared( let exact_out = out_widths.iter().any(|&w| stroke_outside_exact(w)); let (din, dout, dout_exact) = if has_stroke { ( - Some(dist_inside_by(&shape, Metric::Chamfer)), + Some(stroke_inside_distance(&shape, matches!(layer.content, photocraft_doc::LayerContent::Raster(_)))), chamfer_out.then(|| dist_outside_by(&shape, Metric::Chamfer)), exact_out.then(|| dist_outside_by(&shape, Metric::Euclidean)), ) @@ -185,7 +185,7 @@ pub fn premerges_layer(layer: &Layer) -> bool { /// compositor paints them. The shape Stroke Emboss bevels (#8639). fn stroke_band(shape: &Map, st: &photocraft_doc::StrokeFx) -> Map { let (in_w, out_w) = stroke_widths(st); - let din = (in_w > 0.0).then(|| dist_inside_by(shape, Metric::Chamfer)); + let din = (in_w > 0.0).then(|| stroke_inside_distance(shape, false)); let metric = if stroke_outside_exact(out_w) { Metric::Euclidean } else { Metric::Chamfer }; let dout = (out_w > 0.0).then(|| dist_outside_by(shape, metric)); let mut band = Map::new(shape.w, shape.h, 0.0); @@ -318,6 +318,30 @@ fn inside(a: f32) -> bool { a > INSIDE_EPS } +/// Coverage of an inside stroke before the layer applies its own alpha. +#[inline] +fn inside_stroke_coverage(alpha: f32, distance: f32, limit: f32) -> f32 { + if inside(alpha) { (limit - distance).clamp(0.0, 1.0) } else { 0.0 } +} + +/// A Normal stroke replaces the layer beneath its band by coverage, then adds its own paint. +#[inline] +fn replace_under_stroke(pixel: &mut [f32; 4], paint: [f32; 4], coverage: f32) { + if paint[3] <= 0.0 { + return; + } + let kept = pixel[3] * (1.0 - coverage.clamp(0.0, 1.0)); + let alpha = kept + paint[3]; + if alpha > 0.0 { + *pixel = [ + (pixel[0] * kept + paint[0] * paint[3]) / alpha, + (pixel[1] * kept + paint[1] * paint[3]) / alpha, + (pixel[2] * kept + paint[2] * paint[3]) / alpha, + alpha.min(1.0), + ]; + } +} + /// An effect map as a fraction of the shape's own coverage. fn relative_to_shape(m: Map, shape: &Map) -> Map { let v = m.v.iter().zip(&shape.v).map(|(m, a)| if inside(*a) { (m / a).min(1.0) } else { 0.0 }).collect(); @@ -570,25 +594,31 @@ impl<'a> EffectPass<'a> { if in_w <= 0.0 { continue; } - let mut m = Map::new(self.w, self.h, 0.0); - for ((mv, a), dv) in m.v.iter_mut().zip(&shape.v).zip(&fields.din) { - *mv = if inside(*a) { (in_w + 0.5 - dv).clamp(0.0, 1.0) } else { 0.0 }; - } - if st.common.blend == BlendMode::Normal { - // A Normal stroke replaces the layer under it instead of blending with it - // (Photoshop): at 50 % opacity an opaque pixel under the stroke turns into the - // stroke colour at 50 % alpha, not a 50/50 mix. - let mut stroke_px = alloc.filled(self.big, [0.0; 4])?; - paint_fx(&mut stroke_px, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, BlendMode::Normal, st.common.opacity, self.patterns); - for ((p, s), cov) in lay.px.iter_mut().zip(&stroke_px.px).zip(&m.v) { - if s[3] <= 0.0 { + let limit = in_w + 0.5; + let opacity = st.common.opacity; + if let (BlendMode::Normal, FxPaint::Color(color)) = (st.common.blend, &st.paint) { + // Solid colour is constant, so we can paint and replace in one pass. + let [r, g, b] = rgb(color); + for ((pixel, &a), &distance) in lay.px.iter_mut().zip(&shape.v).zip(&fields.din) { + let coverage = inside_stroke_coverage(a, distance, limit); + let alpha = coverage * opacity; + if alpha <= 0.0 { continue; } - let kept = p[3] * (1.0 - cov.clamp(0.0, 1.0)); - let alpha = kept + s[3]; - if alpha > 0.0 { - *p = [(p[0] * kept + s[0] * s[3]) / alpha, (p[1] * kept + s[1] * s[3]) / alpha, (p[2] * kept + s[2] * s[3]) / alpha, alpha.min(1.0)]; - } + let paint = psblend::composite(BlendMode::Normal, [0.0; 4], [r, g, b, alpha], 1.0); + replace_under_stroke(pixel, paint, coverage); + } + continue; + } + let mut m = Map::new(self.w, self.h, 0.0); + for ((coverage, &a), &distance) in m.v.iter_mut().zip(&shape.v).zip(&fields.din) { + *coverage = inside_stroke_coverage(a, distance, limit); + } + if st.common.blend == BlendMode::Normal { + let mut stroke_px = alloc.filled(self.big, [0.0; 4])?; + paint_fx(&mut stroke_px, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, BlendMode::Normal, opacity, self.patterns); + for ((pixel, &paint), &coverage) in lay.px.iter_mut().zip(&stroke_px.px).zip(&m.v) { + replace_under_stroke(pixel, paint, coverage); } } else { paint_fx(lay, &m, &st.paint, self.stroke_frame(st), self.anchor, self.big, st.common.blend, st.common.opacity, self.patterns); diff --git a/crates/compose/src/effects/distance.rs b/crates/compose/src/effects/distance.rs index 1b93cd8ac64..b7ba3da1104 100644 --- a/crates/compose/src/effects/distance.rs +++ b/crates/compose/src/effects/distance.rs @@ -325,30 +325,6 @@ fn covered(s: &Map, test: impl Fn(f32) -> bool + Sync) -> Vec { /// Distance from each pixel centre inside the shape to the shape's edge /// (≤ 0 outside). pub(super) fn dist_inside(s: &Map) -> Vec { - dist_inside_by(s, Metric::Euclidean) -} - -pub(super) fn dist_inside_by(s: &Map, m: Metric) -> Vec { - if m == Metric::Chamfer { - // Partly covered edge pixels (alpha below their neighbourhood's) are seeds starting at - // their coverage, mirroring `dist_outside`: a 25 % edge column puts the edge 0.25 px in. - let cov = local_coverage(s); - let start = - s.v.iter() - .zip(&cov.v) - .map(|(&a, &c)| { - if a <= INSIDE_EPS { - 0.0 - } else if c < 1.0 - INSIDE_EPS { - c - } else { - CHAMFER_INF - } - }) - .collect(); - let (d, _) = chamfer_from(start, s.w, s.h); - return d.iter().zip(&s.v).map(|(d, &a)| if a <= INSIDE_EPS { -0.5 } else { d - 0.5 }).collect(); - } let outside = covered(s, |a| a <= INSIDE_EPS); let (d, _) = edt_nearest(&outside, s.w, s.h); par_fill(s.w, s.h, 0.0f32, |y, row| { @@ -359,6 +335,36 @@ pub(super) fn dist_inside_by(s: &Map, m: Metric) -> Vec { }) } +/// Chamfer distance for Inside and Center strokes. +pub(super) fn stroke_inside_distance(s: &Map, raster: bool) -> Vec { + // Partly covered edge pixels start at their local coverage. Keep these sub-pixel + // distances for the antialiased outline. + let mut seeds = local_coverage(s).v; + for (seed, &alpha) in seeds.iter_mut().zip(&s.v) { + *seed = if alpha <= INSIDE_EPS { + 0.0 + } else if *seed < 1.0 - INSIDE_EPS { + *seed + } else { + CHAMFER_INF + }; + } + let (mut distances, _) = chamfer_from(seeds, s.w, s.h); + for (distance, &alpha) in distances.iter_mut().zip(&s.v) { + let d = *distance; + *distance = if alpha <= INSIDE_EPS { + -0.5 + } else if raster && alpha < 1.0 && d > 1.0 { + // Translucent raster interiors also take the stroke. Apply the distance + // locally, so it cannot move the stroke boundary in nearby opaque pixels. + 0.0 + } else { + d - 0.5 + }; + } + distances +} + /// Alpha relative to the 3×3 neighbourhood maximum: separates edge coverage /// from the fill's own opacity on shape layers. pub(super) fn local_coverage(s: &Map) -> Map { @@ -770,6 +776,8 @@ pub enum FieldKind { ChokeInside, /// Stroke distance inside the shape. StrokeInside, + /// Inside stroke distance with translucent raster pixels covered. + StrokeInsideRaster, /// Exact Euclidean distance outside the shape: a wide raster stroke's outer edge (see /// [`stroke_outside_exact`]). The chamfer's level sets are polygons (an ~8-fold octagon), so a /// wide stroke's outer boundary facets; the shadow / glow spread above keeps the chamfer (#3646). @@ -792,7 +800,8 @@ pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reac FieldKind::BevelInside => bevel_dist_inside(&s, &sharp_edges(&s), reach), FieldKind::StrokeOutside => dist_outside_by(&s, Metric::Chamfer), FieldKind::ChokeInside => dist_outside_by(&s.map(|a| 1.0 - a), Metric::Chamfer), - FieldKind::StrokeInside => dist_inside_by(&s, Metric::Chamfer), + FieldKind::StrokeInside => stroke_inside_distance(&s, false), + FieldKind::StrokeInsideRaster => stroke_inside_distance(&s, true), FieldKind::StrokeOutsideExact => dist_outside_by(&s, Metric::Euclidean), FieldKind::StrokeOutsideVector => dist_outside_by(&local_coverage(&s), Metric::Euclidean), FieldKind::StrokeOutsideVectorChamfer => dist_outside_by(&local_coverage(&s), Metric::Chamfer), diff --git a/crates/compose/src/effects/stroke_partial_alpha_tests.rs b/crates/compose/src/effects/stroke_partial_alpha_tests.rs new file mode 100644 index 00000000000..4f58458169b --- /dev/null +++ b/crates/compose/src/effects/stroke_partial_alpha_tests.rs @@ -0,0 +1,117 @@ +use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; +use photocraft_doc::{Document, Effect, FxCommon, FxPaint, Layer, StrokeFx, StrokePosition}; +use photocraft_geom::{Rect, Size}; + +/// The three squares and blue stroke measured in issue #15002. +fn fixture(depth: SampleType, position: StrokePosition) -> Document { + let mut doc = Document::with_background("Stroke partial alpha", Size::new(240, 120), ColorMode::Rgb, depth, Color::WHITE); + let mut layer = Layer::raster("Orange squares", doc.pixel_format()); + let surface = layer.surface_mut().unwrap(); + for (x, alpha) in [(20, 1.0), (100, 0.5), (180, 0.25)] { + surface.fill_rect(Rect::from_xywh(x, 40, 40, 40), &[1.0, 128.0 / 255.0, 0.0, alpha]); + } + layer.effects.items.push(Effect::Stroke(StrokeFx { + common: FxCommon::new(BlendMode::Normal, 1.0), + size: if position == StrokePosition::Center { 6.0 } else { 5.0 }, + position, + paint: FxPaint::Color(Color::rgb(0.0, 0.0, 1.0)), + overprint: false, + })); + doc.layers.push(layer); + doc +} + +#[test] +fn stroke_partial_alpha_matches_the_measured_square_columns() { + const BLUE: [i32; 3] = [0, 0, 255]; + const ORANGE: [i32; 3] = [255, 128, 0]; + const WHITE: [i32; 3] = [255; 3]; + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for position in [StrokePosition::Inside, StrokePosition::Center, StrokePosition::Outside] { + let doc = fixture(depth, position); + let buf = crate::render(&doc, doc.bounds()); + let close = |x, y, expected: [i32; 3]| { + let pixel = buf.get(x, y); + let actual = [pixel[0], pixel[1], pixel[2]].map(|c| (c * 255.0).round() as i32); + assert!( + actual.iter().zip(expected).all(|(a, b)| (a - b).abs() <= 1), + "{depth:?} {position:?} at ({x}, {y}): {actual:?}, expected {expected:?}" + ); + assert!((pixel[3] - 1.0).abs() < 1e-6); + }; + for (x, inside, outside) in [(120, [127, 127, 255], [128, 64, 127]), (200, [191, 191, 255], [64, 32, 191])] { + for y in 40..80 { + close( + x, + y, + match position { + StrokePosition::Inside => inside, + StrokePosition::Center => BLUE, + StrokePosition::Outside => outside, + }, + ); + } + match position { + StrokePosition::Inside => close(x, 39, WHITE), + StrokePosition::Center => { + close(x, 36, WHITE); + close(x, 37, inside); + close(x, 38, BLUE); + close(x, 39, BLUE); + } + StrokePosition::Outside => { + close(x, 34, WHITE); + close(x, 35, inside); + close(x, 36, BLUE); + close(x, 39, BLUE); + } + } + } + let (first, last) = match position { + StrokePosition::Inside => (40, 44), + StrokePosition::Center => (37, 42), + StrokePosition::Outside => (35, 39), + }; + close(40, first - 1, WHITE); + for y in first..=last { + close(40, y, BLUE); + } + close(40, last + 1, ORANGE); + close(40, 60, ORANGE); + } + } +} + +#[test] +fn the_raster_distance_preserves_the_opaque_interior_and_subpixel_outline() { + use super::{FieldKind, distance_field}; + + let row = [0.0, 0.25, 0.75, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.0]; + let source = row.repeat(9); + let inside = distance_field(FieldKind::StrokeInside, source.clone(), row.len(), 9, 6.0); + let raster = distance_field(FieldKind::StrokeInsideRaster, source, row.len(), 9, 6.0); + let mid = row.len() * 4; + // Opaque pixels retain their distances even beside a translucent area. + assert_eq!(raster[mid..mid + 8], inside[mid..mid + 8]); + assert_eq!(raster[mid + 8], inside[mid + 8], "the existing subpixel seed is retained"); + assert!(inside[mid + 11] > 0.5, "the old outline did not reach this interior"); + assert_eq!(raster[mid + 11], 0.0, "the translucent interior is covered"); + assert_eq!(raster[mid + 15], inside[mid + 15], "the fully transparent pixel stays outside"); +} + +#[test] +fn stroke_partial_alpha_keeps_intrinsic_alpha_for_inside_and_fills_it_for_center() { + for position in [StrokePosition::Inside, StrokePosition::Center] { + let mut doc = fixture(SampleType::U8, position); + let background = doc.layers[0].id; + doc.remove(background).unwrap(); + let pixels = crate::render(&doc, doc.bounds()); + for (x, source_alpha) in [(120, 128.0 / 255.0), (200, 64.0 / 255.0)] { + let actual = pixels.get(x, 60); + let expected_alpha = if position == StrokePosition::Inside { source_alpha } else { 1.0 }; + assert_eq!(&actual[..3], &[0.0, 0.0, 1.0], "{position:?} at x={x}"); + assert!((actual[3] - expected_alpha).abs() < 1e-6, "{position:?} at x={x}: {actual:?}"); + } + assert_eq!(pixels.get(80, 60), [0.0; 4]); + } +} diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index 0ce4f1ab109..2983063dfbc 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -30,6 +30,8 @@ pub(crate) fn layer_identity(layer: &Layer, h: &mut std::collections::hash_map:: h.finish() } layer.id.0.hash(h); + // The same display surface can blend differently before and after rasterizing a text child. + std::mem::discriminant(&layer.content).hash(h); // What the maps depend on: `fill_opacity` shades them; layer `opacity` is applied when the // maps are composited and `visible` only skips the lookup entirely, so neither belongs in // the key (an opacity drag must not rebuild shadows over the whole layer; the GPU's @@ -235,6 +237,8 @@ pub(crate) fn effect_maps_with(layer: &Layer, rect: Rect, cx: &C } let mut h = std::collections::hash_map::DefaultHasher::new(); cx.layer_keys.identity(layer, cx.doc).hash(&mut h); + // Converting a layer can reuse its exact tiles and ID but change how its stroke reads alpha. + std::mem::discriminant(&layer.content).hash(&mut h); (region.x0, region.y0, region.x1, region.y1).hash(&mut h); (cx.light.angle.to_bits(), cx.light.altitude.to_bits()).hash(&mut h); let key = h.finish(); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 6505f2cd1a1..fadc2de4b5f 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -4406,6 +4406,29 @@ fn effect_cache_follows_a_group_childs_blend_if() { assert!(warm.px == cold.px, "stale group effect maps after a child's Blend If changed"); } +#[test] +fn effect_cache_follows_a_group_child_being_rasterized() { + let mut doc = doc_white(32, 32); + let rect = Rect::new(4, 4, 16, 20); + let bottom = solid_layer("pale", rect, [1.0, 1.0, 1.0, 0.5]); + let mut text = solid_layer("text", rect, [0.0, 0.0, 0.0, 0.5]); + let raster = text.content.clone(); + let text_id = text.id; + text.content = LayerContent::Text(photocraft_doc::TextLayer { cache: text.surface().cloned(), ..Default::default() }); + let mut top = solid_layer("blend if", rect, [0.2, 0.6, 0.0, 1.0]); + top.blend_if.set(0, [FULL, range([0, 0], [100, 100])]); + let mut group = Layer::group("group", vec![bottom, text, top]); + group.effects.items = vec![Effect::DropShadow(Shadow { size: 2.0, spread: 0.0, ..shadow(3.0, 90.0) })]; + doc.layers.push(group); + let before = render(&doc, doc.bounds()); + doc.layer_mut(text_id).unwrap().content = raster; + let warm = render(&doc, doc.bounds()); + purge_effect_cache(); + let cold = render(&doc, doc.bounds()); + assert!((0..32).any(|y| (0..32).any(|x| !rect.contains(x, y) && before.get(x, y) != cold.get(x, y))), "the group's shadow changes"); + assert!(warm.px == cold.px, "rasterization must invalidate the group's shadow map"); +} + /// A document whose one-colour areas are found: shared background tiles, a painted patch over /// tile edges, a uniform mask tile, an adjustment, a group, a 16-bit layer and a hidden one. fn sparse_doc(w: u32, h: u32) -> Document { diff --git a/crates/engine-core/src/cmd/actions_cmds.rs b/crates/engine-core/src/cmd/actions_cmds.rs index 66543cd1d6d..6ddc1951f30 100644 --- a/crates/engine-core/src/cmd/actions_cmds.rs +++ b/crates/engine-core/src/cmd/actions_cmds.rs @@ -158,6 +158,9 @@ pub fn playback_params(s: &Session, id: &str, p: &Value) -> Result { { object.remove("__atnCustom"); } + if id == "edit.contentAwareFill" { + crate::atn_cmds::caf_remembered(&mut p, s.prefs())?; + } if id == "layer.setProps" && let Some(target) = p.get("_actionLayer") { diff --git a/crates/engine-core/src/cmd/atn_cmds.rs b/crates/engine-core/src/cmd/atn_cmds.rs index 4b9d2ef489d..25c0003d5d5 100644 --- a/crates/engine-core/src/cmd/atn_cmds.rs +++ b/crates/engine-core/src/cmd/atn_cmds.rs @@ -85,6 +85,8 @@ use events::{EVENTS, event_and_descriptor, event_for}; use fields::Mapped; use files::{load, save}; pub use menu_item::{MENU_ITEM, menu_item_command, menu_item_commands, menu_item_needs_settings}; +pub(crate) use steps_content_aware::caf_remembered; +pub use steps_content_aware::{CAF_CUSTOM_AREA_NOT_REMEMBERED, CAF_WORKSPACE_PREFS}; #[cfg(test)] use steps_doc::crop_from; pub(crate) use steps_gallery::RECORDED_EVENT; @@ -197,6 +199,9 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; +#[cfg(test)] +mod caf_action_values_tests; + #[cfg(test)] mod layer_props_tests; diff --git a/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs b/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs new file mode 100644 index 00000000000..1f4e52822bc --- /dev/null +++ b/crates/engine-core/src/cmd/atn_cmds/caf_action_values_tests.rs @@ -0,0 +1,251 @@ +//! Recorded `cafWorkspace` steps: every measured value maps to the command and back, and an +//! empty step plays with the workspace's remembered settings (#14254). +use super::*; +use crate::actions_cmds::{ActionList, ActionStep, ActionsExt}; + +const CMD: &str = "edit.contentAwareFill"; +const MARK: &str = "_atnCafRemembered"; + +/// A seven-key step with these enumerations and every boolean off. +fn workspace(sampling: &str, color: &str, rotation: &str, output: &str) -> Descriptor { + desc("null") + .with("cafSamplingRegion", enm("cafSamplingRegion", sampling)) + .with("cafSampleAllLayers", D::Boolean(false)) + .with("cafColorAdaptationLevel", enm("cafColorAdaptationLevel", color)) + .with("cafRotationAmount", enm("cafRotationAmount", rotation)) + .with("cafScale", D::Boolean(false)) + .with("cafMirror", D::Boolean(false)) + .with("cafOutput", enm("cafOutput", output)) +} + +/// The params [`workspace`] imports as. +fn params(sampling: &str, color: &str, rotation: &str, output: &str) -> Value { + json!({"sampling":sampling,"sampleAllLayers":false,"colorAdaptation":color, + "rotationAdaptation":rotation,"scale":false,"mirror":false,"output":output}) +} + +fn item(d: Descriptor) -> AtnItem { + AtnItem { event: AtnEvent::name("cafWorkspace"), dictionary: b"Content-Aware Fill".to_vec(), descriptor: Some(d), ..Default::default() } +} + +fn file(d: Descriptor) -> Vec { + atn::write(&AtnFile { + name: UnicodeString::new_nul("S"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item(d)], ..Default::default() }], + ..Default::default() + }) + .unwrap() +} + +/// The single step a one-step file imports as. +fn load(d: Descriptor) -> Action { + let loaded = import(&file(d)).unwrap(); + assert!(loaded.unsupported.is_empty(), "{:?}", loaded.unsupported); + loaded.actions.into_iter().next().unwrap() +} + +/// The item Save Actions writes for one step, or `None` when it refuses the step. A save that succeeds must +/// write a readable file holding the item. +fn exported(p: Value) -> Option { + let a = Action::new("A", vec![ActionStep::new(CMD, p)]); + let (bytes, skipped) = export("S", &[&a], &[], false).ok()?; + assert!(skipped.is_empty()); + let saved = atn::parse(&bytes).expect("a successful save writes a readable file"); + Some(saved.actions.into_iter().next().and_then(|a| a.items.into_iter().next()).expect("the saved file holds the step")) +} + +#[test] +fn every_measured_value_imports_to_its_param_and_saves_back_unchanged() { + let base = ("cafSamplingRegionRectangular", "cafColorAdaptationDefault", "cafRotationAmountNone", "cafOutputToNewLayer"); + let mut cases = Vec::new(); + for (wire, value) in [("cafSamplingRegionAuto", "auto"), ("cafSamplingRegionRectangular", "rectangular"), ("cafSamplingRegionCustom", "custom")] { + cases.push((workspace(wire, base.1, base.2, base.3), params(value, "default", "none", "new"))); + } + for (wire, value) in [ + ("cafColorAdaptationNone", "none"), + ("cafColorAdaptationDefault", "default"), + ("cafColorAdaptationHigh", "high"), + ("cafColorAdaptationVeryHigh", "veryHigh"), + ] { + cases.push((workspace(base.0, wire, base.2, base.3), params("rectangular", value, "none", "new"))); + } + for (wire, value) in [ + ("cafRotationAmountNone", "none"), + ("cafRotationAmountLow", "low"), + ("cafRotationAmountMedium", "medium"), + ("cafRotationAmountHigh", "high"), + ("cafRotationAmountFull", "full"), + ] { + cases.push((workspace(base.0, base.1, wire, base.3), params("rectangular", "default", value, "new"))); + } + for (wire, value) in [("cafOutputToCurrentLayer", "current"), ("cafOutputToNewLayer", "new"), ("cafOutputToDuplicateLayer", "duplicate")] { + cases.push((workspace(base.0, base.1, base.2, wire), params("rectangular", "default", "none", value))); + } + for (d, p) in cases { + let action = load(d.clone()); + assert_eq!(action.steps, vec![ActionStep::new(CMD, p.clone())]); + assert_eq!(exported(p.clone()), Some(item(d.clone())), "{p}"); + let bytes = export("S", &[&action], &[], false).unwrap().0; + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0], item(d)); + } +} + +#[test] +fn an_empty_step_imports_as_remembered_and_saves_back_empty() { + let action = load(desc("null")); + assert_eq!(action.steps, vec![ActionStep::new(CMD, json!({MARK: true}))]); + assert_eq!(exported(json!({MARK: true})), Some(item(desc("null")))); + // A differently named empty descriptor comes back as recorded. + let mut named = desc("null"); + named.name = UnicodeString::new_nul("Recorded CAF"); + let action = load(named.clone()); + assert_eq!(action.steps[0].params[MARK], json!(true)); + let bytes = export("S", &[&action], &[], false).unwrap().0; + assert_eq!(atn::parse(&bytes).unwrap().actions[0].items[0], item(named)); +} + +#[test] +fn a_remembered_step_with_values_of_its_own_is_not_saved_as_an_empty_step() { + for p in [json!({MARK: true, "output": "current"}), json!({MARK: false}), json!({MARK: "yes"}), json!({MARK: true, "seed": 2})] { + assert_eq!(exported(p.clone()), None, "{p}"); + } +} + +/// White 8 x 8 with a red square selected for the fill. +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width":8,"height":8,"background":"white"})).unwrap(); + s.execute("select.rect", json!({"x":3,"y":3,"width":2,"height":2})).unwrap(); + // Painted directly: Edit › Fill is registered by another engine crate. + s.edit("paint", |doc, active| { + let surface = doc.layer_mut(active.ok_or(crate::EngineError::NoDocument)?).and_then(|l| l.surface_mut()).ok_or(crate::EngineError::NoDocument)?; + for (x, y) in [(3, 3), (4, 3), (3, 4), (4, 4)] { + surface.write_pixel(x, y, &[1.0, 0.0, 0.0, 1.0]); + } + Ok(()) + }) + .unwrap(); + s +} + +fn remember(s: &mut Session, settings: Value) { + s.edit_prefs(|p| p.dialogs.insert(CAF_WORKSPACE_PREFS.into(), settings)); +} + +/// Play `d` as a one-step action and return the result. +fn play(s: &mut Session, d: Descriptor) -> Value { + s.actions_mut().list = ActionList::new(); + s.actions_mut().list.push(load(d)).unwrap(); + let result = s.execute("actions.play", json!({"action":0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(result["ran"], 1); + result +} + +/// Every layer's pixels, in stack order. +fn pixels(s: &Session) -> Vec> { + let doc = &s.active().unwrap().doc; + doc.layers.iter().map(|l| (0..64).map(|i| l.surface().unwrap().rgba(i % 8, i / 8)).collect()).collect() +} + +/// What running the command itself with `p` leaves. +fn native(p: Value) -> Vec> { + let mut s = session(); + s.execute(CMD, p).unwrap(); + pixels(&s) +} + +#[test] +fn an_empty_step_fills_a_new_layer_before_anything_is_remembered() { + let mut s = session(); + let layers = s.active().unwrap().doc.layers.len(); + let past = s.active().unwrap().history.past_len(); + play(&mut s, desc("null")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers + 1); + assert_eq!(s.active().unwrap().history.past_len(), past + 1); + assert_eq!(pixels(&s), native(json!({"output":"new"}))); + assert!(!s.prefs().dialogs.contains_key(CAF_WORKSPACE_PREFS), "playing remembers nothing"); +} + +#[test] +fn an_empty_step_plays_with_the_remembered_settings_and_steps_never_change_them() { + let settings = json!({"showOverlay":false,"opacity":20.0,"sampling":"rectangular","sampleAllLayers":false, + "colorAdaptation":"high","rotationAdaptation":"full","scale":true,"mirror":true,"output":"current"}); + let mut s = session(); + remember(&mut s, settings.clone()); + let layers = s.active().unwrap().doc.layers.len(); + play(&mut s, desc("null")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers, "remembered Current Layer"); + let used = json!({"sampling":"rectangular","sampleAllLayers":false,"colorAdaptation":"high", + "rotationAdaptation":"full","scale":true,"mirror":true,"output":"current"}); + assert_eq!(pixels(&s), native(used)); + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&settings)); + + // A step's own values are not remembered: the next empty step still uses Current Layer. + let mut s = session(); + remember(&mut s, settings.clone()); + let layers = s.active().unwrap().doc.layers.len(); + play(&mut s, workspace("cafSamplingRegionAuto", "cafColorAdaptationNone", "cafRotationAmountLow", "cafOutputToNewLayer")); + assert_eq!(s.active().unwrap().doc.layers.len(), layers + 1); + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&settings)); + let next = crate::actions_cmds::playback_params(&s, CMD, &json!({MARK: true})).unwrap(); + assert_eq!(next["output"], "current"); +} + +#[test] +fn remembered_settings_fill_only_what_the_step_does_not_name() { + let resolve = |s: &Session, p: Value| crate::actions_cmds::playback_params(s, CMD, &p).unwrap(); + let mut s = crate::session(); + assert_eq!(resolve(&s, json!({MARK: true})), json!({"output":"new"})); + // Only the command's settings come over, never the overlay's. + remember(&mut s, json!({"showOverlay":true,"opacity":50.0,"color":[1,2,3],"excluded":true,"sampling":"auto","output":"duplicate"})); + assert_eq!(resolve(&s, json!({MARK: true})), json!({"sampling":"auto","output":"duplicate"})); + assert_eq!(resolve(&s, json!({MARK: true, "output": "current"})), json!({"sampling":"auto","output":"current"})); + // A mark that isn't `true` is dropped without bringing the remembered settings in. + assert_eq!(resolve(&s, json!({MARK: false, "output": "current"})), json!({"output":"current"})); + // Steps without the mark and other commands are left alone. + assert_eq!(resolve(&s, json!({"output":"current"})), json!({"output":"current"})); + let other = crate::actions_cmds::playback_params(&s, "edit.fill", &json!({MARK: true})).unwrap(); + assert_eq!(other, json!({MARK: true})); +} + +#[test] +fn damaged_remembered_settings_are_skipped_without_a_panic() { + let resolve = |s: &Session| crate::actions_cmds::playback_params(s, CMD, &json!({MARK: true})).unwrap(); + let mut s = crate::session(); + for damaged in [json!(3), json!(null), json!([]), json!({"output":5,"scale":"yes","sampling":true,"mirror":null})] { + remember(&mut s, damaged.clone()); + assert_eq!(resolve(&s), json!({"output":"new"}), "{damaged}"); + } + // A remembered value the command refuses fails the step with an error, not a panic. + let mut s = session(); + remember(&mut s, json!({"output":"sideways"})); + s.actions_mut().list = ActionList::new(); + s.actions_mut().list.push(load(desc("null"))).unwrap(); + let before = s.active().unwrap().doc.clone(); + let result = s.execute("actions.play", json!({"action":0})).unwrap(); + assert!(result.get("failed").is_some(), "{result}"); + assert_eq!(s.active().unwrap().doc, before); +} + +#[test] +fn folder_batch_plays_an_empty_step_with_the_remembered_settings() { + let dir = tempfile::tempdir().unwrap(); + let join = |name: &str| dir.path().join(name).to_string_lossy().into_owned(); + let mut source = session(); + source.execute("file.saveACopy", json!({"path": join("in.png")})).unwrap(); + let steps = json!([["select.rect", {"x":3,"y":3,"width":2,"height":2}], [CMD, {MARK: true}]]); + // The layer count of each output: Current Layer fills the background, New Layer adds one. + let layers = |s: &mut Session, out: &str| { + let result = s.execute("file.automate.batch", json!({"input":[join("in.png")],"output":join(out),"format":"psd","steps":steps})).unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + let bytes = std::fs::read(dir.path().join(out).join("in.psd")).unwrap(); + photocraft_io::import("in.psd", &bytes).unwrap().document.layers.len() + }; + let mut s = crate::session(); + assert_eq!(layers(&mut s, "default"), 2, "nothing remembered: a new layer"); + remember(&mut s, json!({"output":"current"})); + assert_eq!(layers(&mut s, "remembered"), 1, "the remembered Current Layer"); + // Playing in Batch remembers nothing in the caller either. + assert_eq!(s.prefs().dialogs.get(CAF_WORKSPACE_PREFS), Some(&json!({"output":"current"}))); +} diff --git a/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs b/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs index 3e30609ea2b..958fd1961b7 100644 --- a/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs +++ b/crates/engine-core/src/cmd/atn_cmds/steps_content_aware.rs @@ -3,20 +3,42 @@ use super::descriptors::{desc, enm, jstr}; use super::fields::{Mapped, step}; use super::tables::lookup_back; use super::{D, Descriptor, Map, Value}; +use crate::EngineError; const CMD: &str = "edit.contentAwareFill"; const SOURCE: &str = "_atnCafDescriptor"; -// The measured row bounds these values; its ellipses are not additional enum bindings. -const SAMPLING: &[(&str, &str)] = &[("cafSamplingRegionRectangular", "rectangular")]; -const COLOR: &[(&str, &str)] = &[("cafColorAdaptationDefault", "default")]; -const ROTATION: &[(&str, &str)] = &[("cafRotationAmountNone", "none")]; -// Current Layer is also explicit in the primary Action Manager example cited in docs/atn.md. -const OUTPUT: &[(&str, &str)] = &[("cafOutputToNewLayer", "new"), ("cafOutputToCurrentLayer", "current")]; +// Every value the workspace showed when such a step was played with dialogs on (#14254). +const SAMPLING: &[(&str, &str)] = &[("cafSamplingRegionAuto", "auto"), ("cafSamplingRegionRectangular", "rectangular"), ("cafSamplingRegionCustom", "custom")]; +const COLOR: &[(&str, &str)] = &[ + ("cafColorAdaptationNone", "none"), + ("cafColorAdaptationDefault", "default"), + ("cafColorAdaptationHigh", "high"), + ("cafColorAdaptationVeryHigh", "veryHigh"), +]; +const ROTATION: &[(&str, &str)] = &[ + ("cafRotationAmountNone", "none"), + ("cafRotationAmountLow", "low"), + ("cafRotationAmountMedium", "medium"), + ("cafRotationAmountHigh", "high"), + ("cafRotationAmountFull", "full"), +]; +const OUTPUT: &[(&str, &str)] = &[("cafOutputToCurrentLayer", "current"), ("cafOutputToNewLayer", "new"), ("cafOutputToDuplicateLayer", "duplicate")]; const KEYS: &[&str] = &["cafSamplingRegion", "cafSampleAllLayers", "cafColorAdaptationLevel", "cafRotationAmount", "cafScale", "cafMirror", "cafOutput"]; const PARAMS: &[&str] = &["sampling", "sampleAllLayers", "colorAdaptation", "rotationAdaptation", "scale", "mirror", "output"]; +/// Marks a step recorded with an empty descriptor: it plays with the workspace's remembered +/// settings ([`caf_remembered`]) instead of fixed values. +const REMEMBERED: &str = "_atnCafRemembered"; +/// The `prefs.dialogs` key under which the Content-Aware Fill workspace remembers its settings. +pub const CAF_WORKSPACE_PREFS: &str = "edit.contentAwareFill.workspace"; -/// All seven settings are recorded. Missing keys have no measured Photoshop default here. +/// All seven settings are recorded, or none: an empty descriptor uses the remembered settings. +/// Other missing keys have no measured Photoshop default here. fn recorded(d: &Descriptor) -> Option { + if d.items.is_empty() { + let mut p = Map::new(); + p.insert(REMEMBERED.into(), true.into()); + return Some(Value::Object(p)); + } if d.items.len() != KEYS.len() || KEYS.iter().any(|name| d.items.iter().filter(|(key, _)| key.is(name)).count() != 1) { return None; } @@ -35,15 +57,24 @@ fn recorded(d: &Descriptor) -> Option { Some(Value::Object(p)) } -/// Write only represented native options, making their defaults explicit in all seven fields. +/// Write only represented native options, making their defaults explicit in all seven fields. A step without +/// `sampleAllLayers` is refused: the command then samples the composite when the layer is empty, which neither +/// recorded value says. fn descriptor(p: &Value) -> Option { let object = p.as_object()?; if !super::events::pixel_target(p) - || object.keys().any(|key| !PARAMS.contains(&key.as_str()) && !matches!(key.as_str(), "target" | "seed" | SOURCE)) + || object.keys().any(|key| !PARAMS.contains(&key.as_str()) && !matches!(key.as_str(), "target" | "seed" | SOURCE | REMEMBERED)) || p.get("seed").is_some_and(|seed| seed.as_u64() != Some(1)) { return None; } + if let Some(remembered) = p.get(REMEMBERED) { + // Values next to the mark would be dropped by an empty descriptor. + return (remembered.as_bool() == Some(true) && !PARAMS.iter().any(|param| object.contains_key(*param))).then(|| desc("null")); + } + if !object.contains_key(PARAMS[1]) { + return None; + } let enumeration = |key: &str, param: &str, table: &[(&str, &str)], default: &str| { let value = match p.get(param) { None => default, @@ -67,6 +98,33 @@ fn descriptor(p: &Value) -> Option { ) } +/// Why an empty recorded step refuses remembered Custom sampling ([`caf_remembered`]). The shell shows it translated. +pub const CAF_CUSTOM_AREA_NOT_REMEMBERED: &str = "This step plays with the remembered Content-Aware Fill settings, and their Custom sampling area isn't remembered. Fill once with Auto or Rectangular sampling in Content-Aware Fill, then play it again."; + +/// Resolve an empty recorded step: the remembered settings fill what the step doesn't name, and +/// before any were remembered it writes to a new layer. Playing never changes what is remembered. +/// Remembered Custom sampling is refused: its area is painted in the workspace, which keeps none +/// (Custom reopens empty), and the step must not sample another area instead. +pub(crate) fn caf_remembered(p: &mut Value, prefs: &crate::prefs::Preferences) -> Result<(), EngineError> { + let Some(object) = p.as_object_mut() else { return Ok(()) }; + if object.remove(REMEMBERED).and_then(|v| v.as_bool()) != Some(true) { + return Ok(()); + } + let saved = prefs.dialogs.get(CAF_WORKSPACE_PREFS); + for (param, flag) in PARAMS.iter().map(|param| (*param, matches!(*param, "sampleAllLayers" | "scale" | "mirror"))) { + // Only well-typed values: a damaged entry must not turn into another setting. + let value = saved.and_then(|v| v.get(param)).filter(|v| if flag { v.is_boolean() } else { v.is_string() }); + if let Some(value) = value.filter(|_| !object.contains_key(param)) { + object.insert(param.into(), value.clone()); + } + } + object.entry("output").or_insert_with(|| "new".into()); + if object.get("sampling").and_then(Value::as_str) == Some("custom") && !["area", "channel", "samplingStrokes"].iter().any(|key| object.contains_key(*key)) { + return Err(EngineError::BadParams { cmd: CMD.into(), msg: CAF_CUSTOM_AREA_NOT_REMEMBERED.into() }); + } + Ok(()) +} + /// Import the verified seven-field form, retaining noncanonical wire data for an unchanged save. pub(super) fn caf_from(d: &Descriptor) -> Mapped { let Some(mut p) = recorded(d) else { return Mapped::Unsupported { harmless: false } }; diff --git a/crates/engine-core/src/cmd/file_cmds.rs b/crates/engine-core/src/cmd/file_cmds.rs index d5d8209fc94..a810480736b 100644 --- a/crates/engine-core/src/cmd/file_cmds.rs +++ b/crates/engine-core/src/cmd/file_cmds.rs @@ -434,7 +434,7 @@ pub fn specs() -> Vec { "Layers to Files…", &["File", "Export"], None, - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"iccProfile":bool? (Include ICC Profile: false, no profile in any file; true, the document's profile, or its mode's working profile when it has none, PSD included, and none in a CMYK document's PNG; unset, as before),"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"pdfSpotPlates":bool=true (PDF: spot channels as overprinting Separation plates after the image; a Multichannel document as plates alone, so false refuses it)} → {files}"##, native_doc, layers_to_files ), @@ -576,3 +576,7 @@ mod aces_exr_tests { } } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "file_cmds/layers_to_files_icc_tests.rs"] +mod layers_to_files_icc_tests; diff --git a/crates/engine-core/src/cmd/file_cmds/batch_run.rs b/crates/engine-core/src/cmd/file_cmds/batch_run.rs index 97b0d9fdf9f..6506ce7fdc1 100644 --- a/crates/engine-core/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine-core/src/cmd/file_cmds/batch_run.rs @@ -1030,6 +1030,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let authorize = s.authorize; let raw_ppi = super::open::raw_open_resolution(s); let action_prefs = s.prefs().actions.clone(); + // An empty recorded Content-Aware Fill step plays with the remembered workspace settings. + let caf_workspace = s.prefs().dialogs.get(crate::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); let prefs = s.prefs.clone(); let color_settings = s.color().settings.clone(); let raw_settings = s.batch_raw_open.as_ref().unwrap_or(&s.prefs().raw_defaults).clone(); @@ -1165,7 +1167,13 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { scratch.recording = run.clone(); scratch.recording.playback_steps = carried.get(); scratch.recording.script_steps = script_steps.get(); - scratch.prefs.edit(|prefs| prefs.actions = action_prefs.clone()); + scratch.prefs.edit(|prefs| { + prefs.actions = action_prefs.clone(); + // Only this entry: the scratch session keeps every other remembered dialog value at its default. + if let Some(workspace) = &caf_workspace { + prefs.dialogs.insert(crate::atn_cmds::CAF_WORKSPACE_PREFS.into(), workspace.clone()); + } + }); let owns_history = scratch.action_history.is_none() && scratch.prefs().actions.create_single_history_state; if owns_history { crate::actions_cmds::begin_document_history(scratch, &action_name); diff --git a/crates/engine-core/src/cmd/file_cmds/export.rs b/crates/engine-core/src/cmd/file_cmds/export.rs index b563a5be136..d7724ec064c 100644 --- a/crates/engine-core/src/cmd/file_cmds/export.rs +++ b/crates/engine-core/src/cmd/file_cmds/export.rs @@ -62,7 +62,10 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& // Callers outside `Session::execute` (headless workspace exports) carry the session's gate // into `encode`, so a PSD embeds no file a linked smart object names. let _authorization = crate::jobs::render_authorization_scope(s.authorize); - let save = SaveOpts::from_params(s, p, cmd)?; + let mut save = SaveOpts::from_params(s, p, cmd)?; + // Include ICC Profile (#13973); unset, each file embeds what it did before. + let icc = super::save::tiff_bool_param(p, "iccProfile", cmd)?; + save.embed_icc = icc; let d = s.active().ok_or(EngineError::NoDocument)?; if layers_to_files_needs_more_layers(&d.doc) { return Err(EngineError::Other("Layers to Files needs a document with multiple layers.".into())); @@ -109,6 +112,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& // The prefix is optional; only the layer name needs the empty-name fallback. let prefix_part = if prefix.is_empty() { String::new() } else { part(&prefix) }; let name = format!("{prefix_part}_{:04}_{}.{format}", index, part(&l.name)); + let save = include_icc(&mut one, &format, icc, save); let (bytes, _warnings) = encode(&one, &name, save)?; write(&name, &bytes)?; report.files.push(name); @@ -116,6 +120,20 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& Ok(report) } +/// Include ICC Profile for one layer file: off, no profile; on, the document's profile, or the one +/// its colours are taken to be in when it has none (PSD included), except that a CMYK document's +/// PNG (written as RGB) carries none, as measured. Unset changes nothing. Off only leaves the +/// profile out of the file (`save.embed_icc`): the document keeps it, since its colours (a CMYK +/// document's conversion to RGB) are read through it. +fn include_icc(one: &mut Document, format: &str, icc: Option, mut save: SaveOpts) -> SaveOpts { + match icc { + Some(true) if format == "png" && one.mode == ColorMode::Cmyk => save.embed_icc = Some(false), + Some(true) if one.icc_profile.is_none() => one.icc_profile = Some(crate::color_cmds::working_profile(one.mode).to_bytes()), + _ => {} + } + save +} + /// Adjustment layers that can be represented as an RGB-only LUT, in document stack order. /// A LUT has no spatial coordinates, so masks and clipping geometry are deliberately stripped /// at bake time. Group adjustments need their enclosing group's compositing semantics and are diff --git a/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs new file mode 100644 index 00000000000..19f2b9c24ef --- /dev/null +++ b/crates/engine-core/src/cmd/file_cmds/layers_to_files_icc_tests.rs @@ -0,0 +1,183 @@ +//! Layers to Files: Include ICC Profile (#13973). `iccProfile: false` writes no profile in PNG, +//! JPEG, TIFF or PSD files; `true` embeds the document's profile (a CMYK document's JPEG its CMYK +//! profile, its PNG none); unset keeps what the export wrote before. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::*; + +fn session(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 8, "height": 6, "mode": mode, "depth": depth, "background": "backgroundColor", "backgroundColor": [0.8, 0.1, 0.1]})) + .unwrap(); + // One normal layer: Layers to Files refuses a Background-only document (#13968). + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + s +} + +/// The colour space of each written file's embedded profile (`None`: no profile), by extension. +fn profiles(s: &mut Session, format: &str, extra: Value) -> Vec<(String, Option)> { + let dir = tempfile::tempdir().unwrap(); + let mut p = json!({"dir": dir.path().to_string_lossy(), "prefix": "t", "format": format}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("file.export.layersToFiles", p).unwrap(); + r["files"] + .as_array() + .unwrap() + .iter() + .map(|f| { + let path = f.as_str().unwrap(); + let bytes = std::fs::read(path).unwrap(); + let doc = photocraft_io::import(path, &bytes).unwrap().document; + let space = doc.icc_profile.map(|icc| String::from_utf8_lossy(icc.get(16..20).unwrap()).trim().to_string()); + (format!("{:?}", doc.mode), space) + }) + .collect() +} + +const FORMATS: [&str; 4] = ["png", "jpg", "tif", "psd"]; + +/// RGB and CMYK documents at 8 and 16 bits. +const DOCS: [(&str, u32); 4] = [("rgb", 8), ("rgb", 16), ("cmyk", 8), ("cmyk", 16)]; + +fn one(s: &mut Session, format: &str, extra: Value) -> (String, Option) { + let files = profiles(s, format, extra); + assert_eq!(files.len(), 1, "{format}: one layer, one file"); + files.into_iter().next().unwrap() +} + +#[test] +fn off_writes_no_profile() { + for (mode, depth) in DOCS { + let mut s = session(mode, depth); + for format in FORMATS { + assert_eq!(one(&mut s, format, json!({"iccProfile": false})).1, None, "{mode}{depth} {format}"); + } + } +} + +#[test] +fn on_embeds_the_documents_profile() { + for depth in [8, 16] { + let mut s = session("rgb", depth); + for format in FORMATS { + assert_eq!(one(&mut s, format, json!({"iccProfile": true})), ("Rgb".into(), Some("RGB".into())), "rgb{depth} {format}"); + } + } + // The document's own profile, not a stand-in, when it has one. + let mut s = session("rgb", 8); + let own = crate::color_cmds::working_profile(ColorMode::Rgb).to_bytes(); + let dir = tempfile::tempdir().unwrap(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir.path().to_string_lossy(), "format": "jpg", "iccProfile": true})).unwrap(); + let path = r["files"][0].as_str().unwrap(); + let embedded = photocraft_io::import(path, &std::fs::read(path).unwrap()).unwrap().document.icc_profile; + assert_eq!(embedded.as_deref(), Some(&*own)); +} + +#[test] +fn a_cmyk_documents_jpeg_keeps_its_cmyk_profile_and_its_png_has_none() { + for depth in [8, 16] { + let mut s = session("cmyk", depth); + let on = json!({"iccProfile": true}); + assert_eq!(one(&mut s, "jpg", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} jpg"); + assert_eq!(one(&mut s, "tif", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} tif"); + assert_eq!(one(&mut s, "psd", on.clone()), ("Cmyk".into(), Some("CMYK".into())), "cmyk{depth} psd"); + assert_eq!(one(&mut s, "png", on), ("Rgb".into(), None), "cmyk{depth} png"); + } +} + +#[test] +fn unset_keeps_what_the_export_wrote_before() { + // As main wrote them before the param: flat RGB files and a CMYK document's PNG carry the + // RGB working profile; PSD files and CMYK JPEG and TIFF files carry none. + let rgb = Some("RGB".to_string()); + for depth in [8, 16] { + let mut s = session("rgb", depth); + let got: Vec<_> = FORMATS.iter().map(|f| one(&mut s, f, json!({})).1).collect(); + assert_eq!(got, vec![rgb.clone(), rgb.clone(), rgb.clone(), None], "rgb{depth}"); + let mut s = session("cmyk", depth); + let got: Vec<_> = FORMATS.iter().map(|f| one(&mut s, f, json!({})).1).collect(); + assert_eq!(got, vec![rgb.clone(), None, None, None], "cmyk{depth}"); + // `null` is unset too. + assert_eq!(one(&mut s, "png", json!({"iccProfile": null})).1, rgb, "cmyk{depth} null"); + } +} + +#[test] +fn a_bad_value_is_an_error_and_writes_nothing() { + let mut s = session("rgb", 8); + for bad in [json!("no"), json!(0), json!([false]), json!({})] { + let dir = tempfile::tempdir().unwrap(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir.path().to_string_lossy(), "format": "png", "iccProfile": bad})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0, "{bad}: nothing written"); + } + assert_eq!(s.active().unwrap().doc.icc_profile, None, "the document is untouched"); +} + +/// The pixels of each written file, decoded (RGBA, 0..1), and whether it carries a profile. +fn pixels(s: &mut Session, format: &str, extra: Value) -> Vec<(Vec<[f32; 4]>, bool)> { + let dir = tempfile::tempdir().unwrap(); + let mut p = json!({"dir": dir.path().to_string_lossy(), "prefix": "t", "format": format}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("file.export.layersToFiles", p).unwrap(); + r["files"] + .as_array() + .unwrap() + .iter() + .map(|f| { + let path = f.as_str().unwrap(); + let doc = photocraft_io::import(path, &std::fs::read(path).unwrap()).unwrap().document; + let icc = doc.icc_profile.is_some(); + (photocraft_compose::flatten(&doc).px.to_vec(), icc) + }) + .collect() +} + +#[test] +fn off_keeps_a_cmyk_documents_own_profile_for_its_colours() { + // A CMYK document tagged with a profile other than the built-in coated one, whose layer + // needs compositing (50 % opacity): its colours are converted through its own profile + // whether or not the file carries it (CodeRabbit on #16653). + for depth in [8, 16] { + let mut s = session("cmyk", depth); + s.execute("edit.assignProfile", json!({"profile": "coated-fogra39"})).unwrap(); + s.execute("layer.setProps", json!({"opacity": 0.5})).unwrap(); + let on = pixels(&mut s, "png", json!({"iccProfile": true})); + let off = pixels(&mut s, "png", json!({"iccProfile": false})); + let unset = pixels(&mut s, "png", json!({})); + assert_eq!(off[0].0, on[0].0, "cmyk{depth}: the same pixels with iccProfile false and true"); + assert_eq!(off[0].0, unset[0].0, "cmyk{depth}: the same pixels with iccProfile false and unset"); + for format in FORMATS { + assert!(pixels(&mut s, format, json!({"iccProfile": false})).iter().all(|(_, icc)| !icc), "cmyk{depth} {format}: no profile"); + } + let layered = pixels(&mut s, "tif", json!({"iccProfile": false, "tiffLayers": true})); + assert!(layered.iter().all(|(_, icc)| !icc), "cmyk{depth} layered tif: no profile"); + assert!(s.active().unwrap().doc.icc_profile.is_some(), "the document keeps its profile"); + } +} + +/// An Indexed Color document with an RGB profile: `iccProfile: false` writes no profile in any file, +/// the PSD included, which is written over its colour table (CodeRabbit on #16653), and the +/// layered TIFF; `true` keeps it in the PSD. +#[test] +fn an_indexed_documents_files_follow_the_setting() { + let mut s = session("rgb", 8); + s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})).unwrap(); + // The conversion flattens: a normal layer again (#13968). + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.mode, ColorMode::Indexed); + assert!(doc.icc_profile.is_some(), "the document keeps its profile"); + assert!(doc.layers.iter().any(|l| !doc.is_background(l.id)), "a layer to export"); + for format in ["png", "jpg", "tif", "psd", "bmp"] { + assert!(profiles(&mut s, format, json!({"iccProfile": false})).iter().all(|(_, icc)| icc.is_none()), "indexed {format}: no profile"); + } + let layered = profiles(&mut s, "tif", json!({"iccProfile": false, "tiffLayers": true})); + assert!(layered.iter().all(|(_, icc)| icc.is_none()), "indexed layered tif: no profile"); + assert_eq!(one(&mut s, "psd", json!({"iccProfile": true})).1, Some("RGB".into()), "indexed psd: the profile"); +} diff --git a/crates/engine-paint/src/cmd/retouch_cmds/clone.rs b/crates/engine-paint/src/cmd/retouch_cmds/clone.rs index 59c39ab183e..201990dfc21 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/clone.rs @@ -212,6 +212,11 @@ pub(super) fn clone_result(dmg: Rect, off: (i32, i32), aligned: bool, p: &Value, pub(super) fn blend_param(p: &Value, cmd: &str) -> Result { match p.get("mode").and_then(Value::as_str) { None => Ok(BlendMode::Normal), + // The Healing Brush's Replace row (#12101) is not a blend mode: the stroke copies the + // source, which `healing_brush` reads from the params itself. Here it only opens the live + // preview, whose texture the Replace stroke draws as it stands, through Normal. Every other + // command keeps refusing the word. + Some("replace") if cmd == "paint.healingBrush" => Ok(BlendMode::Normal), Some(m) => parse_blend(m).ok_or_else(|| bad(cmd, format!("unknown blend mode `{m}`"))), } } diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs index 642f8cd211b..db5a0e3fe72 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal.rs @@ -58,6 +58,10 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { let which = sample_layers(p, CMD)?; let source = super::clone_sampling::resolve(s, p, CMD)?; let mode = blend_param(p, CMD)?; + // The options bar's Replace row (#12101): the stroke copies the source pixels without the + // healing solve, composited through `mode` (Normal). It is the command's word, not a blend + // mode; `blend_param` already accepted it for this command alone. + let replace = p.get("mode").and_then(Value::as_str) == Some("replace"); let aligned = flag(p, "aligned", true); let map = clone_mapping(s, p, &stroke, CMD)?; let off = map.offset(); @@ -69,27 +73,34 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { let (g, cov) = pad_coverage(bounds, &cov, 2); let fmt = source.sample_format(surf); let src = clone_sample(pre, id, surf, which, &source, g, &map, wrap, CMD)?; - // The destination the texture is fitted to: the layer itself, or what the user sees when - // sampling several layers (so healing onto an empty layer matches the composite). - let dst = if wrap { - periodic::sample(pre, id, surf, which, g, CMD)? - } else if which == SampleLayers::Current { - Region::read(surf, g) - } else { - composite_region(pre, id, which, g, surf.format()) - }; - let dst = if fmt.alpha && !surf.format().alpha { super::clone_sampling::opaque_alpha(dst, surf.format()) } else { dst }; // The solver can reconstruct positive alpha from the destination boundary even where // no source pixel exists. Keep source availability separate from the solved channels. let alpha = super::alpha_index(&fmt); let has_source = |pixel: &[f32]| alpha.is_none_or(|a| pixel.get(a).is_some_and(|value| *value > 0.0)); - let mask: Vec = cov.iter().zip(src.data.chunks_exact(fmt.channels())).map(|(c, pixel)| *c > 0.0 && has_source(pixel)).collect(); - let mut healed = heal_region(&fmt, &src, &dst, &mask); - for (pixel, sample) in healed.data.chunks_exact_mut(fmt.channels()).zip(src.data.chunks_exact(fmt.channels())) { - if !has_source(sample) { - pixel.fill(0.0); + let healed = if replace { + // Replace (#12101): the sampled source as it stands, no solve against the + // destination. Pixels with no source stay transparent, as they do through the solver. + src + } else { + // The destination the texture is fitted to: the layer itself, or what the user sees when + // sampling several layers (so healing onto an empty layer matches the composite). + let dst = if wrap { + periodic::sample(pre, id, surf, which, g, CMD)? + } else if which == SampleLayers::Current { + Region::read(surf, g) + } else { + composite_region(pre, id, which, g, surf.format()) + }; + let dst = if fmt.alpha && !surf.format().alpha { super::clone_sampling::opaque_alpha(dst, surf.format()) } else { dst }; + let mask: Vec = cov.iter().zip(src.data.chunks_exact(fmt.channels())).map(|(c, pixel)| *c > 0.0 && has_source(pixel)).collect(); + let mut healed = heal_region(&fmt, &src, &dst, &mask); + for (pixel, sample) in healed.data.chunks_exact_mut(fmt.channels()).zip(src.data.chunks_exact(fmt.channels())) { + if !has_source(sample) { + pixel.fill(0.0); + } } - } + healed + }; if wrap { return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, fmt, |_, r| { let part = healed.crop(r); @@ -314,3 +325,7 @@ pub(super) fn spot_healing(s: &mut Session, p: &Value) -> Result { #[cfg(test)] #[path = "heal_indexed_tests.rs"] mod heal_indexed_tests; + +#[cfg(test)] +#[path = "heal_replace_tests.rs"] +mod heal_replace_tests; diff --git a/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs b/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs new file mode 100644 index 00000000000..149dab07f5b --- /dev/null +++ b/crates/engine-paint/src/cmd/retouch_cmds/heal_replace_tests.rs @@ -0,0 +1,173 @@ +//! #12101: the Healing Brush's Replace mode. `paint.healingBrush {"mode":"replace"}` copies the +//! source pixels straight onto the layer: no healing solve, Normal compositing. Every pixel of the +//! tip's full-coverage disc equals the source pixel the stroke maps there, bit for bit, as read +//! from the document's state before the stroke (221 px for the 20 px hard tip); past that disc +//! Replace lays the same source through the antialiased rim's coverage - strictly between ground +//! and source. The other modes keep their results; an unknown `mode` string stays an error, and +//! the stroke's History step keeps the name "Healing Brush". + +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_doc::Size; + +use super::*; + +/// The test document: green 40,160,60 throughout with a 20 x 20 checker at 6,6 (5 px cells +/// alternating 60,60,60 / 200,200,200). The source patch and the click sit far apart, so a +/// straight copy and a heal cannot agree anywhere inside the dab. +fn document() -> Session { + let mut s = crate::session(); + s.add_document( + Document::with_background("t", Size::new(48, 48), ColorMode::Rgb, SampleType::U8, Color::rgb(40.0 / 255.0, 160.0 / 255.0, 60.0 / 255.0)), + None, + ); + for cx in 0..4 { + for cy in 0..4 { + let color = if (cx + cy) % 2 == 0 { "#3c3c3c" } else { "#c8c8c8" }; + s.execute("select.rect", json!({"x": 6 + 5 * cx, "y": 6 + 5 * cy, "width": 5, "height": 5})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + } + } + s.execute("select.deselect", json!({})).unwrap(); + s +} + +/// One click at 30,24 with a 20 px hard round tip; the source point 16,16 is sampled under it. +fn stroke(mode: Option<&str>) -> Value { + let mut p = json!({"points": [[30, 24]], "source": [16, 16], "size": 20, "hardness": 100}); + if let Some(m) = mode { + p["mode"] = json!(m); + } + p +} + +fn pixels(s: &Session) -> Vec { + let st = s.active().unwrap(); + let surf = st.doc.layers[0].surface().unwrap(); + (0..48).flat_map(|y| (0..48).flat_map(move |x| surf.pixel(x, y))).collect() +} + +/// The pixel of the Background at (`x`, `y`). +fn pixel(s: &Session, x: i32, y: i32) -> Vec { + let st = s.active().unwrap(); + st.doc.layers[0].surface().unwrap().pixel(x, y) +} + +#[test] +fn replace_paints_the_source_pixels_bit_for_bit() { + let mut s = document(); + let before = pixels(&s); + let steps = s.active().unwrap().history.past_len(); + s.execute("paint.healingBrush", stroke(Some("replace"))).unwrap(); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Healing Brush"), "the stroke's History name"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "the stroke is one step"); + // Every pixel the hard tip covers fully (out to 8.48 px of its 10 px radius, away from the + // antialiased rim) is the source pixel mapped there, bit for bit; the samples are the + // pre-stroke pixels. + let green: Vec = vec![40.0 / 255.0, 160.0 / 255.0, 60.0 / 255.0, 1.0]; + let ch = pixel(&s, 0, 0).len(); + let src = |x: i32, y: i32| { + let at = usize::try_from(y * 48 + x).unwrap() * ch; + before[at..at + ch].to_vec() + }; + let mut inside = 0; + for dy in -9i32..=9 { + for dx in -9i32..=9 { + // The exact-copy disc reaches to a pixel-centre distance under 9 px of the 10 px hard + // tip: (6, 6) has its centre at 9.19 px and already sits in the antialiased rim, where + // Replace lays the source through its coverage (the hardness-50 test below pins that). + let (ax, ay) = (f64::from(dx.abs()) + 0.5, f64::from(dy.abs()) + 0.5); + if ax * ax + ay * ay >= 81.0 { + continue; + } + let (x, y) = (30 + dx, 24 + dy); + assert_eq!(pixel(&s, x, y), src(x - 14, y - 8), "({x}, {y}) inside the Replace dab"); + inside += 1; + } + } + // The exact-copy disc this engine gives for a 20 px hard tip: 221 pixels (widened from the + // first round's r = 7 disc of 149; the rim test covers what lies beyond). + assert_eq!(inside, 221, "the loop's own shape"); + // Outside the tip nothing changed: the dab's edge is 10 px away, these are 13. + assert_eq!(pixel(&s, 43, 24), green, "right of the dab"); + assert_eq!(pixel(&s, 30, 37), green, "below the dab"); +} + +#[test] +fn replace_at_partial_coverage_lays_the_source_through_the_coverage() { + // The rim of Replace is coverage, not a hard copy edge: a pixel the tip covers only partly + // takes the source pixel composited over the ground by that coverage - strictly between the + // two, and neither one exactly. (The reference's rim, measured on its own document, is about + // 1 px wider than ours; the exact rim width here is not measured.) + let mut s = document(); + let before = pixels(&s); + let mut p = stroke(Some("replace")); + p["hardness"] = json!(50); + s.execute("paint.healingBrush", p).unwrap(); + let q = |v: f32| (v * 255.0).round() as i32; + let lvl = |x: i32, y: i32| { + let at = usize::try_from(y * 48 + x).unwrap() * 4; + [before[at], before[at + 1], before[at + 2]].map(q) + }; + // The tip's centre still holds the full copy: source 6,6..26 puts a 60-cell under the centre. + let centre = pixel(&s, 30, 24); + assert_eq!(centre.iter().map(|&v| q(v)).collect::>(), vec![60, 60, 60, 255], "centre: straight copy at full coverage"); + // 8 px out on a hardness-50 tip the coverage is partial: over the pre-stroke green the 200 + // cell now lies at about 40 %, so the levels sit strictly between the ground and the source. + let rim = pixel(&s, 38, 24).iter().map(|&v| q(v)).collect::>(); + let (src, ground) = (lvl(24, 16), [40, 160, 60]); // the 200-cell source pixel this rim copies from + assert_eq!(src, [200, 200, 200], "fixture check: the rim samples a 200-cell"); + for c in 0..3 { + assert!( + rim[c] > ground[c].min(src[c]) && rim[c] < ground[c].max(src[c]), + "rim {rim:?} channel {c}: between ground {ground:?} and source {src:?}, not either" + ); + } + // And not the full copy the interior shows. + assert_ne!(rim[..3], [200, 200, 200], "the rim is not a hard copy to the tip edge"); +} + +#[test] +fn an_unknown_mode_is_an_error_and_paints_nothing() { + let mut s = document(); + let before = (pixels(&s), s.active().unwrap().history.past_len()); + let err = s.execute("paint.healingBrush", stroke(Some("threshold"))).unwrap_err().to_string(); + assert!(err.contains("unknown blend mode `threshold`"), "{err}"); + assert_eq!((pixels(&s), s.active().unwrap().history.past_len()), (before.0.clone(), before.1), "nothing painted, no step"); +} + +#[test] +fn replace_is_the_healing_brush_command_s_alone() { + let mut s = document(); + let err = s + .execute("paint.cloneStamp", json!({"points": [[30, 24]], "source": [16, 16], "size": 20, "hardness": 100, "mode": "replace"})) + .unwrap_err() + .to_string(); + assert!(err.contains("unknown blend mode `replace`"), "the Clone Stamp still refuses it: {err}"); + // The live stroke parser reads the same mode: a Healing live stroke starts with Replace. + crate::cmd::retouch_cmds::clone::LiveRetouch::begin(&s, "paint.healingBrush", &stroke(Some("replace"))).unwrap(); + // And the blend parameter itself: Normal compositing for the Healing Brush, nothing else. + assert_eq!(blend_param(&json!({"mode": "replace"}), "paint.healingBrush").unwrap(), BlendMode::Normal); + assert!(blend_param(&json!({"mode": "replace"}), "paint.cloneStamp").is_err()); + assert!(blend_param(&json!({"mode": "Replace"}), "paint.healingBrush").is_err(), "the exact lowercase string only"); +} + +#[test] +fn normal_heals_the_same_pixels_as_before() { + // Pin the healed (not copied) result byte for byte: the values from main 984c304b20. If one of + // these moves, a mode the ticket leaves alone moved with it. + let mut s = document(); + s.execute("paint.healingBrush", stroke(Some("normal"))).unwrap(); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Healing Brush")); + let q = |v: f32| (v * 255.0).round() as i32; + let pts = [(30, 24), (34, 26), (26, 22), (24, 24)]; + let got: Vec> = pts.iter().map(|(x, y)| pixel(&s, *x, *y).iter().map(|&v| q(v)).collect()).collect(); + // The values main 984c304b20 gives on this document (R, G, B, A in 8-bit levels). + let pinned: Vec> = vec![vec![62, 56, 61, 255], vec![57, 63, 58, 255], vec![77, 49, 73, 255], vec![82, 53, 77, 255]]; + assert_eq!(got, pinned, "the Normal result is pinned"); + // Replace on the same document gives different pixels than Normal: the straight copy and the + // blend are visibly two different strokes. + let mut r = document(); + r.execute("paint.healingBrush", stroke(Some("replace"))).unwrap(); + let replaced: Vec> = pts.iter().map(|(x, y)| pixel(&r, *x, *y).iter().map(|&v| q(v)).collect()).collect(); + assert_ne!(got, replaced, "Replace is not Normal"); +} diff --git a/crates/engine/tests/it/atn_content_aware_fill.rs b/crates/engine/tests/it/atn_content_aware_fill.rs index 3c7c4b7c521..736508633d8 100644 --- a/crates/engine/tests/it/atn_content_aware_fill.rs +++ b/crates/engine/tests/it/atn_content_aware_fill.rs @@ -152,10 +152,11 @@ fn caf_edited_settings_export_without_stale_wire_metadata() { } /// Missing defaults, malformed/repeated fields and unrepresented workspace state stay complete. +/// An empty descriptor plays with the remembered settings (`atn_cmds/caf_action_values_tests.rs`). #[test] fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { let base = descriptor(); - let mut cases = vec![Descriptor::new("null"), base.clone().with("extra", D::Boolean(true))]; + let mut cases = vec![base.clone().with("extra", D::Boolean(true))]; for i in 0..base.items.len() { let mut missing = base.clone(); missing.items.remove(i); @@ -167,20 +168,9 @@ fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { wrong.items[i].1 = D::Integer(0); cases.push(wrong); } - for (i, key, value) in [ - (0, "cafSamplingRegion", "cafSamplingRegionAuto"), - (0, "cafSamplingRegion", "cafSamplingRegionCustom"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationNone"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationHigh"), - (2, "cafColorAdaptationLevel", "cafColorAdaptationVeryHigh"), - (2, "cafColorAdaptationLevel", "unknown"), - (3, "cafRotationAmount", "cafRotationAmountLow"), - (3, "cafRotationAmount", "cafRotationAmountMedium"), - (3, "cafRotationAmount", "cafRotationAmountHigh"), - (3, "cafRotationAmount", "cafRotationAmountFull"), - (3, "cafRotationAmount", "unknown"), - (6, "cafOutput", "cafOutputToDuplicateLayer"), - ] { + for (i, key, value) in + [(0, "cafSamplingRegion", "unknown"), (2, "cafColorAdaptationLevel", "unknown"), (3, "cafRotationAmount", "unknown"), (6, "cafOutput", "unknown")] + { let mut d = base.clone(); d.items[i].1 = enm(key, value); cases.push(d); @@ -213,28 +203,25 @@ fn caf_unrepresented_descriptors_are_kept_and_never_partially_play() { /// Known native defaults become explicit values; unsupported defaults/options cannot disappear. #[test] fn caf_native_exports_preserve_effective_defaults_and_refuse_unrepresented_options() { - for p in [json!({"sampling":"rectangular","output":"new"}), json!({"sampling":"rectangular","output":"new","seed":1,"target":"pixels"}), params()] { + for p in [ + json!({"sampling":"rectangular","sampleAllLayers":false,"output":"new"}), + json!({"sampling":"rectangular","sampleAllLayers":false,"output":"new","seed":1,"target":"pixels"}), + params(), + ] { let a = load(exported(p).unwrap().descriptor.unwrap()); assert_eq!(a.steps, vec![ActionStep::new(CMD, params())]); } let mut current = params(); current["output"] = json!("current"); - for p in [json!({"sampling":"rectangular"}), current.clone()] { + for p in [json!({"sampling":"rectangular","sampleAllLayers":false}), current.clone()] { let a = load(exported(p).unwrap().descriptor.unwrap()); assert_eq!(a.steps, vec![ActionStep::new(CMD, current.clone())]); } for (key, value) in [ - ("sampling", json!("auto")), - ("sampling", json!("custom")), ("sampling", json!("unknown")), - ("output", json!("duplicate")), - ("colorAdaptation", json!("none")), - ("colorAdaptation", json!("high")), - ("colorAdaptation", json!("veryHigh")), - ("rotationAdaptation", json!("low")), - ("rotationAdaptation", json!("medium")), - ("rotationAdaptation", json!("high")), - ("rotationAdaptation", json!("full")), + ("output", json!("unknown")), + ("colorAdaptation", json!("unknown")), + ("rotationAdaptation", json!("unknown")), ("sampleAllLayers", json!(0)), ("scale", Value::Null), ("mirror", json!("true")), @@ -252,8 +239,19 @@ fn caf_native_exports_preserve_effective_defaults_and_refuse_unrepresented_optio p[key] = value; assert!(exported(p.clone()).is_none(), "{p}"); } - for p in [json!({}), json!({"output":"new"}), json!([])] { - assert!(exported(p.clone()).is_none(), "unrepresented native default: {p}"); + // The command's own defaults (Auto, Current Layer) are written out explicitly. + let mut defaults = params(); + defaults["sampling"] = json!("auto"); + defaults["output"] = json!("current"); + let a = load(exported(json!({"sampleAllLayers":false})).unwrap().descriptor.unwrap()); + assert_eq!(a.steps, vec![ActionStep::new(CMD, defaults.clone())]); + defaults["output"] = json!("new"); + let a = load(exported(json!({"sampleAllLayers":false,"output":"new"})).unwrap().descriptor.unwrap()); + assert_eq!(a.steps, vec![ActionStep::new(CMD, defaults)]); + assert!(exported(json!([])).is_none()); + // Without `sampleAllLayers` an empty layer samples the composite, and a recorded false would not. + for p in [json!({}), json!({"output":"new"}), json!({"colorAdaptation":"none"}), json!({"sampling":"rectangular"})] { + assert!(exported(p.clone()).is_none(), "unrepresented sampling: {p}"); } } diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 8819e5f778e..658849859ea 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -298,22 +298,41 @@ fn offset(angle: f32, distance: f32) -> (f32, f32) { ((-a.cos() * distance).round(), (a.sin() * distance).round()) } +/// Which shape supplies the distance fields for a layer style stroke. +#[derive(Clone, Copy)] +pub(crate) enum StrokeShape { + Raster, + VectorOutline, + Other, +} + +impl StrokeShape { + pub(crate) fn of(layer: &Layer) -> Self { + match &layer.content { + LayerContent::Raster(_) => Self::Raster, + LayerContent::Shape(_) if photocraft_compose::effect_outline(layer).is_none() => Self::VectorOutline, + _ => Self::Other, + } + } +} + /// The map program of one enabled effect (`build_maps`), without pattern sources. #[cfg(test)] pub(crate) fn program(e: &Effect, light: &GlobalLight, vector_shape: bool) -> MapProgram { - program_with(e, light, vector_shape, &[], (0.0, 0.0)) + let shape = if vector_shape { StrokeShape::VectorOutline } else { StrokeShape::Raster }; + program_with(e, light, shape, &[], (0.0, 0.0)) } /// The map program of one enabled effect (`build_maps`); bevel textures tile `patterns` from /// `anchor` (`effects::TextureCtx`). -pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool, patterns: &[Pattern], anchor: (f64, f64)) -> MapProgram { +pub(crate) fn program_with(e: &Effect, light: &GlobalLight, stroke_shape: StrokeShape, patterns: &[Pattern], anchor: (f64, f64)) -> MapProgram { let mut b = B { stages: Vec::new(), fields: Vec::new() }; let maps = match e { Effect::DropShadow(s) | Effect::InnerShadow(s) => b.shadow(s, light, matches!(e, Effect::InnerShadow(_))), Effect::OuterGlow(g) | Effect::InnerGlow(g) => b.glow(g, matches!(e, Effect::InnerGlow(_))), Effect::Satin(s) => b.satin(s), Effect::BevelEmboss(bv) => b.bevel(bv, light, patterns, anchor), - Effect::Stroke(st) => b.stroke(st, vector_shape), + Effect::Stroke(st) => b.stroke(st, stroke_shape), Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } | Effect::PatternOverlay { .. } => return MapProgram::empty(), }; MapProgram { key: b.key(maps), maps, stages: b.stages, fields: b.fields } @@ -554,6 +573,7 @@ pub(crate) fn group_key(layer: &Layer, light: &GlobalLight, pin: &mut dyn FnMut( } fn walk(l: &Layer, h: &mut std::collections::hash_map::DefaultHasher, pin: Pin) { l.id.0.hash(h); + std::mem::discriminant(&l.content).hash(h); (l.visible, l.clipped, l.opacity.to_bits(), l.fill_opacity.to_bits(), format!("{:?}", l.blend)).hash(h); match &l.content { LayerContent::Group(g) => { diff --git a/crates/gpu/src/fx/builders.rs b/crates/gpu/src/fx/builders.rs index 633382b8fe0..ff48eae03ae 100644 --- a/crates/gpu/src/fx/builders.rs +++ b/crates/gpu/src/fx/builders.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use photocraft_compose::effects::{self as fx, BevelGeom, BevelPaint, FieldKind}; use photocraft_doc::{Bevel, BevelTechnique, BevelTexture, GlobalLight, Glow, GlowSource, GlowTechnique, Pattern, Satin, Shadow, StrokeFx}; -use super::{B, In, contour_lut, offset, stage}; +use super::{B, In, StrokeShape, contour_lut, offset, stage}; use crate::plan::{Kernel, stroke_widths}; /// A flag as the shaders read it: 1.0 or 0.0. @@ -178,13 +178,13 @@ impl B { } /// Stroke stages, the outside band into map 0 and the inside band into map 1. Returns 2. - pub(super) fn stroke(&mut self, st: &StrokeFx, vector_shape: bool) -> usize { + pub(super) fn stroke(&mut self, st: &StrokeFx, shape: StrokeShape) -> usize { // Stroke bands: map 0 outside, map 1 inside. let (in_w, out_w) = stroke_widths(st); if out_w > 0.0 { // Narrow strokes keep the fitted chamfer, wide ones the exact transform (#3646); // the CPU picks the same field by the same width (`stroke_outside_exact`). - let kind = match (vector_shape, fx::stroke_outside_exact(out_w)) { + let kind = match (matches!(shape, StrokeShape::VectorOutline), fx::stroke_outside_exact(out_w)) { (true, true) => FieldKind::StrokeOutsideVector, (true, false) => FieldKind::StrokeOutsideVectorChamfer, (false, true) => FieldKind::StrokeOutsideExact, @@ -193,7 +193,8 @@ impl B { self.stroke_band(kind, out_w, 0); } if in_w > 0.0 { - self.stroke_band(FieldKind::StrokeInside, in_w, 1); + let kind = if matches!(shape, StrokeShape::Raster) { FieldKind::StrokeInsideRaster } else { FieldKind::StrokeInside }; + self.stroke_band(kind, in_w, 1); } 2 } diff --git a/crates/gpu/src/fx/tests.rs b/crates/gpu/src/fx/tests.rs index 06342c2fb20..a8d3667e635 100644 --- a/crates/gpu/src/fx/tests.rs +++ b/crates/gpu/src/fx/tests.rs @@ -122,6 +122,7 @@ fn banded_fields_match_whole_region_within_reach() { FieldKind::ChokeInside, FieldKind::StrokeOutside, FieldKind::StrokeInside, + FieldKind::StrokeInsideRaster, FieldKind::StrokeOutsideExact, FieldKind::StrokeOutsideVector, FieldKind::StrokeOutsideVectorChamfer, @@ -266,7 +267,7 @@ fn a_stroke_uses_the_chamfer_narrow_and_the_exact_field_wide() { let vector_wide = program(&stroke(40.0, StrokePosition::Outside), &light, true); assert!(vector_wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVector), "{:?}", vector_wide.fields); let inner = program(&stroke(40.0, StrokePosition::Inside), &light, false); - assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInside), "{:?}", inner.fields); + assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInsideRaster), "{:?}", inner.fields); // The shadow / softer-glow spread is unchanged: still the chamfer. let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() }; s.spread = 0.5; diff --git a/crates/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs index 615677d8403..a02b81b6112 100644 --- a/crates/gpu/src/fx_passes.rs +++ b/crates/gpu/src/fx_passes.rs @@ -114,10 +114,10 @@ impl Compositor { // Programs, and the distance fields they read (max reach per field). // Filled shapes stroke their outline (the effect shape); others estimate it. - let vector_shape = matches!(layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(layer).is_none(); + let stroke_shape = fx::StrokeShape::of(layer); let anchor = layer.effects.reference.unwrap_or((f64::from(f.bounds.x0), f64::from(f.bounds.y0))); let progs: Vec = - layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, anchor)).collect(); + layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, stroke_shape, &doc.patterns, anchor)).collect(); let want = field_reaches(&progs); e.fields.retain(|k, _| want.contains_key(k)); // Each field to recompute: over which rectangle, exact up to which reach. diff --git a/crates/gpu/src/setup.rs b/crates/gpu/src/setup.rs index 3a961074991..3faeb5c8bb4 100644 --- a/crates/gpu/src/setup.rs +++ b/crates/gpu/src/setup.rs @@ -4,7 +4,7 @@ use super::kit::{Kit, tex_entry, uniform_entry}; use super::paging::{cell_rect, field_reaches, first_error, grid_rects}; use super::pipelines::{NO_EFFECT_MAPS, Pipelines}; use super::textures::{FxEntry, Resident, Tex, TexKind}; -use super::{Compositor, DeviceHealth, DocId, Document, Fault, HashMap, LayerContent, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing}; +use super::{Compositor, DeviceHealth, DocId, Document, Fault, HashMap, Plan, Rect, Role, TILE_SIZE, Unsupported, fx, plan, prefix, timing}; /// Classification of a synchronous compositor pipeline build failure. /// @@ -356,14 +356,14 @@ impl Compositor { /// How far beyond a page cell the effect maps of `f` must be computed to be exact in it. pub(crate) fn fx_apron(doc: &Document, f: &plan::FxLayer<'_>) -> i32 { - let vector_shape = matches!(f.layer.content, LayerContent::Shape(_)) && photocraft_compose::effect_outline(f.layer).is_none(); + let stroke_shape = fx::StrokeShape::of(f.layer); let progs: Vec = f .layer .effects .items .iter() .filter(|e| e.enabled()) - .map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, (0.0, 0.0))) + .map(|e| fx::program_with(e, &doc.global_light, stroke_shape, &doc.patterns, (0.0, 0.0))) .collect(); let want = field_reaches(&progs); // Distance fields are exact one pixel inside the window they are computed from. @@ -394,7 +394,7 @@ impl Compositor { if noisy { return Err(Unsupported(format!("effect noise on `{}` uses the CPU path", f.layer.name))); } - for s in fx::program_with(e, &doc.global_light, false, &doc.patterns, (0.0, 0.0)).stages { + for s in fx::program_with(e, &doc.global_light, fx::StrokeShape::Other, &doc.patterns, (0.0, 0.0)).stages { if s.lut.as_ref().is_some_and(|l| l.len() > 4096) { return Err(Unsupported(format!("effect blur on `{}` too wide for the GPU path", f.layer.name))); } diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 6c68854ffcb..d3ffa24f21e 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -2029,6 +2029,29 @@ fn semi_transparent_normal_stroke_knocks_out_the_layer_beneath_it() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } +#[test] +fn stroke_on_partial_raster_alpha_matches_on_gpu_across_page_boundaries() { + let Some(mut g) = gpu() else { return }; + let mut doc = Document::with_background("Partial alpha strokes", Size::new(540, 300), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut layer = Layer::raster("Orange blocks", doc.pixel_format()); + let surface = layer.surface_mut().unwrap(); + for (x, alpha) in [(20, 1.0), (236, 0.5), (460, 0.25)] { + surface.fill_rect(Rect::from_xywh(x, 40, 44, 220), &[1.0, 128.0 / 255.0, 0.0, alpha]); + } + doc.layers.push(layer); + for (position, size) in [(StrokePosition::Inside, 5.0), (StrokePosition::Center, 6.0), (StrokePosition::Outside, 5.0)] { + doc.layers[1].effects.items = vec![Effect::Stroke(stroke(size, position, FxPaint::Color(Color::rgb(0.0, 0.0, 1.0))))]; + let stats = fx_check(&mut g, &doc, &format!("{position:?} stroke across pages")); + assert!(stats.passes > 0, "the GPU rendered the effect"); + } + + // Retouching the same tile from translucent to opaque must invalidate its inside field. + doc.layers[1].effects.items = vec![Effect::Stroke(stroke(5.0, StrokePosition::Inside, FxPaint::Color(Color::rgb(0.0, 0.0, 1.0))))]; + fx_check(&mut g, &doc, "cached inside stroke"); + doc.layers[1].surface_mut().unwrap().fill_rect(Rect::from_xywh(248, 112, 24, 32), &[1.0, 128.0 / 255.0, 0.0, 1.0]); + fx_check(&mut g, &doc, "inside stroke after changing partial alpha"); +} + #[test] fn exterior_effects_merge_from_the_shape_at_any_fill() { // Drop shadows and outer glows alone: the merge builds the layer from its shape (fill inside diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b18d4782093..b8791076908 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1276,6 +1276,7 @@ fn export_stages_with_renderer( document_path: opts.document_path.clone(), read_linked_files: opts.read_linked_files, stage_on_scratch_from: Some(psd_export::STAGE_DOCUMENTS_FROM), + embed_icc: opts.encode.embed_icc, ..Default::default() }; // The preview is rendered first, while only the document is in memory: its full-size diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 1f2a3a3e3ad..8f1e054a574 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -80,6 +80,9 @@ pub struct PsdExportOptions { /// pixel bytes (layers and composite) reach this and spilling is on (`None`: never). The /// save then holds the file model's structure, not a second copy of its pixels (#5333). pub stage_on_scratch_from: Option, + /// Write the document's ICC profile (resource 1039). Off leaves it out of the file only: the + /// document's colours are still read through it (a CMYK document's layers and merged image). + pub embed_icc: bool, } impl Default for PsdExportOptions { @@ -93,6 +96,7 @@ impl Default for PsdExportOptions { document_path: None, read_linked_files: true, stage_on_scratch_from: None, + embed_icc: true, } } } diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index 1755a37ee66..16a48c52493 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -66,7 +66,11 @@ fn document_to_psd_sized_with_patterns( if doc.mode == ColorMode::Multichannel { return crate::multichannel_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns); } - if let Some(file) = crate::palette_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns)? { + if let Some(mut file) = crate::palette_map::document_to_psd(doc, opts.force_psb, layerless_limit, patterns)? { + // An Indexed document's RGB profile is written there too; Include ICC Profile off leaves it out. + if !opts.embed_icc { + file.0.resources.retain(|r| r.id != ids::ICC_PROFILE); + } return Ok(file); } let fmt = doc.pixel_format(); @@ -149,7 +153,7 @@ fn export_supported_document( ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()), ]; - if let Some(icc) = &doc.icc_profile { + if let Some(icc) = doc.icc_profile.as_ref().filter(|_| opts.embed_icc) { resources.push(ImageResource::new(ids::ICC_PROFILE, icc.to_vec())); } if !doc.guides.horizontal.is_empty() || !doc.guides.vertical.is_empty() { diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index 2284c4e86ab..89c8b164792 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -862,3 +862,36 @@ fn a_type_layer_without_a_writable_tysh_drops_its_imported_block() { assert!(!written.blocks.iter().any(|b| b.key == *b"TySh"), "the stale imported TySh is dropped"); assert!(warnings.iter().any(|w| w.contains("no TySh data")), "{warnings:?}"); } + +/// `embed_icc: false` leaves the ICC profile resource out of the file (the document keeps it); +/// on (the default), the file carries it. +#[test] +fn embed_icc_off_writes_no_profile_resource() { + let mut doc = Document::new("icc", photocraft_geom::Size::new(4, 4), ColorMode::Rgb, SampleType::U8); + doc.layers.push(Layer::raster("Layer 1", doc.pixel_format())); + doc.icc_profile = Some(std::sync::Arc::new(craft_cms::Builtin::Srgb.profile().to_bytes().to_vec())); + let has = |opts: &PsdExportOptions| document_to_psd_with(&doc, opts).unwrap().0.resources.iter().any(|r| r.id == ids::ICC_PROFILE); + assert!(has(&PsdExportOptions::default())); + assert!(!has(&PsdExportOptions { embed_icc: false, ..Default::default() })); + assert!(doc.icc_profile.is_some()); +} + +/// An Indexed Color document is written over its colour table (`palette_map`): `embed_icc: false` +/// leaves its RGB profile out there too, as PSD and as PSB (CodeRabbit on #16653). +#[test] +fn embed_icc_off_writes_no_profile_resource_for_an_indexed_document() { + let white = photocraft_color::Color::rgba(1.0, 1.0, 1.0, 1.0); + let mut doc = Document::with_background("indexed", photocraft_geom::Size::new(4, 4), ColorMode::Rgb, SampleType::U8, white); + doc.mode = ColorMode::Indexed; + doc.color_table = Some(photocraft_doc::ColorTable { colors: vec![[255, 255, 255], [0, 0, 0]], transparent: None }); + doc.icc_profile = Some(std::sync::Arc::new(craft_cms::Builtin::Srgb.profile().to_bytes().to_vec())); + for force_psb in [false, true] { + let written = |embed_icc| document_to_psd_with(&doc, &PsdExportOptions { embed_icc, force_psb, ..Default::default() }).unwrap().0; + let on = written(true); + assert_eq!(on.header.color_mode, PsdMode::Indexed, "psb {force_psb}"); + assert!(on.resources.iter().any(|r| r.id == ids::ICC_PROFILE), "psb {force_psb}: on"); + let off = written(false); + assert_eq!((off.header.color_mode, off.header.version == Version::Psb), (PsdMode::Indexed, force_psb)); + assert!(!off.resources.iter().any(|r| r.id == ids::ICC_PROFILE), "psb {force_psb}: off"); + } +} diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 0c21f3ea197..f0814956daf 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -368,6 +368,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr read_linked_files: opts.read_linked_files, // The layered TIFF reads the merged image's bytes directly: they stay in memory. stage_on_scratch_from: None, + embed_icc: opts.encode.embed_icc, }; // TIFF has no palette, bitmap or duotone layout: the PSD model of an Indexed Color, Bitmap // or Duotone document is made in its pixel format (RGB or Grayscale), which the PSD exporter diff --git a/crates/ui-egui/src/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs index 4b1637a3367..8064d1ba62d 100644 --- a/crates/ui-egui/src/brush_mode_menu.rs +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -20,6 +20,9 @@ pub(crate) enum Item { Separator, /// The tool's blend mode. Blend(BlendMode), + /// The Healing Brush's Replace row (#12101): copy the source without healing. It is not a + /// blend mode: the stroke sends it as a mode word, and the keys and the ⇧+ / ⇧− cycle skip it. + HealingReplace, /// Painting-only: paint behind the layer's pixels (Brush, Pencil and Pattern Stamp). Behind, /// Painting-only: paint transparency (Brush, Pencil, Paint Bucket). @@ -39,6 +42,7 @@ impl Item { Item::EditBrush => "Edit Brush…", Item::Separator => return None, Item::Blend(m) => m.label(), + Item::HealingReplace => "Replace", Item::Behind => "Behind", Item::Clear => "Clear", Item::Eraser(m) => match m { @@ -98,8 +102,8 @@ fn blend_items(behind: bool, clear: bool) -> Vec { /// `tool`'s menu, top to bottom. Empty for a tool without one (its Shift+right-click keeps its /// other route). Only what the tool's options bar offers is listed: the reference application's -/// Behind for the Clone Stamp, History Brush, Gradient and Paint Bucket, the Blur, Sharpen and Smudge -/// modes, the Spot Healing modes and the Healing Brush's source and Replace have no setting here. +/// Behind for the Clone Stamp, History Brush, Gradient and Paint Bucket, the Blur, Sharpen and +/// Smudge modes, the Spot Healing modes and the Healing Brush's source have no setting here. pub(crate) fn items(tool: Tool) -> Vec { let with_brush = |rest: Vec| std::iter::once(Item::EditBrush).chain(std::iter::once(Item::Separator)).chain(rest).collect::>(); match tool { @@ -110,7 +114,22 @@ pub(crate) fn items(tool: Tool) -> Vec { Tool::Eraser => ["brush", "pencil", "block"].into_iter().map(Item::Eraser).collect(), Tool::Dodge | Tool::Burn => with_brush(["shadows", "midtones", "highlights"].into_iter().map(Item::Range).collect()), Tool::Sponge => with_brush(["desaturate", "saturate"].into_iter().map(Item::Sponge).collect()), - Tool::Healing => crate::blend_keys::HEALING_MODES.into_iter().map(Item::Blend).collect(), + // The measured list (#12101): Replace after Normal, rules before Multiply and before Color. + Tool::Healing => { + use BlendMode::*; + vec![ + Item::Blend(Normal), + Item::HealingReplace, + Item::Separator, + Item::Blend(Multiply), + Item::Blend(Screen), + Item::Blend(Darken), + Item::Blend(Lighten), + Item::Separator, + Item::Blend(Color), + Item::Blend(Luminosity), + ] + } Tool::Gradient => blend_items(false, false), Tool::PaintBucket => blend_items(false, true), _ => Vec::new(), @@ -151,7 +170,15 @@ pub(crate) fn current(app: &PhotocraftApp, tool: Tool) -> Option { Tool::Brush => painting(o.brush_clear), Tool::Pencil => painting(o.pencil_clear), Tool::PatternStamp => painting(false), - Tool::CloneStamp | Tool::HistoryBrush | Tool::Healing => Item::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)), + Tool::CloneStamp | Tool::HistoryBrush => Item::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)), + // Replace wins over the brush's blend mode: it is the row the tool option selects (#12101). + Tool::Healing => { + if o.healing_replace { + Item::HealingReplace + } else { + Item::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)) + } + } Tool::Gradient => Item::Blend(o.gradient_blend_mode), Tool::PaintBucket if o.bucket_clear => Item::Clear, Tool::PaintBucket => Item::Blend(o.bucket_blend_mode), @@ -231,6 +258,8 @@ pub(crate) fn choose(app: &mut PhotocraftApp, item: Item) { Ok(_) => match tool { Tool::Brush => app.ui.tool_options.brush_clear = item == Item::Clear, Tool::Pencil => app.ui.tool_options.pencil_clear = item == Item::Clear, + // Any of the seven blend modes leaves Replace (#12101). + Tool::Healing => app.ui.tool_options.healing_replace = false, _ => {} }, Err(e) => app.ui.status = e, @@ -246,6 +275,8 @@ pub(crate) fn choose(app: &mut PhotocraftApp, item: Item) { Item::Eraser(m) => app.ui.tool_options.eraser_mode = m.into(), Item::Range(r) => app.ui.tool_options.tone_range = r.into(), Item::Sponge(m) => app.ui.tool_options.sponge_mode = m.into(), + // Replace is a tool option: it runs no command and adds no History step (#12101). + Item::HealingReplace if tool == Tool::Healing => app.ui.tool_options.healing_replace = true, Item::Blend(m) if tool == Tool::Gradient => crate::blend_keys::set_gradient_mode(app, m), Item::Blend(m) if tool == Tool::PaintBucket => { app.ui.tool_options.bucket_clear = false; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 3468795b9a5..ff45431f9a1 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -153,7 +153,17 @@ pub fn transform_app_rows() -> [Entry; 2] { /// Photoshop's pasteboard menu (right-click outside the image): the pasteboard colour, the choice /// Preferences › Interface also offers. The ids are this menu's own: [`choose`] turns them into /// `prefs.set` (`pasteboard.`) or opens the Color Picker. -pub const PASTEBOARD_MENU: &[Row] = &[ +pub const PASTEBOARD_MENU: &[Row] = PASTEBOARD_MOVE_MENU.split_at(2).1; + +/// The Window item the Move tool's pasteboard menu toggles the contextual task bar with (#16757). +pub const PASTEBOARD_TASK_BAR: &str = "window.panel.contextualTaskBar"; + +/// The Move tool's pasteboard menu, as measured (#16757): Hide Contextual Task Bar (Show… while the +/// bar is off, [`row_label`]) and a separator above the colour rows. Other tools weren't measured and +/// keep [`PASTEBOARD_MENU`]. +pub const PASTEBOARD_MOVE_MENU: &[Row] = &[ + Some(("Hide Contextual Task Bar", PASTEBOARD_TASK_BAR)), + None, Some(("Default", "pasteboard.default")), Some(("Black", "pasteboard.black")), Some(("Dark Gray", "pasteboard.darkGray")), @@ -903,6 +913,9 @@ pub(crate) fn row_label(app: &PhotocraftApp, menu: &CanvasToolMenu, label: &'sta if menu.tool == Tool::AddAnchorPoint { return add_anchor_row_label(app, menu, label, command); } + if command == PASTEBOARD_TASK_BAR && !app.ui.panels.context_task_bar { + return "Show Contextual Task Bar"; + } if command != "path.transform" || !matches!(menu.tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen) { return label; } @@ -1189,6 +1202,7 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { match &menu.kind { MenuKind::Crop { .. } | MenuKind::Layers { .. } | MenuKind::BrushMode { .. } => &[], MenuKind::Guide => GUIDE_MENU, + MenuKind::Pasteboard if menu.tool == Tool::Move => PASTEBOARD_MOVE_MENU, MenuKind::Pasteboard => PASTEBOARD_MENU, MenuKind::View => { if menu.tool == Tool::Hand { @@ -1428,8 +1442,13 @@ fn choose_guide(app: &mut PhotocraftApp, ctx: &Context, command: &str) -> Result crate::menus::invoke(app, ctx, command, json!({})).map(|_| ()) } -/// A pasteboard row: set the colour, or open the Color Picker on the custom one. +/// A pasteboard row: set the colour, open the Color Picker on the custom one, or run the Window +/// item that hides or shows the contextual task bar. fn choose_pasteboard(app: &mut PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> Result<(), String> { + if command == PASTEBOARD_TASK_BAR { + let ctx = app.ctx().clone(); + return crate::menus::invoke(app, &ctx, command, json!({})).map(|_| ()); + } if command == PASTEBOARD_PICK { let rgb = prefs::parse_hex(&app.session.prefs().interface.canvas_custom_color).map_or([0.5; 3], |c| c.map(|v| f32::from(v) / 255.0)); crate::color_picker_ui::open_for_target(app, "pasteboard", "Color Picker (Custom Canvas Color)", rgb)?; @@ -1448,7 +1467,7 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) _ => GUIDE_MENU.iter().flatten().any(|(_, id)| *id == command) && crate::menus::is_enabled(app, command), }; } - MenuKind::Pasteboard => return PASTEBOARD_MENU.iter().flatten().any(|(_, id)| *id == command), + MenuKind::Pasteboard => return rows(menu).iter().flatten().any(|(_, id)| *id == command), MenuKind::View if command == "view.fillScreen" => return app.session.active().is_some(), MenuKind::View => return crate::menus::is_enabled(app, command), MenuKind::TypeEdit { .. } => { @@ -1935,6 +1954,8 @@ pub fn entries(app: &PhotocraftApp, menu: &CanvasToolMenu) -> Vec> "Duplicate Layers…" => tl!("Duplicate Layers…"), "Delete Layers" => tl!("Delete Layers"), "Rasterize Layers" => tl!("Rasterize Layers"), + "Hide Contextual Task Bar" => tl!("Hide Contextual Task Bar"), + "Show Contextual Task Bar" => tl!("Show Contextual Task Bar"), key => tl!(key), }; out.push(Entry::new(command.to_string(), text.to_string()).enabled(entry_enabled(app, menu, command)).checked(mode_checked(app, menu, command))); @@ -2017,6 +2038,10 @@ mod cam_menu_tests; #[cfg(test)] pub(crate) mod tests; +#[cfg(test)] +#[path = "../task_bar_pasteboard_entry_tests.rs"] +mod task_bar_pasteboard_entry_tests; + #[cfg(test)] pub(crate) mod count_tests; diff --git a/crates/ui-egui/src/canvas/paint_mouse/tests.rs b/crates/ui-egui/src/canvas/paint_mouse/tests.rs index 0372fbe0812..0bcf80cbfca 100644 --- a/crates/ui-egui/src/canvas/paint_mouse/tests.rs +++ b/crates/ui-egui/src/canvas/paint_mouse/tests.rs @@ -509,7 +509,7 @@ fn shift_right_menu_lists_each_tools_own_rows_in_order() { (Tool::Sponge, edit(vec!["Desaturate", "Saturate"])), (Tool::PaintBucket, with(&["Clear"])), (Tool::MixerBrush, vec!["Edit Brush…"]), - (Tool::Healing, vec!["Normal", "Multiply", "Screen", "Darken", "Lighten", "Color", "Luminosity"]), + (Tool::Healing, vec!["Normal", "Replace", "Multiply", "Screen", "Darken", "Lighten", "Color", "Luminosity"]), (Tool::SpotHealing, vec![]), (Tool::MagicEraser, vec![]), ] { diff --git a/crates/ui-egui/src/canvas/paint_tool.rs b/crates/ui-egui/src/canvas/paint_tool.rs index ac99ee5f89c..49455feaf0c 100644 --- a/crates/ui-egui/src/canvas/paint_tool.rs +++ b/crates/ui-egui/src/canvas/paint_tool.rs @@ -225,6 +225,29 @@ fn click_tool(app: &mut PhotocraftApp, tool: Tool, at: [f64; 2]) -> bool { } } +/// Paint Bucket ⇧-click on the pasteboard sets the pasteboard colour to the foreground colour, as +/// in the reference application (#12534): the custom colour, and use it, as the pasteboard menu's +/// Select Custom Color… does. It is a preference, so no history state and no document change. +/// Only a plain ⇧ with no selection: other modifiers and an active selection were not measured and +/// keep today's fill. True when it handled the click. +pub(crate) fn bucket_pasteboard_click(app: &mut PhotocraftApp, at: [f64; 2], mods: Mods) -> bool { + let plain_shift = mods.shift && !mods.alt && !mods.ctrl && !mods.cmd; + let Some(st) = app.session.active() else { return false }; + let (w, h) = (f64::from(st.doc.size.width), f64::from(st.doc.size.height)); + let (x, y) = (at[0], at[1]); + let outside = x.is_finite() && y.is_finite() && (x < 0.0 || y < 0.0 || x >= w || y >= h); + if !plain_shift || !outside || st.doc.selection.is_some() { + return false; + } + let [r, g, b, _] = app.session.tools.foreground; + let color = crate::color_picker_ui::hex([r, g, b]); + if let Err(e) = app.run("prefs.set", json!({"values": {"interface.canvasColor": "custom", "interface.canvasCustomColor": color}})) { + app.ui.status = e; + app.ui.status_error = true; + } + true +} + fn begin(app: &mut PhotocraftApp, state: &mut PaintState, pointer: &ToolPointer, at: [f64; 2], cx: &mut ToolContext<'_>) -> ToolAction { let tool = app.ui.tool; let (mods, button) = (pointer.mods, pointer.button); diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index 2aa3f272602..c8bd3e62de7 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -367,6 +367,11 @@ impl CanvasTool for Preflight<'_, '_> { return ToolAction::Done; } let at = [doc.x, doc.y]; + // Paint Bucket ⇧-click on the pasteboard sets the pasteboard colour (#12534): a + // preference, so it runs before the painting refusals, as quick pick does. + if tool == Tool::PaintBucket && self.scope.with_app(|app| super::paint_tool::bucket_pasteboard_click(app, at, pointer.mods)) { + return ToolAction::Done; + } // Let the Eyedropper take an Alt press that samples the shape tool's Fill. if self.alt_stand_in && self.scope.with_app(|app| super::cursor_policy::shape_alt_samples(app, pointer.mods, at[0], at[1])) { return ToolAction::Ignored; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5530ed0ec45..6a26256f4ff 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -633,6 +633,10 @@ pub fn open_command_dialog(app: &mut PhotocraftApp, command: &str, label: &str) /// Preference entries the engine reads itself, by key: the engine has no settings store, so they cannot move. const ENGINE_READ: &[&str] = &["ui.layersPanelOptions", "file.print", "file.export.saveForWebLegacy"]; +/// Preference entries the engine reads that a workspace also remembers in the framework's store: they stay, and are +/// copied there only while it holds none. An empty recorded Content-Aware Fill step plays with the engine's copy (#14254). +const ENGINE_READ_SHARED: &[&str] = &[photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS]; + /// The "Don't show again" entries (`{"skip": true}`), by key, as their prompt modules read them. Told apart by key, not /// by the shape of the value. fn dont_show_again_keys() -> [&'static str; 5] { @@ -686,7 +690,9 @@ fn convert_blend_mode(key: &str, value: &mut Value) { /// Moves the dialogs' last-used values out of `Preferences.dialogs` into the remembered section of `host`, once, before /// the first frame. Entries the engine reads and the don't-show-again entries stay; a second run finds nothing to move -/// because every moved entry left `Preferences.dialogs`. An entry that has no table form stays too. +/// because every moved entry left `Preferences.dialogs`. An entry that has no table form stays too, and a shared entry +/// ([`ENGINE_READ_SHARED`]) never replaces what the framework already remembers; a profile without one gets it from +/// what the framework remembers ([`carry_forward_shared`]). pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { let keys: Vec = prefs.dialogs.keys().cloned().collect(); for key in keys { @@ -694,10 +700,38 @@ pub(crate) fn move_memories(prefs: &mut Preferences, host: &Host) { let Some(old) = prefs.dialogs.get(&key) else { continue }; let mut value = without_nulls(old.clone()); convert_blend_mode(&key, &mut value); + if key == photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS { + crate::caf_ui::recorded_to_workspace(&mut value); + } let Ok(table) = toml::Table::try_from(&value) else { continue }; - Remembered::::new(scope).store(host, &table); + let remembered = Remembered::::new(scope); + if ENGINE_READ_SHARED.contains(&key.as_str()) { + // An empty entry holds no settings yet (see `carry_forward_shared`). + if !table.is_empty() && remembered.recall(host).is_none() { + remembered.store(host, &table); + } + continue; + } + remembered.store(host, &table); prefs.dialogs.remove(&key); } + carry_forward_shared(prefs, host); +} + +/// Gives a profile without the engine's copy of a shared entry one, once (#14254). An earlier version moved the +/// Content-Aware Fill settings into the workspace's own memory and kept no copy, so that memory is carried forward: +/// it is all such a profile has, although it also holds settings the workspace closed with and never filled. With no +/// memory the copy starts empty. From then on only a fill that ran sets the copy, so settings closed without a fill +/// are never carried forward. +fn carry_forward_shared(prefs: &mut Preferences, host: &Host) { + for key in ENGINE_READ_SHARED { + if prefs.dialogs.contains_key(*key) { + continue; + } + let Some(scope) = memory_destination(key) else { continue }; + let memory = Remembered::::new(scope).recall(host).and_then(|table| serde_json::to_value(table).ok()); + prefs.dialogs.insert((*key).into(), memory.map_or_else(|| serde_json::json!({}), crate::caf_ui::recorded_from_workspace)); + } } pub mod adjust_dialog; diff --git a/crates/ui-egui/src/dialogs/caf_ui.rs b/crates/ui-egui/src/dialogs/caf_ui.rs index da0f6c0d672..8cd947511da 100644 --- a/crates/ui-egui/src/dialogs/caf_ui.rs +++ b/crates/ui-egui/src/dialogs/caf_ui.rs @@ -37,7 +37,7 @@ mod lifecycle; mod preview; pub use lifecycle::open; -pub(crate) use lifecycle::{describe, take}; +pub(crate) use lifecycle::{describe, on_job_event, recorded_from_workspace, recorded_to_workspace, take}; use preview::{Base, compute_preview, plan_params}; /// Longest side of the document proxy shown in the view (px). diff --git a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs index 36e538eec6e..e2007c3d709 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/lifecycle.rs @@ -6,6 +6,7 @@ use craft::imaging::ui::fill::{FillCommand, FillEvent, FillLimits, FillOpen, Fil use craft::ui::dialog::{DialogId, dialog_id}; use craft::ui::runtime::env::Label; use photocraft_engine::edit_menu_cmds::{MAX_CAF_EDITS, MAX_CAF_POINTS}; +use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -128,11 +129,74 @@ fn report(app: &mut PhotocraftApp, e: &str) { app.ui.status_error = true; } -/// Fills with `command` (one history step); the workspace stays as it is. A refusal is reported. +/// The settings an empty recorded Content-Aware Fill step plays with (#14254). +const RECORDED_SETTINGS: [&str; 7] = ["sampling", "sampleAllLayers", "colorAdaptation", "rotationAdaptation", "scale", "mirror", "output"]; + +/// The workspace's own memory names Rotation Adaptation `rotation`; an empty recorded step reads `rotationAdaptation`. +const WORKSPACE_ROTATION: &str = "rotation"; + +/// The settings an empty recorded step plays with, from what the workspace remembers (#14254). +pub(crate) fn recorded_from_workspace(memory: Value) -> Value { + let Value::Object(mut settings) = memory else { return json!({}) }; + if let Some(rotation) = settings.remove(WORKSPACE_ROTATION) { + settings.insert("rotationAdaptation".into(), rotation); + } + settings.retain(|key, _| RECORDED_SETTINGS.contains(&key.as_str())); + Value::Object(settings) +} + +/// The settings an empty recorded step plays with, in the form the workspace remembers them. +pub(crate) fn recorded_to_workspace(settings: &mut Value) { + if let Some(settings) = settings.as_object_mut() + && let Some(rotation) = settings.remove("rotationAdaptation") + { + settings.insert(WORKSPACE_ROTATION.into(), rotation); + } +} + +/// `command`'s settings that an empty recorded step plays with. +fn recorded(command: &FillCommand) -> Option { + let Ok(Value::Object(mut settings)) = serde_json::to_value(command) else { return None }; + settings.retain(|key, _| RECORDED_SETTINGS.contains(&key.as_str())); + Some(Value::Object(settings)) +} + +/// Keeps `settings` in `prefs.dialogs` too, where an empty recorded step reads them: the workspace remembers its +/// own copy in the framework's store, which the engine can't see. +fn remember(app: &mut PhotocraftApp, settings: Value) { + app.session.prefs.edit(|p| p.dialogs.insert(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS.into(), settings)); +} + +/// The background job a command's reply says is still running. +fn pending_job(reply: &Value) -> Option { + (reply.get("pending") == Some(&Value::Bool(true))).then(|| reply.get("job").and_then(Value::as_u64).map(JobId)).flatten() +} + +/// A background fill ended: its settings are remembered only when it was applied, not when it failed or was +/// cancelled (#14254). +pub(crate) fn on_job_event(app: &mut PhotocraftApp, e: &JobEvent) { + let Some(i) = app.jobs.caf_settings.iter().position(|(job, _)| *job == e.id) else { return }; + let (_, settings) = app.jobs.caf_settings.remove(i); + if matches!(e.outcome, JobOutcome::Done(_)) { + remember(app, settings); + } +} + +/// Fills with `command` (one history step); the workspace stays as it is. A refusal is reported and keeps the +/// settings of the last fill that ran. pub(super) fn apply(app: &mut PhotocraftApp, command: &FillCommand) -> Result<(), String> { let layer = app.caf.as_ref().ok_or("Content-Aware Fill is not open")?.layer; match app.run(CMD, plan_params(command, layer)) { - Ok(_) => Ok(()), + Ok(reply) => { + if let Some(settings) = recorded(command) { + match pending_job(&reply) { + // A background fill can still fail or be cancelled: its settings wait for the job's end. + Some(job) => app.jobs.caf_settings.push((job, settings)), + None => remember(app, settings), + } + } + Ok(()) + } Err(e) => { report(app, &e); Err(e) diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index 74d097e1223..e2d2031ac38 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -1,6 +1,7 @@ use craft::imaging::ui::fill::FillOp; use craft::ui::canvas::PixelRect; use photocraft_doc::LayerId; +use photocraft_engine::actions_cmds::ActionsExt; use serde_json::{Value, json}; use super::preview::{compute_preview, plan_params}; @@ -251,6 +252,191 @@ fn apply_fills_and_stays_open_ok_closes_cancel_keeps_what_was_applied() { assert!(px(&app, top, 100, 80)[3] > 0.99, "the new layer holds the fill"); } +/// Apply and OK keep the settings where an empty recorded step reads them (#14254), as the workspace's own store +/// is out of the engine's reach. +#[test] +fn apply_and_ok_keep_the_settings_for_an_empty_recorded_step() { + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + assert_eq!(saved(&app), Some(json!({})), "a new profile has no settings yet"); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "high", "rotation": "medium", "mirror": true})).unwrap(); + ui(&mut app, json!({"apply": true})).unwrap(); + let after_apply = saved(&app).expect("Apply remembers the settings"); + assert_eq!(after_apply["output"], "current"); + assert_eq!(after_apply["colorAdaptation"], "high"); + assert_eq!(after_apply["rotationAdaptation"], "medium"); + assert_eq!(after_apply["mirror"], true); + let keys: Vec<&str> = after_apply.as_object().unwrap().keys().map(String::as_str).collect(); + assert_eq!(keys.len(), 7, "only the seven recorded settings: {keys:?}"); + ui(&mut app, json!({"output": "duplicate"})).unwrap(); + ui(&mut app, json!({"commit": true})).unwrap(); + close_all(&mut app); + assert_eq!(saved(&app).unwrap()["output"], "duplicate", "OK remembers too"); +} + +/// A fill the engine refuses leaves the settings of the last fill that ran for an empty recorded step (#14254). +#[test] +fn a_refused_fill_keeps_the_last_remembered_settings() { + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "none", "apply": true})).unwrap(); + let remembered = saved(&app).expect("the Apply that ran remembers its settings"); + // The workspace's layer: the fill may have left another layer active. + let layer = app.caf.as_ref().unwrap().layer; + app.session.execute("layer.setProps", json!({"layer": layer.0, "locks": {"pixels": true}})).unwrap(); + let before = facts(&app)["previewRevision"].as_u64().unwrap(); + ui(&mut app, json!({"colorAdaptation": "high", "mirror": true})).unwrap(); + settle(&mut app, |d| d["previewRevision"].as_u64().unwrap() > before && d["previewError"].is_null()); + ui(&mut app, json!({"apply": true})).unwrap(); + assert!(facts(&app)["error"].as_str().is_some_and(|e| e.contains("locked")), "the engine refuses the locked layer: {}", facts(&app)); + assert_eq!(saved(&app), Some(remembered.clone()), "a refused Apply remembers nothing"); + assert!(ui(&mut app, json!({"commit": true})).is_err(), "the engine refuses OK too"); + assert_eq!(saved(&app), Some(remembered), "a refused OK remembers nothing"); +} + +/// A background fill (the desktop app) remembers its settings once its job is applied; a job that fails or is +/// cancelled leaves the last remembered ones (#14254). +#[test] +fn a_background_fill_remembers_its_settings_only_when_its_job_is_applied() { + use photocraft_engine::jobs::{JobEvent, JobId, JobOutcome}; + let mut app = app_with_selection(); + let saved = |app: &PhotocraftApp| app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "colorAdaptation": "none", "apply": true})).unwrap(); + let remembered = saved(&app).expect("the Apply that ran remembers its settings"); + app.background_jobs = true; + ui(&mut app, json!({"colorAdaptation": "high", "mirror": true})).unwrap(); + let id = app.caf.as_ref().unwrap().id; + let command = app.framework.dialogs.get_by_id::(id).unwrap().workspace().command(); + super::lifecycle::apply(&mut app, &command).unwrap(); + assert_eq!(saved(&app), Some(remembered), "nothing is remembered while the fill runs"); + assert_eq!(app.jobs.caf_settings.len(), 1, "the fill runs as a background job"); + let ctx = ctx(&app); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while app.session.has_jobs() { + assert!(std::time::Instant::now() < deadline, "the fill job did not end"); + crate::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let applied = saved(&app).expect("the applied fill remembers its settings"); + assert_eq!((&applied["colorAdaptation"], &applied["mirror"]), (&json!("high"), &json!(true))); + assert!(app.jobs.caf_settings.is_empty()); + for outcome in [JobOutcome::Failed("refused".into()), JobOutcome::Cancelled] { + let job = JobId(u64::MAX); + app.jobs.caf_settings.push((job, json!({"output": "duplicate"}))); + let event = JobEvent { id: job, command: CMD.into(), label: String::new(), document: None, outcome: outcome.clone(), error: None }; + crate::caf_ui::on_job_event(&mut app, &event); + assert_eq!(saved(&app), Some(applied.clone()), "{outcome:?} remembers nothing"); + assert!(app.jobs.caf_settings.is_empty(), "{outcome:?} ends the wait"); + } +} + +/// After a restart an empty recorded step still plays with the last fill's settings: the startup move of the dialogs' +/// memories leaves the engine's copy in the preferences (#14254). +#[test] +fn an_empty_recorded_step_plays_with_the_last_settings_after_a_restart() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "commit": true})).unwrap(); + close_all(&mut app); + let mut restarted = restart(app.session.prefs().clone()); + assert_eq!(play_empty_recorded_step(&mut restarted), 0, "Current Layer, not a new layer"); +} + +/// A profile from an earlier version, which kept the Content-Aware Fill settings only in the workspace's own memory, +/// carries them forward for an empty recorded step on its first start (#14254). +#[test] +fn an_earlier_versions_workspace_settings_carry_forward_to_an_empty_recorded_step() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current", "rotation": "medium"})).unwrap(); + ui(&mut app, json!({"cancel": true})).unwrap(); + close_all(&mut app); + // That version moved the engine's copy into the workspace's memory and kept none. + let mut prefs = app.session.prefs().clone(); + prefs.dialogs.remove(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS); + let mut restarted = restart(prefs); + let carried = restarted.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned().unwrap(); + assert_eq!((&carried["output"], &carried["rotationAdaptation"]), (&json!("current"), &json!("medium")), "{carried}"); + assert_eq!(play_empty_recorded_step(&mut restarted), 0, "Current Layer, as the workspace remembers"); +} + +/// Settings the workspace closed with but never filled are not carried to an empty recorded step: only a fill that ran +/// sets what it plays with (#14254). +#[test] +fn settings_closed_without_a_fill_are_not_carried_forward() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"output": "current"})).unwrap(); + ui(&mut app, json!({"cancel": true})).unwrap(); + close_all(&mut app); + let mut restarted = restart(app.session.prefs().clone()); + assert_eq!(play_empty_recorded_step(&mut restarted), 1, "New Layer: no fill has run"); +} + +/// After a confirmed Custom fill an empty recorded step stops and says why, instead of filling from another area: the +/// workspace remembers Custom but not its painted area (Custom reopens empty), so the step has none (#14254). +#[test] +fn an_empty_recorded_step_after_a_custom_fill_stops_and_says_why() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"sampling": "custom", "output": "current"})).unwrap(); + ui(&mut app, json!({"stroke": {"points": [[20.0, 120.0], [60.0, 120.0]], "size": 8}})).unwrap(); + ui(&mut app, json!({"commit": true})).unwrap(); + close_all(&mut app); + let remembered = app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS).cloned().unwrap(); + assert_eq!(remembered["sampling"], "custom", "the confirmed fill remembers Custom: {remembered}"); + let revision = app.session.active().unwrap().revision; + let result = play_empty_step(&mut app); + assert_eq!(result["ran"], 0, "{result}"); + let error = result["failed"]["error"].as_str().unwrap_or_default(); + assert!(error.contains("Custom sampling area isn't remembered"), "{result}"); + // The status bar shows the shell's translatable copy of the message, not the engine's parameter error. + crate::actions::report_play(&mut app, &result); + let status = &app.ui.status; + assert!(status.contains(photocraft_engine::atn_cmds::CAF_CUSTOM_AREA_NOT_REMEMBERED) && !status.contains("invalid parameters"), "{status}"); + assert_eq!(app.session.active().unwrap().revision, revision, "the document is unchanged"); + assert_eq!(app.session.prefs().dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS), Some(&remembered), "playing remembers nothing"); +} + +/// A new app over the saved preferences `prefs`, moved as startup does. +fn restart(prefs: photocraft_engine::prefs::Preferences) -> Box { + let mut restarted = app_with_selection(); + restarted.session.edit_prefs(|p| *p = prefs); + restarted.framework.move_memories(&mut restarted.session); + restarted +} + +/// Plays an action of one empty recorded Content-Aware Fill step and returns how many layers it added. +fn play_empty_recorded_step(app: &mut PhotocraftApp) -> usize { + let layers = app.session.active().unwrap().doc.layers.len(); + let result = play_empty_step(app); + assert_eq!(result["ran"], 1, "{result}"); + app.session.active().unwrap().doc.layers.len() - layers +} + +/// Plays an action of one empty recorded Content-Aware Fill step and returns what `actions.play` answers. +fn play_empty_step(app: &mut PhotocraftApp) -> Value { + use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; + use craft_psd::descriptor::{Descriptor, UnicodeString}; + let item = AtnItem { + event: AtnEvent::name("cafWorkspace"), + dictionary: b"Content-Aware Fill".to_vec(), + descriptor: Some(Descriptor::new("null")), + ..Default::default() + }; + let file = AtnFile { + name: UnicodeString::new_nul("S"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item], ..Default::default() }], + ..Default::default() + }; + let imported = photocraft_engine::atn_cmds::import(&craft_psd::atn::write(&file).unwrap()).unwrap(); + app.session.actions_mut().list.push(imported.actions.into_iter().next().unwrap()).unwrap(); + app.session.execute("actions.play", json!({"action": 0})).unwrap() +} + /// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill area. fn engine_source(app: &PhotocraftApp) -> (Rect, Vec, Vec) { let c = app.caf.as_ref().unwrap(); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index dec11d58b4e..715f308bf9f 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -148,9 +148,12 @@ fn the_one_time_move_stores_owned_dialog_values_once_and_leaves_engine_read_keys assert_eq!(table("photocraft.edit.fill").unwrap().get("mode"), Some(&toml::Value::String(photocraft_color::BlendMode::ColorBurn.key().to_string()))); let mut left: Vec<&str> = prefs.dialogs.keys().map(String::as_str).collect(); left.sort_unstable(); - let mut kept = vec!["file.print", "ui.layersPanelOptions", "file.export.saveForWebLegacy", live_shape_prompt::PREF]; + // The Content-Aware Fill entry an empty recorded step reads is given to every profile, empty here (#14254). + let mut kept = + vec!["file.print", "ui.layersPanelOptions", "file.export.saveForWebLegacy", live_shape_prompt::PREF, photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS]; kept.sort_unstable(); assert_eq!(left, kept, "only the kept entries stay in the preferences"); + assert_eq!(prefs.dialogs.get(photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS), Some(&json!({}))); // A second run finds nothing to move: a value changed since is not overwritten. Remembered::::new("photocraft.filter.gaussianBlur").store(&host, &toml::Table::new()); @@ -158,6 +161,26 @@ fn the_one_time_move_stores_owned_dialog_values_once_and_leaves_engine_read_keys assert_eq!(table("photocraft.filter.gaussianBlur"), Some(toml::Table::new())); } +/// The Content-Aware Fill settings an empty recorded step reads stay in the preferences; the workspace's own memory +/// gets them only while it has none (#14254). +#[test] +fn the_move_keeps_the_content_aware_fill_settings_and_never_replaces_the_workspaces() { + let host = Host::builder(AppInfo { id: "photocraft", name: "PhotoCraft", version: "0" }).settings(Arc::new(MemorySections::default())).build(); + let key = photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS; + let workspace = Remembered::::new(params::memory_scope(key)); + let output = |table: Option| table.and_then(|t| t.get("output").cloned()); + let mut prefs = photocraft_engine::prefs::Preferences::default(); + prefs.dialogs.insert(key.into(), json!({"output": "current"})); + move_memories(&mut prefs, &host); + assert_eq!(prefs.dialogs.get(key), Some(&json!({"output": "current"})), "the engine's copy stays"); + assert_eq!(output(workspace.recall(&host)), Some(toml::Value::String("current".into())), "an empty workspace memory gets it"); + + prefs.dialogs.insert(key.into(), json!({"output": "new"})); + move_memories(&mut prefs, &host); + assert_eq!(output(workspace.recall(&host)), Some(toml::Value::String("current".into())), "the workspace's own memory wins"); + assert_eq!(prefs.dialogs.get(key), Some(&json!({"output": "new"}))); +} + struct MarkA; struct MarkB; diff --git a/crates/ui-egui/src/healing_mode_menu_tests.rs b/crates/ui-egui/src/healing_mode_menu_tests.rs new file mode 100644 index 00000000000..1cc29736ca5 --- /dev/null +++ b/crates/ui-egui/src/healing_mode_menu_tests.rs @@ -0,0 +1,150 @@ +//! #12101: the Healing Brush's Mode menus gain Replace and the reference's two separators, in the +//! measured order Normal, Replace, separator, Multiply, Screen, Darken, Lighten, separator, Color, +//! Luminosity. Picking Replace is a tool option only: it adds no History step, sends +//! `mode:"replace"` on the next stroke, and any other mode pick leaves it. The keyboard cycle +//! stays inside the seven blend modes. + +use craft::ui::patterns::blend_keys::{BlendShortcut, BlendStep}; +use photocraft_color::BlendMode; +use serde_json::json; + +use super::PaintMode; +use super::fill::mode_entries; +use crate::blend_keys::{fired, test_fired}; +use crate::brush_mode_menu::{Item, current, items, labels}; +use crate::state::Tool; +use crate::{PhotocraftApp, brush_mode_menu}; + +/// The measured row order of the canvas Shift+right-click menu, separators in place. +const MENU_ROWS: [Item; 10] = [ + Item::Blend(BlendMode::Normal), + Item::HealingReplace, + Item::Separator, + Item::Blend(BlendMode::Multiply), + Item::Blend(BlendMode::Screen), + Item::Blend(BlendMode::Darken), + Item::Blend(BlendMode::Lighten), + Item::Separator, + Item::Blend(BlendMode::Color), + Item::Blend(BlendMode::Luminosity), +]; + +/// The same list as the options bar dropdown's entry values (`None` is a rule). +const BAR_ROWS: [Option; 10] = [ + Some(PaintMode::Blend(BlendMode::Normal)), + Some(PaintMode::HealingReplace), + None, + Some(PaintMode::Blend(BlendMode::Multiply)), + Some(PaintMode::Blend(BlendMode::Screen)), + Some(PaintMode::Blend(BlendMode::Darken)), + Some(PaintMode::Blend(BlendMode::Lighten)), + None, + Some(PaintMode::Blend(BlendMode::Color)), + Some(PaintMode::Blend(BlendMode::Luminosity)), +]; + +#[test] +fn both_healing_mode_lists_show_replace_and_the_two_separators() { + assert_eq!(items(Tool::Healing), MENU_ROWS, "the Shift+right-click menu rows"); + assert_eq!( + labels(Tool::Healing), + ["Normal", "Replace", "Multiply", "Screen", "Darken", "Lighten", "Color", "Luminosity"], + "the labels, separators left out" + ); + let entries = mode_entries(Tool::Healing, true, false); + let values: Vec> = entries.iter().map(|e| e.value().cloned()).collect(); + assert_eq!(values, BAR_ROWS, "the options bar dropdown"); + // Another tool's list is untouched by this: the Clone Stamp keeps the layer modes. + assert!(!mode_entries(Tool::CloneStamp, true, false).iter().any(|e| e.value() == Some(&PaintMode::HealingReplace)), "no Replace on the Clone Stamp"); + assert!(items(Tool::CloneStamp).iter().all(|i| *i != Item::HealingReplace), "no Replace row on the Clone Stamp menu"); +} + +/// A Healing Brush app with a document, a set clone source and the tool active. +fn app() -> Box { + let mut a = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + a.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + a.ui.tool = Tool::Healing; + crate::retouch_ui::set_source(&mut a, 8.0, 8.0); + a +} + +/// The mode the next stroke would carry in its params. +fn stroke_mode(a: &PhotocraftApp) -> String { + crate::retouch_ui::clone_params(a).expect("a source is set")["mode"].as_str().unwrap_or_default().to_owned() +} + +fn steps(a: &PhotocraftApp) -> usize { + a.session.active().unwrap().history.past_len() +} + +#[test] +fn the_canvas_menu_replace_row_switches_the_stroke_without_a_history_step() { + let mut a = app(); + let before = steps(&a); + brush_mode_menu::choose(&mut a, Item::HealingReplace); + assert!(a.ui.tool_options.healing_replace, "the row sets the tool option"); + assert_eq!(stroke_mode(&a), "replace", "the next stroke sends mode:\"replace\""); + assert_eq!(current(&a, Tool::Healing), Some(Item::HealingReplace), "the menu checks Replace"); + assert_eq!(steps(&a), before, "picking the Mode adds no History step"); + // An existing row leaves Replace and paints its blend mode. + brush_mode_menu::choose(&mut a, Item::Blend(BlendMode::Multiply)); + assert!(!a.ui.tool_options.healing_replace, "Multiply leaves Replace"); + assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); + assert_eq!(stroke_mode(&a), "Multiply"); + assert_eq!(steps(&a), before, "picking a Mode never adds a History step"); + // Replace is not offered to the other tools' choose route: their rows and options stay. + let mut b = app(); + b.ui.tool = Tool::CloneStamp; + brush_mode_menu::choose(&mut b, Item::HealingReplace); + assert!(!b.ui.tool_options.healing_replace, "the Clone Stamp never takes Replace"); +} + +#[test] +fn the_options_bar_dropdown_replaces_and_picking_a_blend_mode_leaves_it() { + use crate::app::framework::BuildApp as _; + use egui::accesskit::Role; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + // The options bar alone, like the other bar tests: open the Mode dropdown, click a row. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.ui.tool = Tool::Healing; + crate::retouch_ui::set_source(&mut app, 8.0, 8.0); + let mut h = Harness::builder().with_size(egui::vec2(1800.0, 300.0)).with_step_dt(1.0 / 60.0).build_app(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Mode").accesskit_node().value().as_deref(), Some("Normal"), "starts at Normal"); + let before = steps(h.state()); + + h.get_by_role_and_label(Role::ComboBox, "Mode").click(); + h.run_steps(2); + h.get_by_label("Replace").click(); + h.run_steps(3); + assert!(h.state().ui.tool_options.healing_replace, "the dropdown's Replace row sets the option"); + assert_eq!(h.get_by_role_and_label(Role::ComboBox, "Mode").accesskit_node().value().as_deref(), Some("Replace"), "the dropdown reads Replace"); + assert_eq!(crate::retouch_ui::clone_params(h.state()).expect("the source is set")["mode"], json!("replace"), "the next stroke would run in Replace"); + assert_eq!(steps(h.state()), before, "picking a Mode adds no History step"); + + h.get_by_role_and_label(Role::ComboBox, "Mode").click(); + h.run_steps(2); + h.get_by_label("Multiply").click(); + h.run_steps(3); + assert!(!h.state().ui.tool_options.healing_replace, "Multiply leaves Replace"); + assert_eq!(h.state().session.tools.brush.mode, BlendMode::Multiply, "the brush takes the mode"); + assert_eq!(crate::retouch_ui::clone_params(h.state()).expect("the source is set")["mode"], json!("Multiply")); + assert_eq!(steps(h.state()), before, "and no Mode pick ever adds a step"); +} + +#[test] +fn the_mode_keys_keep_the_seven_modes_and_clear_replace() { + // Replace stays out of the letter keys and the ⇧+ / ⇧− cycle: the seven modes and their order. + let mut a = app(); + a.ui.tool_options.healing_replace = true; + assert!(fired(&mut a, &test_fired(BlendShortcut::Multiply.into())), "⇧⌥M is taken"); + assert_eq!(a.session.tools.brush.mode, BlendMode::Multiply); + assert!(!a.ui.tool_options.healing_replace, "a letter pick leaves Replace"); + let mut b = app(); + assert!(fired(&mut b, &test_fired(BlendStep::Next.into())), "⇧+ is taken"); + assert_eq!(b.session.tools.brush.mode, BlendMode::Multiply, "the cycle still runs Normal to Multiply"); + assert!(!b.ui.tool_options.healing_replace, "the cycle never picks Replace"); +} diff --git a/crates/ui-egui/src/input/blend_keys.rs b/crates/ui-egui/src/input/blend_keys.rs index 18c3f66848a..7ece1ee5d5e 100644 --- a/crates/ui-egui/src/input/blend_keys.rs +++ b/crates/ui-egui/src/input/blend_keys.rs @@ -21,7 +21,8 @@ use crate::brush_mode_menu::Item; use crate::state::Tool; use crate::{PhotocraftApp, brush_mode_menu}; -/// Photoshop's Healing Brush modes, less Replace (not implemented yet). +/// Photoshop's Healing Brush modes. Replace is the tool's own option, not a blend mode: the menus +/// add it as a row of its own (#12101), and the letters and steps below keep this list. pub const HEALING_MODES: [BlendMode; 7] = [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Darken, BlendMode::Lighten, BlendMode::Color, BlendMode::Luminosity]; @@ -129,7 +130,10 @@ fn set_tool_mode(app: &mut PhotocraftApp, mode: Option) { brush.insert("behind".into(), json!(false)); } if !brush.is_empty() { - let _ = app.run("tools.setBrush", json!({ "brush": brush })); + // Replace (#12101): a key-picked blend mode leaves it, in the same pick. + if app.run("tools.setBrush", json!({ "brush": brush })).is_ok() && app.ui.tool == Tool::Healing { + app.ui.tool_options.healing_replace = false; + } } } diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index ef932e8bbd4..f01e7304039 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -183,6 +183,8 @@ pub struct JobsUi { /// The file being placed in the background, if any. One at a time: files dropped meanwhile /// wait in the app's drop queue. pub place: Option, + /// Content-Aware Fill settings waiting for their background fill: remembered when it is applied (#14254). + pub(crate) caf_settings: Vec<(JobId, Value)>, } /// Run command `id`: in the background when background jobs are on and the command is a job @@ -607,6 +609,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { } // A Free Transform commit's session ends with its job (then reported like any job). crate::transform_tool::on_job_event(app, &e); + crate::caf_ui::on_job_event(app, &e); if crate::prefs_ui::on_recovery_event(app, &e) { return; } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 102fbc6d515..ce9a6dffae9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -939,6 +939,8 @@ mod move_shift_click_tests; #[cfg(test)] mod move_target_default_tests; +#[cfg(test)] +mod paint_bucket_pasteboard_color_tests; #[cfg(test)] mod wand_press_inside_selection_tests; diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index 4fb2750e5fe..6b7d71db4f4 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -741,27 +741,26 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["View"], "Pixel Art Preview", None, "view.pixelArtPreview"), (&["Window", "Arrange"], "Tile All Vertically", None, "window.arrange.tileAllVertically"), (&["Window", "Arrange"], "Tile All Horizontally", None, "window.arrange.tileAllHorizontally"), - (&["Window", "Arrange"], "2-up Vertical", None, "window.arrange.twoUpVertical"), (&["Window", "Arrange"], "2-up Horizontal", None, "window.arrange.twoUpHorizontal"), - (&["Window", "Arrange"], "3-up Vertical", None, "window.arrange.threeUpVertical"), + (&["Window", "Arrange"], "2-up Vertical", None, "window.arrange.twoUpVertical"), (&["Window", "Arrange"], "3-up Horizontal", None, "window.arrange.threeUpHorizontal"), + (&["Window", "Arrange"], "3-up Vertical", None, "window.arrange.threeUpVertical"), (&["Window", "Arrange"], "3-up Stacked", None, "window.arrange.threeUpStacked"), (&["Window", "Arrange"], "4-up", None, "window.arrange.fourUp"), (&["Window", "Arrange"], "6-up", None, "window.arrange.sixUp"), - (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Consolidate All to Tabs", None, "window.arrange.consolidateAllToTabs"), + (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Cascade", None, "window.arrange.cascade"), (&["Window", "Arrange"], "Tile", None, "window.arrange.tile"), - (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Float in Window", None, "window.arrange.floatInWindow"), (&["Window", "Arrange"], "Float All in Windows", None, "window.arrange.floatAllInWindows"), (&["Window", "Arrange"], "---", None, "---"), - (&["Window", "Arrange"], "New Window", None, "window.arrange.newWindowForDocument"), - (&["Window", "Arrange"], "---", None, "---"), (&["Window", "Arrange"], "Match Zoom", None, "window.arrange.matchZoom"), (&["Window", "Arrange"], "Match Location", None, "window.arrange.matchLocation"), (&["Window", "Arrange"], "Match Rotation", None, "window.arrange.matchRotation"), (&["Window", "Arrange"], "Match All", None, "window.arrange.matchAll"), + (&["Window", "Arrange"], "---", None, "---"), + (&["Window", "Arrange"], "New Window", None, "window.arrange.newWindowForDocument"), (&["Window", "Workspace"], "Essentials", None, "window.workspace.essentials"), (&["Window", "Workspace"], "Photography", None, "window.workspace.photography"), (&["Window", "Workspace"], "Painting", None, "window.workspace.painting"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9da031f57b6..2f62301eb7e 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -118,6 +118,9 @@ mod open_recent_position_tests; #[cfg(test)] mod export_submenu_separator_tests; +#[cfg(test)] +mod arrange_menu_order_tests; + #[cfg(test)] mod bar_cursor_tests; diff --git a/crates/ui-egui/src/menus/arrange_menu_order_tests.rs b/crates/ui-egui/src/menus/arrange_menu_order_tests.rs new file mode 100644 index 00000000000..51a6ebb728a --- /dev/null +++ b/crates/ui-egui/src/menus/arrange_menu_order_tests.rs @@ -0,0 +1,92 @@ +//! Window › Arrange: measured entry order, separators, and dynamic "New Window for " label (#16888). + +use serde_json::json; + +use super::*; + +#[cfg(not(target_arch = "wasm32"))] +fn new_doc(app: &mut PhotocraftApp, name: &str) { + app.run("file.new", json!({"width": 64, "height": 64, "name": name})).unwrap(); +} + +/// The `Window › Arrange` entries returned by `ui.menu.list` as `(id, label, shortcut)`. +#[cfg(not(target_arch = "wasm32"))] +fn arrange_list(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec<(String, String, Option)> { + let (req, _rx) = crate::control::ControlRequest::new("ui.menu.list", json!({})); + let reply = match crate::control::handle(app, ctx, &req) { + crate::control::Reply::Done(v) => v, + _ => panic!("ui.menu.list: expected an immediate reply"), + }; + reply["result"] + .as_array() + .expect("ui.menu.list returns an array") + .iter() + .filter(|it| it["path"] == json!(["Window", "Arrange"])) + .map(|it| { + let label = it["label"].as_str().unwrap_or_default().to_string(); + let id = if label == "---" { "---".to_string() } else { it["id"].as_str().unwrap_or_default().to_string() }; + let shortcut = it["shortcut"].as_str().map(str::to_string); + (id, label, shortcut) + }) + .collect() +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn arrange_menu_matches_measured_order_and_active_document_label() { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + + // Without a document open, the final entry keeps its plain fallback label. + let empty = arrange_list(&mut app, &ctx); + assert_eq!(empty.last().map(|(id, label, _)| (id.as_str(), label.as_str())), Some(("window.arrange.newWindowForDocument", "New Window"))); + + new_doc(&mut app, "W1"); + let got = arrange_list(&mut app, &ctx); + let expected: &[(&str, &str)] = &[ + ("window.arrange.tileAllVertically", "Tile All Vertically"), + ("window.arrange.tileAllHorizontally", "Tile All Horizontally"), + ("window.arrange.twoUpHorizontal", "2-up Horizontal"), + ("window.arrange.twoUpVertical", "2-up Vertical"), + ("window.arrange.threeUpHorizontal", "3-up Horizontal"), + ("window.arrange.threeUpVertical", "3-up Vertical"), + ("window.arrange.threeUpStacked", "3-up Stacked"), + ("window.arrange.fourUp", "4-up"), + ("window.arrange.sixUp", "6-up"), + ("window.arrange.consolidateAllToTabs", "Consolidate All to Tabs"), + ("---", "---"), + ("window.arrange.cascade", "Cascade"), + ("window.arrange.tile", "Tile"), + ("window.arrange.floatInWindow", "Float in Window"), + ("window.arrange.floatAllInWindows", "Float All in Windows"), + ("---", "---"), + ("window.arrange.matchZoom", "Match Zoom"), + ("window.arrange.matchLocation", "Match Location"), + ("window.arrange.matchRotation", "Match Rotation"), + ("window.arrange.matchAll", "Match All"), + ("---", "---"), + ("window.arrange.newWindowForDocument", "New Window for W1"), + ]; + let pairs: Vec<(&str, &str)> = got.iter().map(|(id, label, _)| (id.as_str(), label.as_str())).collect(); + assert_eq!(pairs, expected); + assert!(got.iter().all(|(_, _, shortcut)| shortcut.is_none()), "no Window › Arrange entry carries a shortcut: {got:?}"); + + // Activating another document updates the dynamic label while keeping the command id. + new_doc(&mut app, "W2"); + let second = arrange_list(&mut app, &ctx); + assert_eq!(second.last().map(|(id, label, _)| (id.as_str(), label.as_str())), Some(("window.arrange.newWindowForDocument", "New Window for W2"))); + + app.session.set_active(0); + let back = arrange_list(&mut app, &ctx); + assert_eq!(back.last().map(|(id, label, _)| (id.as_str(), label.as_str())), Some(("window.arrange.newWindowForDocument", "New Window for W1"))); +} + +#[test] +fn new_window_for_document_label_uses_translation_catalog_with_english_fallback() { + let translated = crate::i18n::fixture_lang("fr", "\tNew Window for {name}\tNouvelle fenêtre pour {name}\n"); + let missing = crate::i18n::fixture_lang("fr", ""); + + assert_eq!(translated_menu_label(translated, "window.arrange.newWindowForDocument", "New Window for W1"), "Nouvelle fenêtre pour W1"); + assert_eq!(translated_menu_label(missing, "window.arrange.newWindowForDocument", "New Window for W1"), "New Window for W1"); + assert_eq!(translated_menu_label(crate::i18n::Lang::EN, "window.arrange.newWindowForDocument", "New Window for W1"), "New Window for W1"); +} diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index 0d9bd0e3d3e..6a046a5b8ee 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -258,6 +258,12 @@ pub fn base_rows(app: &PhotocraftApp) -> Vec { if let Some(item) = find(&mut rows, "layer.smartObjects.revealInFinder") { item.label = reveal_label().into(); } + // Window › Arrange › New Window names the active document (#16888). + if let Some(st) = app.session.active() + && let Some(item) = find(&mut rows, "window.arrange.newWindowForDocument") + { + item.label = format!("New Window for {}", st.doc.name); + } // File › Open Recent: a dynamic submenu of recently opened files, after Open as Smart Object… (#14053). if let Some(after) = rows.iter().position(|i| i.command.id == "file.openAsSmartObject").or_else(|| rows.iter().position(|i| i.command.id == "file.openAs")) { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index bf3cd0c253e..05acaf57555 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -235,5 +235,10 @@ pub(super) fn translated_menu_label(lang: crate::i18n::Lang, id: &str, label: &s { return crate::i18n::tr_id(lang, id, "Quick Export as PNG").replace("PNG", fmt); } + if id == "window.arrange.newWindowForDocument" + && let Some(name) = label.strip_prefix("New Window for ") + { + return crate::i18n::fmt(crate::i18n::tr(lang, "New Window for {name}"), &[("name", name)]); + } crate::i18n::tr_id(lang, id, label).to_string() } diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 846a92400a9..6c48c63f297 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -305,6 +305,8 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.sync_views(); + app.run("tools.setColors", json!({"foreground": FOREGROUND})).unwrap(); + app.ui.tool = Tool::PaintBucket; + app +} + +fn click(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, mods); +} + +fn pasteboard(app: &PhotocraftApp) -> (CanvasColor, String) { + let i = &app.session.prefs().interface; + (i.canvas_color, i.canvas_custom_color.clone()) +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn revision(app: &PhotocraftApp) -> u64 { + app.session.active().unwrap().revision +} + +fn pixel(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] { + let st = app.session.active().unwrap(); + let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8) +} + +#[test] +fn shift_click_on_the_pasteboard_sets_the_custom_colour_to_the_foreground() { + // Above-left of the image and past its bottom-right corner: both are pasteboard. + for p in [[-30.0, -30.0], [230.0, 170.0]] { + let mut app = app(); + assert_eq!(pasteboard(&app).0, CanvasColor::Default); + click(&mut app, p, Modifiers::SHIFT); + assert_eq!(pasteboard(&app), (CanvasColor::Custom, FOREGROUND.to_string()), "at {p:?}"); + // The pasteboard menu then shows Custom checked, and only Custom. + assert!(open_at(&mut app, Tool::PaintBucket, Mods::NONE, egui::Pos2::ZERO, [-30.0, -30.0], None)); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(mode_checked(&app, &menu, "pasteboard.custom")); + assert!(!mode_checked(&app, &menu, "pasteboard.default")); + } +} + +#[test] +fn shift_click_on_the_pasteboard_adds_no_history_state_and_keeps_the_document() { + let mut app = app(); + let (before_steps, before_revision) = (steps(&app), revision(&app)); + click(&mut app, [-30.0, -30.0], Modifiers::SHIFT); + assert_eq!(steps(&app), before_steps, "no history state"); + assert_eq!(revision(&app), before_revision, "the document did not change"); + assert!(!app.session.active().unwrap().is_dirty()); + assert_eq!(pixel(&app, 0, 0), [255, 255, 255]); +} + +#[test] +fn shift_click_on_the_pasteboard_with_a_type_layer_active_sets_the_colour_without_a_rasterize_prompt() { + // The active layer is a Type layer: a painting press on it would ask to rasterize it + // first, but this gesture only sets a preference, so it runs before that prompt and + // leaves the layer and the document alone. + let mut app = app(); + app.run("type.create", json!({"x": 10, "y": 40, "text": "Hello"})).unwrap(); + app.ui.tool = Tool::PaintBucket; + let (before_steps, before_revision) = (steps(&app), revision(&app)); + click(&mut app, [-30.0, -30.0], Modifiers::SHIFT); + assert_eq!(pasteboard(&app), (CanvasColor::Custom, FOREGROUND.to_string())); + assert!(app.framework.dialogs.open_dialogs().is_empty(), "no rasterize prompt"); + assert_eq!(steps(&app), before_steps, "no history state"); + assert_eq!(revision(&app), before_revision, "the document did not change"); +} + +#[test] +fn shift_click_on_the_image_fills_as_a_plain_click_does() { + let mut app = app(); + let before = steps(&app); + click(&mut app, [50.0, 50.0], Modifiers::SHIFT); + assert_eq!(steps(&app), before + 1, "the fill was applied"); + assert_eq!(pixel(&app, 50, 50), [0x33, 0x66, 0xcc]); + assert_eq!(pasteboard(&app).0, CanvasColor::Default, "the pasteboard colour is untouched"); +} + +#[test] +fn unmeasured_pasteboard_gestures_keep_the_pasteboard_colour() { + // A plain click, ⇧ with another modifier, and ⇧ with a selection active are not this gesture. + for (mods, select) in + [(Modifiers::NONE, false), (Modifiers::SHIFT | Modifiers::ALT, false), (Modifiers::SHIFT | Modifiers::COMMAND, false), (Modifiers::SHIFT, true)] + { + let mut app = app(); + if select { + app.run("select.rect", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + } + click(&mut app, [-30.0, -30.0], mods); + assert_eq!(pasteboard(&app).0, CanvasColor::Default, "{mods:?}, selection {select}"); + } +} diff --git a/crates/ui-egui/src/panels/actions/runner.rs b/crates/ui-egui/src/panels/actions/runner.rs index 96cc04fcd37..e7ef3a91a19 100644 --- a/crates/ui-egui/src/panels/actions/runner.rs +++ b/crates/ui-egui/src/panels/actions/runner.rs @@ -772,12 +772,24 @@ pub(crate) fn report_play(app: &mut PhotocraftApp, v: &Value) { }; let step = failed.get("step").and_then(Value::as_u64).unwrap_or(0); let id = failed.get("id").and_then(Value::as_str).unwrap_or(""); - let error = failed.get("error").and_then(Value::as_str).unwrap_or(""); + let error = step_error(failed.get("error").and_then(Value::as_str).unwrap_or("")); let template = "Step {step} ({id}) failed: {error}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("step", &(step + 1).to_string()), ("id", id), ("error", error)]); app.ui.status_error = true; } +/// A failed step's `error` in the UI language when the engine's message is one the shell spells out, otherwise as the +/// engine gave it. Automation clients keep the engine's English. +fn step_error(error: &str) -> &str { + if error.ends_with(photocraft_engine::atn_cmds::CAF_CUSTOM_AREA_NOT_REMEMBERED) { + // The engine's text, as a literal the translation coverage report collects (#14254). + return tl!( + "This step plays with the remembered Content-Aware Fill settings, and their Custom sampling area isn't remembered. Fill once with Auto or Rectangular sampling in Content-Aware Fill, then play it again." + ); + } + error +} + /// Resume the recording a paused call suspended and journal that call, once. fn restore_recording(app: &mut PhotocraftApp, owner: Option<&Value>) { let Some(owner) = owner else { return }; diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 961b2318ef7..4fc4946020c 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -262,27 +262,43 @@ fn stamp_members(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) { // Pattern Stamp's list has Behind, greyed on the Background. let entries = fill::mode_entries(tool, crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind), threshold); if !entries.is_empty() { - let current = - if tool == Tool::PatternStamp && brush.behind { PaintMode::Behind } else { PaintMode::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)) }; + let current = if tool == Tool::Healing && app.ui.tool_options.healing_replace { + PaintMode::HealingReplace + } else if tool == Tool::PatternStamp && brush.behind { + PaintMode::Behind + } else { + PaintMode::Blend(crate::blend_keys::brush_tool_mode(tool, brush.mode)) + }; let picked = labelled(ui, tl!("Mode"), |ui| { let select = fill::mode_select(Bind::given(current), &entries); let select = if tool == Tool::CloneStamp { select.tooltip(tl!("Painting Mode")) } else { select }; select.show(ui) }); if let Some(mode) = picked.and_then(|shown| shown.events.value().cloned()) { - let mut after = brush.clone(); - match mode { - PaintMode::Blend(blend) => { - after.mode = blend; - if tool == Tool::PatternStamp { - after.behind = false; - } + if mode == PaintMode::HealingReplace { + // Replace (#12101): a tool option like the painting tools' Clear, with no brush + // value to write: the next stroke carries mode:"replace", and picking a Mode adds + // no History step. + app.ui.tool_options.healing_replace = true; + } else { + if tool == Tool::Healing { + // Any of the seven blend modes leaves Replace (#12101). + app.ui.tool_options.healing_replace = false; } - PaintMode::Behind => after.behind = true, - PaintMode::Clear => {} + let mut after = brush.clone(); + match mode { + PaintMode::Blend(blend) => { + after.mode = blend; + if tool == Tool::PatternStamp { + after.behind = false; + } + } + PaintMode::Behind => after.behind = true, + PaintMode::Clear | PaintMode::HealingReplace => {} + } + // A pick is one step of its own. + crate::brush_panel::commit_keyed(app, &brush, &after, None); } - // A pick is one step of its own. - crate::brush_panel::commit_keyed(app, &brush, &after, None); } } // Both stamps use whole percents. Only Clone Stamp alerts on an out-of-range commit (#12607). @@ -417,3 +433,7 @@ mod clone_stamp_fields_tests; #[cfg(test)] #[path = "art_history_bar_controls_tests.rs"] mod art_history_bar_controls_tests; + +#[cfg(test)] +#[path = "../healing_mode_menu_tests.rs"] +mod healing_mode_menu_tests; diff --git a/crates/ui-egui/src/panels/options_bar/fill.rs b/crates/ui-egui/src/panels/options_bar/fill.rs index 61e9ff4df51..dffe5fb1f10 100644 --- a/crates/ui-egui/src/panels/options_bar/fill.rs +++ b/crates/ui-egui/src/panels/options_bar/fill.rs @@ -16,6 +16,7 @@ fn label_of(mode: PaintMode) -> String { PaintMode::Blend(blend) => tl!(blend.label()).to_owned(), PaintMode::Behind => tl!("Behind").to_owned(), PaintMode::Clear => tl!("Clear").to_owned(), + PaintMode::HealingReplace => tl!("Replace").to_owned(), } } @@ -26,6 +27,25 @@ fn label_of(mode: PaintMode) -> String { pub(crate) fn mode_entries(tool: Tool, behind_enabled: bool, threshold: bool) -> Vec> { static CACHE: crate::i18n::LangCache<(Tool, bool, bool), Vec>> = crate::i18n::LangCache::new(); CACHE.get_or_build((tool, behind_enabled, threshold), || { + if tool == Tool::Healing { + // The Healing Brush's measured list (#12101): Normal, Replace, a rule, Multiply, + // Screen, Darken, Lighten, a rule, Color, Luminosity. Not the blend-group rules: the + // reference starts its groups elsewhere in this short list. Replace has no letter: the + // ⇧⌥ keys and the ⇧+ / ⇧− cycle keep the seven blend modes. + let blend = |b: BlendMode| Entry::new(PaintMode::Blend(b), label_of(PaintMode::Blend(b))); + return vec![ + blend(BlendMode::Normal), + Entry::new(PaintMode::HealingReplace, label_of(PaintMode::HealingReplace)), + Entry::separator(), + blend(BlendMode::Multiply), + blend(BlendMode::Screen), + blend(BlendMode::Darken), + blend(BlendMode::Lighten), + Entry::separator(), + blend(BlendMode::Color), + blend(BlendMode::Luminosity), + ]; + } let keyed: Vec> = if tool == Tool::PatternStamp { crate::brush_mode_menu::pattern_stamp_choices() .into_iter() @@ -78,6 +98,8 @@ pub(super) fn members(app: &mut PhotocraftApp, ui: &mut egui::Ui) { o.bucket_blend_mode = blend; } PaintMode::Behind => {} + // Replace belongs to the Healing Brush's list, never the Paint Bucket's. + PaintMode::HealingReplace => {} } if let Some(opacity) = number_field(ui, tl!("Opacity"), o.fill_opacity, 1.0..=100.0, "%").landed() { o.fill_opacity = *opacity; diff --git a/crates/ui-egui/src/panels/options_bar/paint.rs b/crates/ui-egui/src/panels/options_bar/paint.rs index c98fecb0949..765873a3df7 100644 --- a/crates/ui-egui/src/panels/options_bar/paint.rs +++ b/crates/ui-egui/src/panels/options_bar/paint.rs @@ -28,6 +28,9 @@ pub(crate) enum PaintMode { Behind, /// Paint transparency. Clear, + /// The Healing Brush's Replace (#12101): copy the source without healing. A tool option, not a + /// brush value; only the Healing Brush's Mode list offers it. + HealingReplace, } impl PaintMode { @@ -37,6 +40,7 @@ impl PaintMode { PaintMode::Blend(m) => m.label(), PaintMode::Behind => "Behind", PaintMode::Clear => "Clear", + PaintMode::HealingReplace => "Replace", } } } @@ -209,6 +213,9 @@ fn apply_values(app: &mut PhotocraftApp, tool: Tool, brush: &mut BrushSettings, brush.mode = BlendMode::Normal; } PaintMode::Clear => brush.behind = false, + // Replace is the Healing Brush's row; a paint-bar tool's list never shows it, so + // `after.mode` is never this here. + PaintMode::HealingReplace => {} } } } diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 7c699804aed..7d469db67d0 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -93,6 +93,9 @@ pub struct ToolOptions { pub pattern_stamp_angle: f32, /// current | currentAndBelow | all pub clone_sample: String, + /// Healing Brush › Mode: Replace, which copies the source without healing (#12101). Like the + /// painting tools' Clear flags it is tool-only: the stroke params carry it, not the brush. + pub healing_replace: bool, /// Spot Healing: contentAware | createTexture | proximityMatch pub spot_type: String, /// Patch: source (repair the selection) | destination (repair where it is dragged). @@ -479,6 +482,7 @@ impl Default for ToolOptions { pattern_stamp_scale: 100.0, pattern_stamp_angle: 0.0, clone_sample: "current".into(), + healing_replace: false, spot_type: "contentAware".into(), patch_mode: "source".into(), patch_content_aware: false, diff --git a/crates/ui-egui/src/task_bar_pasteboard_entry_tests.rs b/crates/ui-egui/src/task_bar_pasteboard_entry_tests.rs new file mode 100644 index 00000000000..f88e7fdbbbd --- /dev/null +++ b/crates/ui-egui/src/task_bar_pasteboard_entry_tests.rs @@ -0,0 +1,66 @@ +//! #16757: with the Move tool, the pasteboard's right-click menu starts with Hide Contextual Task Bar +//! (Show Contextual Task Bar while the bar is off) and a separator, and the row toggles the same flag +//! as Window › Contextual Task Bar. + +use egui::{Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::canvas_tool_menu::tests::{harness, right_click}; +use crate::state::Tool; + +fn app(tool: Tool) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.ui.tool = tool; + app +} + +/// Right-clicks the pasteboard and returns the open menu's rows, a separator as `None`. +fn pasteboard_rows(h: &mut Harness<'static, Box>) -> Vec> { + let pasteboard = h.state().last_canvas_rect.min + vec2(5.0, 5.0); + right_click(h, pasteboard, Modifiers::NONE); + let inspected = crate::control::inspect(h.state(), &h.ctx); + assert_eq!(inspected["canvasToolMenu"]["pasteboard"], json!(true), "the pasteboard menu opens"); + let entries = inspected["canvasToolMenu"]["entries"].as_array().expect("pasteboard menu entries"); + entries.iter().map(|e| if e["separator"] == json!(true) { None } else { e["label"].as_str().map(str::to_owned) }).collect() +} + +#[test] +fn the_move_tools_pasteboard_menu_starts_with_the_task_bar_row() { + let mut marquee = harness(app(Tool::RectMarquee)); + let today = pasteboard_rows(&mut marquee); + assert!(!today.iter().flatten().any(|label| label.contains("Contextual Task Bar")), "other tools keep today's menu: {today:?}"); + + let mut h = harness(app(Tool::Move)); + let rows = pasteboard_rows(&mut h); + assert_eq!(rows.first(), Some(&Some("Hide Contextual Task Bar".to_owned())), "{rows:?}"); + assert_eq!(rows.get(1), Some(&None), "a separator under it: {rows:?}"); + assert_eq!(rows[2..], today[..], "then today's colour rows"); +} + +#[test] +fn the_task_bar_row_hides_and_shows_the_bar_as_the_window_item_does() { + let mut h = harness(app(Tool::Move)); + assert!(h.state().ui.panels.context_task_bar); + + pasteboard_rows(&mut h); + h.get_by_label("Hide Contextual Task Bar").click(); + h.run_steps(2); + assert!(!h.state().ui.panels.context_task_bar, "the row hides the bar"); + assert!(h.state().ui.canvas_tool_menu.is_none(), "and closes the menu"); + // The Window item toggles the same flag: one press turns the bar back on, and off again. + let ctx = h.ctx.clone(); + let window_item = + |h: &mut Harness<'static, Box>| crate::menus::invoke(h.state_mut(), &ctx, "window.panel.contextualTaskBar", json!({})).unwrap(); + assert_eq!(window_item(&mut h), json!(true)); + assert_eq!(window_item(&mut h), json!(false)); + + let rows = pasteboard_rows(&mut h); + assert_eq!(rows.first(), Some(&Some("Show Contextual Task Bar".to_owned())), "{rows:?}"); + h.get_by_label("Show Contextual Task Bar").click(); + h.run_steps(2); + assert!(h.state().ui.panels.context_task_bar, "the row shows the bar again"); +} diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 78538b64b58..0cf75450bff 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -48,6 +48,11 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { // View › Pattern Preview: both tools carry a stroke on across the canvas edges (#8883). let sample = if clone_stamp_indexed(app) { "current" } else { o.clone_sample.as_str() }; let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview}); + // The Healing Brush's Replace row (#12101): the stroke copies the source; the word rides the + // params in place of the brush's blend mode. The Clone Stamp never sends it. + if app.ui.tool == Tool::Healing && o.healing_replace { + p["mode"] = json!("replace"); + } if app.ui.tool == Tool::CloneStamp { p["opacity"] = json!(app.session.tools.brush.opacity * 100.0); p["flow"] = json!(app.session.tools.brush.flow * 100.0); diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index f324663a30e..8f75a3c8be8 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -234,7 +234,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Zoom => reset!(zoom_scrubby, zoom_in), Tool::Hand => reset!(hand_scroll_all), Tool::SpotHealing => reset!(spot_type), - Tool::Healing => reset!(clone_aligned, clone_sample), + Tool::Healing => reset!(clone_aligned, clone_sample, healing_replace), Tool::Patch => reset!(patch_mode, patch_content_aware, patch_structure, patch_color), Tool::ContentAwareMove => reset!(cam_mode, cam_structure, cam_color, cam_transform_on_drop), Tool::RedEye => reset!(red_eye_pupil_size, red_eye_darken), diff --git a/crates/ui-egui/src/tools/vector_ui/custom_shape_path_make_tests.rs b/crates/ui-egui/src/tools/vector_ui/custom_shape_path_make_tests.rs new file mode 100644 index 00000000000..c6a9f9f45a7 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/custom_shape_path_make_tests.rs @@ -0,0 +1,81 @@ +//! #13471: in Path mode the Custom Shape tool's options bar shows Make: Selection… · Mask · Shape, greyed with no path; +//! with a path just drawn they are enabled and Shape turns the path into a shape layer. Shape mode has no Make row. + +use egui::{Modifiers, PointerButton}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +use super::super::test_input::harness; +use crate::PhotocraftApp; +use crate::canvas::testing; +use crate::state::Tool; +use craft::draw::ui::VectorMode; + +type H = Harness<'static, Box>; + +const MAKE: [&str; 3] = ["Selection…", "Mask", "Shape"]; + +fn custom_shape(mode: VectorMode) -> H { + let mut h = harness(Tool::CustomShape); + h.state_mut().ui.tool_options.shape_mode = mode; + h.run_steps(3); + h +} + +/// The button labelled `label`: the bar's Shape picker shares the Make button's name, so only buttons count. +fn button<'a>(h: &'a H, label: &'a str) -> Option> { + h.query_all_by_label(label).find(|n| n.accesskit_node().role() == egui::accesskit::Role::Button) +} + +/// Whether each Make button is there and enabled; `None` when it isn't shown. +fn make_buttons(h: &H) -> Vec> { + MAKE.iter().map(|label| button(h, label).map(|n| !n.accesskit_node().is_disabled())).collect() +} + +/// A drag on the canvas from `a` to `b` (document points). +fn drag(h: &mut H, a: [f64; 2], b: [f64; 2]) { + let p = testing::to_screen(h.state_mut(), a); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for i in 1..=6 { + let t = f64::from(i) / 6.0; + let q = testing::to_screen(h.state_mut(), [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]); + h.event(egui::Event::PointerMoved(q)); + h.run_steps(1); + } + let q = testing::to_screen(h.state_mut(), b); + h.event(egui::Event::PointerButton { pos: q, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); +} + +fn shape_layers(h: &H) -> usize { + let doc = &h.state().session.active().unwrap().doc; + doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, photocraft_doc::LayerContent::Shape(_))).count() +} + +#[test] +fn path_mode_shows_the_make_buttons_greyed_without_a_path() { + let h = custom_shape(VectorMode::Path); + assert!(h.query_by_label("Make:").is_some(), "the Make: label"); + assert_eq!(make_buttons(&h), vec![Some(false); 3], "all three greyed with no path"); +} + +#[test] +fn a_drawn_path_enables_them_and_shape_makes_a_shape_layer() { + let mut h = custom_shape(VectorMode::Path); + drag(&mut h, [40.0, 20.0], [140.0, 80.0]); + assert!(h.state().session.active().unwrap().doc.work_path.is_some(), "the Custom Shape tool drew a path"); + assert_eq!(make_buttons(&h), vec![Some(true); 3], "enabled with a path"); + let before = shape_layers(&h); + button(&h, "Shape").expect("the Make: Shape button").click(); + h.run_steps(3); + assert_eq!(shape_layers(&h), before + 1, "Make: Shape made a shape layer from the path"); +} + +#[test] +fn shape_mode_has_no_make_row() { + let h = custom_shape(VectorMode::Shape); + assert_eq!(make_buttons(&h), vec![None; 3]); +} diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index a23fed2de77..6f194ed3c66 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -604,6 +604,10 @@ mod line_arrow_concavity_field_tests; #[path = "pen_make_mask_tests.rs"] mod pen_make_mask_tests; +#[cfg(test)] +#[path = "custom_shape_path_make_tests.rs"] +mod custom_shape_path_make_tests; + #[cfg(test)] #[path = "triangle_path_make_tests.rs"] mod triangle_path_make_tests; diff --git a/docs/atn.md b/docs/atn.md index 76090963146..87a3de37014 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -411,35 +411,42 @@ stored descriptor no longer describes it. ### Content-Aware Fill recordings -`cafWorkspace` maps Rectangular / Default color adaptation / None rotation with New Layer or -Current Layer output to `edit.contentAwareFill`, retaining all seven keys and the three booleans: -Sample All Layers, Scale and Mirror. The selection comes from the preceding selection step. -New Layer is in the measured reference; Current Layer and the enumeration type IDs are explicit -in [Stephen Marsh's published Action Manager example](https://community.adobe.com/questions-712/expand-and-content-aware-fill-functions-are-not-working-via-javascript-1172085). +`cafWorkspace` maps every value the reference workspace shows to `edit.contentAwareFill`, +retaining all seven keys and the three booleans: Sample All Layers, Scale and Mirror. The +selection comes from the preceding selection step. The values were measured by playing each +step with dialogs on (#14254); the enumeration type IDs are explicit in +[Stephen Marsh's published Action Manager example](https://community.adobe.com/questions-712/expand-and-content-aware-fill-functions-are-not-working-via-javascript-1172085). -| Recorded key, in order | Supported value | Native parameter | +| Recorded key, in order | Supported values | Native parameter | |---|---|---| -| `cafSamplingRegion` | `cafSamplingRegionRectangular` | `sampling: "rectangular"` | +| `cafSamplingRegion` | `cafSamplingRegionAuto`, `…Rectangular`, `…Custom` | `sampling: "auto"`, `"rectangular"`, `"custom"` | | `cafSampleAllLayers` | boolean | `sampleAllLayers` | -| `cafColorAdaptationLevel` | `cafColorAdaptationDefault` | `colorAdaptation: "default"` | -| `cafRotationAmount` | `cafRotationAmountNone` | `rotationAdaptation: "none"` | +| `cafColorAdaptationLevel` | `cafColorAdaptationNone`, `…Default`, `…High`, `…VeryHigh` | `colorAdaptation: "none"`, `"default"`, `"high"`, `"veryHigh"` | +| `cafRotationAmount` | `cafRotationAmountNone`, `…Low`, `…Medium`, `…High`, `…Full` | `rotationAdaptation: "none"`, `"low"`, `"medium"`, `"high"`, `"full"` | | `cafScale` | boolean | `scale` | | `cafMirror` | boolean | `mirror` | -| `cafOutput` | `cafOutputToNewLayer`, `cafOutputToCurrentLayer` | `output: "new"`, `"current"` | +| `cafOutput` | `cafOutputToCurrentLayer`, `…NewLayer`, `…DuplicateLayer` | `output: "current"`, `"new"`, `"duplicate"` | + +An empty descriptor (no keys) plays with the settings the fill workspace remembers +(`prefs.dialogs["edit.contentAwareFill.workspace"]`), New Layer before any are remembered; it +imports as `{"_atnCafRemembered": true}`, which `playback_params` resolves, and saves back +empty. Playing a step never changes what is remembered. When the remembered sampling is Custom, +the step stops with a message instead of filling: the workspace doesn't remember the painted +Custom area (Custom reopens empty), and the step must not sample another area instead. Descriptor types, source identity and key order survive save while its native settings are unchanged. Editing a supported setting exports the new values in canonical form instead of restoring stale source values; malformed preservation data still refuses export. -Native export writes the seven keys explicitly; the known native boolean, color -adaptation, rotation and Current Layer output defaults are supported when sampling is explicitly -Rectangular. A native call using the Auto sampling default cannot yet be exported. +Native export writes the seven keys explicitly, including the command's own defaults (Auto +sampling, Current Layer output). A native step without `sampleAllLayers` refuses export: on an +empty layer the command then samples the visible composite, which neither recorded value says. -The reference's ellipses do not establish additional enum forms. Auto/Custom sampling, -other adaptation levels, Duplicate Layer output, absent keys, unknown settings and -malformed or repeated fields remain complete kept steps. Native layer targets, sampling/fill -edits and nondefault seeds also refuse export rather than lose their settings. Playback uses -the existing native fill and its selection, authorization, job and Undo/Redo behavior. The -remaining CAF forms and the other recorded tools in #10710 are still separate work. +Steps that carry only some of the seven keys (not measured), unknown settings and malformed +or repeated fields remain complete kept steps. Native layer targets, sampling/fill edits and +nondefault seeds also refuse export rather than lose their settings. Playback uses the existing +native fill and its selection, authorization, job and Undo/Redo behavior; Custom sampling +without a painted sampling area fails the step with the command's error. The other recorded +tools in #10710 are still separate work. ### Layer Style menu recordings