From 09ae3ac57144ce0afae869d1b2709e7b0742a3d5 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:23:23 +0100 Subject: [PATCH 001/136] docs: repair the moved ATN regression coverage link Corrected file path for regression coverage in gaps.md. --- docs/gaps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/gaps.md b/docs/gaps.md index ef86e534cd..62efa22d51 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -126,7 +126,7 @@ what an agent can't finish alone. - **Done 2026-10-31 (#10606):** all twelve Stylize/Pixelate ATN events (Group D) load, play and save with measured defaults, documented clamping and strict export checks. The [event reference](atn.md) now lists 128 supported and 89 unmapped events. Other Actions/scripting gaps remain; no overall readiness percentage or estimate changed. - **2026-10-21 evidence (#8304):** Save Actions expands compound layer-property edits into separate Photoshop Set events, with rename last so named layer references remain valid. - Exported descriptors and native playback at RGB 8/16/32-bit have [regression coverage](../crates/engine/src/atn_cmds/layer_props_tests.rs); + Exported descriptors and native playback at RGB 8/16/32-bit have [regression coverage](../crates/engine/src/cmd/atn_cmds/layer_props_tests.rs); independent Photoshop replay of the fix is still pending. No readiness percentage or estimate changed. - **Done 2026-10-17 (#7101):** `.atn` Apply Layer Comp steps with a named `compsClass` reference import as `layerComp.apply` and export to the same Photoshop event. Names resolve From fd7c786a7b9874c83e705d10b724e1be5bfa116e Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 4 Nov 2026 21:23:41 +0100 Subject: [PATCH 002/136] docs: repair moved Patch and Vertical Type evidence links --- docs/target-app-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ea92f30ec6..3b8e7a4ff6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -515,8 +515,8 @@ one undo step (`strokes`), Esc (or ⊘) drops them (#1750). 2026-10-08: the tools update above is checked against the current toolbar groups in [`panels.rs`](../crates/ui-egui/src/panels.rs), the Pencil and tool-cycle tests in [`pencil_tests.rs`](../crates/ui-egui/src/pencil_tests.rs), Patch's live-preview test in -[`patch_preview.rs`](../crates/ui-egui/src/patch_preview.rs), and Vertical Type's point/paragraph -creation and undo test in [`type_tool_tests.rs`](../crates/ui-egui/src/type_tool_tests.rs). +[`patch_preview.rs`](../crates/ui-egui/src/canvas/patch_preview.rs), and Vertical Type's point/paragraph +creation and undo test in [`type_tool/canvas_tests.rs`](../crates/ui-egui/src/tools/type_tool/canvas_tests.rs). These implementations remove the tools from the missing list; they do not establish Photoshop behavioural parity. The historical estimates and corpus measurements in this assessment are unchanged; current measured floors remain in the scorecard. From 0d9e6995727b54c7d6bed753220483af9d1fbc42 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:13:07 +0100 Subject: [PATCH 003/136] fix(atn): refuse lossy Black & White coefficients Use the existing ExactLong mapping for all six Black & White coefficients so strict ATN export reports fractions it cannot preserve. Whole coefficients and native edits retain their existing behavior. --- crates/engine/src/cmd/atn_cmds/adjustments.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/adjustments.rs b/crates/engine/src/cmd/atn_cmds/adjustments.rs index 383b0b6267..39454e94d6 100644 --- a/crates/engine/src/cmd/atn_cmds/adjustments.rs +++ b/crates/engine/src/cmd/atn_cmds/adjustments.rs @@ -240,12 +240,12 @@ fn color_balance_to(p: &Value) -> Option { } const BW: &[F] = &[ - F("Rd ", "reds", Kind::Long), - F("Yllw", "yellows", Kind::Long), - F("Grn ", "greens", Kind::Long), - F("Cyn ", "cyans", Kind::Long), - F("Bl ", "blues", Kind::Long), - F("Mgnt", "magentas", Kind::Long), + F("Rd ", "reds", Kind::ExactLong), + F("Yllw", "yellows", Kind::ExactLong), + F("Grn ", "greens", Kind::ExactLong), + F("Cyn ", "cyans", Kind::ExactLong), + F("Bl ", "blues", Kind::ExactLong), + F("Mgnt", "magentas", Kind::ExactLong), F("useTint", "tint", Kind::Bool), F("tintColor", "tintColor", Kind::Color), ]; From ec143207512e83d6def0d875264a98a43910df69 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:14:20 +0100 Subject: [PATCH 004/136] test(atn): cover exact Black & White coefficients Cover all six fractional coefficients through new, direct and existing adjustment exports, strict refusal and explicit skipping, whole-number/tint controls, and native 8/16/32-bit pixel differences. The regression fails on upstream before the six field mappings change; all 234 ATN tests and 2,985 engine unit tests pass with the fix. --- crates/engine/src/cmd/atn_cmds/tests.rs | 66 +++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index b7c3764346..c2e3c564d0 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -2362,6 +2362,72 @@ fn black_white_adjustment_layer_saves_as_photoshops_class_and_old_class_still_im assert_eq!(t.actions.list[0].steps[1].1["reds"], 17, "{r}"); } +/// #11517: a native Black & White coefficient may be fractional, but an ATN long cannot. +#[test] +fn black_white_fractional_coefficients_refuse_lossy_export() { + for key in ["reds", "yellows", "greens", "cyans", "blues", "magentas"] { + for id in ["layer.newAdjustmentLayer.blackWhite", "image.adjustments.blackWhite", "layer.setAdjustment"] { + let mut params = json!({key: 40.4}); + if id == "layer.setAdjustment" { + params["kind"] = json!("blackWhite"); + } + let action = Action::new("Fractional BW", vec![(id.into(), params.clone())]); + let error = export("BW", &[&action], &[], false).unwrap_err(); + assert!(error.contains(id) && error.contains("skipUnsupported"), "{id} {key}: {error}"); + let (bytes, skipped) = export("BW", &[&action], &[], true).unwrap(); + assert_eq!(skipped, vec![Skipped { action: "Fractional BW".into(), step: 0, id: id.into() }]); + assert!(import(&bytes).unwrap().actions[0].steps.is_empty()); + assert_eq!(action.steps[0].1, params, "export must preserve the native action"); + } + } +} + +#[test] +fn black_white_whole_coefficients_and_defaults_round_trip() { + for id in ["layer.newAdjustmentLayer.blackWhite", "image.adjustments.blackWhite", "layer.setAdjustment"] { + for mut params in [ + json!({}), + json!({"reds": 40.0}), + json!({"reds": 17, "yellows": 83, "greens": -12, "cyans": 107, "blues": 51, "magentas": 133, "tint": true, "tintColor": "#c08040"}), + ] { + if id == "layer.setAdjustment" && params == json!({}) { + continue; + } + if id == "layer.setAdjustment" { + params["kind"] = json!("blackWhite"); + } + let action = Action::new("Whole BW", vec![(id.into(), params.clone())]); + let (bytes, skipped) = export("BW", &[&action], &[], false).unwrap(); + assert!(skipped.is_empty()); + let imported = import(&bytes).unwrap(); + assert!(imported.unsupported.is_empty() && imported.warnings.is_empty()); + let (back_id, back) = &imported.actions[0].steps[0]; + assert_eq!(back_id, id); + for key in ["reds", "yellows", "greens", "cyans", "blues", "magentas"] { + assert_eq!(back.get(key).and_then(Value::as_f64), params.get(key).and_then(Value::as_f64), "{id} {key}: {back}"); + } + for key in ["tint", "tintColor"] { + assert_eq!(back.get(key), params.get(key), "{id} {key}"); + } + } + } +} + +/// The reported fraction remains a real native edit at every supported document depth. +#[test] +fn black_white_native_fraction_keeps_its_pixels_at_every_depth() { + for depth in [8, 16, 32] { + let mut samples = Vec::new(); + for reds in [40.4, 40.0] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1, "height": 1, "background": "#ff0000", "depth": depth})).unwrap(); + s.execute("layer.newAdjustmentLayer.blackWhite", json!({"reds": reds})).unwrap(); + samples.push(photocraft_compose::flatten(&s.active().unwrap().doc).into_px()); + } + assert_ne!(samples[0], samples[1], "{depth}-bit native 40.4 must differ from rounded 40"); + } +} + /// Smart Blur's quality uses Photoshop's `SmBQ` codes (`SBQL`/`SBQM`/`SBQH`): measured in /// Photoshop, the old `Hgh `/`Mdm `/`Low ` play back as its fallback quality. Old codes still read. #[test] From 1f22e5e6e2bcb7e7ab6b8ced7c18e3a04ac10485 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 5 Nov 2026 20:15:40 +0100 Subject: [PATCH 005/136] docs(atn): explain fractional Black & White refusal Document integer ATN coefficient storage, strict refusal and explicit skip reporting while native Black & White commands retain fractional coefficients. --- docs/atn.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/atn.md b/docs/atn.md index 0e72430eeb..b9f900afaf 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -372,6 +372,9 @@ This is another implemented subset of #10723, not support for its remaining even - Close without `Svng` preserves the unanswered save choice. Headless playback refuses to discard a changed document. Native `file.close` still defaults to discard; `save: "ask"` opts into this policy. - Photo Filter converts recorded Lab colours through `photocraft-cms`. +- Black & White exports store coefficients as signed 32-bit integers. Strict export refuses + fractional coefficients; `skipUnsupported:true` reports the omitted step. Native commands + retain fractional coefficients. - Direct Vibrance and Gradient Map save as the string events `vibrance` and `gradientMapEvent`. Stroke Outside uses `StrL.Otsd`, group Pass Through uses `BlnM.passThrough`, Canvas Size extension colours use `FrgC` and `Clr `, and Absolute Colorimetric intent uses `Inte.AClr`. From 7612783032165849f02fd7d228cd99da50e4ee46 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:29:19 +0100 Subject: [PATCH 006/136] fix(atn): preserve explicit Image Size dimensions over percent Write each Image Size dimension once. Use percent only for a side without an explicit numeric size and keep mixed dimensions unconstrained. Fixes the lossy export path reported in #11516. --- crates/engine/src/cmd/atn_cmds/steps_doc.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/atn_cmds/steps_doc.rs b/crates/engine/src/cmd/atn_cmds/steps_doc.rs index f4f8bf883c..f48ce3c937 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_doc.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_doc.rs @@ -556,7 +556,18 @@ pub(super) fn image_size_to(_: &str, p: &Value) -> Option { return None; } if let Some(pc) = jnum(p, "percent").filter(|_| !resolution_only) { - d = d.with("Wdth", pct(pc)).with("Hght", pct(pc)).with("CnsP", D::Boolean(true)); + // An explicit side wins in the native command; never write duplicate dimension keys. + let width_percent = jnum(p, "width").is_none(); + let height_percent = jnum(p, "height").is_none(); + if width_percent { + d = d.with("Wdth", pct(pc)); + } + if height_percent { + d = d.with("Hght", pct(pc)); + } + if width_percent || height_percent { + d = d.with("CnsP", D::Boolean(width_percent && height_percent)); + } } if let Some(w) = jnum(p, "width").filter(|_| !resolution_only) { if unit == PT && w <= 0.0 { From f9a1d97ba1c5ff3e0748b1afab8a1258a7127a23 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:30:06 +0100 Subject: [PATCH 007/136] test(atn): cover explicit Image Size and percent precedence Compare native resize and strict ATN save/load/play across 8, 16 and 32-bit documents, including explicit width, explicit height, both sides, percent-only and no-resample controls. Verify each wire dimension key appears once. --- crates/engine/src/cmd/atn_cmds/tests.rs | 60 +++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index b7c3764346..72ad9c58dc 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3419,6 +3419,66 @@ fn image_size_resolution_only_does_not_gain_keep_print_size() { assert_eq!(image_size_round_trip(¶ms), None); } +/// Explicit sides override percent in native commands; strict ATN export must keep that edit. +#[test] +fn image_size_explicit_sides_keep_precedence_over_percent() { + for depth in [8, 16, 32] { + for (params, expected) in [ + (json!({"width": 20, "percent": 50, "resample": "nearest"}), (20, 12)), + (json!({"height": 18, "percent": 50, "resample": "nearest"}), (16, 18)), + (json!({"width": 20, "height": 18, "percent": 50, "resample": "nearest"}), (20, 18)), + (json!({"percent": 50, "resample": "nearest"}), (16, 12)), + (json!({"width": 20, "resample": "nearest"}), (20, 15)), + (json!({"height": 18, "resample": "nearest"}), (24, 18)), + (json!({"width": 20, "percent": 50, "resample": "none", "resolution": 144}), (32, 24)), + ] { + let mut native = Session::new(); + native.execute("file.new", json!({"width": 32, "height": 24, "depth": depth})).unwrap(); + native.execute("image.imageSize", params.clone()).unwrap(); + let size = native.active().unwrap().doc.size; + assert_eq!((size.width, size.height), expected, "native {params} at {depth} bits"); + + let mut recorded = Session::new(); + recorded.actions.list.push(Action::new("Resize", vec![("image.imageSize".into(), params.clone())])); + let before = recorded.actions.list.clone(); + let saved = recorded.execute("actions.save", json!({"action": "Resize"})).unwrap(); + assert_eq!(saved["skipped"], json!([])); + assert_eq!(saved["steps"], 1); + assert_eq!(recorded.actions.list, before); + + let mut replay = Session::new(); + let loaded = replay.execute("actions.load", json!({"data": saved["data"]})).unwrap(); + assert_eq!(loaded["unsupported"], json!([])); + replay.execute("file.new", json!({"width": 32, "height": 24, "depth": depth})).unwrap(); + let played = replay.execute("actions.play", json!({"action": "Resize"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(replay.active().unwrap().doc.size, size, "ATN {params} at {depth} bits"); + } + } +} + +#[test] +fn image_size_dimensions_have_unique_atn_keys() { + for (params, width, height, constrained) in [ + (json!({"width": 20, "percent": 50}), D::UnitFloat { unit: PX, value: 20.0 }, pct(50.0), Some(false)), + (json!({"height": 18, "percent": 50}), pct(50.0), D::UnitFloat { unit: PX, value: 18.0 }, Some(false)), + (json!({"width": 20, "height": 18, "percent": 50}), D::UnitFloat { unit: PX, value: 20.0 }, D::UnitFloat { unit: PX, value: 18.0 }, None), + (json!({"percent": 50}), pct(50.0), pct(50.0), Some(true)), + ] { + let action = Action::new("Resize", vec![("image.imageSize".into(), params.clone())]); + let (bytes, skipped) = export("Size", &[&action], &[], false).unwrap(); + assert!(skipped.is_empty()); + let file = atn::parse(&bytes).unwrap(); + let d = file.actions[0].items[0].descriptor.as_ref().unwrap(); + for (key, value) in [("Wdth", width), ("Hght", height)] { + assert_eq!(d.items.iter().filter(|(id, _)| id.is(key)).count(), 1, "{key}: {params}"); + assert_eq!(d.get(key), Some(&value), "{key}: {params}"); + } + assert_eq!(get_bool(d, "CnsP"), constrained, "{params}"); + } +} + #[test] fn image_size_intentional_controls_still_round_trip() { for params in [ From 5f9275bb2405b219eaba2729558c6fe1a8a731a0 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:30:49 +0100 Subject: [PATCH 008/136] docs(atn): describe explicit Image Size precedence Document that explicit pixel dimensions override percent while a missing side keeps its percentage. --- docs/atn.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/atn.md b/docs/atn.md index 0e72430eeb..f14ce6138a 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -400,7 +400,8 @@ The Vibrance event and adjustment-opacity handling incorporate [@bommerts' contr - Image Size preserves `scaleStyles`. Native calls default to true; an absent ATN flag means false (the reference application plays both alike), so Save writes the key only when it is true. - Crop and resolution-only resizing retain their existing behavior. + Explicit pixel dimensions take precedence over `percent`; a side without an explicit size + keeps its percentage. Crop and resolution-only resizing retain their existing behavior. - Convert to Profile preserves `Dthr`, `Fltt` and `rasterizePlaced`, defaulting to false. `sdwM` is written as the reference application records it (-1); other values and malformed flags remain kept steps. Absolute intent writes `AClr`, with `AbsC` still accepted on import. From e0194f143e8de8a383d86fee6d1045f9402f559f Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 00:49:22 +0100 Subject: [PATCH 009/136] WIP: Tools: add the Adjustment Brush Tool (#12519) From 8e54fc2df3af8c3e816939874730d216f8b657a1 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:04:59 +0100 Subject: [PATCH 010/136] Engine: paint.adjustmentBrush, the Adjustment Brush Tool's stroke (#12519) --- crates/engine/src/cmd.rs | 4 + .../engine/src/cmd/adjustment_brush_cmds.rs | 263 +++++++++++++++ .../src/cmd/adjustment_brush_cmds_tests.rs | 302 ++++++++++++++++++ crates/engine/src/cmd/brush_cmds.rs | 6 + crates/engine/src/cmd/channel_cmds.rs | 2 +- .../engine/src/cmd/channel_cmds/targeting.rs | 5 + crates/engine/src/lib.rs | 1 + 7 files changed, 582 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/adjustment_brush_cmds.rs create mode 100644 crates/engine/src/cmd/adjustment_brush_cmds_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index d44758cd52..b6ed6ed878 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -58,6 +58,9 @@ pub mod actions_cmds; pub mod actions_edit_cmds; pub mod adjust_cmds; mod adjust_params; +pub mod adjustment_brush_cmds; +#[cfg(test)] +mod adjustment_brush_cmds_tests; pub mod align_cmds; pub mod analysis_cmds; pub mod artboard_cmds; @@ -1375,6 +1378,7 @@ fn build() -> Vec { v.extend(crate::actions_edit_cmds::specs()); v.extend(crate::swatch_cmds::specs()); v.extend(crate::retouch_cmds::specs()); + v.extend(crate::adjustment_brush_cmds::specs()); v.extend(crate::redeye_cmds::specs()); v.extend(crate::image_cmds::specs()); v.extend(crate::perspective_crop_cmds::specs()); diff --git a/crates/engine/src/cmd/adjustment_brush_cmds.rs b/crates/engine/src/cmd/adjustment_brush_cmds.rs new file mode 100644 index 0000000000..73c228f46e --- /dev/null +++ b/crates/engine/src/cmd/adjustment_brush_cmds.rs @@ -0,0 +1,263 @@ +//! The Adjustment Brush Tool (#12519): painting on the image makes an adjustment layer whose mask +//! is what was painted, or paints into the mask of the active adjustment layer of the chosen kind. +//! The kinds it offers, which of them a document's colour mode and bit depth grey out, and the +//! starting values a new layer gets, as measured in the reference application. + +use photocraft_doc::{Adjustment, ColorMode, Layer, LayerContent, LayerMask, SampleType}; +use serde_json::{Value, json}; + +use super::adjust_params::adjustment_kind; +use super::layer_params::{mask_at_depth, selection_mask}; +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +const CMD: &str = "paint.adjustmentBrush"; + +/// The history state of a stroke that makes the layer. +pub const NEW_LAYER_LABEL: &str = "New Adjustment Layer"; +/// The history state of a stroke into an existing adjustment layer's mask. +pub const STROKE_LABEL: &str = "Adjustment Brush"; + +/// The alert a stroke on an Indexed Color document shows; nothing changes. +pub const INDEXED_ALERT: &str = + "Could not complete your request because the tool does not work with Indexed Color images. Please convert the image to RGB or another supported mode before using."; + +/// One entry of the options bar's Adjustment dropdown: the kind id (the `layer.newAdjustmentLayer` +/// suffix for the kinds that exist), its label, and whether a separator follows it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Entry { + pub kind: &'static str, + pub label: &'static str, + pub separator_after: bool, +} + +const fn entry(kind: &'static str, label: &'static str, separator_after: bool) -> Entry { + Entry { kind, label, separator_after } +} + +/// The dropdown in the reference application's order, separators after Grain, Exposure and +/// Selective Color. +pub const ENTRIES: [Entry; 18] = [ + entry("light", "Light", false), + entry("colorVibrance", "Color and vibrance", false), + entry("clarityDehaze", "Clarity and dehaze", false), + entry("grain", "Grain", true), + entry("levels", "Levels", false), + entry("curves", "Curves", false), + entry("exposure", "Exposure", true), + entry("hueSaturation", "Hue/Saturation", false), + entry("colorBalance", "Color Balance", false), + entry("blackWhite", "Black & White", false), + entry("photoFilter", "Photo Filter", false), + entry("channelMixer", "Channel Mixer", false), + entry("colorLookup", "Color Lookup", false), + entry("selectiveColor", "Selective Color", true), + entry("invert", "Invert", false), + entry("posterize", "Posterize", false), + entry("threshold", "Threshold", false), + entry("gradientMap", "Gradient Map", false), +]; + +/// Entries whose adjustment doesn't exist yet: always greyed. +const MISSING: [&str; 4] = ["light", "colorVibrance", "clarityDehaze", "grain"]; + +/// The entry the tool starts on: the reference application's default (Light) while it is +/// available, else the first enabled entry. +pub const DEFAULT_KIND: &str = "levels"; + +/// The entry with id `kind`. +pub fn entry_of(kind: &str) -> Option<&'static Entry> { + ENTRIES.iter().find(|e| e.kind == kind) +} + +/// Is `kind` offered (not greyed) in a document of `mode` and `depth`? Indexed Color refuses +/// the stroke as a whole ([`INDEXED_ALERT`]), so its entries stay as RGB's. Bitmap, Duotone and +/// Multichannel were not measured and grey nothing extra. +pub fn enabled_in(kind: &str, mode: ColorMode, depth: SampleType) -> bool { + if entry_of(kind).is_none() || MISSING.contains(&kind) { + return false; + } + let greyed: &[&str] = match mode { + ColorMode::Grayscale => &["hueSaturation", "colorBalance", "blackWhite", "photoFilter", "channelMixer", "colorLookup", "selectiveColor"], + ColorMode::Cmyk => &["exposure", "blackWhite"], + ColorMode::Lab => &["exposure", "blackWhite", "channelMixer", "selectiveColor"], + _ => &[], + }; + let float: &[&str] = if depth == SampleType::F32 { &["invert", "posterize", "threshold", "gradientMap"] } else { &[] }; + !greyed.contains(&kind) && !float.contains(&kind) +} + +/// The kind the dropdown shows when `kind` is greyed in this document: `kind` itself when it is +/// offered, else the first offered entry. +pub fn offered_kind<'a>(kind: &'a str, mode: ColorMode, depth: SampleType) -> &'a str { + if enabled_in(kind, mode, depth) { + return kind; + } + ENTRIES.iter().map(|e| e.kind).find(|k| enabled_in(k, mode, depth)).unwrap_or(kind) +} + +/// The params of the starting values a layer of `kind` gets (the layer already changes the +/// image; these are not Layer › New Adjustment Layer's identity values). Color Lookup starts on a +/// built-in film look: the reference application ships its own film-stock table, which is not +/// ours to copy. +pub fn starting_params(kind: &str) -> Option { + Some(match kind { + "levels" => json!({"inBlack": 20, "gamma": 1.0, "inWhite": 220, "outBlack": 0, "outWhite": 255}), + "curves" => json!({"points": [[0, 0], [127, 191], [255, 255]]}), + "exposure" => json!({"exposure": 1.0, "offset": 0.0, "gamma": 1.0}), + "hueSaturation" => json!({"hue": 0, "saturation": 30, "lightness": 0, "colorize": false}), + "colorBalance" => json!({"shadows": [0, 0, 0], "midtones": [20, -15, 15], "highlights": [0, 0, 0], "preserveLuminosity": true}), + "blackWhite" => json!({"reds": 40, "yellows": 60, "greens": 40, "cyans": 60, "blues": 20, "magentas": 80, "tint": false}), + // Warming Filter (85), the reference application's Lab (67.06, 32, 120) shown in sRGB. + "photoFilter" => json!({"filter": "warming85", "density": 25, "preserveLuminosity": true}), + "channelMixer" => json!({"red": [80, 10, 10, 5], "green": [0, 100, 0, 0], "blue": [0, 0, 100, 0], "monochrome": false}), + "colorLookup" => json!({"lut": "fadedFilm"}), + "selectiveColor" => json!({"method": "relative", "reds": [-20, 100, -60, 40]}), + "invert" => json!({}), + "posterize" => json!({"levels": 4}), + "threshold" => json!({"level": 128}), + "gradientMap" => json!({"stops": [[0, "#000000"], [1, "#ffffff"]], "reverse": false, "dither": false}), + _ => return None, + }) +} + +fn bad(msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } +} + +/// The adjustment a new layer of `kind` starts with in a document of `mode`. +pub fn starting_adjustment(kind: &str, mode: ColorMode) -> Result { + let p = starting_params(kind).ok_or_else(|| bad(format!("`{kind}` is not available yet")))?; + crate::adjust_params::from_params(kind, &p, None, mode) +} + +/// The mask colours of the stroke: white adds the adjustment, black (Subtract) takes it away. +fn paint_colors(subtract: bool) -> ([f32; 4], [f32; 4]) { + let (white, black) = ([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]); + if subtract { (black, white) } else { (white, black) } +} + +/// The kind of the active layer when it is an adjustment layer (the dropdown follows it). +pub fn active_kind(s: &Session) -> Option<&'static str> { + let st = s.active()?; + let layer = st.doc.layer(st.active_layer?)?; + match &layer.content { + LayerContent::Adjustment(adj) => Some(adjustment_kind(adj)).filter(|k| entry_of(k).is_some()), + _ => None, + } +} + +fn kind_param(p: &Value) -> Result<&str> { + match p.get("kind") { + None | Some(Value::Null) => Ok(DEFAULT_KIND), + Some(Value::String(k)) => entry_of(k).map(|e| e.kind).ok_or_else(|| bad(format!("unknown adjustment `{k}`"))), + Some(other) => Err(bad(format!("`kind` must be an adjustment id, not {other}"))), + } +} + +fn subtract_param(p: &Value) -> Result { + match p.get("subtract") { + None | Some(Value::Null) => Ok(false), + Some(v) => v.as_bool().ok_or_else(|| bad("`subtract` must be true or false")), + } +} + +/// `paint.adjustmentBrush`. +fn run(s: &mut Session, p: &Value) -> Result { + if !p.is_object() { + return Err(bad("params must be an object")); + } + let (mode, depth) = { + let st = s.active().ok_or(EngineError::NoDocument)?; + (st.doc.mode, st.doc.depth) + }; + if mode == ColorMode::Indexed { + return Err(EngineError::Other(INDEXED_ALERT.into())); + } + let kind = kind_param(p)?; + if MISSING.contains(&kind) { + return Err(bad(format!("`{kind}` is not available yet"))); + } + if !enabled_in(kind, mode, depth) { + return Err(bad(format!("`{kind}` is not available in this document's color mode or bit depth"))); + } + let subtract = subtract_param(p)?; + let (fg, bg) = paint_colors(subtract); + // The stroke params without the tool's own keys, painting the mask in its colour. + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.remove("kind"); + o.remove("subtract"); + o.remove("erase"); + o.remove("mode"); + o.remove("fill"); + o.insert("color".into(), json!([fg[0], fg[1], fg[2]])); + o.insert("target".into(), json!("mask")); + } + let pts = super::brush_cmds::parse_points(&q, CMD)?; + let mut brush = super::brush_cmds::resolve_brush(s, &q, CMD)?; + brush.color = fg; + brush.color_cmyk = None; + brush.erase = false; + brush.mode = photocraft_color::BlendMode::Normal; + brush.behind = false; + let zoom = q.get("zoom").and_then(Value::as_f64).filter(|z| z.is_finite() && *z > 0.0).unwrap_or(1.0) as f32; + + // An adjustment layer of this kind with a mask is active: paint into its mask. + let paints_active = active_kind(s) == Some(kind) + && s.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|l| l.mask.is_some()); + let result = if paints_active { + let mut r = super::brush_cmds::stroke_into(s, CMD, &q, STROKE_LABEL, brush, pts)?; + r["created"] = json!(false); + r + } else { + let adj = starting_adjustment(kind, mode)?; + let label = entry_of(kind).map_or(kind, |e| e.label); + let (id, damage) = s.edit(NEW_LAYER_LABEL, |doc, active| { + let mut l = Layer::new(doc.next_layer_name(label), LayerContent::Adjustment(adj)); + // The selection becomes the mask and goes away; the stroke adds to it unclipped. + let (mut mask, revealed) = match selection_mask(doc)? { + Some(mask) => { + let revealed = doc.selection.take().map_or(photocraft_geom::Rect::EMPTY, |sel| sel.content_bounds()); + (mask, revealed) + } + None => (mask_at_depth(LayerMask::hide_all(), doc.depth)?, photocraft_geom::Rect::EMPTY), + }; + let clip = doc.bounds().union(&mask.surface.tile_bounds()); + let painted = photocraft_paint::render_stroke_clipped(&mut mask.surface, &brush, &pts, None, false, zoom, Some(clip)); + l.mask = Some(mask); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + *active = Some(id); + // The image changes where the mask reveals the adjustment: the selection and the stroke. + Ok((id, painted.union(&revealed).intersect(&doc.bounds()))) + })?; + s.hint_damage(damage); + json!({"layer": id.0, "created": true, "damage": [damage.x0, damage.y0, damage.width(), damage.height()]}) + }; + // The new layer's mask is the target, and the colours are the stroke's. + super::channel_cmds::target_layer_mask(s); + s.tools.foreground = fg; + s.tools.background = bg; + Ok(result) +} + +/// Enabled with a document open. +fn enabled(s: &Session) -> std::result::Result<(), String> { + if s.active().is_none() { + return Err("no document".into()); + } + Ok(()) +} + +pub fn specs() -> Vec { + vec![CommandSpec { + id: CMD, + label: "Adjustment Brush", + menu: &[], + shortcut: None, + params: r#"{"kind":"levels|curves|exposure|hueSaturation|colorBalance|blackWhite|photoFilter|channelMixer|colorLookup|selectiveColor|invert|posterize|threshold|gradientMap"="levels","subtract":bool=false (paint black: remove the adjustment),"points":[[x,y,pressure?],…],"size":px=tool size,"hardness":0..1,"opacity":0..1,"flow":0..1,"smoothing":0..1,"seed":u64?,"zoom":number=1} → {"layer"?,"created":bool,"damage"?} (with an adjustment layer of this kind active, the stroke paints its mask; else it makes the layer above the active one, its mask black or the selection, and paints the stroke white)"#, + enabled, + run, + journal: true, + }] +} diff --git a/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs b/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs new file mode 100644 index 0000000000..c88936af84 --- /dev/null +++ b/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs @@ -0,0 +1,302 @@ +//! Tests of `paint.adjustmentBrush`, the Adjustment Brush Tool's stroke (#12519). Reference +//! values measured in the reference application: a 100 px soft dab centred at (600, 450) on an +//! 1200 x 900 document. + +use photocraft_doc::{Adjustment, ColorMode, LayerContent, SampleType}; +use serde_json::{Value, json}; + +use super::adjustment_brush_cmds::{ENTRIES, INDEXED_ALERT, NEW_LAYER_LABEL, STROKE_LABEL, enabled_in, starting_adjustment}; +use crate::Session; + +const CMD: &str = "paint.adjustmentBrush"; + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1200, "height": 900, "background": "white"})).unwrap(); + s +} + +fn dab(kind: &str) -> Value { + json!({"kind": kind, "points": [[600, 450, 1.0]], "size": 100, "hardness": 0.0, "opacity": 1.0, "flow": 1.0}) +} + +fn active(s: &Session) -> &photocraft_doc::Layer { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap() +} + +fn mask_at(s: &Session, x: i32, y: i32) -> f32 { + active(s).mask.as_ref().expect("a layer mask").surface.sample_channel(x, y, 0) * 255.0 +} + +fn layer_count(s: &Session) -> usize { + s.active().unwrap().doc.walk().len() +} + +fn past(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +#[test] +fn first_stroke_makes_a_masked_adjustment_layer_in_one_history_state() { + let mut s = doc(); + let before = (layer_count(&s), past(&s)); + let bg = s.active().unwrap().active_layer.unwrap(); + let r = s.execute(CMD, dab("levels")).unwrap(); + assert_eq!(r["created"], json!(true)); + assert_eq!(layer_count(&s), before.0 + 1); + assert_eq!(past(&s), before.1 + 1, "one history state"); + let st = s.active().unwrap(); + assert_eq!(st.history.undo_label(), Some(NEW_LAYER_LABEL)); + let l = active(&s); + assert_eq!(l.name, "Levels 1"); + assert!(matches!(l.content, LayerContent::Adjustment(Adjustment::Levels { .. }))); + assert_eq!((l.blend, l.opacity, l.clipped), (photocraft_doc::BlendMode::Normal, 1.0, false)); + // Directly above the Background. + let order: Vec<_> = st.doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(order, vec![bg, l.id]); + // Black outside the dab, white at its centre. + assert_eq!(mask_at(&s, 10, 10), 0.0); + assert_eq!(mask_at(&s, 680, 450), 0.0); + assert!(mask_at(&s, 600, 450) >= 250.0, "centre {}", mask_at(&s, 600, 450)); + // The mask is the target, white over black. + assert!(st.channel_view.target == crate::channel_cmds::ChannelTarget::LayerMask); + assert_eq!((s.tools.foreground, s.tools.background), ([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])); +} + +#[test] +fn a_soft_dab_falls_off_like_the_reference() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + // The reference row: 550: 22, 570: 119, 590: 237, 600: 254, 620: 172, 640: 52, 660: 2, 670: 0. + let row: Vec = [550, 570, 590, 600, 620, 640, 660, 670].iter().map(|&x| mask_at(&s, x, 450)).collect(); + for w in row[..4].windows(2) { + assert!(w[0] <= w[1], "rises to the centre: {row:?}"); + } + for w in row[3..].windows(2) { + assert!(w[0] >= w[1], "falls off past it: {row:?}"); + } + assert!(row[7] <= 3.0 && row[0] < 128.0 && row[3] > 240.0, "{row:?}"); +} + +#[test] +fn layer_names_count_per_label() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + s.execute(CMD, dab("blackWhite")).unwrap(); + assert_eq!(active(&s).name, "Black & White 1"); + s.execute("layer.select", json!({"layer": {"background": true}})).unwrap(); + s.execute(CMD, dab("levels")).unwrap(); + assert_eq!(active(&s).name, "Levels 2"); +} + +#[test] +fn the_selection_becomes_the_mask_and_the_dab_is_not_clipped_to_it() { + let mut s = doc(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 400, "height": 900})).unwrap(); + let before = past(&s); + s.execute(CMD, json!({"kind": "curves", "points": [[400, 450, 1.0]], "size": 100, "hardness": 0.0})).unwrap(); + assert_eq!(past(&s), before + 1, "still one history state"); + assert!(s.active().unwrap().doc.selection.is_none(), "the selection is gone"); + assert_eq!(mask_at(&s, 100, 100), 255.0, "inside the selection"); + assert_eq!(mask_at(&s, 900, 100), 0.0, "outside it"); + // The dab reaches past the selection edge at x 400. + assert!(mask_at(&s, 420, 450) > 100.0, "{}", mask_at(&s, 420, 450)); +} + +#[test] +fn inside_an_active_group_the_layer_goes_into_the_group() { + let mut s = doc(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let group = s.active().unwrap().active_layer.unwrap(); + // An open group takes new layers, as Layer › New Adjustment Layer puts them. + s.execute("layer.setExpanded", json!({"expanded": true})).unwrap(); + s.execute(CMD, dab("invert")).unwrap(); + let id = active(&s).id; + let st = s.active().unwrap(); + let children = st.doc.layer(group).and_then(|g| g.children()).unwrap(); + assert!(children.iter().any(|l| l.id == id), "the new layer is inside the group"); +} + +#[test] +fn starting_values_are_read_back_from_the_new_layer() { + for e in ENTRIES.iter().filter(|e| enabled_in(e.kind, ColorMode::Rgb, SampleType::U8)) { + let mut s = doc(); + s.execute(CMD, dab(e.kind)).unwrap(); + let LayerContent::Adjustment(adj) = &active(&s).content else { panic!("{}: an adjustment layer", e.kind) }; + assert_eq!(adj.label(), e.label, "{}", e.kind); + assert_eq!(*adj, starting_adjustment(e.kind, ColorMode::Rgb).unwrap(), "{}", e.kind); + } +} + +#[test] +fn starting_values_match_the_reference() { + let close = |a: f32, b: f32| (a - b).abs() < 1e-3; + let adj = |kind: &str| starting_adjustment(kind, ColorMode::Rgb).unwrap(); + let Adjustment::Levels { master, .. } = adj("levels") else { panic!() }; + assert!(close(master.in_black * 255.0, 20.0) && close(master.in_white * 255.0, 220.0) && close(master.gamma, 1.0)); + assert!(close(master.out_black, 0.0) && close(master.out_white, 1.0)); + let Adjustment::Curves { master, .. } = adj("curves") else { panic!() }; + let pts: Vec<(f32, f32)> = master.iter().map(|p| (p.input * 255.0, p.output * 255.0)).collect(); + assert_eq!(pts.len(), 3); + assert!(close(pts[1].0, 127.0) && close(pts[1].1, 191.0), "{pts:?}"); + assert_eq!(adj("exposure"), Adjustment::Exposure { exposure: 1.0, offset: 0.0, gamma: 1.0 }); + let Adjustment::HueSaturation { hue, saturation, lightness, colorize, .. } = adj("hueSaturation") else { panic!() }; + assert_eq!((hue, saturation, lightness, colorize), (0.0, 30.0, 0.0, false)); + let Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } = adj("colorBalance") else { panic!() }; + assert_eq!((shadows, midtones, highlights, preserve_luminosity), ([0.0; 3], [20.0, -15.0, 15.0], [0.0; 3], true)); + assert_eq!(adj("blackWhite"), Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }); + let Adjustment::PhotoFilter { density, preserve_luminosity, .. } = adj("photoFilter") else { panic!() }; + assert!(close(density, 0.25) && preserve_luminosity); + let Adjustment::ChannelMixer { matrix, monochrome } = adj("channelMixer") else { panic!() }; + assert!(!monochrome); + let want = [[0.8, 0.1, 0.1, 0.05], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]; + assert!(matrix.iter().flatten().zip(want.iter().flatten()).all(|(a, b)| close(*a, *b)), "{matrix:?}"); + assert!(matches!(adj("colorLookup"), Adjustment::ColorLookup { lut: Some(_), .. })); + let Adjustment::SelectiveColor { relative, adjustments } = adj("selectiveColor") else { panic!() }; + assert!(relative); + assert_eq!(adjustments[0], [-20.0, 100.0, -60.0, 40.0]); + assert_eq!(adj("invert"), Adjustment::Invert); + assert_eq!(adj("posterize"), Adjustment::Posterize { levels: 4 }); + assert!(matches!(adj("threshold"), Adjustment::Threshold { level } if close(level * 255.0, 128.0))); + let Adjustment::GradientMap { stops, reverse, dither, .. } = adj("gradientMap") else { panic!() }; + assert_eq!((stops.first().map(|s| s.1), stops.last().map(|s| s.1), reverse, dither), (Some([0.0; 3]), Some([1.0; 3]), false, false)); +} + +#[test] +fn a_later_stroke_paints_the_active_layers_mask() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + let (id, n, depth) = (active(&s).id, layer_count(&s), past(&s)); + assert_eq!(mask_at(&s, 900, 450), 0.0); + let r = s.execute(CMD, json!({"kind": "levels", "points": [[900, 450, 1.0]], "size": 100, "hardness": 0.0})).unwrap(); + assert_eq!(r["created"], json!(false)); + assert_eq!((active(&s).id, layer_count(&s), past(&s)), (id, n, depth + 1), "no new layer, one more state"); + assert_eq!(s.active().unwrap().history.undo_label(), Some(STROKE_LABEL)); + assert!(mask_at(&s, 900, 450) >= 250.0); +} + +#[test] +fn a_layer_made_by_new_adjustment_layer_takes_the_stroke_too() { + let mut s = doc(); + s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + let (id, n) = (active(&s).id, layer_count(&s)); + s.execute(CMD, dab("curves")).unwrap(); + assert_eq!((active(&s).id, layer_count(&s)), (id, n)); +} + +#[test] +fn another_kind_makes_a_new_layer_above_the_active_one() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + let first = active(&s).id; + s.execute(CMD, dab("exposure")).unwrap(); + let st = s.active().unwrap(); + let order: Vec<_> = st.doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(order.len(), 3); + assert_eq!(order[1], first); + assert_eq!(active(&s).name, "Exposure 1"); +} + +#[test] +fn subtract_paints_black_and_swaps_the_colours() { + let mut s = doc(); + s.execute(CMD, json!({"kind": "levels", "points": [[600, 450], [800, 450]], "size": 100, "hardness": 1.0})).unwrap(); + assert!(mask_at(&s, 700, 450) >= 250.0); + s.execute(CMD, json!({"kind": "levels", "subtract": true, "points": [[700, 450]], "size": 40, "hardness": 1.0})).unwrap(); + assert_eq!(mask_at(&s, 700, 450), 0.0); + assert!(mask_at(&s, 610, 450) >= 250.0, "the rest stays"); + assert_eq!((s.tools.foreground, s.tools.background), ([0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0])); + s.execute(CMD, json!({"kind": "levels", "points": [[700, 450]], "size": 40, "hardness": 1.0})).unwrap(); + assert!(mask_at(&s, 700, 450) >= 250.0, "Add paints white again"); + assert_eq!(s.tools.foreground, [1.0, 1.0, 1.0, 1.0]); +} + +#[test] +fn entries_grey_out_per_mode_and_depth() { + let off = |mode, depth| -> Vec<&str> { ENTRIES.iter().map(|e| e.kind).filter(|k| !enabled_in(k, mode, depth)).collect() }; + let missing = ["light", "colorVibrance", "clarityDehaze", "grain"]; + let with = |more: &[&'static str]| -> Vec<&'static str> { + ENTRIES.iter().map(|e| e.kind).filter(|k| missing.contains(k) || more.contains(k)).collect() + }; + assert_eq!(off(ColorMode::Rgb, SampleType::U8), with(&[])); + assert_eq!(off(ColorMode::Rgb, SampleType::U16), with(&[])); + assert_eq!(off(ColorMode::Rgb, SampleType::F32), with(&["invert", "posterize", "threshold", "gradientMap"])); + assert_eq!( + off(ColorMode::Grayscale, SampleType::U8), + with(&["hueSaturation", "colorBalance", "blackWhite", "photoFilter", "channelMixer", "colorLookup", "selectiveColor"]) + ); + assert_eq!(off(ColorMode::Cmyk, SampleType::U8), with(&["exposure", "blackWhite"])); + assert_eq!(off(ColorMode::Lab, SampleType::U8), with(&["exposure", "blackWhite", "channelMixer", "selectiveColor"])); +} + +#[test] +fn a_greyed_entry_is_refused_and_an_offered_one_works_in_other_modes() { + for (mode, refused, works) in [ + ("image.mode.grayscale", "hueSaturation", "levels"), + ("image.mode.cmyk", "exposure", "curves"), + ("image.mode.lab", "channelMixer", "invert"), + ("image.mode.bits32", "posterize", "exposure"), + ("image.mode.bits16", "", "gradientMap"), + ] { + let mut s = doc(); + s.execute(mode, json!({})).unwrap(); + if !refused.is_empty() { + let before = layer_count(&s); + assert!(s.execute(CMD, dab(refused)).is_err(), "{mode}: {refused}"); + assert_eq!(layer_count(&s), before); + } + s.execute(CMD, dab(works)).unwrap_or_else(|e| panic!("{mode}: {works}: {e}")); + assert!(matches!(active(&s).content, LayerContent::Adjustment(_))); + } +} + +#[test] +fn indexed_color_refuses_the_stroke_with_the_alert() { + let mut s = doc(); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + let (n, depth) = (layer_count(&s), past(&s)); + let e = s.execute(CMD, dab("levels")).unwrap_err().to_string(); + assert!(e.contains(INDEXED_ALERT), "{e}"); + assert_eq!((layer_count(&s), past(&s)), (n, depth), "nothing changes"); +} + +#[test] +fn bad_params_are_errors_not_panics() { + let mut s = Session::new(); + assert!(s.execute(CMD, dab("levels")).is_err(), "no document"); + let mut s = doc(); + for p in [ + json!(null), + json!([]), + json!("levels"), + json!({}), + json!({"kind": "levels"}), + json!({"kind": "levels", "points": []}), + json!({"kind": "levels", "points": "x"}), + json!({"kind": "levels", "points": [[f64::MAX, 1.0]]}), + json!({"kind": "levels", "points": [[1e30, -1e30]]}), + json!({"kind": "light", "points": [[10, 10]]}), + json!({"kind": "grain", "points": [[10, 10]]}), + json!({"kind": "nope", "points": [[10, 10]]}), + json!({"kind": 7, "points": [[10, 10]]}), + json!({"kind": "levels", "subtract": "yes", "points": [[10, 10]]}), + json!({"kind": "levels", "points": [[10, 10]], "size": -5}), + json!({"kind": "levels", "points": [[10, 10]], "size": 1e12}), + json!({"kind": "levels", "points": [[10, 10]], "zoom": -1}), + json!({"kind": "levels", "points": [[10, 10]], "preset": "no such preset"}), + json!({"kind": "levels", "points": [[10, 10]], "brush": {"size": "big"}}), + ] { + let _ = s.execute(CMD, p.clone()); + } + for p in [json!({"kind": "light", "points": [[10, 10]]}), json!({"kind": "nope", "points": [[10, 10]]}), json!({"kind": "levels", "subtract": 1})] { + let n = layer_count(&s); + assert!(s.execute(CMD, p).is_err()); + assert_eq!(layer_count(&s), n, "a refused stroke leaves no layer behind"); + } + // Painting off the canvas still makes the layer, with nothing painted. + let mut s = doc(); + s.execute(CMD, json!({"kind": "levels", "points": [[-5000, -5000]]})).unwrap(); + assert_eq!(mask_at(&s, 0, 0), 0.0); +} diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 82abc3d436..22d8e04c92 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -276,6 +276,12 @@ pub(crate) fn doc_cmyk_space(s: &Session) -> Option) -> Result { + stroke_with(s, cmd, p, label, brush, pts, false) +} + /// Stroke with a resolved brush onto the target layer (pixels or mask). fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushSettings, pts: Vec, auto_erase: bool) -> Result { let raw_bg = s.tools.background; diff --git a/crates/engine/src/cmd/channel_cmds.rs b/crates/engine/src/cmd/channel_cmds.rs index 5fe3b4fd19..07256328a6 100644 --- a/crates/engine/src/cmd/channel_cmds.rs +++ b/crates/engine/src/cmd/channel_cmds.rs @@ -134,7 +134,7 @@ use spot::{is_flat, merge, merge_spot, mergeable, split}; use targeting::{SLOT_KEY, target_cmd, target_slot}; pub(crate) use targeting::{ Target, channel_surface_for_filter, clear_channel, clear_color_channel, color_restriction, edits_channel, filter_mask_layer, inject_target, invert_region, - is_channel_target, is_spot_target, mask_target_enabled, restrict_to_color, routed, target_of, target_surface, targeted_channel, + is_channel_target, is_spot_target, mask_target_enabled, restrict_to_color, routed, target_layer_mask, target_of, target_surface, targeted_channel, }; pub use targeting::{follows_filter_mask, follows_target, follows_vector_mask_target, gray_target, read_target_surface}; pub use tone_target::{ToneTarget, resolve_tone_target}; diff --git a/crates/engine/src/cmd/channel_cmds/targeting.rs b/crates/engine/src/cmd/channel_cmds/targeting.rs index 80215708f7..b4e7880c5e 100644 --- a/crates/engine/src/cmd/channel_cmds/targeting.rs +++ b/crates/engine/src/cmd/channel_cmds/targeting.rs @@ -399,6 +399,11 @@ pub(crate) fn edits_channel(s: &Session) -> bool { }) } +/// Target the active layer's mask, as clicking its thumbnail does. +pub(crate) fn target_layer_mask(s: &mut Session) { + target(s, ChannelTarget::LayerMask); +} + /// Make `t` the edit target and show it the way Photoshop does when its row is clicked. pub(super) fn target(s: &mut Session, t: ChannelTarget) { if let Some(st) = s.active_mut() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ef4eae9be2..a88eb800a8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -68,6 +68,7 @@ pub use cmd as commands; pub use cmd::actions_cmds; pub use cmd::actions_edit_cmds; pub use cmd::adjust_cmds; +pub use cmd::adjustment_brush_cmds; pub use cmd::align_cmds; pub use cmd::analysis_cmds; pub use cmd::artboard_cmds; From e6c5ae759aece8fb8f23e0a09768ba7e2bd49ba9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:08:57 +0100 Subject: [PATCH 011/136] WIP: Art History Brush: a click paints strokes inside the Area circle (#12624) From 1cd68c3538764b48a9b69eecd24538c80a24dc25 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:23:09 +0100 Subject: [PATCH 012/136] UI: the Adjustment Brush Tool's toolbar slot, options bar and strokes (#12519) --- .../engine/src/cmd/adjustment_brush_cmds.rs | 7 +- .../src/cmd/adjustment_brush_cmds_tests.rs | 4 +- .../src/adjustment_brush_tool_tests.rs | 253 ++++++++++++++++++ crates/ui-egui/src/canvas/gesture.rs | 3 +- crates/ui-egui/src/canvas/paint_mouse.rs | 10 +- crates/ui-egui/src/canvas/strokes.rs | 1 + crates/ui-egui/src/canvas/tool_input.rs | 9 +- crates/ui-egui/src/icons.rs | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/panels.rs | 1 + crates/ui-egui/src/panels/brush_controls.rs | 2 +- crates/ui-egui/src/panels/options_bar.rs | 11 +- crates/ui-egui/src/panels/toolbar.rs | 5 + crates/ui-egui/src/state/tool.rs | 16 +- crates/ui-egui/src/state/tool_options.rs | 14 + crates/ui-egui/src/tools.rs | 1 + crates/ui-egui/src/tools/adjustment_brush.rs | 159 +++++++++++ crates/ui-egui/src/tools/tool_reset.rs | 1 + 18 files changed, 482 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/src/adjustment_brush_tool_tests.rs create mode 100644 crates/ui-egui/src/tools/adjustment_brush.rs diff --git a/crates/engine/src/cmd/adjustment_brush_cmds.rs b/crates/engine/src/cmd/adjustment_brush_cmds.rs index 73c228f46e..90dc8b915c 100644 --- a/crates/engine/src/cmd/adjustment_brush_cmds.rs +++ b/crates/engine/src/cmd/adjustment_brush_cmds.rs @@ -19,8 +19,7 @@ pub const NEW_LAYER_LABEL: &str = "New Adjustment Layer"; pub const STROKE_LABEL: &str = "Adjustment Brush"; /// The alert a stroke on an Indexed Color document shows; nothing changes. -pub const INDEXED_ALERT: &str = - "Could not complete your request because the tool does not work with Indexed Color images. Please convert the image to RGB or another supported mode before using."; +pub const INDEXED_ALERT: &str = "Could not complete your request because the tool does not work with Indexed Color images. Please convert the image to RGB or another supported mode before using."; /// One entry of the options bar's Adjustment dropdown: the kind id (the `layer.newAdjustmentLayer` /// suffix for the kinds that exist), its label, and whether a separator follows it. @@ -204,8 +203,8 @@ fn run(s: &mut Session, p: &Value) -> Result { let zoom = q.get("zoom").and_then(Value::as_f64).filter(|z| z.is_finite() && *z > 0.0).unwrap_or(1.0) as f32; // An adjustment layer of this kind with a mask is active: paint into its mask. - let paints_active = active_kind(s) == Some(kind) - && s.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|l| l.mask.is_some()); + let paints_active = + active_kind(s) == Some(kind) && s.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|l| l.mask.is_some()); let result = if paints_active { let mut r = super::brush_cmds::stroke_into(s, CMD, &q, STROKE_LABEL, brush, pts)?; r["created"] = json!(false); diff --git a/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs b/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs index c88936af84..bc927059b9 100644 --- a/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs +++ b/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs @@ -217,9 +217,7 @@ fn subtract_paints_black_and_swaps_the_colours() { fn entries_grey_out_per_mode_and_depth() { let off = |mode, depth| -> Vec<&str> { ENTRIES.iter().map(|e| e.kind).filter(|k| !enabled_in(k, mode, depth)).collect() }; let missing = ["light", "colorVibrance", "clarityDehaze", "grain"]; - let with = |more: &[&'static str]| -> Vec<&'static str> { - ENTRIES.iter().map(|e| e.kind).filter(|k| missing.contains(k) || more.contains(k)).collect() - }; + let with = |more: &[&'static str]| -> Vec<&'static str> { ENTRIES.iter().map(|e| e.kind).filter(|k| missing.contains(k) || more.contains(k)).collect() }; assert_eq!(off(ColorMode::Rgb, SampleType::U8), with(&[])); assert_eq!(off(ColorMode::Rgb, SampleType::U16), with(&[])); assert_eq!(off(ColorMode::Rgb, SampleType::F32), with(&["invert", "posterize", "threshold", "gradientMap"])); diff --git a/crates/ui-egui/src/adjustment_brush_tool_tests.rs b/crates/ui-egui/src/adjustment_brush_tool_tests.rs new file mode 100644 index 0000000000..2d42777d0c --- /dev/null +++ b/crates/ui-egui/src/adjustment_brush_tool_tests.rs @@ -0,0 +1,253 @@ +//! #12519: the Adjustment Brush Tool in the shell: its toolbar slot between the Blur and Dodge +//! slots (no letter, its own tooltip), its options bar, and strokes through the real pointer +//! path that make an adjustment layer whose mask is the stroke, or paint into it. + +use egui::accesskit::Role; +use egui::{Key, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{Adjustment, LayerContent}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::panels::toolbar::TOOL_SECTIONS; +use crate::state::{DialogKind, Tool}; + +/// A 200 x 200 document with a painted layer active and the Adjustment Brush picked, its brush +/// swapped in as a frame does. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#808080"})).unwrap(); + pick(&mut app); + app +} + +fn pick(app: &mut PhotocraftApp) { + app.ui.tool = Tool::AdjustmentBrush; + crate::paint_mouse::sync_tool_brush(app); + app.sync_views(); +} + +fn stroke(app: &mut PhotocraftApp, y: f64) { + tool_event(app, ToolEvent::Down { x: 40.0, y, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 160.0, y, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 160.0, y }, Modifiers::NONE); + app.sync_views(); +} + +fn active(app: &PhotocraftApp) -> &photocraft_doc::Layer { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap() +} + +fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.walk().len() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn mask_at(app: &PhotocraftApp, x: i32, y: i32) -> f32 { + active(app).mask.as_ref().expect("a mask").surface.sample_channel(x, y, 0) +} + +fn alerts(app: &PhotocraftApp) -> Vec { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(Value::as_str).map(str::to_string)).collect() +} + +#[test] +fn its_own_slot_sits_between_the_blur_and_dodge_slots() { + let slots: Vec<&[Tool]> = TOOL_SECTIONS.iter().flat_map(|s| s.iter().copied()).collect(); + let i = slots.iter().position(|s| *s == [Tool::AdjustmentBrush]).expect("an own slot"); + assert_eq!(slots[i - 1], [Tool::Blur, Tool::Sharpen, Tool::Smudge]); + assert_eq!(slots[i + 1], [Tool::Dodge, Tool::Burn, Tool::Sponge]); + assert_eq!(Tool::AdjustmentBrush.key(), '\0', "no letter"); + assert_eq!(Tool::from_name("adjustmentBrush"), Some(Tool::AdjustmentBrush)); +} + +#[test] +fn the_toolbar_tooltip_names_it_and_says_what_it_does() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = Harness::builder().with_size(vec2(400.0, 1600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + crate::panels::toolbar(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(2); + let tip = "Adjustment Brush Tool\nCreate local adjustment layers."; + let button = h.get_by_label(tip); + button.click(); + h.run_steps(2); + assert_eq!(h.state().ui.tool, Tool::AdjustmentBrush); +} + +/// Shift+letter and plain letters, pressed from every tool, never pick the Adjustment Brush. +#[test] +fn no_letter_or_shift_letter_cycle_reaches_it() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); + let ctx = egui::Context::default(); + let press = |app: &mut PhotocraftApp, key: Key, modifiers: Modifiers| { + ctx.begin_pass(egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + for key in [Key::O, Key::B, Key::J, Key::S, Key::Y, Key::E] { + for _ in 0..8 { + press(&mut app, key, Modifiers::SHIFT); + assert_ne!(app.ui.tool, Tool::AdjustmentBrush, "{key:?}"); + press(&mut app, key, Modifiers::NONE); + assert_ne!(app.ui.tool, Tool::AdjustmentBrush, "{key:?}"); + } + } +} + +#[test] +fn it_starts_with_a_100_px_soft_round() { + let app = app(); + let b = &app.session.tools.brush; + assert_eq!((b.size, b.hardness), (100.0, 0.0)); +} + +fn bar(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder() + .with_size(vec2(1800.0, 200.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium)) + .build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + h +} + +fn x_of(h: &Harness<'static, PhotocraftApp>, role: Role, label: &str) -> f32 { + let all = || h.query_all_by_role(role).map(|n| n.accesskit_node().label()).collect::>(); + h.query_all_by_role(role) + .find(|n| n.accesskit_node().label().as_deref() == Some(label)) + .unwrap_or_else(|| panic!("no {role:?} {label:?} in {:?}", all())) + .rect() + .center() + .x +} + +#[test] +fn the_options_bar_shows_its_controls_in_order() { + let h = bar(app()); + let xs = [ + x_of(&h, Role::ComboBox, "Adjustment:"), + x_of(&h, Role::Button, "Subtract"), + x_of(&h, Role::Button, "Add"), + x_of(&h, Role::Button, "Always use pressure for size"), + x_of(&h, Role::Button, "Choose an object and have the adjustment applied to it"), + x_of(&h, Role::CheckBox, "Overlay"), + x_of(&h, Role::SpinButton, "Opacity:"), + x_of(&h, Role::Button, "Always use pressure for opacity"), + x_of(&h, Role::SpinButton, "Flow:"), + x_of(&h, Role::Button, "Enable airbrush-style build-up effects"), + ]; + assert!(xs.windows(2).all(|w| w[0] < w[1]), "left to right: {xs:?}"); + // Light is the reference default; it isn't available yet, so the first enabled entry shows. + let kind = h.query_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().label().as_deref() == Some("Adjustment:")).unwrap(); + assert_eq!(kind.accesskit_node().value().as_deref(), Some("Levels")); +} + +#[test] +fn subtract_and_add_swap_the_colours_and_the_paint() { + let mut h = bar(app()); + h.get_by_label("Subtract").click(); + h.run_steps(2); + let app = h.state(); + assert!(app.ui.tool_options.adjustment_brush_subtract); + assert_eq!((app.session.tools.foreground, app.session.tools.background), ([0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0])); + h.get_by_label("Add").click(); + h.run_steps(2); + let app = h.state(); + assert!(!app.ui.tool_options.adjustment_brush_subtract); + assert_eq!((app.session.tools.foreground, app.session.tools.background), ([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])); +} + +#[test] +fn the_first_stroke_makes_the_layer_in_one_history_state() { + let mut app = app(); + let (n, past) = (layers(&app), steps(&app)); + stroke(&mut app, 100.0); + assert_eq!((layers(&app), steps(&app)), (n + 1, past + 1), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("New Adjustment Layer")); + assert_eq!(active(&app).name, "Levels 1"); + assert!(matches!(active(&app).content, LayerContent::Adjustment(Adjustment::Levels { .. }))); + assert!(mask_at(&app, 100, 100) > 0.98 && mask_at(&app, 100, 10) == 0.0); + assert!(app.ui.mask_target, "the new mask is targeted"); + // A second stroke paints the same mask. + stroke(&mut app, 30.0); + assert_eq!((layers(&app), steps(&app)), (n + 1, past + 2)); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Adjustment Brush")); + assert!(mask_at(&app, 100, 30) > 0.98); +} + +#[test] +fn a_hidden_locked_or_group_layer_does_not_refuse_the_stroke() { + for setup in ["hidden", "locked", "group", "type"] { + let mut app = app(); + let id = active(&app).id.0; + match setup { + "hidden" => app.run("layer.setProps", json!({"layer": id, "visible": false})).map(|_| ()), + "locked" => app.run("layer.lockLayers", json!({"all": true})).map(|_| ()), + "group" => app.run("layer.new.group", json!({})).map(|_| ()), + _ => app.run("type.create", json!({"text": "Hi", "x": 20, "y": 40})).map(|_| ()), + } + .unwrap_or_else(|e| panic!("{setup}: {e}")); + pick(&mut app); + let n = layers(&app); + stroke(&mut app, 100.0); + assert!(alerts(&app).is_empty() && app.ui.dialogs.is_empty(), "{setup}: {:?}", app.ui.dialogs); + assert_eq!(layers(&app), n + 1, "{setup}: {}", app.ui.status); + assert!(matches!(active(&app).content, LayerContent::Adjustment(_)), "{setup}"); + } +} + +#[test] +fn selecting_an_adjustment_layer_sets_the_dropdown() { + let mut app = app(); + app.run("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + crate::adjustment_brush::follow_active_layer(&mut app); + assert_eq!(crate::adjustment_brush::kind(&app), "curves"); + // A pick after that sticks while the layer stays active. + app.ui.tool_options.adjustment_brush_kind = "exposure".into(); + crate::adjustment_brush::follow_active_layer(&mut app); + assert_eq!(crate::adjustment_brush::kind(&app), "exposure"); + // And a stroke with it makes an Exposure layer above the Curves one. + let n = layers(&app); + stroke(&mut app, 100.0); + assert_eq!((layers(&app), active(&app).name.as_str()), (n + 1, "Exposure 1")); +} + +#[test] +fn greyed_entries_fall_back_to_the_first_offered_one() { + let mut app = app(); + app.run("image.mode.bits32", json!({})).unwrap(); + app.ui.tool_options.adjustment_brush_kind = "posterize".into(); + assert_eq!(crate::adjustment_brush::kind(&app), "levels"); + stroke(&mut app, 100.0); + assert_eq!(active(&app).name, "Levels 1", "{}", app.ui.status); +} + +#[test] +fn indexed_color_alerts_at_the_press_and_changes_nothing() { + let mut app = app(); + app.run("layer.flatten", json!({})).ok(); + app.run("image.mode.indexedColor", json!({})).unwrap(); + pick(&mut app); + let (n, past) = (layers(&app), steps(&app)); + stroke(&mut app, 100.0); + assert_eq!(alerts(&app), [photocraft_engine::adjustment_brush_cmds::INDEXED_ALERT]); + assert_eq!((layers(&app), steps(&app)), (n, past)); +} diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index 155ae25ac8..27951d8be5 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -97,7 +97,8 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option) { if live_retouch_command(d.tool).is_some() || crate::retouch_ui::dab_params(app, d.tool).is_some() || d.tool == Tool::ColorReplacement { app.live_stroke = None; } - let finished = crate::eraser_ui::finish_stroke(app, d.tool, &d.points, d.line) + let finished = crate::adjustment_brush::finish_stroke(app, d.tool, &d.points, d.line) + || crate::eraser_ui::finish_stroke(app, d.tool, &d.points, d.line) || crate::retouch_ui::finish_stroke_with(app, d.tool, &d.points, d.modifiers, d.line, d.history_params.clone()); app.session.clear_live_stroke(); if finished { diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index c611df6f40..0322494301 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -45,7 +45,11 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools, the Clone // Stamp and the Smudge tool start with their own measured tips instead, as the whole brush // Reset Tool gives them (#11911, #12099, #12671, #12684, #13029, #12601, #12964). - None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge) => { + None if matches!( + tool, + Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge | Tool::AdjustmentBrush + ) => + { fresh_brush(tool, ¤t) } // The Pencil starts with its own 1 px hard round (#12200) regardless of the Brush, keeping @@ -104,6 +108,9 @@ const CLONE_STAMP_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25); const REMOVE_TOOL_SIZE: f32 = 19.0; /// The Smudge tool's tip after Reset Tool (#12964): a 13 px soft round at 25 % spacing. const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); +/// The Adjustment Brush's starting tip (#12519): a 100 px soft round (hardness 0 %). Its spacing +/// was not measured, so it stays the default brush's. +const ADJUSTMENT_BRUSH_TIP: (f32, f32) = (100.0, 0.0); /// `tool`'s brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's /// smoothing, with the session's own fields of `current`. The Brush tool's tip is @@ -126,6 +133,7 @@ pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings brush.smoothing.amount = 0.0; } Tool::Remove => brush.size = REMOVE_TOOL_SIZE, + Tool::AdjustmentBrush => (brush.size, brush.hardness) = ADJUSTMENT_BRUSH_TIP, _ => {} } session_fields(current, &brush) diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index 678cb9892f..5d4686bb09 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -676,6 +676,7 @@ pub(crate) fn freehand_tool(tool: Tool) -> bool { | Tool::Blur | Tool::Sharpen | Tool::Smudge + | Tool::AdjustmentBrush | Tool::Dodge | Tool::Burn | Tool::Sponge diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index 4f4325cbb0..d1a95a21a1 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -540,12 +540,19 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods: // Painting a type, shape, Smart Object or fill layer asks to rasterize it first // (⌥-click with the Clone Stamp or Healing Brush only sets the source). let sets_source = matches!(tool, Tool::CloneStamp | Tool::Healing) && mods.alt; + // The Adjustment Brush paints a new layer's mask whatever the active layer is (hidden, + // locked, a group or type): only Indexed Color refuses it (#12519). + let own_layer = tool == Tool::AdjustmentBrush; + if own_layer && crate::adjustment_brush::press_refused(app) { + return; + } // Painting on or moving a hidden layer is refused at the press, as in Photoshop (#571). - if !sets_source && press_refused(app, tool) { + if !sets_source && !own_layer && press_refused(app, tool) { return; } // The Clone Stamp's no-source alert opens at the press, after any rasterize prompt. if !sets_source + && !own_layer && (crate::rasterize_prompt::intercept(app, tool, x, y, pressure) || refuse_group(app, tool) || crate::retouch_ui::clone_stamp_without_source(app, tool)) diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index c8594a61cd..635155cca4 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -188,6 +188,7 @@ pub fn tool_icon(t: Tool) -> &'static str { Tool::Sharpen => "triangle", Tool::Smudge => "pointer", Tool::Dodge => "lollipop", + Tool::AdjustmentBrush => "adjustment-layer", Tool::Burn => "flame", Tool::Sponge => "cloud", Tool::QuickSelection => "quick-selection", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c..7eaa1185a6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -276,6 +276,7 @@ pub use text::egui_fonts; use text::font_filters; use text::font_preview; pub use text::served_fonts; +pub use tools::adjustment_brush; use tools::align_bar; pub use tools::analysis_ui; pub use tools::anchor_tools; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 1f660fb4cd..f3c799b3a7 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -65,6 +65,7 @@ pub(crate) mod toolbar; pub mod type_panels_ui; pub(super) mod variables_ui; +pub(crate) use brush_controls::brush_preset_chip; #[cfg(test)] use color::color_field_height; pub(crate) use color::{color_field, color_field_fill_id, field_chips, field_hsva, offer_color_field_fill, srgb_hsva}; diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index 7f2aa4996b..79c9a67a90 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -223,7 +223,7 @@ pub(super) fn mixer_load_swatch(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// Options-bar brush chip: a click shows or hides Photoshop's Brush Preset picker below it (size, /// hardness, the preset library), the one a right-click on the canvas opens. -pub(super) fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushSettings, state: &mut crate::state::UiState) { +pub(crate) fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushSettings, state: &mut crate::state::UiState) { let t = Tokens::get(ui.ctx()); let (r, _) = ui.allocate_exact_size(vec2(44.0, 30.0), Sense::hover()); let resp = ui.interact(r, crate::brush_picker::chip_id(), Sense::click()); diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 005bf4793e..eeb7a129c3 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -133,7 +133,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // chip, so a tool change swaps the brush with it (Photoshop keeps one per tool). crate::paint_mouse::sync_tool_brush(app); // Brush edits here go through `tools.setBrush`, one journal entry per gesture (Rule 1). - if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser)) + if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser | Tool::AdjustmentBrush)) || tool == Tool::QuickSelection { brush_preset_chip(ui, &app.session.tools.brush, &mut app.ui); @@ -181,7 +181,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); widgets::vline(ui, 22.0); } - if crate::eraser_ui::options_bar(app, ui, tool) + if crate::adjustment_brush::options_bar(app, ui, tool) + || crate::eraser_ui::options_bar(app, ui, tool) || crate::retouch_ui::options_bar(app, ui, tool) || crate::vector_ui::options_bar(app, ui, tool) || crate::analysis_ui::options_bar(app, ui, tool) @@ -993,7 +994,7 @@ fn fixed_size_field(ui: &mut egui::Ui, px: &mut f32, units: widgets::FieldUnits, picked } -fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) -> egui::Response { +pub(crate) fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) -> egui::Response { opt_label(ui, label); let mut percent = *value * 100.0; let r = widgets::value_field_named(ui, label, &mut percent, range, "%", width); @@ -1005,7 +1006,7 @@ fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::op /// A pressure toggle named `name` (for screen readers and tests); its tooltip is `name`, unless /// `own_tip` leaves the tooltip to the caller (the Brush's own texts, #11813). -fn pressure_button(ui: &mut egui::Ui, on: bool, name: &str, own_tip: bool) -> egui::Response { +pub(crate) fn pressure_button(ui: &mut egui::Ui, on: bool, name: &str, own_tip: bool) -> egui::Response { icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), on, name, !own_tip) } @@ -1036,7 +1037,7 @@ pub(crate) fn range_alert(ui_state: &mut crate::state::UiState, text: &str) { /// [`percent_field`] that keeps whole percents (`33.7` becomes 34 %). A value set elsewhere (a /// `tools.setBrush` fraction, an older saved 0) shows as the whole percent in range. -fn whole_percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) -> egui::Response { +pub(crate) fn whole_percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) -> egui::Response { opt_label(ui, label); let mut percent = (*value * 100.0).round().max(*range.start()).min(*range.end()); let r = widgets::value_field_named(ui, label, &mut percent, range.clone(), "%", width); diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index a8ed212b72..ebb495933b 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -36,6 +36,7 @@ pub(crate) const TOOL_SECTIONS: &[&[&[Tool]]] = &[ &[Tool::Eraser, Tool::BackgroundEraser, Tool::MagicEraser], &[Tool::Gradient, Tool::PaintBucket], &[Tool::Blur, Tool::Sharpen, Tool::Smudge], + &[Tool::AdjustmentBrush], &[Tool::Dodge, Tool::Burn, Tool::Sponge], ], &[ @@ -262,6 +263,10 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { Some(sc) => format!("{} ({})", tl!(tool.label()), crate::shortcuts::pretty(&sc)), None => tl!(tool.label()).to_string(), }; + let tip = match tool.description() { + Some(d) => format!("{tip}\n{}", tl!(d)), + None => tip, + }; let resp = icons::button_with_icon_size_tip(ui, icons::tool_icon(tool), bx, toolbar_icon_size(bx, t.pro), sel, &tip, tool_tips); if slot.len() > 1 { paint_toolbar_flyout_indicator(ui, &t, &resp, side); diff --git a/crates/ui-egui/src/state/tool.rs b/crates/ui-egui/src/state/tool.rs index 66aa7d53f6..b1d4624bda 100644 --- a/crates/ui-egui/src/state/tool.rs +++ b/crates/ui-egui/src/state/tool.rs @@ -52,6 +52,8 @@ pub enum Tool { Blur, Sharpen, Smudge, + /// Paints an adjustment layer's mask, making the layer on the first stroke (#12519). + AdjustmentBrush, Dodge, Burn, Sponge, @@ -81,7 +83,7 @@ pub enum Tool { } impl Tool { - pub const ALL: [Tool; 69] = [ + pub const ALL: [Tool; 70] = [ Tool::Move, Tool::Artboard, Tool::RectMarquee, @@ -128,6 +130,7 @@ impl Tool { Tool::Blur, Tool::Sharpen, Tool::Smudge, + Tool::AdjustmentBrush, Tool::Dodge, Tool::Burn, Tool::Sponge, @@ -204,6 +207,7 @@ impl Tool { Tool::Blur => "Blur Tool", Tool::Sharpen => "Sharpen Tool", Tool::Smudge => "Smudge Tool", + Tool::AdjustmentBrush => "Adjustment Brush Tool", Tool::Dodge => "Dodge Tool", Tool::Burn => "Burn Tool", Tool::Sponge => "Sponge Tool", @@ -226,6 +230,13 @@ impl Tool { Tool::CustomShape => "Custom Shape Tool", } } + /// The second line of the toolbar tooltip, for the tools whose description was measured. + pub fn description(self) -> Option<&'static str> { + match self { + Tool::AdjustmentBrush => Some("Create local adjustment layers."), + _ => None, + } + } pub fn is_type(self) -> bool { matches!(self, Self::Type | Self::VerticalType | Self::HorizontalTypeMask | Self::VerticalTypeMask) } @@ -258,6 +269,7 @@ impl Tool { | Tool::Blur | Tool::Sharpen | Tool::Smudge + | Tool::AdjustmentBrush | Tool::Dodge | Tool::Burn | Tool::Sponge @@ -284,6 +296,8 @@ impl Tool { Tool::CloneStamp | Tool::PatternStamp => 'S', Tool::HistoryBrush | Tool::ArtHistoryBrush => 'Y', Tool::Blur | Tool::Sharpen | Tool::Smudge => '\0', + // Its own slot without a letter: no Shift+letter cycle reaches it. + Tool::AdjustmentBrush => '\0', // In the Marquee flyout, but M cycles only the Rectangular and Elliptical Marquee. Tool::SingleRowMarquee | Tool::SingleColumnMarquee => '\0', Tool::Dodge | Tool::Burn | Tool::Sponge => 'O', diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 874c444d19..55eb02c485 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -18,6 +18,16 @@ pub struct ToolOptions { /// Remove tool: each stroke is filled when released (Photoshop's default). Off, the strokes /// collect as a tint on the canvas and ↩ applies them together (Esc drops them). pub remove_after_each_stroke: bool, + /// Adjustment Brush: the Adjustment dropdown's entry (`photocraft_engine::adjustment_brush_cmds::ENTRIES`). + pub adjustment_brush_kind: String, + /// Adjustment Brush: Subtract (paints black into the mask) instead of Add. + pub adjustment_brush_subtract: bool, + /// Adjustment Brush: the Overlay checkbox (its tint over the mask is #12520). + pub adjustment_brush_overlay: bool, + /// Adjustment Brush: the active layer the dropdown last followed, so selecting another + /// adjustment layer sets it once and a pick in the dropdown sticks. + #[serde(skip)] + pub adjustment_brush_followed: Option, pub feather: f32, /// linear | radial | angle | reflected | diamond pub gradient_style: String, @@ -469,6 +479,10 @@ impl Default for ToolOptions { object_finder: true, remove_new_layer: false, remove_after_each_stroke: true, + adjustment_brush_kind: photocraft_engine::adjustment_brush_cmds::DEFAULT_KIND.into(), + adjustment_brush_subtract: false, + adjustment_brush_overlay: false, + adjustment_brush_followed: None, feather: 0.0, gradient_style: "linear".into(), gradient_reverse: false, diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 503bbe0a7d..452a5002fd 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -1,3 +1,4 @@ +pub mod adjustment_brush; pub(super) mod align_bar; pub mod analysis_ui; pub mod anchor_tools; diff --git a/crates/ui-egui/src/tools/adjustment_brush.rs b/crates/ui-egui/src/tools/adjustment_brush.rs new file mode 100644 index 0000000000..7ef98338d7 --- /dev/null +++ b/crates/ui-egui/src/tools/adjustment_brush.rs @@ -0,0 +1,159 @@ +//! The Adjustment Brush Tool (#12519): its options bar and its stroke. Painting runs +//! `paint.adjustmentBrush`, which makes an adjustment layer of the dropdown's kind whose mask is +//! the stroke, or paints into the mask of the active adjustment layer of that kind. The stroke +//! shows as the painting tools' trail while it is drawn and is applied on release. + +use photocraft_engine::adjustment_brush_cmds::{self as ab, ENTRIES, INDEXED_ALERT}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::panels::options_bar::{opt_label, percent_field, pressure_button, whole_percent_field}; +use crate::state::Tool; + +/// The kind a stroke paints: the dropdown's entry, or the first offered one when the document's +/// colour mode or bit depth greys it. +pub fn kind(app: &PhotocraftApp) -> &'static str { + let stored = ab::entry_of(&app.ui.tool_options.adjustment_brush_kind).map_or(ab::DEFAULT_KIND, |e| e.kind); + match app.session.active() { + Some(st) => ab::offered_kind(stored, st.doc.mode, st.doc.depth), + None => stored, + } +} + +/// Selecting an adjustment layer sets the dropdown to its kind, once per selection, so a later +/// pick in the dropdown sticks. +pub fn follow_active_layer(app: &mut PhotocraftApp) { + let active = app.session.active().and_then(|st| st.active_layer).map(|l| l.0); + if app.ui.tool_options.adjustment_brush_followed == active { + return; + } + app.ui.tool_options.adjustment_brush_followed = active; + if let Some(k) = ab::active_kind(&app.session) { + app.ui.tool_options.adjustment_brush_kind = k.into(); + } +} + +/// Subtract (black over white) or Add (white over black): the mode and the colours the stroke +/// paints the mask with. +pub fn set_subtract(app: &mut PhotocraftApp, subtract: bool) { + app.ui.tool_options.adjustment_brush_subtract = subtract; + let (fg, bg) = if subtract { ("#000000", "#ffffff") } else { ("#ffffff", "#000000") }; + if let Err(e) = app.run("tools.setColors", json!({"foreground": fg, "background": bg})) { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// A press in an Indexed Color document: the reference application's alert, and no stroke. +pub fn press_refused(app: &mut PhotocraftApp) -> bool { + let indexed = app.session.active().is_some_and(|st| st.doc.mode == photocraft_doc::ColorMode::Indexed); + if indexed { + crate::brush_refusal::prompt(app, tl!(INDEXED_ALERT)); + } + indexed +} + +/// Applies a finished drag. Returns false for another tool. +pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], line: bool) -> bool { + if tool != Tool::AdjustmentBrush { + return false; + } + follow_active_layer(app); + let mut p = json!({ + "kind": kind(app), + "subtract": app.ui.tool_options.adjustment_brush_subtract, + "points": points, + "zoom": app.point_zoom(), + }); + crate::canvas::unsmoothed_line(&mut p, line); + match app.run("paint.adjustmentBrush", p) { + Ok(_) => { + // The layer painted is active with its mask targeted, as after a New Adjustment Layer. + app.ui.mask_target = true; + app.ui.vector_mask_target = false; + app.ui.tool_options.adjustment_brush_followed = app.session.active().and_then(|st| st.active_layer).map(|l| l.0); + } + Err(e) if e.contains(INDEXED_ALERT) => crate::brush_refusal::prompt(app, tl!(INDEXED_ALERT)), + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + } + } + true +} + +/// Does a separator line go above `kind` in the dropdown? +fn starts_group(kind: &str) -> bool { + let i = ENTRIES.iter().position(|e| e.kind == kind); + i.and_then(|i| i.checked_sub(1)).and_then(|i| ENTRIES.get(i)).is_some_and(|e| e.separator_after) +} + +/// The options bar, left to right as in the reference application: (the tool preset picker) · +/// Adjustment · Subtract / Add · Brush Preset · Pressure for Size · Choose an object · Overlay · +/// Opacity · Pressure for Opacity · Flow · Airbrush. Returns false for another tool. +pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { + if tool != Tool::AdjustmentBrush { + return false; + } + follow_active_layer(app); + let (mode, depth) = app.session.active().map_or((photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8), |st| (st.doc.mode, st.doc.depth)); + opt_label(ui, tl!("Adjustment:")); + let options: Vec<(&'static str, &str)> = ENTRIES.iter().map(|e| (e.kind, e.label)).collect(); + let mut current = kind(app); + let chosen = crate::widgets::dropdown_wheel_grouped_enabled( + ui, + "adjustment-brush-kind", + tl!("Adjustment"), + &mut current, + &options, + 150.0, + |k| starts_group(k), + |k| ab::enabled_in(k, mode, depth), + ) + .0; + // Choosing an entry is no history state; the keys may land on a greyed one, which keeps the choice. + if let Some(&k) = chosen.last() + && ab::enabled_in(k, mode, depth) + { + app.ui.tool_options.adjustment_brush_kind = k.into(); + } + let subtract = app.ui.tool_options.adjustment_brush_subtract; + let sub = crate::icons::button(ui, "minus", 24.0, subtract, tl!("Subtract from mask areas to remove adjustment from areas of the image")); + let add = crate::icons::button(ui, "plus", 24.0, !subtract, tl!("Add to mask areas to apply adjustment to more of the image")); + if crate::brush_picker::named(sub, "Subtract").clicked() && !subtract { + set_subtract(app, true); + } else if crate::brush_picker::named(add, "Add").clicked() && subtract { + set_subtract(app, false); + } + crate::widgets::vline(ui, 22.0); + crate::panels::brush_preset_chip(ui, &app.session.tools.brush, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + let before = app.session.tools.brush.clone(); + let mut b = before.clone(); + if pressure_button(ui, b.pressure_size, tl!("Always use pressure for size"), false).clicked() { + b.pressure_size = !b.pressure_size; + } + crate::widgets::vline(ui, 22.0); + // Present but inert: what it does was not measured. + ui.add_enabled_ui(false, |ui| { + crate::icons::button(ui, "square-dashed-mouse-pointer", 24.0, false, tl!("Choose an object and have the adjustment applied to it")); + }); + // Its tint over the painted mask is its own item (#12520). + crate::widgets::checkbox(ui, &mut app.ui.tool_options.adjustment_brush_overlay, tl!("Overlay")); + crate::widgets::vline(ui, 22.0); + whole_percent_field(ui, tl!("Opacity"), &mut b.opacity, 1.0..=100.0, 62.0); + if pressure_button(ui, b.pressure_opacity, tl!("Always use pressure for opacity"), false).clicked() { + b.pressure_opacity = !b.pressure_opacity; + } + percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0); + let airbrush = crate::icons::button(ui, "sparkles", 24.0, b.build_up, tl!("Enable airbrush-style build-up effects")); + if crate::brush_picker::named(airbrush, "Enable airbrush-style build-up effects").clicked() { + b.build_up = !b.build_up; + } + crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &b); + true +} + +#[cfg(test)] +#[path = "../adjustment_brush_tool_tests.rs"] +mod adjustment_brush_tool_tests; diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index ba62a52b9d..d24b277659 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -233,6 +233,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Pencil => reset!(pencil_auto_erase, pencil_clear), Tool::Eraser => reset!(eraser_mode, erase_to_history), Tool::Remove => reset!(remove_new_layer, remove_after_each_stroke), + Tool::AdjustmentBrush => reset!(adjustment_brush_kind, adjustment_brush_subtract, adjustment_brush_overlay), Tool::BackgroundEraser => reset!(bg_sampling, bg_limits, bg_tolerance, bg_protect_fg, bg_tolerance_control), Tool::ColorReplacement => reset!(cr_mode, cr_sampling, cr_limits, cr_tolerance, cr_anti_alias), Tool::MagicEraser => reset!(tolerance, anti_alias, contiguous, magic_eraser_opacity), From 3d69cbcecb145d58ef215676b6ff9819a4cc0c5b Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 11:57:47 +0100 Subject: [PATCH 013/136] fix(ui): Color Lookup opens at its defaults, not the last LUT The remembered-dialog mechanism made Image > Adjustments > Color Lookup reopen with the look, Dither and interpolation of its last OK, while the reference application reopens that dialog at its defaults after every OK (#14422). Color Lookup now restores nothing, and so saves nothing: with no restore, the stored values would only sit in the preferences unread. A recorded or scripted step's own values still prefill the dialog, because the Actions panel seeds them after it opens, and Alt+Cancel (Reset) already fell back to the schema defaults. --- crates/ui-egui/src/dialogs.rs | 2 + .../dialogs/color_lookup_no_remember_tests.rs | 139 ++++++++++++++++++ crates/ui-egui/src/dialogs/filter_dialog.rs | 12 ++ 3 files changed, 153 insertions(+) create mode 100644 crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cd5de48bba..03d6d6aa24 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1307,6 +1307,8 @@ pub(super) mod camera_raw_preview_ui; pub(super) mod camera_raw_scope_ui; pub mod camera_raw_ui; pub mod channel_options_ui; +#[cfg(test)] +mod color_lookup_no_remember_tests; pub(crate) mod color_picker_preview; pub mod color_picker_ui; pub mod color_range_ui; diff --git a/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs b/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs new file mode 100644 index 0000000000..5dd6c64a7c --- /dev/null +++ b/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs @@ -0,0 +1,139 @@ +//! #14422: Image › Adjustments › Color Lookup opens at its defaults every time. +//! +//! A schema dialog normally reopens with what its last OK kept in the preferences +//! (`filter_dialog::remember` → `filter_dialog::restore_remembered`). The reference application's +//! Color Lookup does not: after an OK with a built-in look or a LUT file it opens again with no LUT +//! chosen and Dither at its default. What stays as today is the prefill a recorded or scripted +//! Action step carries, and every other dialog's own memory. + +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::dialogs::filter_dialog::{open, remember, reset_fields}; + +const COLOR_LOOKUP: &str = "image.adjustments.colorLookup"; + +/// The fields Color Lookup opens with: no 3D LUT (`lut` = none, no `file`), Dither off (the +/// schema default; #14419 is the item that changes it) and trilinear interpolation. +fn assert_defaults(fields: &Map, opened: &str) { + assert_eq!(fields["lut"], json!("none"), "{opened}: lut"); + assert_eq!(fields["file"], json!(""), "{opened}: file"); + assert_eq!(fields["dither"], json!(false), "{opened}: dither"); + assert_eq!(fields["interpolation"], json!("trilinear"), "{opened}: interpolation"); +} + +/// An 8×8 RGB document, so `image.adjustments.colorLookup` has something to adjust. +fn app_with_doc() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8, "background": "#000000"})).unwrap(); + app +} + +/// Set the dialog's fields and confirm it, as clicking OK does. +fn ok_with(app: &mut PhotocraftApp, id: u64, changed: Value) { + let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + fields.extend(changed.as_object().unwrap().clone()); + app.ui.dialog_mut(id).unwrap().fields = fields; + crate::dialogs::confirm(app, id).unwrap(); +} + +/// Play a one-step action whose step shows its dialog, and return that dialog's id. +fn step_dialog(app: &mut PhotocraftApp, params: Value) -> u64 { + use photocraft_engine::actions_cmds::Action; + let mut action = Action::new("Color lookup step", vec![(COLOR_LOOKUP.into(), params)]); + action.dialogs.insert(0); + app.session.actions.list.push(action); + let played = crate::panels::actions::play(app, &json!({"action": "Color lookup step"})).unwrap(); + played["paused"]["dialog"].as_u64().expect("the toggled step opens its dialog") +} + +/// The measured case: OK with a built-in look, and the next opening shows the defaults again +/// instead of that look. It also asserts that OK keeps nothing at all for Color Lookup, so no +/// unread values gather in the preferences. +#[test] +fn color_lookup_ok_with_a_builtin_look_reopens_at_the_defaults() { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + assert_defaults(&app.ui.dialog_mut(id).unwrap().fields, "the first opening"); + ok_with(&mut app, id, json!({"lut": "warm", "dither": true, "interpolation": "tetrahedral"})); + + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + assert_defaults(&app.ui.dialog_mut(id).unwrap().fields, "after OK with the built-in look warm"); + assert!(!app.session.prefs().dialogs.contains_key(COLOR_LOOKUP), "OK keeps no Color Lookup values"); +} + +/// The other measured opening: a LUT file loaded and OK'd. The next opening shows no file and no +/// built-in look. +#[test] +fn color_lookup_ok_with_a_lut_file_reopens_at_the_defaults() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("film.cube"); + std::fs::write(&path, "LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").unwrap(); + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + ok_with(&mut app, id, json!({"file": path.to_str().unwrap(), "dither": true})); + + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + assert_defaults(&app.ui.dialog_mut(id).unwrap().fields, "after OK with a LUT file"); + assert!(app.ui.dialog_mut(id).unwrap().fields.get("__folderLut").is_none(), "the LUT folder pick is not kept either"); +} + +/// A scripted step with no values of its own and its dialog shown opens at the defaults, even +/// after a menu OK had chosen a look. +#[test] +fn color_lookup_step_dialog_without_recorded_values_opens_at_the_defaults() { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + ok_with(&mut app, id, json!({"lut": "cool", "dither": true})); + + let id = step_dialog(&mut app, json!({})); + assert_defaults(&app.ui.dialog_mut(id).unwrap().fields, "the scripted step with no values"); +} + +/// The prefill a step carries is not the remembered-dialog mechanism: a recorded look still shows +/// up in its dialog. +#[test] +fn color_lookup_step_dialog_still_prefills_its_recorded_values() { + let mut app = app_with_doc(); + let id = step_dialog(&mut app, json!({"lut": "dayForNight", "dither": true, "interpolation": "tetrahedral"})); + let fields = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!( + (&fields["lut"], &fields["dither"], &fields["interpolation"]), + (&json!("dayForNight"), &json!(true), &json!("tetrahedral")), + "the step's own values still prefill" + ); +} + +/// Alt+Cancel (Reset) returns the changed fields to the defaults, and that OK keeps nothing for +/// the opening after it. +#[test] +fn color_lookup_alt_reset_returns_to_the_defaults() { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + fields.insert("lut".into(), json!("dayForNight")); + fields.insert("file".into(), json!("night.cube")); + fields.insert("dither".into(), json!(true)); + fields.insert("interpolation".into(), json!("tetrahedral")); + reset_fields(&app, &mut fields); + assert_defaults(&fields, "Alt+Cancel (Reset)"); + assert!(fields.contains_key("__lutFolder"), "the dialog's own chrome stays"); + app.ui.dialog_mut(id).unwrap().fields = fields; + crate::dialogs::confirm(&mut app, id).unwrap(); + + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + assert_defaults(&app.ui.dialog_mut(id).unwrap().fields, "the opening after the Reset OK"); +} + +/// Only Color Lookup stopped remembering: another schema dialog still reopens with what its OK +/// kept. +#[test] +fn other_schema_dialogs_still_remember_their_choices() { + let mut app = app_with_doc(); + let mut fields = Map::new(); + fields.insert("__filter".into(), json!(true)); + fields.insert("radius".into(), json!(11.0)); + remember(&mut app, "filter.blur.gaussianBlur", &fields); + let id = open(&mut app, "filter.blur.gaussianBlur").unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["radius"], json!(11.0), "the blur dialog still remembers"); +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 2f02574690..7ad8c769f9 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -366,6 +366,13 @@ fn rememberable(kind: &Kind, value: &Value) -> bool { } fn restore_remembered(app: &PhotocraftApp, command: &str, spec: &str, fields: &mut Map) { + // Color Lookup opens at its defaults every time, as the reference application's does: an OK + // with a built-in look or a LUT file leaves the next opening at "no LUT" and Dither at its + // default (#14422). A recorded or scripted step still prefills, because the Actions panel + // seeds its own values after the dialog opens. + if command == COLOR_LOOKUP { + return; + } let Some(Value::Object(saved)) = app.session.prefs().dialogs.get(command) else { return }; // Select and Mask starts from its defaults unless Remember Settings was on, as in Photoshop // (#9423). @@ -385,6 +392,11 @@ fn restore_remembered(app: &PhotocraftApp, command: &str, spec: &str, fields: &m /// Remember successful built-in schema dialogs; failed or cancelled dialogs do not persist. pub(crate) fn remember(app: &mut PhotocraftApp, command: &str, fields: &Map) { + // Color Lookup restores nothing (#14422), so saving its choices would only leave values in the + // preferences that nothing reads. + if command == COLOR_LOOKUP { + return; + } if !fields.contains_key("__filter") || fields.contains_key("__spec") || fields.contains_key("__smartFilter") { return; } From df6e324920d3c2e273512249ff99c0e29a690187 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:28:38 +0100 Subject: [PATCH 014/136] docs: correct MCP switches and repeated read roots Clarified usage of launch options and their requirements. --- book/src/automation/mcp.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 36d5e6be5e..57a76c5c5d 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -29,8 +29,8 @@ client's launch directory. In bridge mode the roots are configured on the deskto flags on `photocraft-cli mcp --bridge` are rejected. Explicit `--control-token` and `--control-token-file` flags require `--bridge` (or `PHOTOCRAFT_CONTROL_PORT`) and are mutually exclusive; bridge credentials can also come from `PHOTOCRAFT_CONTROL_TOKEN` or -`PHOTOCRAFT_CONTROL_TOKEN_FILE`. Each launch option -except `--help`/`-h` takes one non-empty value and cannot be repeated. Stray positional arguments, +`PHOTOCRAFT_CONTROL_TOKEN_FILE`. `--headless`, `--gpu`, `--no-gpu` and `--help`/`-h` take no value. Other launch options +take one non-empty value; only `--automation-read-root` may repeat, adding ordered read directories. Stray positional arguments, missing values and options for the wrong mode are usage errors (exit 2) reported on stderr before the server starts. From 4ae6e4df37847a82656c417026de958120858b14 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:30:02 +0100 Subject: [PATCH 015/136] docs: list repeatable read-root flags in CLI guide --- book/src/automation/cli.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/src/automation/cli.md b/book/src/automation/cli.md index c7278455ef..97540c0ecd 100644 --- a/book/src/automation/cli.md +++ b/book/src/automation/cli.md @@ -84,7 +84,7 @@ layers because that would lose their group's blending semantics. Paths supplied to the current CLI are ordinary operating-system paths. The CLI does not restrict them to a workspace root. Batch output creates the requested output directory, and save operations may create parent directories. `batch` refuses an output directory that is its input directory (the results would replace the originals) unless `--in-place` is given. Run untrusted action files only in an appropriately isolated account or environment. -CLI parsing checks the flags and their values before any work starts. A flag the subcommand doesn't take (a typo such as `--fromat`), a flag given twice (only `--cmd` and `--params` may repeat), a value out of range (`--quality 0`), malformed `--new` or `--params` JSON, `` together with `--new`, and `--control-token` together with `--control-token-file` are all usage errors (exit status 2), rather than being ignored or failing later. A value flag never takes the next flag as its value, so a value starting with `-` is written with `=` (`--out=-image.png`) or as `./-image.png`; negative numbers such as `--filter -1` still work. A path that is not valid Unicode reaches the command instead of being a usage error: `convert` reads and writes it, while `info`, `run` and `batch` open files through the automation layer, which still needs UTF-8 paths and fails with exit status 1 (`droplet` takes its arguments as text, so it refuses such a path as a usage error). `photocraft-cli --version` (or `-V`) prints the version; there is no `version` subcommand. +CLI parsing checks the flags and their values before any work starts. A flag the subcommand doesn't take (a typo such as `--fromat`), a flag given twice (`--cmd`, `--params` and `--automation-read-root` may repeat), a value out of range (`--quality 0`), malformed `--new` or `--params` JSON, `` together with `--new`, and `--control-token` together with `--control-token-file` are all usage errors (exit status 2), rather than being ignored or failing later. A value flag never takes the next flag as its value, so a value starting with `-` is written with `=` (`--out=-image.png`) or as `./-image.png`; negative numbers such as `--filter -1` still work. A path that is not valid Unicode reaches the command instead of being a usage error: `convert` reads and writes it, while `info`, `run` and `batch` open files through the automation layer, which still needs UTF-8 paths and fails with exit status 1 (`droplet` takes its arguments as text, so it refuses such a path as a usage error). `photocraft-cli --version` (or `-V`) prints the version; there is no `version` subcommand. `mcp` and `serve` reject positional arguments, empty values and options for the wrong mode before starting a server. Explicit control-token flags require `mcp --bridge` or `serve --port` (or From b61e51d0b2da8605c220d560595bccb6ff82843c Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:30:53 +0100 Subject: [PATCH 016/136] docs: align MCP reference with repeatable roots and switches Clarify usage of MCP and serve launch options regarding value requirements and repetition. --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 64fd88baa5..59859326be 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -171,8 +171,9 @@ flags on `photocraft-cli mcp --bridge` are rejected. Explicit `--control-token` `--control-token-file` flags require `--bridge` (or `PHOTOCRAFT_CONTROL_PORT`) and are mutually exclusive. Bridge credentials can also come from `PHOTOCRAFT_CONTROL_TOKEN` or `PHOTOCRAFT_CONTROL_TOKEN_FILE`. -MCP and `serve` launch options (all but `--help`/`-h`) take one non-empty value each and cannot -be repeated. Missing values, stray positional arguments and options for the wrong mode are +MCP and `serve` switches such as `--headless`, `--gpu`, `--no-gpu` and `--help`/`-h` take no +value. Value options take one non-empty value each; `--automation-read-root` may repeat to +add ordered read directories, while other launch options cannot be repeated. Missing values, stray positional arguments and options for the wrong mode are usage errors (exit 2), reported on stderr before the server starts; stdout stays available for protocol messages. For `serve`, explicit credential flags require `--port` (or `PHOTOCRAFT_CONTROL_PORT`); stdio needs no control token. From c37ba78a45bc945e3ed3652f55a6212303d0ec1c Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:37:06 +0100 Subject: [PATCH 017/136] Update viewport meta tag for initial scale --- apps/photocraft-web/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/photocraft-web/index.html b/apps/photocraft-web/index.html index 30ea522b66..043ffefc0e 100644 --- a/apps/photocraft-web/index.html +++ b/apps/photocraft-web/index.html @@ -2,7 +2,7 @@ - + PhotoCraft +
+

Loading PhotoCraft…

This is taking longer than usual. If PhotoCraft doesn't start, its files may have failed to download or come from a different version of this page. Reload to try again; the browser From ecc766d199a064cacd1109766bd4759ea0046171 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:08:25 +0100 Subject: [PATCH 028/136] fix(web): keep the boot host no-script fallback in sync Added a noscript section to inform users about JavaScript requirements. --- apps/photocraft-web-boot/index.html | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/apps/photocraft-web-boot/index.html b/apps/photocraft-web-boot/index.html index 7d15b18daa..ff3e548534 100644 --- a/apps/photocraft-web-boot/index.html +++ b/apps/photocraft-web-boot/index.html @@ -26,10 +26,16 @@ #photocraft_stopped a { color: #ffffff; } #photocraft_stopped_detail { color: #b8b8b8; } +

+

Loading PhotoCraft…

This is taking longer than usual. If PhotoCraft doesn't start, its files may have failed to download or come from a different version of this page. Reload to try again; the browser From bd7eee7880a77c6cb289a5c6ff2c16edd32a7992 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:12:07 +0100 Subject: [PATCH 029/136] docs: clarify that the print guard needs a nonempty value --- docs/development.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development.md b/docs/development.md index 7ed68e61b1..1a41c439a9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -190,7 +190,7 @@ A file dragged in from the desktop logs two lines at `info` (`file_open.rs`; fil |---|---| | `PHOTOCRAFT_GPU=1` (or `=0`) | Headless CLI: prefer GPU composition and flat export (0 to disable, empty to unset). Explicit `--gpu`/`--no-gpu` CLI flags override this variable. `file.export.quickExport` composites and encodes inside the engine, which has no renderer, so it always runs on the CPU; `run --gpu` prints a one-time warning when a step uses it | | `PHOTOCRAFT_CONTROL_PORT` | Same as `--control `; also the port for `photocraft-cli serve --port` and `mcp --bridge` when the flag is absent. Empty is unset | -| `PHOTOCRAFT_NO_PRINT` | Set to anything but `0`: `file.print` / `file.printOneCopy` refuse to spool (`dryRun` still works). CI sets it, with `LPDEST=photocraft-no-such-printer` as a second net; set both when running the panic hunt or fuzzers locally | +| `PHOTOCRAFT_NO_PRINT` | Set to a non-empty value other than `0`: `file.print` / `file.printOneCopy` refuse to spool (`dryRun` still works). CI sets it, with `LPDEST=photocraft-no-such-printer` as a second net; set both when running the panic hunt or fuzzers locally | | `RUST_LOG` | Log levels for standard error and the log file (see [Logs](#logs)) | | `PHOTOCRAFT_CONTROL_TOKEN` | 64-hex bearer token for control TCP (avoid on shared systems where environment inspection is possible) | | `PHOTOCRAFT_CONTROL_TOKEN_FILE` | Read, or create for a server, the control bearer-token file | From 08551d5eb3d1efd132b3ef4a5a8ac9f005bd806a Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:28:51 +0100 Subject: [PATCH 030/136] docs: document DPX bit depth for headless saves --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ecf603fe9a..fb44cdad4a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -552,7 +552,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | -| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default, and refuses a Multichannel document, which has no image to write without them; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | +| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, dpxBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `dpxBits` selects 8, 10, 12 or 16 bits per sample for DPX (unset: 8 for an 8-bit document, otherwise 16); `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default, and refuses a Multichannel document, which has no image to write without them; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | | `doc.inspect` | `{index?}`: same JSON as `document.inspect` | | `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | | `doc.select` / `doc.close` | `{index}` / `{index?}` | From 414febdf1022aab925d86861d4deccaf8c8fbb55 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:35:08 +0100 Subject: [PATCH 031/136] docs: distinguish absolute normalization from relative path syntax --- book/src/automation/control-protocol.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/book/src/automation/control-protocol.md b/book/src/automation/control-protocol.md index 129eee9b77..8d5b49e4e8 100644 --- a/book/src/automation/control-protocol.md +++ b/book/src/automation/control-protocol.md @@ -26,9 +26,12 @@ budgets. Headless previews have source-pixel, requested-edge, and encoded-PNG ce bridge bounds incoming reply frames and screenshot decoding. Automation file methods require separately configured read and write roots. Request paths may be relative or absolute beneath the canonical or configured spelling of the applicable granted root. -Absolute paths are translated to relative paths and resolved through the held directory capability. -Outside-root absolute paths, parent traversal, malformed relative components and link escapes are -rejected before file effects. +Absolute paths outside that root are rejected. Accepted absolute paths are translated to relative +paths and resolved through the held directory capability. Relative requests reject empty or `.` +components and alternate separators. Absolute requests are split into native path components +before checking the root-relative remainder, so repeated separators and interior `.` components +are normalized. Both forms reject parent traversal in the remainder, disallowed component names +and link escapes before file effects. **Known limitations:** the token is a bearer credential and grants the complete non-filesystem control surface. There is no encryption, client identity, general per-method capability check, From fac4e4507944b2eceb0b9470693d06d554aab85a Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:35:33 +0100 Subject: [PATCH 032/136] docs: align automation security with native path normalization --- book/src/security/automation-security.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md index 462f232c70..b7b7147443 100644 --- a/book/src/security/automation-security.md +++ b/book/src/security/automation-security.md @@ -44,9 +44,12 @@ Automation is a privilege boundary because requests can cause filesystem access, writes back only to the document's own PSD, PSB or `.pcraft` file in its own format; any other save needs an explicit `path`, so automation never flattens or converts over the file it opened. - Automation paths may be relative or absolute beneath the canonical or configured spelling of - the applicable granted root. Absolute paths are translated to relative paths and resolved through - the held directory capability. Outside-root absolute paths, parent traversal, malformed relative - components and link escapes are rejected before file effects. + the applicable granted root. Absolute paths outside that root are rejected. Accepted absolute + paths are translated to relative paths and resolved through the held directory capability. + Relative requests reject empty or `.` components and alternate separators. Absolute requests + are split into native path components before checking the root-relative remainder, so repeated + separators and interior `.` components are normalized. Both forms reject parent traversal in + the remainder, disallowed component names and link escapes before file effects. - Engine commands that still use ambient paths fail closed at the automation boundary. Synthetic UI input reaches the same command policy, and automation-triggered file hooks do not run user-configured script-event paths. The policy also covers every command a command runs on its From e15b4445b8c240c796da2d90b7596834b9f5a6b5 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:36:13 +0100 Subject: [PATCH 033/136] docs: scope parent requirements to ordinary file writes --- book/src/security/secure-file-handling.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/book/src/security/secure-file-handling.md b/book/src/security/secure-file-handling.md index ffa63bf6ee..91861c444b 100644 --- a/book/src/security/secure-file-handling.md +++ b/book/src/security/secure-file-handling.md @@ -14,10 +14,12 @@ Remote automation paths are untrusted names resolved beneath explicitly granted - Absolute paths beneath the canonical or configured spelling of the applicable granted root are translated to relative paths and resolved through the held directory capability. Absolute paths outside that root are rejected. -- The relative path rejects parent traversal, alternate separators, drive/device/stream prefixes, - reserved Windows device names, empty or dot components, and link escapes before file effects. -- Non-existent output files are supported when their parent already exists beneath the write - root. Automation does not create caller-selected directory trees. +- Relative requests reject empty or `.` components and alternate separators. Absolute requests + are split into native path components before checking the root-relative remainder, so repeated + separators and interior `.` components are normalized. Both forms reject parent traversal in + the remainder, disallowed component names and link escapes before file effects. +- Ordinary single-file writes support non-existent output files when their parent already exists + beneath the write root; they do not create caller-selected directory trees. - Filesystem-bearing engine commands that have not migrated to capability I/O fail closed for automation. Trusted local CLI subcommands and user-driven desktop file pickers keep their intended ambient authority. @@ -44,8 +46,9 @@ AuthorizedWorkspace The handle is created from an explicit launch-time grant, preserves separate read/write permissions, checks absolute paths against the granted root and rejects escaping paths. Operations use the held directory capability; the requested path is never resolved with ambient authority. -New files require an existing in-root parent because a non-existent target cannot be canonicalized -safely. +Ordinary single-file writes require an existing in-root parent. Capability-scoped multi-file +exports create their required export directory and missing ancestors beneath the write root +before writing files. ## Design requirements From 92bfcce4e35b63aca882f8be57fa2134a0b38628 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:45:56 +0100 Subject: [PATCH 034/136] fix(tablet): reset cached samples when device mappings change --- crates/tablet/src/xi.rs | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/crates/tablet/src/xi.rs b/crates/tablet/src/xi.rs index 2195acd3ce..943dc9cf98 100644 --- a/crates/tablet/src/xi.rs +++ b/crates/tablet/src/xi.rs @@ -133,8 +133,14 @@ pub struct State { impl State { /// Replace the device list (after `XIQueryDevice`, on start and hierarchy changes). pub fn set_devices(&mut self, devices: impl IntoIterator) { - self.devices = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect(); - self.last.retain(|id, _| self.devices.contains_key(id)); + let devices: HashMap<_, _> = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect(); + // Cached values are already mapped: changed ranges or axes make them stale. + // XIQueryDevice may return the same classes in a different order. + self.last.retain(|id, _| match (self.devices.get(id), devices.get(id)) { + (Some(old), Some(new)) => old.eraser == new.eraser && old.axes.len() == new.axes.len() && old.axes.iter().all(|axis| new.axes.contains(axis)), + _ => false, + }); + self.devices = devices; } pub fn device(&self, id: u16) -> Option<&Device> { @@ -252,6 +258,35 @@ mod tests { assert_eq!(st.handle(2, [(2, 3.0)]), Update::Keep); } + #[test] + fn refreshing_devices_resets_changed_mappings_only() { + let original = wacom(9, "Pen stylus"); + let unchanged = wacom(10, "Pen eraser"); + let removed = wacom(11, "Pen stylus"); + let mut st = State::default(); + st.set_devices([original.clone(), unchanged.clone(), removed.clone()]); + let _ = st.handle(9, [(2, 32767.5), (3, -30.0), (4, 45.0)]); + let cached = sample(st.handle(10, [(2, 49151.25), (3, 12.0), (5, 0.0)])); + let _ = st.handle(11, [(2, 65535.0)]); + + let mut changed = original; + changed.axes.retain(|a| a.kind != AxisKind::TiltY); + changed.axes.iter_mut().find(|a| a.kind == AxisKind::Pressure).unwrap().max *= 2.0; + // XIQueryDevice does not promise a stable class order. + let mut reordered = unchanged.clone(); + reordered.axes.reverse(); + st.set_devices([changed.clone(), reordered]); + + let fresh = sample(st.handle(9, [])); + assert_eq!((fresh.pressure, fresh.tilt_x, fresh.tilt_y, fresh.rotation), (0.0, 0.0, 0.0, 0.0)); + assert_eq!(sample(st.handle(9, [(2, 32767.5)])).pressure, 0.25); + assert_eq!(sample(st.handle(10, [])), cached, "unchanged mappings retain their sample"); + assert_eq!(st.handle(11, []), Update::Keep); + + st.set_devices([changed, unchanged, removed]); + assert_eq!(sample(st.handle(11, [])).pressure, 0.0, "removed devices lose their cached sample"); + } + #[test] fn tilt_ranges_that_are_not_degrees_are_scaled() { let d = From 65adc6e7933b532a9550c407a05c6e15fab5a630 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:48:12 +0100 Subject: [PATCH 035/136] fix(text): honor explicit Hans in served font language fallback --- crates/text/src/served.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/text/src/served.rs b/crates/text/src/served.rs index 952f43cb25..4599982387 100644 --- a/crates/text/src/served.rs +++ b/crates/text/src/served.rs @@ -156,6 +156,8 @@ pub fn language_script(tag: &str) -> Option<&'static str> { "ka" => "Geor", "ja" => "Jpan", "ko" => "Kore", + // An explicit script takes precedence over regional defaults. + "zh" if rest.contains(&"hans") => "Hans", "zh" if rest.iter().any(|r| matches!(*r, "hant" | "tw" | "hk" | "mo")) => "Hant", "zh" => "Hans", _ => return None, @@ -503,6 +505,12 @@ mod tests { ("ja-JP", Some("Jpan")), ("zh-CN", Some("Hans")), ("zh-TW", Some("Hant")), + ("zh-HK", Some("Hant")), + ("zh-MO", Some("Hant")), + ("zh-Hans-TW", Some("Hans")), + ("zh-Hans-HK", Some("Hans")), + ("zh-Hans-MO", Some("Hans")), + ("zh-Hant-CN", Some("Hant")), ("zh-Hant-HK", Some("Hant")), ("ko", Some("Kore")), ("en-US", None), From 996b9a2a1e50889db4de0db06284c5becdf7a4a0 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:04:34 +0100 Subject: [PATCH 036/136] docs: qualify guarded Windows UNC path operations --- book/src/security/secure-file-handling.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/book/src/security/secure-file-handling.md b/book/src/security/secure-file-handling.md index 91861c444b..40b6181577 100644 --- a/book/src/security/secure-file-handling.md +++ b/book/src/security/secure-file-handling.md @@ -44,8 +44,12 @@ AuthorizedWorkspace ``` The handle is created from an explicit launch-time grant, preserves separate read/write -permissions, checks absolute paths against the granted root and rejects escaping paths. Operations -use the held directory capability; the requested path is never resolved with ambient authority. +permissions, checks absolute paths against the granted root and rejects escaping paths. File +contents are read and written through the held directory capability. On Windows UNC write roots, +directory creation and atomic-save renames use guarded ambient paths beneath the canonical root, +with each ancestor verified through its parent handle and held open. See +[Windows UNC write roots](../automation/security-model.md#windows-unc-write-roots) for the +provider and WSL limitations. Ordinary single-file writes require an existing in-root parent. Capability-scoped multi-file exports create their required export directory and missing ancestors beneath the write root before writing files. From 380df930ca19a2f6777f891694ddfcb4ce5592b3 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:11:47 +0100 Subject: [PATCH 037/136] fix(text): ignore language extensions when choosing scripts Stop script and region matching at extension/private-use singletons so a numbering-system value cannot override an explicit Chinese script. Extend the existing language table with extension, private-use, and extlang controls. --- crates/text/src/served.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/text/src/served.rs b/crates/text/src/served.rs index 4599982387..96382946a5 100644 --- a/crates/text/src/served.rs +++ b/crates/text/src/served.rs @@ -144,7 +144,8 @@ pub fn language_script(tag: &str) -> Option<&'static str> { let tag = tag.trim().to_ascii_lowercase().replace('_', "-"); let mut parts = tag.split('-'); let lang = parts.next()?; - let rest: Vec<&str> = parts.collect(); + // RFC 5646: a singleton starts extensions/private use; their values do not choose the script. + let rest: Vec<&str> = parts.take_while(|part| part.len() != 1).collect(); Some(match lang { "ar" | "fa" | "ur" | "ps" | "ckb" | "sd" | "ug" => "Arab", "he" | "iw" | "yi" => "Hebr", @@ -512,6 +513,12 @@ mod tests { ("zh-Hans-MO", Some("Hans")), ("zh-Hant-CN", Some("Hant")), ("zh-Hant-HK", Some("Hant")), + ("zh-Hant-TW-u-nu-hans", Some("Hant")), + ("zh-TW-u-nu-hans", Some("Hant")), + ("zh-CN-u-nu-hant", Some("Hans")), + ("zh-cmn-Hans-TW", Some("Hans")), + ("zh-cmn-Hant-CN", Some("Hant")), + ("zh-TW-x-hans", Some("Hant")), ("ko", Some("Kore")), ("en-US", None), ("ru", None), From a85dd2730eaa2f6e1cfd8c5e854ba131a7f8a9b7 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:31:45 +0100 Subject: [PATCH 038/136] fix(color): reuse the winning CMYK space after concurrent builds Recheck the allocation cache under its insertion lock after building transforms, so concurrent first renders retain one shared CMYK space. Add a four-caller regression using the public profile lookup. --- crates/color/src/convert.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/color/src/convert.rs b/crates/color/src/convert.rs index 584dd40569..9e36d55651 100644 --- a/crates/color/src/convert.rs +++ b/crates/color/src/convert.rs @@ -42,7 +42,12 @@ impl CmykSpace { } } let space = Self::build(bytes); - cache.lock().unwrap_or_else(|e| e.into_inner()).push((Arc::downgrade(bytes), space.clone())); + let mut c = cache.lock().unwrap_or_else(|e| e.into_inner()); + // Another render may have cached this allocation while its transforms were built. + if let Some((_, cached)) = c.iter().find(|(w, _)| w.as_ptr() == Arc::as_ptr(bytes)) { + return cached.clone(); + } + c.push((Arc::downgrade(bytes), space.clone())); space } @@ -329,6 +334,32 @@ mod tests { }); } + #[test] + fn concurrent_profile_requests_share_the_cached_space() { + const CALLERS: usize = 4; + let params = craft_cms::synth::CmykParams { + description: "Concurrent CMYK cache".into(), + tvi: [0.26, 0.26, 0.26, 0.3], + grid_a2b: 5, + grid_b2a: 9, + ..Default::default() + }; + let bytes = craft_cms::synth::cmyk_profile(¶ms).unwrap().to_bytes(); + let start = std::sync::Barrier::new(CALLERS); + let spaces = std::thread::scope(|scope| { + let handles: Vec<_> = (0..CALLERS) + .map(|_| { + scope.spawn(|| { + start.wait(); + CmykSpace::for_profile(Some(&bytes)).expect("a synthetic CMYK space") + }) + }) + .collect(); + handles.into_iter().map(|h| h.join().unwrap()).collect::>() + }); + assert!(spaces.iter().all(|space| Arc::ptr_eq(space, &spaces[0])), "parallel first callers must share one cached CMYK space"); + } + /// Lab round-trips sRGB and puts white at L 100 and black at L 0. #[test] fn lab_roundtrip_and_anchors() { From 43a6155ac40cdc0ec077b841f23eb4061c9b155f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 14 Nov 2026 21:13:24 +0100 Subject: [PATCH 039/136] fix(ui): Color Lookup keeps Dither and Interpolation, forgets only the LUT The first version skipped remembering for the whole command. #14422 only asks for no LUT chosen on the next opening and keeps today's behaviour for the other values, so Dither and Interpolation are remembered again and only the "lut" and "file" fields are left out of saving and restoring. --- .../dialogs/color_lookup_no_remember_tests.rs | 21 ++++++++------ crates/ui-egui/src/dialogs/filter_dialog.rs | 28 +++++++++---------- 2 files changed, 26 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs b/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs index 5dd6c64a7c..a305c927bb 100644 --- a/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs +++ b/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs @@ -47,19 +47,24 @@ fn step_dialog(app: &mut PhotocraftApp, params: Value) -> u64 { played["paused"]["dialog"].as_u64().expect("the toggled step opens its dialog") } -/// The measured case: OK with a built-in look, and the next opening shows the defaults again -/// instead of that look. It also asserts that OK keeps nothing at all for Color Lookup, so no -/// unread values gather in the preferences. +/// The measured case: OK with a built-in look, and the next opening shows no LUT again instead of +/// that look. Dither and Interpolation are not the LUT and keep today's behaviour: they come back +/// as they were OK'd, and the preferences keep no LUT choice. #[test] -fn color_lookup_ok_with_a_builtin_look_reopens_at_the_defaults() { +fn color_lookup_ok_with_a_builtin_look_reopens_with_no_lut() { let mut app = app_with_doc(); let id = open(&mut app, COLOR_LOOKUP).unwrap(); assert_defaults(&app.ui.dialog_mut(id).unwrap().fields, "the first opening"); ok_with(&mut app, id, json!({"lut": "warm", "dither": true, "interpolation": "tetrahedral"})); let id = open(&mut app, COLOR_LOOKUP).unwrap(); - assert_defaults(&app.ui.dialog_mut(id).unwrap().fields, "after OK with the built-in look warm"); - assert!(!app.session.prefs().dialogs.contains_key(COLOR_LOOKUP), "OK keeps no Color Lookup values"); + let fields = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(fields["lut"], json!("none"), "after OK with the built-in look warm: lut"); + assert_eq!(fields["file"], json!(""), "after OK with the built-in look warm: file"); + assert_eq!(fields["dither"], json!(true), "Dither keeps its remembered value"); + assert_eq!(fields["interpolation"], json!("tetrahedral"), "Interpolation keeps its remembered value"); + let saved = app.session.prefs().dialogs.get(COLOR_LOOKUP).and_then(Value::as_object).cloned().unwrap_or_default(); + assert!(!saved.contains_key("lut") && !saved.contains_key("file"), "no LUT choice is kept: {saved:?}"); } /// The other measured opening: a LUT file loaded and OK'd. The next opening shows no file and no @@ -71,7 +76,7 @@ fn color_lookup_ok_with_a_lut_file_reopens_at_the_defaults() { std::fs::write(&path, "LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").unwrap(); let mut app = app_with_doc(); let id = open(&mut app, COLOR_LOOKUP).unwrap(); - ok_with(&mut app, id, json!({"file": path.to_str().unwrap(), "dither": true})); + ok_with(&mut app, id, json!({"file": path.to_str().unwrap()})); let id = open(&mut app, COLOR_LOOKUP).unwrap(); assert_defaults(&app.ui.dialog_mut(id).unwrap().fields, "after OK with a LUT file"); @@ -84,7 +89,7 @@ fn color_lookup_ok_with_a_lut_file_reopens_at_the_defaults() { fn color_lookup_step_dialog_without_recorded_values_opens_at_the_defaults() { let mut app = app_with_doc(); let id = open(&mut app, COLOR_LOOKUP).unwrap(); - ok_with(&mut app, id, json!({"lut": "cool", "dither": true})); + ok_with(&mut app, id, json!({"lut": "cool"})); let id = step_dialog(&mut app, json!({})); assert_defaults(&app.ui.dialog_mut(id).unwrap().fields, "the scripted step with no values"); diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 7ad8c769f9..5f441f9fa2 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -365,14 +365,15 @@ fn rememberable(kind: &Kind, value: &Value) -> bool { } } +/// Color Lookup opens with no LUT chosen every time, as the reference application does: an OK with +/// a built-in look or a LUT file leaves the next opening at "no LUT" (#14422). Its other values +/// (Dither, Interpolation) are remembered like any schema dialog's. A recorded or scripted step +/// still prefills, because the Actions panel seeds its own values after the dialog opens. +fn forgotten(command: &str, key: &str) -> bool { + command == COLOR_LOOKUP && matches!(key, "lut" | "file") +} + fn restore_remembered(app: &PhotocraftApp, command: &str, spec: &str, fields: &mut Map) { - // Color Lookup opens at its defaults every time, as the reference application's does: an OK - // with a built-in look or a LUT file leaves the next opening at "no LUT" and Dither at its - // default (#14422). A recorded or scripted step still prefills, because the Actions panel - // seeds its own values after the dialog opens. - if command == COLOR_LOOKUP { - return; - } let Some(Value::Object(saved)) = app.session.prefs().dialogs.get(command) else { return }; // Select and Mask starts from its defaults unless Remember Settings was on, as in Photoshop // (#9423). @@ -384,7 +385,7 @@ fn restore_remembered(app: &PhotocraftApp, command: &str, spec: &str, fields: &m } } for p in parse_spec(spec) { - if let Some(v) = saved.get(&p.key).filter(|v| rememberable(&p.kind, v)) { + if let Some(v) = saved.get(&p.key).filter(|v| rememberable(&p.kind, v) && !forgotten(command, &p.key)) { fields.insert(p.key, v.clone()); } } @@ -392,17 +393,14 @@ fn restore_remembered(app: &PhotocraftApp, command: &str, spec: &str, fields: &m /// Remember successful built-in schema dialogs; failed or cancelled dialogs do not persist. pub(crate) fn remember(app: &mut PhotocraftApp, command: &str, fields: &Map) { - // Color Lookup restores nothing (#14422), so saving its choices would only leave values in the - // preferences that nothing reads. - if command == COLOR_LOOKUP { - return; - } if !fields.contains_key("__filter") || fields.contains_key("__spec") || fields.contains_key("__smartFilter") { return; } let Some(spec) = photocraft_engine::commands::find(command) else { return }; - let mut saved: Map = - parse_spec(spec.params).into_iter().filter_map(|p| fields.get(&p.key).filter(|v| rememberable(&p.kind, v)).map(|v| (p.key, v.clone()))).collect(); + let mut saved: Map = parse_spec(spec.params) + .into_iter() + .filter_map(|p| fields.get(&p.key).filter(|v| rememberable(&p.kind, v) && !forgotten(command, &p.key)).map(|v| (p.key, v.clone()))) + .collect(); // Select and Mask with Remember Settings off keeps only that choice, so the next one starts // from the defaults (#9423). if command == crate::select_mask_view::COMMAND { From 9de0b92a8aaed1a777abe0386c35eabaa65dc222 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sun, 15 Nov 2026 12:16:11 +0100 Subject: [PATCH 040/136] test(ui-egui): legacy saved Color Lookup preferences restore everything but the LUT --- .../src/dialogs/color_lookup_no_remember_tests.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs b/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs index a305c927bb..75f9b094f0 100644 --- a/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs +++ b/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs @@ -142,3 +142,18 @@ fn other_schema_dialogs_still_remember_their_choices() { let id = open(&mut app, "filter.blur.gaussianBlur").unwrap(); assert_eq!(app.ui.dialog_mut(id).unwrap().fields["radius"], json!(11.0), "the blur dialog still remembers"); } +/// Preferences written before this change can hold a saved LUT choice. The restore filter rejects +/// it while the other saved fields still come back. +#[test] +fn color_lookup_legacy_saved_preferences_restore_everything_but_the_lut() { + let mut app = app_with_doc(); + app.session + .prefs + .edit(|prefs| prefs.dialogs.insert(COLOR_LOOKUP.into(), json!({"lut": "warm", "file": "old.cube", "dither": true, "interpolation": "tetrahedral"}))); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + let fields = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(fields["lut"], json!("none"), "a legacy saved look is not restored"); + assert_eq!(fields["file"], json!(""), "a legacy saved LUT file is not restored"); + assert_eq!(fields["dither"], json!(true), "a legacy saved Dither still is"); + assert_eq!(fields["interpolation"], json!("tetrahedral"), "a legacy saved Interpolation still is"); +} From 223e60df6a4a57f6cc8cd077a5b398071b82f206 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:19:32 +0100 Subject: [PATCH 041/136] fix(automation): ignore relative XDG config directories Ignore invalid relative XDG_CONFIG_HOME values instead of creating settings under the launch directory. Keep rooted Unix paths and the explicit PhotoCraft override, with focused regression coverage. --- crates/automation/src/app_dirs.rs | 65 ++++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/crates/automation/src/app_dirs.rs b/crates/automation/src/app_dirs.rs index d493536eff..80b38c86a0 100644 --- a/crates/automation/src/app_dirs.rs +++ b/crates/automation/src/app_dirs.rs @@ -72,7 +72,9 @@ pub fn platform_dir(env: &impl Fn(&str) -> Option) -> Option if cfg!(windows) { return env("APPDATA").filter(|a| !a.is_empty()).map(|a| PathBuf::from(a).join("Photocraft")); } - env("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).map(PathBuf::from).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft")) + // XDG requires absolute paths. With Windows handled above, a root is sufficient, + // including on wasm where is_absolute does not recognize rooted paths. + env("XDG_CONFIG_HOME").map(PathBuf::from).filter(|x| x.has_root()).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft")) } /// The first portable marker file in `exe_dir`, if any. @@ -112,3 +114,64 @@ pub fn from_env() -> DataDir { let exe = std::env::current_exe().ok(); resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent)) } + +#[cfg(all(test, not(windows), not(target_os = "macos")))] +mod tests { + use super::*; + + #[test] + fn relative_xdg_config_home_is_ignored() { + for xdg in ["relative/config", ".", "~/config"] { + for (home, expected) in [(Some("/home/test"), Some("/home/test/.config/photocraft")), (None, None), (Some(""), None)] { + let env = |key: &str| { + match key { + "HOME" => home, + "XDG_CONFIG_HOME" => Some(xdg), + _ => None, + } + .map(OsString::from) + }; + assert_eq!(platform_dir(&env), expected.map(PathBuf::from), "HOME={home:?}, XDG_CONFIG_HOME={xdg:?}"); + } + } + } + + #[test] + fn absolute_and_default_xdg_config_home_still_work() { + for (xdg, home, expected) in [ + (Some("/config"), Some("/home/test"), Some("/config/photocraft")), + (Some("/config"), None, Some("/config/photocraft")), + (None, Some("/home/test"), Some("/home/test/.config/photocraft")), + (Some(""), Some("/home/test"), Some("/home/test/.config/photocraft")), + (None, None, None), + (Some(""), None, None), + ] { + let env = |key: &str| { + match key { + "HOME" => home, + "XDG_CONFIG_HOME" => xdg, + _ => None, + } + .map(OsString::from) + }; + assert_eq!(platform_dir(&env), expected.map(PathBuf::from), "HOME={home:?}, XDG_CONFIG_HOME={xdg:?}"); + } + } + + #[test] + fn custom_config_override_still_accepts_relative_paths() { + let env = |key: &str| { + match key { + "PHOTOCRAFT_CONFIG_DIR" => Some("custom/config"), + "XDG_CONFIG_HOME" => Some("/config"), + "HOME" => Some("/home/test"), + _ => None, + } + .map(OsString::from) + }; + let result = resolve(env, None); + assert_eq!(result.dir, Some(PathBuf::from("custom/config"))); + assert_eq!(result.mode, Mode::Override); + assert!(result.warning.is_none()); + } +} From 4f9f5a233fe2ef27082a966ee76f32f9ad4c6e81 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:32:28 +0100 Subject: [PATCH 042/136] fix(web): distinguish unreachable requests from Wasm traps Avoid treating ordinary network or resource errors containing unreachable as a stopped Wasm module. Preserve recognized browser trap messages and RuntimeError handling, with positive and negative regressions. --- apps/photocraft-web/src/diagnostics.rs | 48 ++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/apps/photocraft-web/src/diagnostics.rs b/apps/photocraft-web/src/diagnostics.rs index 134e0e4035..cd9c4da765 100644 --- a/apps/photocraft-web/src/diagnostics.rs +++ b/apps/photocraft-web/src/diagnostics.rs @@ -39,9 +39,26 @@ pub fn take_panic() -> Option { pub fn is_trap(name: &str, message: &str) -> bool { let message = message.to_ascii_lowercase(); name == "RuntimeError" - || ["unreachable", "memory access out of bounds", "maximum call stack", "could not allocate memory", "out of memory"] - .iter() - .any(|m| message.contains(m)) + // A failed request can call its host "unreachable" without stopping the module. + || matches!( + message.trim(), + "unreachable" + | "error: unreachable" + | "runtimeerror: unreachable" + | "uncaught error: unreachable" + | "uncaught runtimeerror: unreachable" + | "uncaught (in promise) runtimeerror: unreachable" + ) + || [ + "unreachable executed", + "unreachable code should not be executed", + "memory access out of bounds", + "maximum call stack", + "could not allocate memory", + "out of memory", + ] + .iter() + .any(|m| message.contains(m)) } /// Trap messages (lowercase, matched ignoring case) that mean an allocation failed: @@ -109,13 +126,38 @@ mod tests { fn only_traps_count() { assert!(is_trap("RuntimeError", "unreachable")); assert!(is_trap("RuntimeError", "")); + assert!(is_trap("RuntimeError", "divide by zero")); + for message in [ + "unreachable", + "Error: unreachable", + "RuntimeError: unreachable", + "Uncaught Error: unreachable", + "Uncaught RuntimeError: unreachable", + "Uncaught (in promise) RuntimeError: unreachable", + "RuntimeError: unreachable executed", + ] { + assert!(is_trap("", message), "{message}"); + } assert!(is_trap("RangeError", "Maximum call stack size exceeded")); assert!(is_trap("RangeError", "WebAssembly.Memory(): could not allocate memory")); // Matched ignoring case: Safari's wording, reported without the RuntimeError name. assert!(is_trap("Error", "Unreachable code should not be executed")); + assert!(is_trap("Error", "Unreachable code should not be executed (evaluating 'module.run()')")); assert!(is_trap("Error", "Out of memory")); assert!(!is_trap("TypeError", "Failed to fetch")); assert!(!is_trap("Error", "ResizeObserver loop completed")); + for (name, message) in [ + ("Error", "server unreachable"), + ("TypeError", "Failed to fetch: host unreachable"), + ("", "Error: endpoint unreachable"), + ("Error", "unreachable resource"), + ("Error", "Uncaught Error: server unreachable"), + ("Error", "network unreachable"), + ("", "server: unreachable"), + ("", "NetworkError: unreachable"), + ] { + assert!(!is_trap(name, message), "unrelated error classified as a trap: {name}: {message}"); + } } #[test] From 481872835bee46f5a8eb8728b1392b4008b0b32a Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:48:57 +0100 Subject: [PATCH 043/136] fix(linux): honor loader separators in library preflight Parse colon and semicolon separators and preserve empty components in nonempty LD_LIBRARY_PATH lists. Add focused parser and startup-decision regressions. --- apps/photocraft/src/linux_libs.rs | 50 +++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/apps/photocraft/src/linux_libs.rs b/apps/photocraft/src/linux_libs.rs index b1682144d8..6a31cf1ab7 100644 --- a/apps/photocraft/src/linux_libs.rs +++ b/apps/photocraft/src/linux_libs.rs @@ -227,7 +227,14 @@ pub fn missing_message(session: DisplaySession, missing: &[AnyOf], distro: Distr /// Library directories to search: `LD_LIBRARY_PATH`, then the usual system and Flatpak paths. fn search_dirs(ld_library_path: Option<&str>) -> Vec { - let mut dirs: Vec = ld_library_path.unwrap_or("").split(':').filter(|d| !d.is_empty()).map(PathBuf::from).collect(); + // ld.so accepts either separator; an empty entry in a nonempty list means the current directory. + // An unset or entirely empty variable adds no directories. + let mut dirs: Vec = ld_library_path + .filter(|value| !value.is_empty()) + .into_iter() + .flat_map(|value| value.split([':', ';'])) + .map(|dir| PathBuf::from(if dir.is_empty() { "." } else { dir })) + .collect(); let triplet = if cfg!(target_arch = "aarch64") { "aarch64-linux-gnu" } else if cfg!(target_arch = "riscv64") { @@ -404,7 +411,8 @@ mod tests { fn library_dirs_count_and_unread_cache_is_inconclusive() { let dirs = search_dirs(Some("/opt/x/lib::/nix/store/abc/lib")); assert_eq!(dirs[0], PathBuf::from("/opt/x/lib")); - assert_eq!(dirs[1], PathBuf::from("/nix/store/abc/lib")); + assert_eq!(dirs[1], PathBuf::from(".")); + assert_eq!(dirs[2], PathBuf::from("/nix/store/abc/lib")); // Found by file in a directory (no ldconfig, as on NixOS). let probe = Probe { ldconfig: None, dirs: vec![PathBuf::from("/nix/lib")] }; let present = ["/nix/lib/libwayland-client.so.0", "/nix/lib/libxkbcommon.so.0", "/nix/lib/libEGL.so.1"]; @@ -418,6 +426,44 @@ mod tests { assert!(msg.contains("dnf install libwayland-client libxkbcommon vulkan-loader"), "{msg}"); } + #[test] + fn library_path_separators_and_empty_entries_follow_the_loader() { + let defaults = search_dirs(None); + assert_eq!(search_dirs(Some("")), defaults, "an entirely empty variable adds no directories"); + for (value, entries) in [ + ("/opt/a:/opt/b", &["/opt/a", "/opt/b"][..]), + ("/opt/a;/opt/b", &["/opt/a", "/opt/b"][..]), + ("/opt/a;/opt/b:/opt/c", &["/opt/a", "/opt/b", "/opt/c"][..]), + (":/opt/b", &[".", "/opt/b"][..]), + ("/opt/a:", &["/opt/a", "."][..]), + ("/opt/a::/opt/b", &["/opt/a", ".", "/opt/b"][..]), + ("/opt/a;;/opt/b", &["/opt/a", ".", "/opt/b"][..]), + (":", &[".", "."][..]), + (";", &[".", "."][..]), + (" /opt/a ;relative/lib", &[" /opt/a ", "relative/lib"][..]), + (" ", &[" "][..]), + ] { + let mut expected: Vec = entries.iter().map(PathBuf::from).collect(); + expected.extend(defaults.iter().cloned()); + assert_eq!(search_dirs(Some(value)), expected, "LD_LIBRARY_PATH={value:?}"); + } + } + + #[test] + fn loader_search_paths_prevent_false_startup_errors() { + let soname = "libxkbcommon-x11.so.0"; + let names: Vec<&str> = ALL_X11.iter().copied().filter(|name| *name != soname).collect(); + let probe = Probe { ldconfig: Some(cache_for_this_arch(&names)), dirs: search_dirs(None) }; + let missing = check(DisplaySession::X11, &probe, |_| false); + assert!(decide(DisplaySession::X11, missing, || Distro::Debian).is_err(), "a genuinely missing library still blocks startup"); + for (value, directory) in [("/opt/a;/opt/b", "/opt/b"), (":/opt/a", "."), ("/opt/a:", ".")] { + let probe = Probe { ldconfig: Some(cache_for_this_arch(&names)), dirs: search_dirs(Some(value)) }; + let present = Path::new(directory).join(soname); + let verdict = check(DisplaySession::X11, &probe, |path| path == present); + assert_eq!(decide(DisplaySession::X11, verdict, || Distro::Debian), Ok(()), "LD_LIBRARY_PATH={value:?}, library at {}", present.display()); + } + } + #[test] fn unreadable_cache_never_warns_or_fails() { // Issue #1144: Alpine (musl) has no `ldconfig -p`, so a library that exists was reported missing. From 299d237afa3acf899902d6e44879d9327bba6662 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:54:59 +0100 Subject: [PATCH 044/136] docs: align architecture overview with granted-root paths Complete the existing absolute-path documentation correction in the architecture overview. Reused mdBook build and source-policy checks passed. --- book/src/architecture/automation.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/book/src/architecture/automation.md b/book/src/architecture/automation.md index cbdd207acd..280c7e14b8 100644 --- a/book/src/architecture/automation.md +++ b/book/src/architecture/automation.md @@ -18,8 +18,9 @@ The control and headless TCP listeners are restricted to loopback addresses. Std Loopback is not authentication. TCP transports require a bearer token and enforce request-byte, batch-step, and active-connection limits. Remote file methods use an `AuthorizedWorkspace` with -independent read and write directory capabilities; paths are relative to a configured root and -fail closed when the applicable root is absent. General per-method scopes, client identity, +independent read and write directory capabilities; paths may be relative or absolute beneath an +applicable granted root. File methods fail closed when the applicable read or write authority is +absent. General per-method scopes, client identity, encryption, and operation budgets are not implemented. See the [Automation security model](../automation/security-model.md) and [Automation security](../security/automation-security.md) before exposing or extending these From e61766d32ce54253755865a682370a5fd9ec5f93 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:12:58 +0100 Subject: [PATCH 045/136] fix(format): respect chosen chunk size in read probes Cap EOF and growth probe reads at the normalized chunk size. Add a bounded-reader regression covering zero, short and full probe sizes and missing, partial and exact length hints. --- crates/format/src/read.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/format/src/read.rs b/crates/format/src/read.rs index e089af6ea3..8dc8314ce9 100644 --- a/crates/format/src/read.rs +++ b/crates/format/src/read.rs @@ -92,8 +92,9 @@ fn read_all_with(reader: &mut impl Read, size_hint: u64, chunk: usize, max: u64) loop { if buf.len() == buf.capacity() { let mut probe = [0; 4096]; + let probe_len = chunk.min(probe.len()); let n = loop { - match reader.read(&mut probe) { + match reader.read(&mut probe[..probe_len]) { Err(e) if e.kind() == io::ErrorKind::Interrupted => {} r => break r?, } @@ -186,6 +187,30 @@ mod tests { } } + #[test] + fn probe_reads_respect_the_configured_chunk_size() { + struct SmallReads<'a> { + data: &'a [u8], + max_request: usize, + } + impl Read for SmallReads<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if buf.len() > self.max_request { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "read request exceeds the configured chunk size")); + } + self.data.read(buf) + } + } + let data = b"ninebytes"; + for chunk in [0, 1, 7, 4096] { + for hint in [0, 3, data.len() as u64] { + let mut reader = SmallReads { data, max_request: chunk.max(1) }; + let result = read_all_with(&mut reader, hint, chunk, 64); + assert_eq!(result.unwrap_or_else(|e| panic!("chunk {chunk}, hint {hint}: {e}")), data); + } + } + } + /// Nothing over the total limit is returned (#8601): a file larger than it, a reader that /// gives more than it whatever its hint says, and one that never ends are `FileTooLarge` /// errors, while a file exactly at the limit is read whole. From 041f3823a8c4f32b9e64121dd87a14608372029d Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:18:52 +0100 Subject: [PATCH 046/136] fix(xtask): preserve inline comments around workspace versions Read the canonical quoted workspace version before its comment and accept a commented workspace.package header. Preserve surrounding version-line text on replacement, with focused regressions for comments, formatting and line endings. --- xtask/src/version.rs | 59 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 5 deletions(-) diff --git a/xtask/src/version.rs b/xtask/src/version.rs index 7dae638077..99b37fa65c 100644 --- a/xtask/src/version.rs +++ b/xtask/src/version.rs @@ -8,17 +8,30 @@ use std::path::Path; /// The `version = "…"` value inside `[workspace.package]`. pub fn read(manifest: &str) -> Result { let (_, line) = find_line(manifest)?; - let v = line.split_once('=').map(|(_, v)| v.trim().trim_matches('"').to_string()).unwrap_or_default(); + let (_, v, _) = version_parts(line)?; if v.is_empty() { return Err("empty [workspace.package] version".into()); } - Ok(v) + Ok(v.to_owned()) +} + +/// The canonical double-quoted SemVer form, not general TOML string syntax. Keep the +/// surrounding text opaque so formatting and comments, including their quotes, survive. +fn version_parts(line: &str) -> Result<(&str, &str, &str), String> { + let bad = || "expected a double-quoted [workspace.package] version".to_string(); + if !line.split_once('=').is_some_and(|(_, value)| value.trim_start().starts_with('"')) { + return Err(bad()); + } + let (prefix, rest) = line.split_once('"').ok_or_else(bad)?; + let (value, suffix) = rest.split_once('"').ok_or_else(bad)?; + Ok((prefix, value, suffix)) } /// `manifest` with the workspace version replaced; everything else is byte-for-byte unchanged. pub fn replace(manifest: &str, new: &str) -> Result { validate(new)?; - let (idx, _) = find_line(manifest)?; + let (idx, line) = find_line(manifest)?; + let (prefix, _, suffix) = version_parts(line)?; let mut out = String::with_capacity(manifest.len() + 8); for (i, line) in manifest.split_inclusive('\n').enumerate() { if i == idx { @@ -29,7 +42,7 @@ pub fn replace(manifest: &str, new: &str) -> Result { } else { "" }; - out.push_str(&format!("version = \"{new}\"{eol}")); + out.push_str(&format!("{prefix}\"{new}\"{suffix}{eol}")); } else { out.push_str(line); } @@ -66,7 +79,10 @@ fn find_line(manifest: &str) -> Result<(usize, &str), String> { for (i, line) in manifest.lines().enumerate() { let t = line.trim(); if t.starts_with('[') { - in_section = t == "[workspace.package]"; + in_section = t.strip_prefix("[workspace.package]").is_some_and(|rest| { + let rest = rest.trim_start(); + rest.is_empty() || rest.starts_with('#') + }); continue; } if in_section @@ -137,6 +153,39 @@ mod tests { assert_eq!(out, crlf.replace("\"0.1.0\"", "\"2.0.0\"")); } + #[test] + fn reads_the_version_before_an_inline_comment() { + let manifest = MANIFEST.replace("version = \"0.1.0\"", "version = \"0.1.0\" # release note with \"quotes\" and #"); + assert_eq!(read(&manifest).unwrap(), "0.1.0"); + } + + #[test] + fn rejects_unsupported_string_syntax_before_comment_quotes() { + let manifest = MANIFEST.replace("version = \"0.1.0\"", "version = '0.1.0' # \"keep\""); + assert!(read(&manifest).is_err()); + assert!(replace(&manifest, "1.2.3").is_err()); + } + + #[test] + fn accepts_a_comment_after_the_workspace_package_header() { + let manifest = MANIFEST.replace("[workspace.package]", "[workspace.package] # shared package metadata"); + assert_eq!(read(&manifest).unwrap(), "0.1.0"); + assert_eq!(replace(&manifest, "1.2.3").unwrap(), manifest.replace("version = \"0.1.0\"", "version = \"1.2.3\"")); + } + + #[test] + fn preserves_version_line_formatting_comments_and_endings() { + for ending in ["\n", "\r\n", ""] { + let newline = if ending.is_empty() { "\n" } else { ending }; + let manifest = + format!("[package]{newline}version = \"9.0.0\"{newline}[workspace.package]{newline}\tversion\t=\t\"0.1.0\"\t # keep \"0.1.0\" and #{ending}"); + let expected = manifest.replacen("\"0.1.0\"", "\"1.2.3-rc.1\"", 1); + let updated = replace(&manifest, "1.2.3-rc.1").unwrap(); + assert_eq!(updated, expected, "ending={ending:?}"); + assert_eq!(read(&updated).unwrap(), "1.2.3-rc.1"); + } + } + #[test] fn validates_versions() { for ok in ["0.1.0", "1.20.300", "1.0.0-rc.1", "1.0.0-alpha", "1.0.0-x-y.2"] { From 94140691b777c2dace4e6542bedf0978700d9a44 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:27:06 +0100 Subject: [PATCH 047/136] docs(automation): describe agent bridge challenge authentication Replace the obsolete PID-check and token-transmission description with the current challenge-proof flow. No runtime code changes. --- crates/automation/src/agent_link.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index c89a14246a..89bcc4345c 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -12,10 +12,11 @@ //! //! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then //! listens on its port ([`probe`]), and the app's next launch replaces it or removes it -//! ([`remove_stale_connection`]). Until then another program could take that port, so a client -//! checks that [`Connection::pid`] is still running before it sends the token. That narrows the -//! gap without closing it (a pid can be reused); `docs/control-protocol.md` says when a client -//! should not send the token on the strength of this file. +//! ([`remove_stale_connection`]). Until then another program could take that port. PhotoCraft's +//! bridge uses challenge authentication: the listener must prove it holds the token before the +//! client sends its own proof, and the token itself is never sent. The bridge never falls back +//! to sending the token. [`Connection::pid`] identifies the publisher and distinguishes app +//! restarts; it is not used to authenticate the listener. See `docs/control-protocol.md`. //! //! The app starts and stops that server at once when the switch changes. `photocraft-cli mcp` //! ([`crate::live`]) reads the connection file on every tool call, so MCP client configurations From be328082515e6228451f56e4b82fe0d276a599ab Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:35:08 +0100 Subject: [PATCH 048/136] fix(logging): preserve logs with an unknown lock state Only a missing lock file proves an instance log is inactive. Preserve logs on other lock-open errors and extend the real-file rotation regression. --- apps/photocraft/src/logging.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/photocraft/src/logging.rs b/apps/photocraft/src/logging.rs index e525197a27..868a6bbe0b 100644 --- a/apps/photocraft/src/logging.rs +++ b/apps/photocraft/src/logging.rs @@ -219,7 +219,7 @@ fn prune_instance_logs(dir: &Path) { // A missing lock file means nobody holds it; an unknown lock state counts as running. let running = match OpenOptions::new().read(true).write(true).open(instance_lock(dir, pid)) { Ok(lock) => !try_hold(&lock).unwrap_or(false), - Err(_) => false, + Err(e) => e.kind() != std::io::ErrorKind::NotFound, }; if !running { let modified = entry.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH); @@ -542,6 +542,15 @@ mod tests { let held = File::create(instance_lock(&dir, 5)).expect("lock file"); held.try_lock().expect("hold"); + // An older log whose lock cannot be opened has an unknown owner, so keep it too. + let unknown = instance_log(&dir, 6); + std::fs::write(&unknown, "unknown owner").expect("write"); + File::options().write(true).open(&unknown).expect("open").set_modified(now - Duration::from_secs(1000)).expect("mtime"); + let unknown_lock = instance_lock(&dir, 6); + std::fs::create_dir(&unknown_lock).expect("unusable lock path"); + let error = OpenOptions::new().read(true).write(true).open(&unknown_lock).expect_err("a directory is not a lock file"); + assert_ne!(error.kind(), std::io::ErrorKind::NotFound); + let second = rotate(&dir).expect("second start"); assert_eq!(second.path, instance_log(&dir, std::process::id())); // The newest KEEP finished ones stay, the rest go with their lock files. @@ -549,6 +558,8 @@ mod tests { assert!(!instance_log(&dir, 2).exists() && !instance_log(&dir, 1).exists()); assert!(!instance_lock(&dir, 2).exists()); assert_eq!(read(&live), "live"); + assert_eq!(read(&unknown), "unknown owner"); + assert!(unknown_lock.is_dir()); drop((first, second, held)); let _ = std::fs::remove_dir_all(&dir); } From 94315dbafed968d78b962ba3af823a06d9b7b8b0 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:46:06 +0100 Subject: [PATCH 049/136] fix(text): keep supported left apostrophes inside spelling words Recognize U+2018 inside words, consistently with dictionary normalization. Cover exact UTF-8 token boundaries, real-dictionary misspellings and all supported apostrophe forms. --- crates/text/src/spell.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/text/src/spell.rs b/crates/text/src/spell.rs index 31ddf7bf03..04b3085d84 100644 --- a/crates/text/src/spell.rs +++ b/crates/text/src/spell.rs @@ -190,7 +190,7 @@ fn capitalize(w: &str) -> String { /// Byte ranges of the words in `text`: letters/digits with inner apostrophes (hyphens split). pub fn words(text: &str) -> Vec<(usize, usize)> { - let is_apos = |c: char| matches!(c, '\'' | '\u{2019}' | '\u{02BC}'); + let is_apos = |c: char| matches!(c, '\'' | '\u{2019}' | '\u{2018}' | '\u{02BC}'); let mut out = Vec::new(); let mut start: Option = None; let chars: Vec<(usize, char)> = text.char_indices().collect(); @@ -310,6 +310,29 @@ mod tests { assert_eq!(&text[mm.start..mm.end], "wrld"); } + #[test] + fn normalized_apostrophes_stay_inside_words() { + let d = Dictionary::english(); + for word in ["doesn't", "doesn\u{2019}t", "doesn\u{2018}t", "doesn\u{02BC}t"] { + let text = format!("({word})"); + assert!(d.check(word, &none()), "{word}"); + assert_eq!(words(&text), vec![(1, 1 + word.len())], "{word}"); + } + } + + #[test] + fn normalized_contractions_are_not_reported_as_misspellings() { + let d = Dictionary::english(); + for word in ["doesn't", "doesn\u{2019}t", "doesn\u{2018}t", "doesn\u{02BC}t"] { + let text = format!("({word})"); + let found = d.misspellings(&text, &none()); + assert!(found.is_empty(), "{word}: {found:?}"); + } + let typo = "doesn\u{2018}tt"; + let found = d.misspellings(typo, &none()); + assert_eq!(found, vec![Misspelling { start: 0, end: typo.len(), word: typo.into() }]); + } + /// `cargo test --release -p photocraft-text -- --ignored --nocapture spell_timing` #[test] #[ignore] From 160dffe86294124216cc6233591a8946e407ccfe Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:23:32 +0100 Subject: [PATCH 050/136] fix(xtask): require PIXLS checksum pins before fetching Reject incomplete checksum manifests before cache checks or downloads, with hermetic regressions for missing pins and valid cached/update paths. --- xtask/src/pinned.rs | 90 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 88 insertions(+), 2 deletions(-) diff --git a/xtask/src/pinned.rs b/xtask/src/pinned.rs index ddca8a6163..0618cf4838 100644 --- a/xtask/src/pinned.rs +++ b/xtask/src/pinned.rs @@ -370,9 +370,13 @@ fn file_hex(path: &std::path::Path) -> Option { /// per-file download rather than a git upstream; the manifest discipline is the same /// (`--update-manifest` re-pins). Opt-in: not part of `--all` or CI until a maintainer says so. pub fn fetch_pixls(update: bool) -> Result<(), String> { - let dest = crate::root().join("corpus").join("pixls"); + fetch_pixls_at(&crate::root(), update) +} + +fn fetch_pixls_at(root: &Path, update: bool) -> Result<(), String> { + let dest = root.join("corpus").join("pixls"); std::fs::create_dir_all(&dest).map_err(|e| format!("create {}: {e}", dest.display()))?; - let manifest = crate::root().join("xtask").join("pixls.sha256"); + let manifest = root.join("xtask").join("pixls.sha256"); if update { let mut names: Vec<&str> = crate::corpus_pins::PIXLS_FILES.iter().map(|(_, n)| *n).collect(); names.sort_unstable(); @@ -390,6 +394,12 @@ pub fn fetch_pixls(update: bool) -> Result<(), String> { .lines() .filter_map(|l| l.split_once(" ").map(|(s, n)| (n.to_string(), s.to_string()))) .collect(); + // Check every pin before any download: two absent hashes must not count as a cache hit. + for (_, name) in crate::corpus_pins::PIXLS_FILES { + if !want.contains_key(*name) { + return Err(format!("pixls {name}: missing sha256 entry in {}", manifest.display())); + } + } for (path, name) in crate::corpus_pins::PIXLS_FILES { let file = dest.join(name); if file_hex(&file).as_deref() == want.get(*name).map(String::as_str) { @@ -478,4 +488,80 @@ mod tests { let _ = std::fs::remove_dir_all(&tmp); } + + struct PixlsFixture(PathBuf); + + impl PixlsFixture { + fn new(case: &str) -> Self { + let root = std::env::temp_dir().join(format!("photocraft-pixls-{}-{case}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + std::fs::create_dir(root.join("xtask")).unwrap(); + std::fs::create_dir_all(root.join("corpus/pixls")).unwrap(); + Self(root) + } + + fn populate(&self, omitted: Option<&str>, cached: bool) { + let hash = crate::sha256::hex(b"camera fixture"); + let mut manifest = String::new(); + for (_, name) in crate::corpus_pins::PIXLS_FILES { + if Some(*name) != omitted { + manifest.push_str(&format!("{hash} {name}\n")); + } + if cached { + std::fs::write(self.0.join("corpus/pixls").join(name), b"camera fixture").unwrap(); + } + } + std::fs::write(self.0.join("xtask/pixls.sha256"), manifest).unwrap(); + } + + fn missing_pin_error(&self, name: &str) -> String { + format!("pixls {name}: missing sha256 entry in {}", self.0.join("xtask").join("pixls.sha256").display()) + } + } + + impl Drop for PixlsFixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn pixls_rejects_empty_manifest_without_claiming_missing_files_are_verified() { + let fixture = PixlsFixture::new("empty-manifest"); + std::fs::write(fixture.0.join("xtask/pixls.sha256"), "").unwrap(); + let name = crate::corpus_pins::PIXLS_FILES[0].1; + assert_eq!(super::fetch_pixls_at(&fixture.0, false), Err(fixture.missing_pin_error(name))); + } + + #[test] + fn pixls_rejects_missing_pin_even_when_file_is_cached() { + let fixture = PixlsFixture::new("cached-missing-pin"); + let name = crate::corpus_pins::PIXLS_FILES[0].1; + fixture.populate(Some(name), true); + assert_eq!(super::fetch_pixls_at(&fixture.0, false), Err(fixture.missing_pin_error(name))); + } + + #[test] + fn pixls_checks_last_pin_before_downloading_an_earlier_missing_file() { + let fixture = PixlsFixture::new("last-pin"); + let name = crate::corpus_pins::PIXLS_FILES.last().unwrap().1; + fixture.populate(Some(name), false); + assert_eq!(super::fetch_pixls_at(&fixture.0, false), Err(fixture.missing_pin_error(name))); + } + + #[test] + fn pixls_accepts_complete_matching_cached_files() { + let fixture = PixlsFixture::new("complete-cache"); + fixture.populate(None, true); + assert_eq!(super::fetch_pixls_at(&fixture.0, false), Ok(())); + } + + #[test] + fn pixls_update_manifest_still_hashes_cached_files() { + let fixture = PixlsFixture::new("update-manifest"); + fixture.populate(None, true); + std::fs::write(fixture.0.join("xtask/pixls.sha256"), "").unwrap(); + assert_eq!(super::fetch_pixls_at(&fixture.0, true), Ok(())); + assert_eq!(super::fetch_pixls_at(&fixture.0, false), Ok(())); + } } From efb349e838b7ccdef16f2fd4e57d18afcc8a9482 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:11:59 +0100 Subject: [PATCH 051/136] docs: clarify screenshot paths within the write grant Document the same scoped absolute paths accepted by the screenshot writer and the other automation file operations. --- docs/control-protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ecf603fe9a..0f4095ee6a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -154,7 +154,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - `ui.resize {width, height}`: resize the main window - `ui.gpu.simulateLoss {error?}`: act as if the wgpu device was lost (or reported an error with `error: true`). The app switches to the CPU image compositor (after a loss for the rest of the session; after an error until a successful Retry GPU) and shows the same recovery warning as on a real loss. `gpuFallbackNotice` in `ui.inspect` contains the reason while the warning is open. Keep Using CPU saves CPU compatibility for the next launch. Retry GPU saves GPU mode; after an error (`error: true`) it also builds a new GPU canvas on the same device at once (`gpuInfo.canvas` is `gpu` again, #6577), and after a loss it asks the user to save and restart. The window renderer still requires a working graphics or software adapter. Returns `wasActive` and `gpuInfo`. For testing the fallback. With `destroy: true` it destroys the window's real wgpu device instead, as a driver reset does (see `docs/development.md` › device loss): the app saves every unsaved document for recovery and closes. Returns `destroyed` - `ui.screenshot {path?, focus?}`: capture the main window (PNG). With no path the reply contains - base64 PNG data; a path is relative to the automation write root. Raises the window first + base64 PNG data; a supplied path may be relative to the automation write root or absolute beneath its canonical or configured spelling. Raises the window first (default) because occluded macOS windows stop rendering. A request sent before the first frame is queued (within the same limits and deadline) and captures once the window geometry is known, as on 0.15. At most four captures may be outstanding (waiting for geometry, rendered or awaiting From 6bd15bc0d6a224eeeaeacbf1780ca97553156129 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:15:02 +0100 Subject: [PATCH 052/136] fix(xtask): skip linked source entries in statistics Classify directory entries without following links so source aliases and directory cycles do not inflate counts. Add regressions for normal source exclusions and linked files and directories. --- xtask/src/stats.rs | 65 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 62 insertions(+), 3 deletions(-) diff --git a/xtask/src/stats.rs b/xtask/src/stats.rs index f40b1300ac..b4e6923617 100644 --- a/xtask/src/stats.rs +++ b/xtask/src/stats.rs @@ -15,15 +15,18 @@ fn walk(dir: &Path, c: &mut Counts) { return; }; for e in rd.flatten() { + // Do not count linked source trees twice or follow a directory link back to an ancestor. + let Ok(kind) = e.file_type() else { continue }; let p = e.path(); let name = e.file_name(); let name = name.to_string_lossy(); - if p.is_dir() { + if kind.is_dir() { // Nested fuzz workspaces and build output are not part of the crate. if name != "target" && name != "fuzz" && !name.starts_with('.') { walk(&p, c); } - } else if name.ends_with(".rs") + } else if kind.is_file() + && name.ends_with(".rs") && let Ok(s) = std::fs::read_to_string(&p) { c.files += 1; @@ -108,7 +111,63 @@ pub fn run(_root: &Path, exact: bool) -> Result<(), String> { #[cfg(test)] mod tests { - use super::count_tests; + use super::{Counts, count_tests, walk}; + use std::path::PathBuf; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Fixture(PathBuf); + + impl Fixture { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let root = std::env::temp_dir().join(format!("photocraft-stats-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir(&root).unwrap(); + Self(root) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Remove the fixture's known links before recursively removing its own directory. + let _ = std::fs::remove_file(self.0.join("project/linked.rs")); + #[cfg(unix)] + let _ = std::fs::remove_file(self.0.join("project/linked-dir")); + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn walk_counts_sources_and_skips_excluded_directories() { + let fixture = Fixture::new(); + for dir in ["src/nested", "target", "fuzz", ".hidden"] { + std::fs::create_dir_all(fixture.0.join(dir)).unwrap(); + } + std::fs::write(fixture.0.join("src/a.rs"), "#[test]\nfn a() {}\n").unwrap(); + std::fs::write(fixture.0.join("src/nested/b.rs"), "proptest! {}\n").unwrap(); + for path in ["target/a.rs", "fuzz/a.rs", ".hidden/a.rs", "src/not-rust.txt"] { + std::fs::write(fixture.0.join(path), "#[test]\n").unwrap(); + } + + let mut counts = Counts::default(); + walk(&fixture.0, &mut counts); + assert_eq!((counts.files, counts.lines, counts.tests, counts.proptests), (2, 3, 1, 1)); + } + + #[cfg(unix)] + #[test] + fn walk_ignores_linked_sources() { + let fixture = Fixture::new(); + std::fs::create_dir(fixture.0.join("project")).unwrap(); + std::fs::create_dir(fixture.0.join("external")).unwrap(); + std::fs::write(fixture.0.join("project/real.rs"), "#[test]\nfn real() {}\n").unwrap(); + std::fs::write(fixture.0.join("external/extra.rs"), "#[test]\nfn extra() {}\n").unwrap(); + std::os::unix::fs::symlink(fixture.0.join("external"), fixture.0.join("project/linked-dir")).unwrap(); + std::os::unix::fs::symlink(fixture.0.join("external/extra.rs"), fixture.0.join("project/linked.rs")).unwrap(); + + let mut counts = Counts::default(); + walk(&fixture.0.join("project"), &mut counts); + assert_eq!((counts.files, counts.lines, counts.tests, counts.proptests), (1, 2, 1, 0)); + } #[test] fn counts_attributes_and_proptest_blocks() { From d52dcb575edb9a188edcb5ad83f03d316c17650c Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:36:13 +0100 Subject: [PATCH 053/136] fix(xtask): reject unknown corpus arguments before fetching Validate corpus options before dispatch so a typo cannot silently succeed or start corpus downloads. Preserve existing aliases and modifier flags. --- xtask/src/corpus.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/xtask/src/corpus.rs b/xtask/src/corpus.rs index 0be1f83625..ca622490ca 100644 --- a/xtask/src/corpus.rs +++ b/xtask/src/corpus.rs @@ -27,6 +27,13 @@ const HEIF_CRATES: &[&str] = &["photocraft-io"]; const CRITICAL: &[&str] = &["crates/io/", "crates/compose/", "crates/gpu/", "crates/text/", "crates/format/", "crates/raw/", "crates/engine/src/atn_cmds"]; /// `cargo xtask corpus [--all | --pngsuite | --download | --psd | --psd-tools | --heif | --exr | --pixls | --affinity | --atn | --photoshop [--local] | --gimp [--local]] [--update-manifest]` pub fn cmd(args: &[&str]) -> Result<(), String> { + for arg in args { + match *arg { + "--all" | "--pngsuite" | "--download" | "--psd" | "--psd-tools" | "--heif" | "--pixls" | "--exr" | "--affinity" | "--atn" | "--photoshop" + | "--gimp" | "--local" | "--update-manifest" => {} + other => return Err(format!("corpus: unknown argument `{other}`")), + } + } let update = args.contains(&"--update-manifest"); let mut did = false; if args.contains(&"--all") { From 068b3d23d485162f3277eda6ecfdc7232882aa5d Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:37:14 +0100 Subject: [PATCH 054/136] test(xtask): cover corpus argument errors before fetching Check a misspelled corpus flag by itself and alongside --all in both orders. --- xtask/src/corpus/tests.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/xtask/src/corpus/tests.rs b/xtask/src/corpus/tests.rs index b1c7b515a9..9f89d39ae2 100644 --- a/xtask/src/corpus/tests.rs +++ b/xtask/src/corpus/tests.rs @@ -1,5 +1,12 @@ use super::*; +#[test] +fn corpus_rejects_unknown_arguments_before_fetching() { + for args in [vec!["--psd-tool"], vec!["--all", "--psd-tool"], vec!["--psd-tool", "--all"]] { + assert_eq!(cmd(&args), Err("corpus: unknown argument `--psd-tool`".into())); + } +} + /// The flags each pinned corpus is fetched with by `fetch_all(local, update)`. fn calls(local: bool, update: bool) -> Vec<(&'static str, bool)> { let mut seen = Vec::new(); From 473b0a6d74e52b7f9c48a39be49d3ee4f7ff03ee Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:54:45 +0100 Subject: [PATCH 055/136] fix(color): keep shared dither noise below one Use the 65,536 possible hash values as a half-open noise range. Pin the maximum hash and signed-coordinate bounds with a regression. --- crates/color/src/lib.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 281c3e01b9..4a2f2fdba3 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -18,7 +18,7 @@ pub fn dither_noise(x: i32, y: i32) -> f32 { h ^= h >> 15; h = h.wrapping_mul(0x2C1B_3C6D); h ^= h >> 12; - f32::from((h & 0xFFFF) as u16) / 65535.0 + f32::from((h & 0xFFFF) as u16) / 65536.0 } use serde::{Deserialize, Serialize}; @@ -225,6 +225,16 @@ impl Color { mod tests { use super::*; + #[test] + fn dither_noise_keeps_the_largest_hash_below_one() { + // This position hashes to 65535: a full-opacity probability must still include it. + assert_eq!(dither_noise(8, 246), 65535.0 / 65536.0); + assert_eq!(dither_noise(0, 0), 0.0); + for (x, y) in [(8, 246), (-8, -246), (i32::MIN, i32::MAX), (i32::MAX, i32::MIN)] { + assert!((0.0..1.0).contains(&dither_noise(x, y))); + } + } + #[test] fn colors_convert_into_a_document_mode() { let blue = Color::rgba(0.0, 0.0, 1.0, 0.5); From 3c32f873375ea781b7d254a66f91636b2e5a8dd2 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:55:53 +0100 Subject: [PATCH 056/136] fix(gpu): synchronize gradient dither normalization Keep the shader gradient noise mirror identical to the shared CPU hash normalization. --- crates/gpu/src/compose.wgsl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index e24605d9fd..4cdfffb1f1 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -827,7 +827,7 @@ fn dither_noise(d: vec2) -> f32 { h = h ^ (h >> 15u); h = h * 0x2C1B3C6Du; h = h ^ (h >> 12u); - return f32(h & 0xFFFFu) / 65535.0; + return f32(h & 0xFFFFu) / 65536.0; } fn layer_texel(d: vec2) -> vec4 { From 3109c80fc6669721e5960ff5a6275a3c3e8bfb41 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:56:19 +0100 Subject: [PATCH 057/136] fix(engine): retain centered profile dither bins Recover the same 16-bit hash bins after the shared helper switches to a half-open range, then keep the existing half-bin centering. --- crates/engine/src/cmd/color_cmds/profile_dither.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/color_cmds/profile_dither.rs b/crates/engine/src/cmd/color_cmds/profile_dither.rs index 791374e30a..82874d27fe 100644 --- a/crates/engine/src/cmd/color_cmds/profile_dither.rs +++ b/crates/engine/src/cmd/color_cmds/profile_dither.rs @@ -136,8 +136,8 @@ fn dither_tile(s: &Surface, out: &Surface, t: &Transform, bounds: Rect, c: TileC *d = f32::from(*s) / 255.0; } t.eval_fast(&input[..ni], &mut output[..no]).map_err(super::cms_err)?; - // The hash can return 1.0; recenter its 65536 bins strictly inside (0, 1). - let threshold = (f64::from(photocraft_color::dither_noise(x, y)) * 65535.0 + 0.5) / 65536.0; + // Recenter the hash's 65536 bins strictly inside (0, 1). + let threshold = (f64::from(photocraft_color::dither_noise(x, y)) * 65536.0 + 0.5) / 65536.0; for (d, value) in dp.iter_mut().zip(output).take(no) { *d = quantize(value, threshold); } From e27d4e777560b230e3a1943f563e3aef111be75e Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:56:50 +0100 Subject: [PATCH 058/136] test(engine): cover opaque Dissolve fill endpoint Exercise the maximum hash coordinate through edit.fill at 8, 16 and 32 bits, including zero/full opacity and undo/redo. --- crates/engine/src/cmd/fill_cmds/tests.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/engine/src/cmd/fill_cmds/tests.rs b/crates/engine/src/cmd/fill_cmds/tests.rs index bf46b6f4a6..66689506e1 100644 --- a/crates/engine/src/cmd/fill_cmds/tests.rs +++ b/crates/engine/src/cmd/fill_cmds/tests.rs @@ -84,6 +84,25 @@ fn opacity_mode_and_preserve_transparency() { })); } +#[test] +fn opaque_dissolve_fill_covers_the_largest_noise_sample_at_every_depth() { + // (8, 246) hashes to the largest noise sample: it must still be below full coverage. + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 9, "height": 247, "depth": depth, "background": "transparent"})).unwrap(); + s.execute(CMD, json!({"contents": "white", "mode": "dissolve", "opacity": 0})).unwrap(); + assert_eq!(px(&s, 8, 246)[3], 0.0, "{depth}-bit zero-opacity fill"); + + s.execute(CMD, json!({"contents": "white", "mode": "dissolve", "opacity": 100})).unwrap(); + assert_eq!(px(&s, 8, 246), [1.0; 4], "{depth}-bit opaque fill at the largest noise sample"); + assert_eq!(px(&s, 0, 0), [1.0; 4], "{depth}-bit opaque fill at an ordinary sample"); + assert!(s.undo()); + assert_eq!(px(&s, 8, 246)[3], 0.0, "{depth}-bit undo"); + assert!(s.redo()); + assert_eq!(px(&s, 8, 246), [1.0; 4], "{depth}-bit redo"); + } +} + #[test] fn preserve_transparency_blends_source_atop_on_semi_transparent_pixels() { // White at 50%, then black at 50% keeping alpha: Photoshop gives (127,127,127,128), the From 5a537149b721822b467777f733846f36ea27c993 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:18:41 +0100 Subject: [PATCH 059/136] fix(text): preserve possessive endings in spelling suggestions Suggest corrections for the possessive stem, then restore its ending and case. Cover the bundled dictionary, proper nouns, normalized apostrophes, and duplicate endings. --- crates/text/src/spell.rs | 48 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/crates/text/src/spell.rs b/crates/text/src/spell.rs index 31ddf7bf03..7851c7f06a 100644 --- a/crates/text/src/spell.rs +++ b/crates/text/src/spell.rs @@ -110,9 +110,15 @@ impl Dictionary { } /// Up to `max` suggestions for a misspelled word, nearest first (then most common), with the - /// word's case pattern applied. + /// word's case pattern and possessive ending applied. pub fn suggest(&self, word: &str, max: usize) -> Vec { - let w = normalize(word); + let normalized = normalize(word); + let (w, suffix) = normalized + .strip_suffix("'s") + .filter(|w| !w.is_empty()) + .map(|w| (w, "'s")) + .or_else(|| normalized.strip_suffix("'S").filter(|w| !w.is_empty()).map(|w| (w, "'S"))) + .unwrap_or((&normalized, "")); let lower = w.to_lowercase(); let lc: Vec = lower.chars().collect(); let n = lc.len(); @@ -132,6 +138,10 @@ impl Dictionary { continue; }; for (cand, cc, lvl) in bucket { + // The input's ending is restored below; do not append it to another possessive. + if !suffix.is_empty() && cand.ends_with("'s") { + continue; + } if let Some(d) = distance(&lc, cc, max_d, &mut rows) { found.push((d, !anagram(cand), *lvl, cand)); } @@ -146,14 +156,15 @@ impl Dictionary { let mut forms: Vec<&String> = self.by_lower.get(cand).into_iter().flatten().collect(); forms.sort_by_key(|f| f.chars().any(char::is_uppercase)); for form in forms { - let s = if all_caps { + let mut s = if all_caps { form.to_uppercase() } else if first_cap { capitalize(form) } else { form.clone() }; - if !out.contains(&s) && s != w { + s.push_str(suffix); + if !out.contains(&s) && s != normalized { out.push(s); } } @@ -298,6 +309,35 @@ mod tests { assert_eq!(d.suggest("HELO", 5).first().map(|s| s.chars().all(|c| c.is_uppercase())), Some(true)); } + #[test] + fn possessive_suggestions_keep_the_ending_and_case() { + let d = Dictionary::from_list("#10\nworld\nworlds\nMonday\n"); + for (word, want) in [("wrold's", "world's"), ("Wrold's", "World's"), ("WROLD'S", "WORLD'S"), ("WROLD's", "WORLD's"), ("Mnday's", "Monday's")] { + assert_eq!(d.suggest(word, 1), vec![want.to_string()], "{word}"); + } + assert!(d.suggest("wrold's", 0).is_empty()); + assert_eq!(d.suggest("wrold", 1), vec!["world".to_string()]); + } + + #[test] + fn possessive_suggestions_normalize_apostrophes_without_doubling_the_ending() { + let d = Dictionary::from_list("world\nworld's\n"); + for apostrophe in ['\'', '\u{2019}', '\u{2018}', '\u{02BC}'] { + assert_eq!(d.suggest(&format!("wrold{apostrophe}s"), 1), vec!["world's".to_string()]); + } + assert!(d.suggest("world's", 8).is_empty(), "a listed possessive must not gain a second ending"); + } + + #[test] + fn bundled_dictionary_suggests_a_correction_for_a_misspelled_possessive() { + let d = Dictionary::english(); + let text = "The wrold's best photo."; + let found = d.misspellings(text, &none()); + assert_eq!(found, vec![Misspelling { start: 4, end: 11, word: "wrold's".into() }]); + assert_eq!(d.suggest(&found[0].word, 1), vec!["world's".to_string()]); + assert!(d.check("world's", &none())); + } + #[test] fn misspellings_and_user_words() { let d = Dictionary::from_list("#10\nhello\nworld\nParis\n"); From cd9c1a43bd262164639e4bedb9ceaf1e21d1fb91 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:22:21 +0100 Subject: [PATCH 060/136] fix(xtask): report invalid performance baselines Only treat a missing performance baseline as absent. Report read and JSON errors before running benchmarks or updating saved baselines, with regressions for all run modes and valid baseline preservation. --- xtask/src/perf.rs | 60 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/xtask/src/perf.rs b/xtask/src/perf.rs index 23c05f61c7..51100559ed 100644 --- a/xtask/src/perf.rs +++ b/xtask/src/perf.rs @@ -874,7 +874,11 @@ pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { return Err(format!("perf: unknown bench `{name}` (see {BUDGETS})")); } } - let baseline_value: Option = std::fs::read_to_string(root.join(BASELINE)).ok().and_then(|t| serde_json::from_str(&t).ok()); + let baseline_value: Option = match std::fs::read_to_string(root.join(BASELINE)) { + Ok(text) => Some(serde_json::from_str(&text).map_err(|e| format!("parse {BASELINE}: {e}"))?), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(format!("read {BASELINE}: {e}")), + }; if !o.from.is_empty() { return baseline_from_files(root, &budgets, baseline_value.as_ref(), &o); } @@ -1581,6 +1585,60 @@ row = "r99" assert_eq!(after, baseline, "an unknown bench must not update the baseline"); } + struct BaselineFixture(PathBuf); + + impl Drop for BaselineFixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn invalid_baseline_stops_before_benchmarks_or_saved_run_updates() { + let root = std::env::temp_dir().join(format!("photocraft-perf-invalid-baseline-{}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + let _cleanup = BaselineFixture(root.clone()); + std::fs::create_dir(root.join("perf")).unwrap(); + std::fs::write(root.join(BUDGETS), "[settings]\nbaseline_min_runs = 1\n").unwrap(); + let saved = root.join("run.json"); + std::fs::write(&saved, r#"{"mode":"quick","machine":{"class":"test"},"scenarios":{}}"#).unwrap(); + let modes = [vec!["--update-baseline", "--from", saved.to_str().unwrap()], vec![], vec!["--update-baseline"]]; + for (bytes, context) in [(b"{malformed".as_slice(), "parse"), (b"\xff".as_slice(), "read")] { + for args in &modes { + std::fs::write(root.join(BASELINE), bytes).unwrap(); + let result = run(&root, args); + let after = std::fs::read(root.join(BASELINE)).unwrap(); + assert!(result.as_ref().is_err_and(|e| e.starts_with(&format!("{context} {BASELINE}:"))), "{args:?}: {result:?}"); + assert_eq!(after, bytes, "a failed load must not replace the baseline"); + } + } + std::fs::remove_file(root.join(BASELINE)).unwrap(); + std::fs::create_dir(root.join(BASELINE)).unwrap(); + for args in &modes { + assert!(run(&root, args).is_err_and(|e| e.starts_with(&format!("read {BASELINE}:"))), "{args:?}"); + } + } + + #[test] + fn saved_run_updates_allow_a_missing_baseline_and_preserve_other_valid_modes() { + let root = std::env::temp_dir().join(format!("photocraft-perf-load-baseline-{}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + let _cleanup = BaselineFixture(root.clone()); + std::fs::create_dir(root.join("perf")).unwrap(); + std::fs::write(root.join(BUDGETS), "[settings]\nbaseline_min_runs = 1\n").unwrap(); + let saved = root.join("run.json"); + std::fs::write(&saved, r#"{"mode":"quick","machine":{"class":"test"},"scenarios":{}}"#).unwrap(); + let args = ["--update-baseline", "--from", saved.to_str().unwrap()]; + run(&root, &args).unwrap(); + let initial: Value = serde_json::from_str(&std::fs::read_to_string(root.join(BASELINE)).unwrap()).unwrap(); + assert!(initial["modes"]["quick"].is_object()); + std::fs::write(root.join(BASELINE), r#"{"machine_class":"test","modes":{"full":{"sentinel":true}}}"#).unwrap(); + run(&root, &args).unwrap(); + let updated: Value = serde_json::from_str(&std::fs::read_to_string(root.join(BASELINE)).unwrap()).unwrap(); + assert_eq!(updated["modes"]["full"]["sentinel"], true); + assert!(updated["modes"]["quick"].is_object()); + } + #[test] fn options() { assert!(parse_opts(&["--bogus"]).is_err()); From fd62490d0d44bea9499ae70a9c4c538df833adb1 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:08:00 +0100 Subject: [PATCH 061/136] docs: use the full shortcut snapshot test path Include the enclosing prefs module in the exact libtest filter so the documented command selects the GPU snapshot test. --- docs/development.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development.md b/docs/development.md index cb1bffc0a5..126bef6c66 100644 --- a/docs/development.md +++ b/docs/development.md @@ -99,7 +99,7 @@ On a native host with a working wgpu adapter, capture the two images into a fres set -eu shortcut_snapshots="$(mktemp -d)" PHOTOCRAFT_SHORTCUT_SNAPSHOTS="$shortcut_snapshots" cargo test -p photocraft-ui-egui --lib \ - prefs_ui::shortcut_capture_tests::captured_shortcut_gpu_snapshots -- --exact + prefs::prefs_ui::shortcut_capture_tests::captured_shortcut_gpu_snapshots -- --exact test -s "$shortcut_snapshots/ctrl-k-1x.png" test -s "$shortcut_snapshots/ctrl-k-2x.png" printf 'Review the shortcut row and conflict message in %s\n' "$shortcut_snapshots" From a340b9b316796da0f675eedd97c343c46b463a88 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:17:22 +0100 Subject: [PATCH 062/136] fix(xtask): include multiline translation literals in reports Allow whitespace around single tl! string literals so formatted UI calls contribute to coverage and missing-translation lists. Preserve the literal-only extraction policy and add formatting plus real-tooltip regressions. --- xtask/src/i18n_report.rs | 64 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/xtask/src/i18n_report.rs b/xtask/src/i18n_report.rs index 3f0d7866ad..d15f854a29 100644 --- a/xtask/src/i18n_report.rs +++ b/xtask/src/i18n_report.rs @@ -227,8 +227,10 @@ fn tl_keys(sources: &[(PathBuf, String)]) -> BTreeSet { } let code = without_test_modules(source); let mut rest = code.as_str(); - while let Some(at) = rest.find("tl!(\"") { - rest = rest.get(at + 5..).unwrap_or(""); + while let Some(at) = rest.find("tl!(") { + rest = rest.get(at + 4..).unwrap_or("").trim_start(); + let Some(literal) = rest.strip_prefix('"') else { continue }; + rest = literal; let bytes = rest.as_bytes(); let mut end = 0; while end < bytes.len() && !(bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\')) { @@ -236,7 +238,7 @@ fn tl_keys(sources: &[(PathBuf, String)]) -> BTreeSet { } if let Some(raw) = rest.get(..end) { let source = unescape_rust_string(raw); - if rest.get(end + 1..end + 2) == Some(")") { + if rest.get(end + 1..).is_some_and(|after| after.trim_start().starts_with(')')) { keys.insert(Key { context: String::new(), source }); } } @@ -627,6 +629,62 @@ mod tests { } } + #[test] + fn literal_translation_keys_allow_formatting_whitespace() { + for newline in ["\n", "\r\n"] { + let source = format!("tl!({newline} \"multiline key\"{newline}); tl!( \t\"inline key\" \t); tl!(\"compact key\");"); + let sources = vec![(PathBuf::from("ui.rs"), source)]; + let keys = tl_keys(&sources); + assert_eq!( + keys, + ["multiline key", "inline key", "compact key"].into_iter().map(|source| Key { context: String::new(), source: source.into() }).collect() + ); + } + let sources = vec![(PathBuf::from("ui.rs"), r#"tl!(dynamic); tl!("prefix".to_string()); tl!("first", "second"); tl!("key" + suffix);"#.into())]; + assert!(tl_keys(&sources).is_empty()); + } + + #[test] + fn gathers_multiline_tooltips_used_by_the_ui() { + let source = r#" + tl!( + "Drag the pin to move the band, or its ring to change its blur. Drag the solid lines to widen the sharp band, the dashed lines to set the transition, and the dots to turn it." + ); + tl!( + "How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with." + ); + tl!( + "The estimate is above 8 GiB and the available memory is unknown, so this process or browser tab may run out of memory. You can still try to open it." + ); + tl!( + "Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it." + ); + tl!( + "The layers need {needed} of GPU memory and may hold {budget}, so edits that redraw the whole document do it on the CPU. Click to set GPU Memory." + ); + tl!( + "WinTab reads pressure, tilt, rotation and the eraser end from the tablet driver. Turn off Windows Ink in your tablet's software utility (for example Wacom Center) before using it." + ); + tl!( + "AI apps such as Claude can open, edit and save documents in this window while ArtCraft Launcher › Settings › AI agents › Let AI agents use Craft apps is on. Only programs on this computer can connect." + ); + tl!( + "PhotoCraft found your keyboard shortcut set {set} from another image editor on this computer: {n} of its shortcuts differ from PhotoCraft's. Import it?" + ); + "#; + let expected: BTreeSet = quoted_strings(source).into_iter().map(|source| Key { context: String::new(), source }).collect(); + assert_eq!(expected.len(), 8); + let keys = tl_keys(&[(PathBuf::from("ui.rs"), source.into())]); + assert_eq!(keys, expected); + let languages = [Language { code: "en".into() }, Language { code: "fr".into() }]; + let report = format_report(&languages, &keys, &BTreeMap::from([("fr".into(), BTreeSet::new())]), &BTreeMap::new()); + assert_eq!(report.lines().find(|line| line.starts_with("fr ")).and_then(|line| line.split_whitespace().nth(1)), Some("0/8")); + assert!(report.contains("fr: 8 missing\n")); + for key in &expected { + assert!(report.contains(&format!(" {}\n", key.source)), "{}", key.source); + } + } + #[test] fn plural_forms_follow_count_expressions_and_dynamic_forms_are_not_literal_keys() { let sources = vec![( From 45f6fc671f1c978a8889c13713da5c9863f637ca Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:29:15 +0100 Subject: [PATCH 063/136] fix(xtask): decode translation string continuations Remove escaped LF/CRLF continuations and only their permitted ASCII whitespace, matching Rust string values. Cover direct decoded keys, ordinary newlines, escaped backslashes, and non-ASCII whitespace. --- xtask/src/i18n_report.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/xtask/src/i18n_report.rs b/xtask/src/i18n_report.rs index d15f854a29..c61adc9e67 100644 --- a/xtask/src/i18n_report.rs +++ b/xtask/src/i18n_report.rs @@ -510,6 +510,10 @@ fn unescape_rust_string(raw: &str) -> String { continue; } match chars.next() { + // Rust normalizes CRLF source lines before removing string continuations. + Some(ch) if ch == '\n' || (ch == '\r' && chars.as_str().starts_with('\n')) => { + chars = chars.as_str().trim_start_matches(['\t', '\n', '\r', ' ']).chars(); + } Some('n') => out.push('\n'), Some('r') => out.push('\r'), Some('t') => out.push('\t'), @@ -685,6 +689,30 @@ mod tests { } } + #[test] + fn continued_literal_keys_match_rust_string_values() { + let expected = "Open \ + image"; + assert_eq!(expected, "Open image"); + for newline in ["\n", "\r\n"] { + let source = format!("tl!({newline} \"Open \\{newline} \t{newline} image\"{newline});"); + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source)]), BTreeSet::from([Key { context: String::new(), source: expected.into() }])); + } + } + + #[test] + fn continuations_preserve_other_newlines_and_non_ascii_whitespace() { + for (raw, expected) in [ + (r"Open \n image", "Open \n image"), + ("Open \n image", "Open \n image"), + ("Open \\\\\n image", "Open \\\n image"), + ("Open \\\n \u{a0}image", "Open \u{a0}image"), + ] { + let source = format!("tl!(\n \"{raw}\"\n);"); + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source)]), BTreeSet::from([Key { context: String::new(), source: expected.into() }]), "{raw:?}"); + } + } + #[test] fn plural_forms_follow_count_expressions_and_dynamic_forms_are_not_literal_keys() { let sources = vec![( From 36afc8755498d564ab89c1276aacf55ce0be1bb6 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:40:40 +0100 Subject: [PATCH 064/136] fix(xtask): match escaped literal boundaries and CRLF values Recognize closing quotes after even backslashes in both literal scanners and normalize physical CRLF once without altering escaped newline values. Add direct compiler-value and adjacent-key regressions. --- xtask/src/i18n_report.rs | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/xtask/src/i18n_report.rs b/xtask/src/i18n_report.rs index c61adc9e67..2cbbbd88ad 100644 --- a/xtask/src/i18n_report.rs +++ b/xtask/src/i18n_report.rs @@ -233,7 +233,9 @@ fn tl_keys(sources: &[(PathBuf, String)]) -> BTreeSet { rest = literal; let bytes = rest.as_bytes(); let mut end = 0; - while end < bytes.len() && !(bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\')) { + let mut escaped = false; + while end < bytes.len() && (bytes[end] != b'"' || escaped) { + escaped = bytes[end] == b'\\' && !escaped; end += 1; } if let Some(raw) = rest.get(..end) { @@ -490,7 +492,9 @@ fn quoted_strings(source: &str) -> Vec { rest = rest.get(at + 1..).unwrap_or(""); let bytes = rest.as_bytes(); let mut end = 0; - while end < bytes.len() && !(bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\')) { + let mut escaped = false; + while end < bytes.len() && (bytes[end] != b'"' || escaped) { + escaped = bytes[end] == b'\\' && !escaped; end += 1; } if let Some(raw) = rest.get(..end) { @@ -505,6 +509,10 @@ fn unescape_rust_string(raw: &str) -> String { let mut out = String::with_capacity(raw.len()); let mut chars = raw.chars(); while let Some(ch) = chars.next() { + // Rust normalizes physical CRLF pairs before interpreting escapes. + if ch == '\r' && chars.as_str().starts_with('\n') { + continue; + } if ch != '\\' { out.push(ch); continue; @@ -713,6 +721,34 @@ mod tests { } } + #[test] + fn literal_boundaries_distinguish_escaped_quotes_and_trailing_backslashes() { + for (literal, expected) in [(r#""Folder\\""#, "Folder\\"), (r#""Say \"Open\".""#, "Say \"Open\"."), (r#""Folder\\\\""#, "Folder\\\\")] { + assert_eq!(quoted_strings(literal), vec![expected]); + for padding in ["", "\n "] { + let source = format!("tl!({padding}{literal}{padding}); tl!(\"next\");"); + let expected = [expected, "next"].into_iter().map(|source| Key { context: String::new(), source: source.into() }).collect(); + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source)]), expected); + } + } + } + + #[test] + fn physical_crlf_keys_match_rust_string_values() { + let expected = "A\ + B +C"; + assert_eq!(expected, "AB\nC"); + for newline in ["\n", "\r\n"] { + let source = format!("tl!(\n \"A\\{newline} B{newline}C\"\n);"); + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source)]), BTreeSet::from([Key { context: String::new(), source: expected.into() }])); + let source = format!("tl!(\"A{newline}B\");"); + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source)]), BTreeSet::from([Key { context: String::new(), source: "A\nB".into() }])); + } + let source = r#"tl!("A\r\nB");"#; + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source.into())]), BTreeSet::from([Key { context: String::new(), source: "A\r\nB".into() }])); + } + #[test] fn plural_forms_follow_count_expressions_and_dynamic_forms_are_not_literal_keys() { let sources = vec![( From 8cca993d49a856bfd55feaa4992013ea573339ef Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 23:47:19 +0100 Subject: [PATCH 065/136] Adjustment Brush: add its slot to main's stored toolbar layout and tool list Main now builds the toolbar from DEFAULT_TOOLBAR and resolves tool names through shell_commands::TOOLS, so the new slot needs an entry in both. Main also gained a tool meanwhile: 70 tools in Tool::ALL and the README. The Free Transform switch test's window grows to 1000 px so the longer tool column keeps the Hand Tool on screen. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- crates/engine/src/prefs.rs | 1 + crates/engine/src/shell_commands.rs | 1 + crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/src/transform_switch_tests.rs | 6 +++--- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 04508f9637..2e9ed0502a 100644 --- a/README.md +++ b/README.md @@ -185,8 +185,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
-

🧰 69 tools

- Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom +

🧰 70 tools

+ Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Adjustment Brush · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom

🖌️ A real brush engine

diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index d9b6fb7144..2f079c87ef 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1361,6 +1361,7 @@ pub const DEFAULT_TOOLBAR: &[&[&str]] = &[ &["Eraser", "BackgroundEraser", "MagicEraser"], &["Gradient", "PaintBucket"], &["Blur", "Sharpen", "Smudge"], + &["AdjustmentBrush"], &["Dodge", "Burn", "Sponge"], &["Pen", "FreeformPen", "CurvaturePen", "AddAnchorPoint", "DeleteAnchorPoint", "ConvertPoint"], &["Type", "VerticalType", "VerticalTypeMask", "HorizontalTypeMask"], diff --git a/crates/engine/src/shell_commands.rs b/crates/engine/src/shell_commands.rs index cec9e757be..05b2b7f940 100644 --- a/crates/engine/src/shell_commands.rs +++ b/crates/engine/src/shell_commands.rs @@ -154,6 +154,7 @@ pub const TOOLS: &[(&str, &str, Option<&str>)] = &[ ("tools.select.blur", "Blur Tool", None), ("tools.select.sharpen", "Sharpen Tool", None), ("tools.select.smudge", "Smudge Tool", None), + ("tools.select.adjustmentBrush", "Adjustment Brush Tool", None), ("tools.select.dodge", "Dodge Tool", Some("O")), ("tools.select.burn", "Burn Tool", Some("O")), ("tools.select.sponge", "Sponge Tool", Some("O")), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 138d995469..91211c5545 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -865,7 +865,7 @@ mod tests { assert!(!Tool::RedEye.is_brushlike()); assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp)); assert_eq!(Tool::from_name("Pattern Stamp Tool"), Some(Tool::PatternStamp)); - assert_eq!(Tool::ALL.len(), 69); + assert_eq!(Tool::ALL.len(), 70); } fn vector_tool_names_parse() { diff --git a/crates/ui-egui/src/transform_switch_tests.rs b/crates/ui-egui/src/transform_switch_tests.rs index f5be113d2a..857669010e 100644 --- a/crates/ui-egui/src/transform_switch_tests.rs +++ b/crates/ui-egui/src/transform_switch_tests.rs @@ -8,9 +8,9 @@ use serde_json::json; use crate::PhotocraftApp; /// The app with a 400 × 300 document: a red 100 × 60 rectangle at (100, 100) on its own layer -/// above the Background. +/// above the Background. Tall enough that the whole tool column, Hand Tool included, is on screen. fn app() -> Harness<'static, PhotocraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_max_steps(64).build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); @@ -58,7 +58,7 @@ fn picking_another_tool_in_the_toolbar_applies_the_transform() { /// the same step), as Place Embedded leaves it for the box `begin_placed` opens: cancelling the /// place takes that step back. fn placed_app() -> Harness<'static, PhotocraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_max_steps(64).build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); From 96093d624cd7d9b23645bc8d4692d48972777b0e Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:53:25 +0100 Subject: [PATCH 066/136] fix(xtask): reject incomplete PNG icon headers Require complete IHDR framing and its fixed 13-byte payload length before extracting icon dimensions. Add truncated-header and invalid-length regressions. Fixes #15667. --- xtask/src/ico.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/xtask/src/ico.rs b/xtask/src/ico.rs index 021572a12f..6646ea3812 100644 --- a/xtask/src/ico.rs +++ b/xtask/src/ico.rs @@ -8,7 +8,8 @@ use std::path::Path; /// Width and height from a PNG's IHDR chunk. pub fn png_size(png: &[u8]) -> Result<(u32, u32), String> { const SIG: &[u8] = b"\x89PNG\r\n\x1a\n"; - if png.len() < 24 || &png[..8] != SIG || &png[12..16] != b"IHDR" { + // Require the complete first chunk: IHDR has 13 payload bytes followed by its CRC. + if png.len() < 33 || &png[..8] != SIG || &png[8..12] != b"\0\0\0\x0d" || &png[12..16] != b"IHDR" { return Err("not a PNG file".into()); } let w = u32::from_be_bytes([png[16], png[17], png[18], png[19]]); @@ -93,6 +94,26 @@ mod tests { assert_eq!(png_size(&fake_png(48)).unwrap(), (48, 48)); } + #[test] + fn rejects_truncated_ihdr_chunks() { + let png = fake_png(48); + for len in 0..png.len() { + assert!(png_size(&png[..len]).is_err(), "accepted a truncated IHDR at {len} bytes"); + } + assert_eq!(png_size(&png), Ok((48, 48))); + assert!(pack(&[png[..24].to_vec()]).is_err()); + } + + #[test] + fn rejects_wrong_ihdr_payload_lengths() { + for length in [0u32, 8, 12, 14, u32::MAX] { + let mut png = fake_png(48); + png[8..12].copy_from_slice(&length.to_be_bytes()); + assert!(png_size(&png).is_err(), "accepted IHDR payload length {length}"); + assert!(pack(&[png]).is_err(), "packed IHDR payload length {length}"); + } + } + #[test] fn committed_icon_is_valid() { let path = crate::root().join("assets/app-icon/photocraft.ico"); From 687ded0284ce3d22a1aa0de4b6d3cf849bc4b406 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:11:26 +0100 Subject: [PATCH 067/136] fix(automation): reject malformed RPC save parameters Reject non-object params and wrong-type path/format values before they can become an implicit save to the stored layered file. Preserve missing/null behavior. Fixes #15670. --- crates/automation/src/rpc.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 404891f61e..0a616e07b2 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -167,6 +167,15 @@ impl Headless { } "doc.new" => self.command_run("file.new", p), "doc.save" => { + // A malformed Save As request must not become an implicit save to the stored path. + if !p.is_object() { + return Err(bad("doc.save params must be an object")); + } + for key in ["path", "format"] { + if p.get(key).is_some_and(|value| !value.is_null() && !value.is_string()) { + return Err(bad(format!("`{key}` must be a string"))); + } + } let tga_bits = photocraft_engine::file_cmds::tga_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; let pdf_spot_plates = photocraft_engine::file_cmds::pdf_spot_plates_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; let mut opts = photocraft_io::ExportOptions { From 8c106a42c7836bf1f8b10509ce6a8568d6c38ea2 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:13:19 +0100 Subject: [PATCH 068/136] test(automation): preserve saved files after malformed RPC saves Check path/format types and non-object params against an edited .pcraft document; preserve stored bytes and document state on refusal, with valid implicit and explicit save controls. --- crates/automation/src/rpc/tests.rs | 46 ++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 51f053b595..76af659221 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -1186,3 +1186,49 @@ fn doc_place_forwards_high_memory_approval() { drop(t); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +fn doc_save_rejects_malformed_requests_without_writing_the_stored_path() { + let dir = std::env::temp_dir().join(format!("pc-rpc-save-path-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let workspace = crate::AuthorizedWorkspace::new(Some(&dir), Some(&dir)).unwrap(); + let mut h = Headless::with_workspace(workspace); + h.handle("doc.new", json!({"width": 8, "height": 8})).unwrap(); + h.handle("doc.save", json!({"path": "saved.pcraft"})).unwrap(); + let path = dir.join("saved.pcraft"); + let original = std::fs::read(&path).unwrap(); + h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Unsaved"}})).unwrap(); + let unsaved = h.inspect(None).unwrap(); + + for field in ["path", "format"] { + for value in [json!(123), json!(false), json!([]), json!({})] { + let mut params = json!({}); + params[field] = value.clone(); + let error = h.handle("doc.save", params).unwrap_err().to_string(); + assert!(error.contains(field), "{field} {value}: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), original, "invalid {field} {value} wrote the stored file"); + assert_eq!(h.inspect(None).unwrap(), unsaved, "invalid {field} {value} changed the document"); + } + } + for params in [json!(123), json!(false), json!([]), json!("saved.pcraft")] { + let error = h.handle("doc.save", params.clone()).unwrap_err().to_string(); + assert!(error.contains("object"), "{params}: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), original, "invalid params {params} wrote the stored file"); + assert_eq!(h.inspect(None).unwrap(), unsaved, "invalid params {params} changed the document"); + } + + let mut previous = original; + for params in [json!({}), json!({"path": null}), json!({"format": null}), Value::Null] { + h.handle("engine.execute", json!({"command": "layer.new.layer"})).unwrap(); + let saved = h.handle("doc.save", params).unwrap(); + assert_eq!(saved["path"], "saved.pcraft"); + let bytes = std::fs::read(&path).unwrap(); + assert_ne!(bytes, previous, "an implicit save did not write the edited document"); + previous = bytes; + } + let saved = h.handle("doc.save", json!({"path": "copy.pcraft", "format": "pcraft"})).unwrap(); + assert_eq!(saved["path"], "copy.pcraft"); + assert!(dir.join("copy.pcraft").is_file()); + drop(h); + std::fs::remove_dir_all(dir).unwrap(); +} From 79ce13a573d9781a55a52269d9e687a510cd3bcc Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:17:52 +0100 Subject: [PATCH 069/136] fix(automation): reject malformed RPC close parameters Reject non-object doc.close params before they can become an implicit close of the active document. Preserve null/default and valid index handling. Fixes #15815. --- crates/automation/src/rpc.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 404891f61e..ffed87c42a 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -253,7 +253,13 @@ impl Headless { let i = index_of(&p)?.ok_or_else(|| bad("doc.select needs `index`"))?; self.select(i) } - "doc.close" => self.close(index_of(&p)?), + "doc.close" => { + // A non-object would look like a missing index and close the active document. + if !p.is_object() { + return Err(bad("doc.close params must be an object")); + } + self.close(index_of(&p)?) + } "batch" => self.batch(&p), "methods" => Ok(json!(METHODS)), other => Err(bad(format!("{} (try `methods`)", photocraft_engine::command_hints::unknown_method(other, METHODS)))), From 3bab5b5ae0ffbe0d3d488ba785b447596e81aacc Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:19:50 +0100 Subject: [PATCH 070/136] test(automation): preserve documents after malformed close requests Check arrays, booleans, numbers and strings leave the session unchanged. Verify missing/null/default and explicit index requests close the intended document. --- crates/automation/src/rpc/tests.rs | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 51f053b595..36d8718e52 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -1186,3 +1186,39 @@ fn doc_place_forwards_high_memory_approval() { drop(t); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +fn doc_close_rejects_non_object_params_without_closing_documents() { + let h = session(); + for _ in 0..2 { + assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true); + } + let before = h.lock().unwrap().session_list(); + for params in [json!([]), json!([0]), json!(true), json!(false), json!(1), json!("0")] { + let reply = respond(&h, &json!({"method": "doc.close", "params": params}).to_string()); + assert_eq!(reply["ok"], false, "{params}: {reply}"); + assert!(reply["error"].as_str().unwrap().contains("doc.close params must be an object"), "{reply}"); + assert_eq!(h.lock().unwrap().session_list(), before, "invalid params {params} changed the session"); + } + + // Missing/null params and indices close the active document; an explicit index selects its target. + for (params, remaining_index) in + [(None, 0), (Some(Value::Null), 0), (Some(json!({})), 0), (Some(json!({"index": null})), 0), (Some(json!({"index": 0})), 1)] + { + let h = session(); + for width in [8, 16] { + let request = json!({"method": "doc.new", "params": {"width": width, "height": 8}}); + assert_eq!(respond(&h, &request.to_string())["ok"], true); + } + let mut expected = h.lock().unwrap().session_list()["documents"][remaining_index].clone(); + expected["index"] = json!(0); + let mut request = json!({"method": "doc.close"}); + if let Some(params) = params { + request["params"] = params; + } + let reply = respond(&h, &request.to_string()); + assert_eq!(reply["ok"], true, "{request}: {reply}"); + assert_eq!(reply["result"]["documents"], json!([expected]), "{request}: {reply}"); + assert_eq!(reply["result"]["active"], 0, "{reply}"); + } +} From 8909d97314f2a9e37c52da485fe6ab568a382a92 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:35:54 +0100 Subject: [PATCH 071/136] fix(automation): preserve native filenames in saved manifests Derive the .pcraft snapshot name from the native Path leaf so Unix backslashes remain filename characters. Preserve portable byte-name handling. Fixes #15820. --- crates/automation/src/files.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index 1913566f4a..a3b3f5234a 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -146,7 +146,11 @@ pub fn save_with_renderer_keeping( .or_else(|| path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase())) .ok_or_else(|| AutomationError::BadRequest(format!("cannot tell the format of `{}`; pass a format", path.display())))?; if ext == photocraft_format::EXTENSION { - let named = named_for_output(doc, &path.to_string_lossy()); + let mut named = doc.clone(); + // Native filenames may contain a literal backslash on Unix. + if let Some(name) = path.file_name() { + named.name = name.to_string_lossy().into_owned(); + } let mut local = PcraftWriter::new(); let w = writer.unwrap_or(&mut local); w.save_path(&named, path, &native_options(&named, opts)?)?; From 6acc50db72d843865014cd26a9464e6af243e66e Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:37:15 +0100 Subject: [PATCH 072/136] test(automation): preserve Unix backslashes in native save names Check the raw manifest and reopened .pcraft filename after a native filesystem save, and verify the source document name is unchanged. --- .../automation/tests/it/native_save_name.rs | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/automation/tests/it/native_save_name.rs b/crates/automation/tests/it/native_save_name.rs index 18319c5f31..2a840d4b59 100644 --- a/crates/automation/tests/it/native_save_name.rs +++ b/crates/automation/tests/it/native_save_name.rs @@ -38,3 +38,28 @@ fn workspace_encoded_native_bundle_uses_requested_name_without_mutating_source() assert_eq!(reopened.name, "Renamed.pcraft"); assert_eq!(doc.name, "Original", "a copy should not retarget the open document"); } + +#[cfg(unix)] +#[test] +fn native_save_preserves_backslashes_in_the_written_filename() { + let dir = std::env::temp_dir().join(format!( + "pc-native-backslash-name-{}-{}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let filename = r"Renamed\Copy.pcraft"; + let path = dir.join(filename); + let mut headless = Headless::trusted_local(); + headless.handle("doc.new", json!({"width": 8, "height": 8, "name": "Original"})).unwrap(); + let doc = &headless.session.active().unwrap().doc; + + files::save(doc, &path, None, &Default::default(), None).unwrap(); + + let manifest = photocraft_format::read_manifest(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(manifest.document.name, filename); + assert_eq!(files::open(&path).unwrap().document.name, filename); + assert_eq!(doc.name, "Original", "saving a snapshot must not rename the source"); + drop(headless); + std::fs::remove_dir_all(dir).unwrap(); +} From 1008be1a69003bc04ca2db576aa075a601af715b Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:41:36 +0100 Subject: [PATCH 073/136] fix(xtask): reject device names in PSD recipe IDs Reject reserved Windows device names case-insensitively before the runner creates output artifacts. Cover all reserved IDs and ordinary near matches through recipe schema validation. Fixes #15822. --- xtask/src/psd_write_oracle.rs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/xtask/src/psd_write_oracle.rs b/xtask/src/psd_write_oracle.rs index b1f4cc2b0c..c0cfb4f13e 100644 --- a/xtask/src/psd_write_oracle.rs +++ b/xtask/src/psd_write_oracle.rs @@ -81,7 +81,13 @@ fn read_limited(path: &Path) -> Result, String> { /// Accept a case identifier that can safely name one output subdirectory. fn valid_id(id: &str) -> bool { - !id.is_empty() && id.len() <= 100 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + if id.is_empty() || id.len() > 100 || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') { + return false; + } + // These names resolve to devices on Windows, so the case cannot hold its output files. + let name = id.to_ascii_uppercase(); + let port = name.strip_prefix("COM").or_else(|| name.strip_prefix("LPT")).is_some_and(|n| matches!(n.as_bytes(), [b'1'..=b'9'])); + !matches!(name.as_str(), "CON" | "PRN" | "AUX" | "NUL") && !port } /// Reject unsupported recipes, unsafe paths, duplicate IDs, and incomplete checks. @@ -649,4 +655,25 @@ exit 1 assert_eq!(verify(&[Check::ChangedTo { path: "/n".into(), value: json!(17) }], &json!({}), &after)[0]["status"], "pass"); assert_eq!(verify(&[Check::Equals { path: "/m".into(), value: json!(1) }], &before, &after)[0]["status"], "fail"); } + + #[test] + fn schema_rejects_windows_device_ids_but_allows_near_matches() { + let recipe = json!({"version":1,"corpus_revision":"pin","cases":[{"id":"case","base":"x.psd","base_sha256":"a".repeat(64), + "target":{"kind":"Text"},"checks":[{"op":"unchanged","path":"/name"}]}]}); + let mut recipes: Recipes = serde_json::from_value(recipe).unwrap(); + let mut reserved = vec!["CON".to_string(), "PRN".to_string(), "AUX".to_string(), "NUL".to_string()]; + for n in 1..=9 { + reserved.extend([format!("COM{n}"), format!("LPT{n}")]); + } + for id in reserved { + for variant in [id.clone(), id.to_ascii_lowercase(), format!("{}{}", &id[..1], id[1..].to_ascii_lowercase())] { + recipes.cases[0].id = variant.clone(); + assert_eq!(validate(&recipes), Err(format!("invalid or duplicate case id: {variant}")), "{variant}"); + } + } + for id in ["console", "PRN-1", "auxiliary", "NUL_", "COM0", "COM10", "LPT0", "LPT10", "case-1"] { + recipes.cases[0].id = id.to_string(); + assert!(validate(&recipes).is_ok(), "{id}"); + } + } } From df85542f8b0d5dd02dbc61971a5eba689be2a1c9 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:53:09 +0100 Subject: [PATCH 074/136] fix(cli): discover GIMP XCF inputs in batch folders Updated the input recognition logic to include new file extensions and added tests for GIMP XCF file handling. --- apps/photocraft-cli/src/batch.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index d64f3318d1..55e90c790d 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -21,10 +21,12 @@ fn same_dir(a: &Path, b: &Path) -> bool { pub(crate) fn is_input(p: &Path) -> bool { let known = |e: &str| { - matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub") + matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub" | "xcf" | "xcfgz") || photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read) }; - p.is_file() && p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase())) + // Only GIMP's compound suffix is an image; an arbitrary .gz is not a batch input. + let gzipped_xcf = p.file_name().is_some_and(|name| name.to_string_lossy().to_ascii_lowercase().ends_with(".xcf.gz")); + p.is_file() && (gzipped_xcf || p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase()))) } /// Drops the Save and view steps the desktop records from `action` (Batch saves each result @@ -295,6 +297,32 @@ mod tests { use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; + #[test] + fn batch_inputs_recognize_gimp_xcf_names_but_not_arbitrary_gzip() { + let dir = tempfile::tempdir().unwrap(); + for name in ["plain.xcf", "upper.XCF", "alias.xcfgz", "upper-alias.XCFGZ", "compressed.xcf.gz", "upper-compressed.XCF.GZ", "ordinary.PNG"] { + let path = dir.path().join(name); + std::fs::write(&path, b"").unwrap(); + assert!(is_input(&path), "{name} should be selected"); + } + for name in ["notes.txt.gz", "archive.tar.gz", "backup.xcf.gz.tmp", "notes.txt"] { + let path = dir.path().join(name); + std::fs::write(&path, b"").unwrap(); + assert!(!is_input(&path), "{name} should be skipped"); + } + let directory = dir.path().join("folder.xcf.gz"); + std::fs::create_dir(&directory).unwrap(); + assert!(!is_input(&directory), "a directory is not an input image"); + assert!(!is_input(&dir.path().join("missing.xcf.gz")), "a missing file is not an input image"); + #[cfg(unix)] + { + use std::os::unix::ffi::OsStringExt; + let path = dir.path().join(std::ffi::OsString::from_vec(b"non-utf8-\xff.XCF.GZ".to_vec())); + std::fs::write(&path, b"").unwrap(); + assert!(is_input(&path), "a non-UTF8 filename can still have the compound suffix"); + } + } + struct RecordingRenderer { calls: Arc, } From 63164a7a791241db8ad8a87020b9638d363faae9 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:00:44 +0100 Subject: [PATCH 075/136] docs(cli): list doc.replaceSmartObject in serve help --- apps/photocraft-cli/src/args.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 429fcb4547..f2c4d91a38 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -307,7 +307,7 @@ pub(crate) struct McpArgs { /// /// Each request is a JSON line {"id", "method", "params"}. Methods: engine.execute, /// jobs.list/cancel, engine.commands, -/// doc.open/new/place/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close, +/// doc.open/new/place/replaceSmartObject/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close, /// session.list, batch, methods (docs/control-protocol.md#headless-server). The token flags require /// --port (or PHOTOCRAFT_CONTROL_PORT); stdio needs no control token. #[derive(Args)] From e0e8c0fde2942559aaacf8bb4331700f1295f4b5 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:07:16 +0100 Subject: [PATCH 076/136] fix(cli): reject lossy paths during flat batch discovery Fail before output planning when a recognized input path cannot be represented in the headless API. Add a Linux CLI regression with the invalid-byte filename and its valid replacement-character alias. --- apps/photocraft-cli/src/batch.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index 55e90c790d..553ee7b356 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -72,7 +72,8 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> for entry in entries { let path = entry.map_err(|source| CliError::ReadDir { path: in_dir.to_path_buf(), source })?.path(); if is_input(&path) { - images.push(photocraft_engine::file_cmds::BatchInput { path: path.to_string_lossy().into_owned(), rel_dir: String::new() }); + let input = path.to_str().ok_or_else(|| CliError::BatchOption(format!("batch input path must be valid UTF-8: {path:?}")))?; + images.push(photocraft_engine::file_cmds::BatchInput { path: input.to_owned(), rel_dir: String::new() }); } } // The tree listing already holds the engine's order (each folder's files, then its @@ -323,6 +324,33 @@ mod tests { } } + #[cfg(target_os = "linux")] + #[test] + fn flat_batch_rejects_non_utf8_input_before_writing_output() { + use std::os::unix::ffi::OsStringExt; + + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("in"); + std::fs::create_dir(&input).unwrap(); + let original = input.join(std::ffi::OsString::from_vec(b"photo-\xff.xcf".to_vec())); + let alias = input.join("photo-\u{fffd}.xcf"); + std::fs::write(&original, b"original file").unwrap(); + std::fs::write(&alias, b"replacement-character file").unwrap(); + let actions = dir.path().join("actions.json"); + std::fs::write(&actions, "[]").unwrap(); + let output = dir.path().join("out"); + let crate::test_support::Invoke { code, stdout, stderr } = + crate::test_support::invoke(&["batch", "--actions", actions.to_str().unwrap(), "--in", input.to_str().unwrap(), "--out", output.to_str().unwrap()]); + + assert_eq!(code, 1, "{stdout}{stderr}"); + assert!(stderr.contains("batch input path must be valid UTF-8"), "{stderr}"); + assert!(stderr.contains(&format!("{original:?}")), "the diagnostic must distinguish the invalid bytes from the valid alias: {stderr}"); + assert!(stdout.is_empty(), "discovery must fail before processing any input: {stdout}"); + assert!(!output.exists(), "discovery must fail before creating the output directory"); + assert_eq!(std::fs::read(&original).unwrap(), b"original file"); + assert_eq!(std::fs::read(&alias).unwrap(), b"replacement-character file"); + } + struct RecordingRenderer { calls: Arc, } From 9445f7a0b0e120c55d1b533318a18b1f8e5194c5 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:10:10 +0100 Subject: [PATCH 077/136] docs(cli): spell out doc.replaceSmartObject in serve help Use the full RPC method name so users can search for it in help and the generated man page. The method list still matches all 19 entries in the RPC registry. --- apps/photocraft-cli/src/args.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index f2c4d91a38..88344574ab 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -307,7 +307,8 @@ pub(crate) struct McpArgs { /// /// Each request is a JSON line {"id", "method", "params"}. Methods: engine.execute, /// jobs.list/cancel, engine.commands, -/// doc.open/new/place/replaceSmartObject/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close, +/// doc.open/new/place/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close, +/// doc.replaceSmartObject, /// session.list, batch, methods (docs/control-protocol.md#headless-server). The token flags require /// --port (or PHOTOCRAFT_CONTROL_PORT); stdio needs no control token. #[derive(Args)] From e31b356c63a6be853c16536c11d9f85611692b75 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:16:53 +0100 Subject: [PATCH 078/136] fix(algo): reject Exact palettes that exceed 256 with forced colours Count distinct image and forced colours before building the Exact palette. Report an overflow instead of dropping source colours. --- crates/algo/src/quantize.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/algo/src/quantize.rs b/crates/algo/src/quantize.rs index 75bb09145c..1ddb62c8e5 100644 --- a/crates/algo/src/quantize.rs +++ b/crates/algo/src/quantize.rs @@ -404,6 +404,11 @@ pub fn build_palette(px: &[[f32; 4]], kind: PaletteKind, colors: usize, forced: if hist.len() > 256 { return Err(format!("the image has {} colours; Exact needs 256 or fewer", hist.len())); } + // Forced entries absent from the image still consume palette slots. + let required = hist.len() + pal.iter().filter(|color| !hist.iter().any(|(existing, _)| existing == *color)).count(); + if required > 256 { + return Err(format!("the image and forced colours need {required} entries; Exact needs 256 or fewer")); + } hist.iter().map(|h| h.0).collect() } PaletteKind::SystemMac => mac_palette(), From 81bf5826fe73f3893b261c73c3123b3c5d503947 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:17:54 +0100 Subject: [PATCH 079/136] Add test for exact palette with forced colors Exercise a full opaque image palette with forced black and white, a union that fits at 256 entries, and forced colours already present in the image. --- crates/algo/src/quantize/tests.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/algo/src/quantize/tests.rs b/crates/algo/src/quantize/tests.rs index 5f27ff8f5d..4ab37d126c 100644 --- a/crates/algo/src/quantize/tests.rs +++ b/crates/algo/src/quantize/tests.rs @@ -270,6 +270,34 @@ fn exact_palette_and_failure() { assert!(build_palette(&gradient(64, 64), PaletteKind::Exact, 256, Forced::None).is_err()); } +#[test] +fn exact_palette_counts_forced_colours_without_dropping_image_colours() { + let pixels = |count: u16| (0..count).map(|r| [f32::from(r) / 255.0, 42.0 / 255.0, 7.0 / 255.0, 1.0]).collect::>(); + let px = pixels(256); + let error = build_palette(&px, PaletteKind::Exact, 256, Forced::BlackWhite).unwrap_err(); + assert!(error.contains("258") && error.contains("forced"), "{error}"); + + let boundary = pixels(254); + let palette = build_palette(&boundary, PaletteKind::Exact, 256, Forced::BlackWhite).unwrap(); + assert_eq!(palette.len(), 256); + assert_eq!(&palette[..2], &[[0, 0, 0], [255, 255, 255]], "forced colours retain their order"); + for r in 0..254u8 { + assert!(palette.contains(&[r, 42, 7]), "the source colour {r} was dropped"); + } + + let mut overlap = boundary; + overlap.extend([[0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0]]); + let palette = build_palette(&overlap, PaletteKind::Exact, 256, Forced::BlackWhite).unwrap(); + assert_eq!(palette.len(), 256, "forced colours already in the image count only once"); + for colors in [2, 256] { + let palette = build_palette(&px, PaletteKind::Exact, colors, Forced::None).unwrap(); + assert_eq!(palette.len(), 256, "Exact still retains every image colour regardless of the requested count"); + for r in 0..=255u8 { + assert!(palette.contains(&[r, 42, 7]), "the source colour {r} was dropped"); + } + } +} + #[test] fn adaptive_and_perceptual_respect_count_and_forced() { let px = gradient(40, 40); From 5490e9c3f999d648155c75e3821ab6cd23e3ef76 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:35:02 +0100 Subject: [PATCH 080/136] fix(automation): reject invalid doc.render parameters before rendering Validate the parameter object and optional output path before rendering. Keep the existing behavior for an omitted or null path and string output paths. --- crates/automation/src/rpc.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 404891f61e..a0a62ebd82 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -223,6 +223,15 @@ impl Headless { } "doc.inspect" => self.inspect(index_of(&p)?), "doc.render" => { + // Invalid file requests must not fall back to a base64 response. + if !p.is_object() { + return Err(bad("doc.render params must be an object")); + } + let path = match p.get("path") { + None | Some(Value::Null) => None, + Some(Value::String(path)) => Some(path.as_str()), + Some(_) => return Err(bad("`path` must be a string")), + }; let max = match p.get("maxSide") { None => 1024, Some(value) => { @@ -232,7 +241,7 @@ impl Headless { let png = self.render_png(index_of(&p)?, max)?; // A GPU to CPU fallback is reported with this reply, not on the next save. let warnings = self.drain_diagnostics(); - let mut reply = match str_of(&p, "path") { + let mut reply = match path { Some(path) => { self.write_render(&PathBuf::from(path), &png)?; json!({"path": path, "bytes": png.len()}) From 84c9cbb3a09ff00ac844f30fffe0c4366421a747 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:35:41 +0100 Subject: [PATCH 081/136] test(automation): cover malformed doc.render requests Check rejection for invalid parameter containers and path types. Verify that omitted and null paths still return an inline PNG. --- crates/automation/src/rpc/tests.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 51f053b595..d2dc3e0fc7 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -176,6 +176,32 @@ fn batch_rejects_too_many_steps() { assert!(error.to_string().contains("maximum is 256")); } +#[test] +fn render_rejects_malformed_requests_and_keeps_missing_or_null_path_behavior() { + let h = session(); + let mut g = h.lock().unwrap(); + g.handle("doc.new", json!({"width": 8, "height": 8})).unwrap(); + let before = g.inspect(None).unwrap(); + for params in [json!([]), json!([0]), json!(123), json!(false), json!("out.png")] { + let error = g.handle("doc.render", params.clone()).unwrap_err(); + assert!(matches!(&error, AutomationError::BadRequest(_)), "{params}: {error}"); + assert!(error.to_string().contains("doc.render params must be an object"), "{params}: {error}"); + assert_eq!(g.inspect(None).unwrap(), before, "invalid params {params} changed the document"); + } + for path in [json!(123), json!(false), json!([]), json!({})] { + let error = g.handle("doc.render", json!({"path": path})).unwrap_err(); + assert!(matches!(&error, AutomationError::BadRequest(_)), "{path}: {error}"); + assert!(error.to_string().contains("`path` must be a string"), "{path}: {error}"); + assert_eq!(g.inspect(None).unwrap(), before, "invalid path {path} changed the document"); + } + for params in [Value::Null, json!({}), json!({"path": null})] { + let reply = g.handle("doc.render", params.clone()).unwrap(); + assert_eq!(reply["mime"], "image/png", "{params}: {reply}"); + let png = base64::engine::general_purpose::STANDARD.decode(reply["base64"].as_str().unwrap()).unwrap(); + assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (8, 8)); + } +} + #[test] fn render_to_file_and_base64() { let h = session(); From 9b67220c927d3656b29a0d626219fb4bf86737b8 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:50:11 +0100 Subject: [PATCH 082/136] docs(automation): clarify null params for doc.render Document the tested shorthand for an empty request and the distinction between inline PNG and string output paths. --- docs/control-protocol.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 22225621a7..ff18862c2d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -571,6 +571,10 @@ An `index` targets that one call: `doc.place`, `doc.exportLayers`, `doc.exportDa without making it the active one, so the next call without `index` still runs on the document that was active before (`doc.select` is the method that changes it). +`doc.render` treats omitted `params` and `"params": null` as `{}`. Pass a string `path` +for a file reply. An omitted or null `path` requests an inline PNG. Other parameter +container or path types return an error before rendering. + ```sh printf '%s\n' \ '{"id":1,"method":"doc.open","params":{"path":"in.jpg"}}' \ From 4c727f324fc2007f2c4f34a4dd136fc9f1149cde Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:58:16 +0100 Subject: [PATCH 083/136] fix(io): report OpenRaster blending losses on export Report channel exclusions and non-default Blend If settings for editable layers in the shared writer and dry loss check. --- crates/io/src/ora.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/io/src/ora.rs b/crates/io/src/ora.rs index 07c00ff126..cf1f6b810d 100644 --- a/crates/io/src/ora.rs +++ b/crates/io/src/ora.rs @@ -509,6 +509,12 @@ impl Writer<'_> { if layer.clipped { self.warnings.layer(&layer.name, "OpenRaster has no clipping masks; these layers were saved unclipped"); } + if layer.excluded_channels != 0 { + self.warnings.layer(&layer.name, "OpenRaster drops channel blending restrictions from editable layers"); + } + if !layer.blend_if.is_default() { + self.warnings.layer(&layer.name, "OpenRaster drops Blend If settings from editable layers"); + } if !layer.effects.items.is_empty() || layer.effects.psd_raw.is_some() { self.warnings.layer(&layer.name, "layer styles are not saved to OpenRaster"); } From d5fcd848c2a6509373551ee8cec829a9b7809771 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:59:03 +0100 Subject: [PATCH 084/136] test(io): cover OpenRaster layer blending loss warnings Exercise both losses independently and keep explicitly full-range Blend If warning-free. --- crates/io/src/ora/tests.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/io/src/ora/tests.rs b/crates/io/src/ora/tests.rs index e073b01908..42b0a5e848 100644 --- a/crates/io/src/ora/tests.rs +++ b/crates/io/src/ora/tests.rs @@ -1,5 +1,5 @@ use super::*; -use photocraft_doc::{Adjustment, Color, Fill, LayerMask}; +use photocraft_doc::{Adjustment, BlendRange, Color, Fill, LayerMask}; const CANVAS: Size = Size { width: 70, height: 50 }; @@ -540,6 +540,8 @@ fn lossy_documents() -> Vec<(&'static str, Document)> { with(&move |d| d.layers.push(l.clone())) }), ("clipped", with(&|d| d.layers[1].clipped = true)), + ("channel blending", with(&|d| d.layers[0].excluded_channels = 1)), + ("Blend If", with(&|d| d.layers[0].blend_if.set(0, [BlendRange { black: [128, 128], ..BlendRange::FULL }, BlendRange::FULL]))), ("fill opacity", with(&|d| d.layers[0].fill_opacity = 0.5)), ("pixel lock", with(&|d| d.layers[0].locks.pixels = true)), // Not the bottom layer: with its transparency lock, `Base` would become the Background. @@ -567,6 +569,8 @@ fn plain_documents_lose_nothing() { for depth in [SampleType::U8, SampleType::U16] { let mut d = doc(depth); assert_eq!(losses(&d), Vec::::new(), "{depth:?}"); + d.layers[0].blend_if.ranges = vec![[BlendRange::FULL; 2]; 4]; + assert_eq!(losses(&d), Vec::::new(), "{depth:?} full Blend If ranges"); d.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes()); assert_eq!(losses(&d), Vec::::new(), "{depth:?} tagged sRGB"); assert_eq!(export(&d).unwrap().warnings, Vec::::new()); From 22c43575c5e2539f26f74ca99be2396924d422c5 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 20 Nov 2026 14:40:37 +0530 Subject: [PATCH 085/136] Tests: run the slow type-tool grids pairwise (#15939) The paragraph-handle, click, transform-scale and caret-font tests crossed every axis; each now runs one case per value of its widest axis, pairwise over the rest, keeping the ends of the range in points. --- .../src/tools/type_tool/canvas_tests.rs | 309 +++++++++--------- .../src/tools/type_tool/font_commit_tests.rs | 108 +++--- 2 files changed, 212 insertions(+), 205 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs index 6bedef6125..d64725526d 100644 --- a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs @@ -530,52 +530,57 @@ fn selection(h: &Harness<'static, Box>) -> (usize, usize) { #[test] fn clicks_and_drags_land_on_the_glyph_under_the_pointer() { let rotated = Affine { m: [1.4 * 0.94, 1.4 * 0.342, -1.4 * 0.342, 1.4 * 0.94, 500.0, 420.0] }; - for ppp in [1.0, 2.0] { - for zoom in [0.25f32, 0.5, 1.0, 2.0] { - for (flip, pan) in [(false, [0.0, 0.0]), (true, [37.0, -21.0])] { - for (shape, tf) in [("point", None), ("box", None), ("point", Some(rotated)), ("box", Some(rotated))] { - let mut app = new_app(); - let size = 60.0 / zoom; - let mut p = json!({"text": "HOHOHO HOHO", "size": size, "x": 300, "y": 420}); - if shape == "box" { - p["box"] = json!([250.0, 250.0, size * 6.0, size * 4.0]); - } - let id = LayerId(app.run("type.create", p).unwrap()["layer"].as_u64().unwrap()); - if let Some(a) = tf { - app.run("type.edit", json!({"layer": id.0, "transform": a.m})).unwrap(); - } - app.ui.view.flip_horizontal = flip; - let mut h = harness(ppp, app); - // Centre the view on the text's middle, then pan. - let (l, aff, _) = layout(h.state_mut(), id).unwrap(); - let b = l.bounds().unwrap(); - let m = aff.apply(Point::new(f64::from(b[0] + b[2]) / 2.0, f64::from(b[1] + b[3]) / 2.0)); - set_view(&mut h, zoom, [m.x as f32 + pan[0], m.y as f32 + pan[1]]); - h.run_steps(2); - let ctx = format!("ppp {ppp} zoom {zoom} flip {flip} {shape} transformed {}", tf.is_some()); - let rect = canvas_rect(h.state()); - for (i, f) in [(0, 0.2), (2, 0.8), (4, 0.3), (8, 0.7)] { - let p = glyph(&mut h, id, i, f); - assert!(rect.contains(p), "{ctx}: glyph {i} off screen at {p:?}"); - } - // Click into the layer: caret before glyph 2 (left part), then after glyph 4. - let p = glyph(&mut h, id, 2, 0.2); - click(&mut h, p); - assert_eq!(selection(&h), (2, 2), "{ctx}: click on the left of glyph 2"); - let p = glyph(&mut h, id, 4, 0.8); - click(&mut h, p); - assert_eq!(selection(&h), (5, 5), "{ctx}: click on the right of glyph 4"); - // Drag from glyph 1 (left part) to glyph 8 (right part): characters 1..9. - let (a, b) = (glyph(&mut h, id, 1, 0.25), glyph(&mut h, id, 8, 0.75)); - drag(&mut h, a, b); - assert_eq!(selection(&h), (1, 9), "{ctx}: drag selection"); - // And backwards, starting inside the egui drag threshold of a glyph edge. - let (a, b) = (glyph(&mut h, id, 5, 0.85), glyph(&mut h, id, 3, 0.15)); - drag(&mut h, a, b); - assert_eq!(selection(&h), (6, 3), "{ctx}: backwards drag selection"); - } - } + // One case per zoom, pairwise over the other axes: every ppp, flip and pan, and shape and transform + // appears, ppp meets both flips, and the two ends of the range in points (25 % at 2x is 12.5 %, 200 % + // at 1x is 200 %) are kept. The view maps the pointer to the document (the shown view's `to_doc`) + // the same way for any layer, and the layer's transform maps the document to text space the same way + // at any view, so the two halves need not be crossed. + let pan = [37.0, -21.0]; + for (ppp, zoom, flip, pan, shape, tf) in [ + (2.0, 0.25f32, false, [0.0, 0.0], "point", None), + (1.0, 0.5, true, pan, "box", None), + (2.0, 1.0, true, pan, "point", Some(rotated)), + (1.0, 2.0, false, [0.0, 0.0], "box", Some(rotated)), + ] { + let mut app = new_app(); + let size = 60.0 / zoom; + let mut p = json!({"text": "HOHOHO HOHO", "size": size, "x": 300, "y": 420}); + if shape == "box" { + p["box"] = json!([250.0, 250.0, size * 6.0, size * 4.0]); } + let id = LayerId(app.run("type.create", p).unwrap()["layer"].as_u64().unwrap()); + if let Some(a) = tf { + app.run("type.edit", json!({"layer": id.0, "transform": a.m})).unwrap(); + } + app.ui.view.flip_horizontal = flip; + let mut h = harness(ppp, app); + // Centre the view on the text's middle, then pan. + let (l, aff, _) = layout(h.state_mut(), id).unwrap(); + let b = l.bounds().unwrap(); + let m = aff.apply(Point::new(f64::from(b[0] + b[2]) / 2.0, f64::from(b[1] + b[3]) / 2.0)); + set_view(&mut h, zoom, [m.x as f32 + pan[0], m.y as f32 + pan[1]]); + h.run_steps(2); + let ctx = format!("ppp {ppp} zoom {zoom} flip {flip} {shape} transformed {}", tf.is_some()); + let rect = canvas_rect(h.state()); + for (i, f) in [(0, 0.2), (2, 0.8), (4, 0.3), (8, 0.7)] { + let p = glyph(&mut h, id, i, f); + assert!(rect.contains(p), "{ctx}: glyph {i} off screen at {p:?}"); + } + // Click into the layer: caret before glyph 2 (left part), then after glyph 4. + let p = glyph(&mut h, id, 2, 0.2); + click(&mut h, p); + assert_eq!(selection(&h), (2, 2), "{ctx}: click on the left of glyph 2"); + let p = glyph(&mut h, id, 4, 0.8); + click(&mut h, p); + assert_eq!(selection(&h), (5, 5), "{ctx}: click on the right of glyph 4"); + // Drag from glyph 1 (left part) to glyph 8 (right part): characters 1..9. + let (a, b) = (glyph(&mut h, id, 1, 0.25), glyph(&mut h, id, 8, 0.75)); + drag(&mut h, a, b); + assert_eq!(selection(&h), (1, 9), "{ctx}: drag selection"); + // And backwards, starting inside the egui drag threshold of a glyph edge. + let (a, b) = (glyph(&mut h, id, 5, 0.85), glyph(&mut h, id, 3, 0.15)); + drag(&mut h, a, b); + assert_eq!(selection(&h), (6, 3), "{ctx}: backwards drag selection"); } } @@ -1082,54 +1087,56 @@ fn temporary_type_transform_visibility_and_cursors() { /// Real canvas input: layer-local scaling stays correct across orientation, zoom, HiDPI and flip. #[test] fn temporary_type_transform_scales_without_reflow_or_leaving_type() { - for ppp in [1.0, 2.0] { - for zoom in [0.25, 1.0, 2.0, 8.0] { - for (paragraph, vertical, flip) in [(false, false, false), (true, false, true), (false, true, true)] { - let transform = Affine { m: [1.2, 0.25, 0.18, 0.9, 500.0, 360.0] }; - let (app, id) = transform_app(paragraph, vertical, transform); - let mut h = harness(ppp, app); - let f = frame_of(h.state_mut()).unwrap(); - let center = f.pivot; - h.state_mut().ui.view.flip_horizontal = flip; - // At high zoom, show the dragged corner; a release beyond the canvas is valid. - let at = if zoom >= 2.0 { [f.quad[2][0] as f32, f.quad[2][1] as f32] } else { [center[0] as f32 + 17.0, center[1] as f32 - 9.0] }; - set_view(&mut h, zoom, at); - h.run_steps(2); - let before = text(h.state(), id); - let count = history_len(&h); - let (a, b) = (f.quad[2], [f.quad[0][0] + 1.25 * (f.quad[2][0] - f.quad[0][0]), f.quad[0][1] + 1.25 * (f.quad[2][1] - f.quad[0][1])]); - let (a, b) = (frame_point(h.state(), a), frame_point(h.state(), b)); - assert!(canvas_rect(h.state()).contains(a)); - transform_drag(&mut h, a, b, type_command() | Modifiers::SHIFT, true); - let after = text(h.state(), id); - assert_affine( - after.transform, - transform.mul(&Affine::translate(f.rect[0], f.rect[1])).mul(&Affine::scale(1.25)).mul(&Affine::translate(-f.rect[0], -f.rect[1])), - ); - assert_eq!( - (after.text.as_str(), &after.runs, &after.paragraphs, after.orientation, after.shape), - (before.text.as_str(), &before.runs, &before.paragraphs, before.orientation, before.shape) - ); - assert_eq!(selection(&h), (3, 3)); - assert_eq!(h.state().ui.text_edit.as_ref().unwrap().layer, id.0); - assert!(h.state().ui.tool.is_type()); - assert!(h.state().ui.transform.is_none()); - assert!(h.state().ui.type_transform.is_none()); - assert_eq!(history_len(&h), count + 1); - // Typing goes through the window host, as the platform's reaches the focused editor. - super::commit_tests::type_keys(h.state_mut(), "!"); - assert!(text(h.state(), id).text.starts_with("Hel!lo")); - h.key_press(if vertical { egui::Key::ArrowUp } else { egui::Key::ArrowLeft }); - h.run_steps(1); - assert_eq!(selection(&h), (3, 3)); - assert_eq!(history_len(&h), count + 1, "one edit session"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_affine(text(h.state(), id).transform, before.transform); - assert_eq!(text(h.state(), id).text, before.text); - h.state_mut().run("edit.redo", json!({})).unwrap(); - assert_eq!(text(h.state(), id).transform, after.transform); - } - } + // One case per zoom, pairwise over the other axes: both ppp values meet both flips, point, paragraph + // and vertical type each appear, both sides of the 200 % view choice below run twice, and the ends of + // the range in points (25 % at 2x, 800 % at 1x) are kept. The frame and the drag map through the view + // the same way for any kind of type, and the kind decides the layer's frame the same way at any view. + for (ppp, zoom, (paragraph, vertical, flip)) in + [(2.0, 0.25, (false, false, false)), (1.0, 1.0, (true, false, true)), (2.0, 2.0, (false, true, true)), (1.0, 8.0, (false, false, false))] + { + let transform = Affine { m: [1.2, 0.25, 0.18, 0.9, 500.0, 360.0] }; + let (app, id) = transform_app(paragraph, vertical, transform); + let mut h = harness(ppp, app); + let f = frame_of(h.state_mut()).unwrap(); + let center = f.pivot; + h.state_mut().ui.view.flip_horizontal = flip; + // At high zoom, show the dragged corner; a release beyond the canvas is valid. + let at = if zoom >= 2.0 { [f.quad[2][0] as f32, f.quad[2][1] as f32] } else { [center[0] as f32 + 17.0, center[1] as f32 - 9.0] }; + set_view(&mut h, zoom, at); + h.run_steps(2); + let before = text(h.state(), id); + let count = history_len(&h); + let (a, b) = (f.quad[2], [f.quad[0][0] + 1.25 * (f.quad[2][0] - f.quad[0][0]), f.quad[0][1] + 1.25 * (f.quad[2][1] - f.quad[0][1])]); + let (a, b) = (frame_point(h.state(), a), frame_point(h.state(), b)); + assert!(canvas_rect(h.state()).contains(a)); + transform_drag(&mut h, a, b, type_command() | Modifiers::SHIFT, true); + let after = text(h.state(), id); + assert_affine( + after.transform, + transform.mul(&Affine::translate(f.rect[0], f.rect[1])).mul(&Affine::scale(1.25)).mul(&Affine::translate(-f.rect[0], -f.rect[1])), + ); + assert_eq!( + (after.text.as_str(), &after.runs, &after.paragraphs, after.orientation, after.shape), + (before.text.as_str(), &before.runs, &before.paragraphs, before.orientation, before.shape) + ); + assert_eq!(selection(&h), (3, 3)); + assert_eq!(h.state().ui.text_edit.as_ref().unwrap().layer, id.0); + assert!(h.state().ui.tool.is_type()); + assert!(h.state().ui.transform.is_none()); + assert!(h.state().ui.type_transform.is_none()); + assert_eq!(history_len(&h), count + 1); + // Typing goes through the window host, as the platform's reaches the focused editor. + super::commit_tests::type_keys(h.state_mut(), "!"); + assert!(text(h.state(), id).text.starts_with("Hel!lo")); + h.key_press(if vertical { egui::Key::ArrowUp } else { egui::Key::ArrowLeft }); + h.run_steps(1); + assert_eq!(selection(&h), (3, 3)); + assert_eq!(history_len(&h), count + 1, "one edit session"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_affine(text(h.state(), id).transform, before.transform); + assert_eq!(text(h.state(), id).text, before.text); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!(text(h.state(), id).transform, after.transform); } } @@ -2027,66 +2034,64 @@ const HANDLE_SIDES: [(bool, bool, bool, bool); 8] = [ fn every_paragraph_box_handle_resizes_the_box_with_snapping_on() { let scaled = Affine { m: [1.5, 0.0, 0.0, 0.75, 300.0, 300.0] }; let rotated = Affine { m: [1.2 * 0.94, 1.2 * 0.342, -1.2 * 0.342, 1.2 * 0.94, 300.0, 300.0] }; - for ppp in [1.0, 2.0] { - // The ends of the range only: the frame's handles and their grab area are screen-space parts of the - // framework's `TransformBox::text_frame` (`controls.rs`, `frame_box`) and the snap reach is a screen distance, - // so the zoom only scales the view, with no step in between. 25 % and 200 % at 1x and 2x span 12.5 % to - // 200 % in points, which holds 50 % and 100 %. - for zoom in [0.25f32, 2.0] { - for (name, tf) in [("plain", None), ("scaled", Some(scaled)), ("rotated", Some(rotated))] { - let mut app = new_app(); - assert!(app.ui.extras.snap, "snapping is on by default"); - let size = 24.0 / zoom; - let p = json!({"text": "HOHOHO HOHO HOHOHO HOHO HOHOHO", "size": size, "x": 300, "y": 300, "box": [300.0, 300.0, size * 8.0, size * 4.0]}); - let id = LayerId(app.run("type.create", p).unwrap()["layer"].as_u64().unwrap()); - if let Some(a) = tf { - app.run("type.edit", json!({"layer": id.0, "transform": a.m})).unwrap(); - } - let mut h = harness(ppp, app); + // Pairwise over (ppp, zoom, transform): each value of each axis appears once or more, and the two + // cases at the ends of the range in points are kept. The frame's handles and their grab area are + // screen-space parts of the framework's `TransformBox::text_frame` (`controls.rs`, `frame_box`) and + // the snap reach is a screen distance, so the zoom and ppp only scale the view: 25 % at 2x is 12.5 % + // in points and 200 % at 1x is 200 %, which hold 50 % and 100 % between them. The layer transform + // goes through the same frame mapping at any view scale, so each one runs at one view. + for (ppp, zoom, name, tf) in [(2.0, 0.25f32, "plain", None), (1.0, 2.0, "scaled", Some(scaled)), (2.0, 2.0, "rotated", Some(rotated))] { + let mut app = new_app(); + assert!(app.ui.extras.snap, "snapping is on by default"); + let size = 24.0 / zoom; + let p = json!({"text": "HOHOHO HOHO HOHOHO HOHO HOHOHO", "size": size, "x": 300, "y": 300, "box": [300.0, 300.0, size * 8.0, size * 4.0]}); + let id = LayerId(app.run("type.create", p).unwrap()["layer"].as_u64().unwrap()); + if let Some(a) = tf { + app.run("type.edit", json!({"layer": id.0, "transform": a.m})).unwrap(); + } + let mut h = harness(ppp, app); + let (bx, by, w, bh) = super::box_shape(h.state(), id).unwrap(); + let aff = layout(h.state_mut(), id).unwrap().1; + let m = aff.apply(Point::new(f64::from(bx + w / 2.0), f64::from(by + bh / 2.0))); + set_view(&mut h, zoom, [m.x as f32, m.y as f32]); + h.run_steps(2); + let ctx = format!("ppp {ppp} zoom {zoom} {name}"); + let p = glyph(&mut h, id, 2, 0.2); + click(&mut h, p); + assert_eq!(selection(&h), (2, 2), "{ctx}: editing"); + for (i, (l, r, t, b)) in HANDLE_SIDES.into_iter().enumerate() { + // Press at the handle and inside its grab area, towards the text. + for off in [0.0f32, 4.0] { let (bx, by, w, bh) = super::box_shape(h.state(), id).unwrap(); - let aff = layout(h.state_mut(), id).unwrap().1; - let m = aff.apply(Point::new(f64::from(bx + w / 2.0), f64::from(by + bh / 2.0))); - set_view(&mut h, zoom, [m.x as f32, m.y as f32]); - h.run_steps(2); - let ctx = format!("ppp {ppp} zoom {zoom} {name}"); - let p = glyph(&mut h, id, 2, 0.2); - click(&mut h, p); - assert_eq!(selection(&h), (2, 2), "{ctx}: editing"); - for (i, (l, r, t, b)) in HANDLE_SIDES.into_iter().enumerate() { - // Press at the handle and inside its grab area, towards the text. - for off in [0.0f32, 4.0] { - let (bx, by, w, bh) = super::box_shape(h.state(), id).unwrap(); - let hx = if l { - bx - } else if r { - bx + w - } else { - bx + w / 2.0 - }; - let hy = if t { - by - } else if b { - by + bh - } else { - by + bh / 2.0 - }; - let dir = vec2(f32::from(u8::from(r)) - f32::from(u8::from(l)), f32::from(u8::from(b)) - f32::from(u8::from(t))); - let at = screen(&mut h, id, hx, hy); - let out = (screen(&mut h, id, hx + dir.x * 10.0, hy + dir.y * 10.0) - at).normalized(); - let a = at - out * off; - drag(&mut h, a, a + out * 30.0); - let ctx = format!("{ctx} handle {i} offset {off}"); - assert_eq!(selection(&h), (2, 2), "{ctx}: the caret stays put"); - let (_, _, w2, h2) = super::box_shape(h.state(), id).unwrap(); - // 30 points outward (a corner's diagonal: about 21 per side) is that over - // zoom × layer scale in text units; snapping may shift the release by up to - // its 8 point reach. - let min = 6.0 / (zoom / h.state().canvas_ppp()) / 1.5; - let grew = |was: f32, now: f32, moved: bool| if moved { now - was >= min } else { (now - was).abs() < 1e-3 }; - assert!(grew(w, w2, l || r), "{ctx}: width {w} -> {w2}"); - assert!(grew(bh, h2, t || b), "{ctx}: height {bh} -> {h2}"); - } - } + let hx = if l { + bx + } else if r { + bx + w + } else { + bx + w / 2.0 + }; + let hy = if t { + by + } else if b { + by + bh + } else { + by + bh / 2.0 + }; + let dir = vec2(f32::from(u8::from(r)) - f32::from(u8::from(l)), f32::from(u8::from(b)) - f32::from(u8::from(t))); + let at = screen(&mut h, id, hx, hy); + let out = (screen(&mut h, id, hx + dir.x * 10.0, hy + dir.y * 10.0) - at).normalized(); + let a = at - out * off; + drag(&mut h, a, a + out * 30.0); + let ctx = format!("{ctx} handle {i} offset {off}"); + assert_eq!(selection(&h), (2, 2), "{ctx}: the caret stays put"); + let (_, _, w2, h2) = super::box_shape(h.state(), id).unwrap(); + // 30 points outward (a corner's diagonal: about 21 per side) is that over + // zoom × layer scale in text units; snapping may shift the release by up to + // its 8 point reach. + let min = 6.0 / (zoom / h.state().canvas_ppp()) / 1.5; + let grew = |was: f32, now: f32, moved: bool| if moved { now - was >= min } else { (now - was).abs() < 1e-3 }; + assert!(grew(w, w2, l || r), "{ctx}: width {w} -> {w2}"); + assert!(grew(bh, h2, t || b), "{ctx}: height {bh} -> {h2}"); } } } diff --git a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs index 8b47bc69d3..c3bc50fe94 100644 --- a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs @@ -147,63 +147,65 @@ fn caret_font_choices_style_only_subsequent_typing_including_ime() { // One app: each case's text layer goes with Undo before the next case makes its own. // Every acceptance, as each reaches the caret's pending style by its own route through the // family field (ArrowDown applies its row once per step). One original font, as it only decides - // which font is chosen, and the carets at both ends. + // which font is chosen. Every text meets the carets at both ends, where the inserted text and its + // pending font land on a character boundary of that text (a combined emoji, a paragraph break); + // each acceptance runs at both ends too. The acceptance only sets the pending font + // (`type_insertion_style`) before any character is typed, so it need not meet every text. let mut h = document(); let base = past_len(&h); let original = 0; - for accept in ["enter", "click", "arrow-enter"] { - for text in ["abcdef", "AéB👩‍💻", "ab\ncdé"] { - for caret in [0, text.chars().count()] { - let label = (accept, text, caret); - undo_to(&mut h, base); - let id = text_layer(&mut h, original, text); - select(&mut h, [caret, caret]); - h.run(); - let before = saved(&h, id); - let steps = h.state().session.active().unwrap().history.entries().len(); - let requested = FONTS[1 - original]; - choose(&mut h, requested, accept); - // ArrowDown steps to the row below the typed match, which depends on the installed fonts - // ("JetBrains Mono NL" where it is installed), so the pending font is the row it accepted. - let font = h - .state() - .ui - .type_insertion_style - .as_ref() - .map(|s| s.style.font_family.clone()) - .unwrap_or_else(|| panic!("a pending font at the caret: {label:?}")); - let font = font.as_str(); - assert!(font.starts_with(requested) && font != FONTS[original], "the accepted row matches the typed name: {font} {label:?}"); - if accept != "arrow-enter" { - assert_eq!(font, requested, "{label:?}"); - } - assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters: {label:?}"); - assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "{label:?}"); - crate::type_font_preview::set(h.state_mut(), font.into()); - assert!(crate::type_font_preview::display_doc(h.state_mut(), 0).is_none()); - // Two preedit replacements and the final commit keep the pending font. - surrender_focus(&mut h); - ime(h.state_mut(), egui::ImeEvent::Preedit { text: "é".into(), active_range_chars: None }); - h.run(); - ime(h.state_mut(), egui::ImeEvent::Preedit { text: "éX".into(), active_range_chars: None }); - h.run(); - ime(h.state_mut(), egui::ImeEvent::Commit("éX".into())); - h.run(); - super::host::type_text(h.state_mut(), "Z"); - h.run(); - let mut expected = families(&before); - expected.splice(caret..caret, std::iter::repeat_n(font.to_string(), 3)); - assert_eq!(families(&saved(&h, id)), expected, "{label:?}"); - let mut expected_text: Vec = text.chars().collect(); - expected_text.splice(caret..caret, "éXZ".chars()); - let typed = saved(&h, id); - assert_eq!(typed["text"], expected_text.into_iter().collect::(), "the IME and typed text land at the caret: {label:?}"); - assert!(h.state().ui.type_insertion_style.is_some(), "the pending font is still set before the commit: {label:?}"); - checkmark(&mut h); - assert_eq!(saved(&h, id), typed, "{label:?}"); - assert!(h.state().ui.type_insertion_style.is_none(), "the commit clears the pending font: {label:?}"); - } + for (accept, text, end) in [ + ("enter", "abcdef", false), + ("click", "abcdef", true), + ("arrow-enter", "AéB👩‍💻", false), + ("enter", "AéB👩‍💻", true), + ("click", "ab\ncdé", false), + ("arrow-enter", "ab\ncdé", true), + ] { + let caret = if end { text.chars().count() } else { 0 }; + let label = (accept, text, caret); + undo_to(&mut h, base); + let id = text_layer(&mut h, original, text); + select(&mut h, [caret, caret]); + h.run(); + let before = saved(&h, id); + let steps = h.state().session.active().unwrap().history.entries().len(); + let requested = FONTS[1 - original]; + choose(&mut h, requested, accept); + // ArrowDown steps to the row below the typed match, which depends on the installed fonts + // ("JetBrains Mono NL" where it is installed), so the pending font is the row it accepted. + let font = + h.state().ui.type_insertion_style.as_ref().map(|s| s.style.font_family.clone()).unwrap_or_else(|| panic!("a pending font at the caret: {label:?}")); + let font = font.as_str(); + assert!(font.starts_with(requested) && font != FONTS[original], "the accepted row matches the typed name: {font} {label:?}"); + if accept != "arrow-enter" { + assert_eq!(font, requested, "{label:?}"); } + assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters: {label:?}"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "{label:?}"); + crate::type_font_preview::set(h.state_mut(), font.into()); + assert!(crate::type_font_preview::display_doc(h.state_mut(), 0).is_none()); + // Two preedit replacements and the final commit keep the pending font. + surrender_focus(&mut h); + ime(h.state_mut(), egui::ImeEvent::Preedit { text: "é".into(), active_range_chars: None }); + h.run(); + ime(h.state_mut(), egui::ImeEvent::Preedit { text: "éX".into(), active_range_chars: None }); + h.run(); + ime(h.state_mut(), egui::ImeEvent::Commit("éX".into())); + h.run(); + super::host::type_text(h.state_mut(), "Z"); + h.run(); + let mut expected = families(&before); + expected.splice(caret..caret, std::iter::repeat_n(font.to_string(), 3)); + assert_eq!(families(&saved(&h, id)), expected, "{label:?}"); + let mut expected_text: Vec = text.chars().collect(); + expected_text.splice(caret..caret, "éXZ".chars()); + let typed = saved(&h, id); + assert_eq!(typed["text"], expected_text.into_iter().collect::(), "the IME and typed text land at the caret: {label:?}"); + assert!(h.state().ui.type_insertion_style.is_some(), "the pending font is still set before the commit: {label:?}"); + checkmark(&mut h); + assert_eq!(saved(&h, id), typed, "{label:?}"); + assert!(h.state().ui.type_insertion_style.is_none(), "the commit clears the pending font: {label:?}"); } } From 4671d84130c7b05250c54502698dc32a4623e769 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 20 Nov 2026 15:37:33 +0530 Subject: [PATCH 086/136] Tests: fewer frames per case in the handle and caret-font tests (#15939) The handle test presses each handle once per case, at the centre or in its grab area by turns, with a two-move drag; the caret-font test keeps one caret-at-start case and one caret-at-end case per text. --- .../src/tools/type_tool/canvas_tests.rs | 80 ++++++++++--------- .../src/tools/type_tool/font_commit_tests.rs | 18 ++--- 2 files changed, 50 insertions(+), 48 deletions(-) diff --git a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs index d64725526d..5740d44b36 100644 --- a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs @@ -506,11 +506,16 @@ fn double_click(h: &mut Harness<'static, Box>, p: Pos2) { } fn drag(h: &mut Harness<'static, Box>, a: Pos2, b: Pos2) { + drag_in(h, a, b, 6); +} + +/// [`drag`] in `moves` pointer moves, one frame each. +fn drag_in(h: &mut Harness<'static, Box>, a: Pos2, b: Pos2, moves: u8) { h.hover_at(a); h.run_steps(1); press(h, a, true); - for k in 1..=6 { - h.hover_at(a + (b - a) * (k as f32 / 6.0)); + for k in 1..=moves { + h.hover_at(a + (b - a) * (f32::from(k) / f32::from(moves))); h.run_steps(1); } press(h, b, false); @@ -2040,7 +2045,8 @@ fn every_paragraph_box_handle_resizes_the_box_with_snapping_on() { // the snap reach is a screen distance, so the zoom and ppp only scale the view: 25 % at 2x is 12.5 % // in points and 200 % at 1x is 200 %, which hold 50 % and 100 % between them. The layer transform // goes through the same frame mapping at any view scale, so each one runs at one view. - for (ppp, zoom, name, tf) in [(2.0, 0.25f32, "plain", None), (1.0, 2.0, "scaled", Some(scaled)), (2.0, 2.0, "rotated", Some(rotated))] { + let cases = [(2.0, 0.25f32, "plain", None), (1.0, 2.0, "scaled", Some(scaled)), (2.0, 2.0, "rotated", Some(rotated))]; + for (case, (ppp, zoom, name, tf)) in cases.into_iter().enumerate() { let mut app = new_app(); assert!(app.ui.extras.snap, "snapping is on by default"); let size = 24.0 / zoom; @@ -2060,39 +2066,41 @@ fn every_paragraph_box_handle_resizes_the_box_with_snapping_on() { click(&mut h, p); assert_eq!(selection(&h), (2, 2), "{ctx}: editing"); for (i, (l, r, t, b)) in HANDLE_SIDES.into_iter().enumerate() { - // Press at the handle and inside its grab area, towards the text. - for off in [0.0f32, 4.0] { - let (bx, by, w, bh) = super::box_shape(h.state(), id).unwrap(); - let hx = if l { - bx - } else if r { - bx + w - } else { - bx + w / 2.0 - }; - let hy = if t { - by - } else if b { - by + bh - } else { - by + bh / 2.0 - }; - let dir = vec2(f32::from(u8::from(r)) - f32::from(u8::from(l)), f32::from(u8::from(b)) - f32::from(u8::from(t))); - let at = screen(&mut h, id, hx, hy); - let out = (screen(&mut h, id, hx + dir.x * 10.0, hy + dir.y * 10.0) - at).normalized(); - let a = at - out * off; - drag(&mut h, a, a + out * 30.0); - let ctx = format!("{ctx} handle {i} offset {off}"); - assert_eq!(selection(&h), (2, 2), "{ctx}: the caret stays put"); - let (_, _, w2, h2) = super::box_shape(h.state(), id).unwrap(); - // 30 points outward (a corner's diagonal: about 21 per side) is that over - // zoom × layer scale in text units; snapping may shift the release by up to - // its 8 point reach. - let min = 6.0 / (zoom / h.state().canvas_ppp()) / 1.5; - let grew = |was: f32, now: f32, moved: bool| if moved { now - was >= min } else { (now - was).abs() < 1e-3 }; - assert!(grew(w, w2, l || r), "{ctx}: width {w} -> {w2}"); - assert!(grew(bh, h2, t || b), "{ctx}: height {bh} -> {h2}"); - } + // Press at the handle or inside its grab area, towards the text: corners (even `i`) and sides + // take turns, and the next case swaps them, so every handle is pressed both ways and every case + // presses both ways. The press picks the handle (`TransformBox::text_frame`) and the pass that + // commits carries the final box (`box_of`), so the drag needs the move that starts it and the end. + let off = if (i + case) % 2 == 0 { 0.0f32 } else { 4.0 }; + let (bx, by, w, bh) = super::box_shape(h.state(), id).unwrap(); + let hx = if l { + bx + } else if r { + bx + w + } else { + bx + w / 2.0 + }; + let hy = if t { + by + } else if b { + by + bh + } else { + by + bh / 2.0 + }; + let dir = vec2(f32::from(u8::from(r)) - f32::from(u8::from(l)), f32::from(u8::from(b)) - f32::from(u8::from(t))); + let at = screen(&mut h, id, hx, hy); + let out = (screen(&mut h, id, hx + dir.x * 10.0, hy + dir.y * 10.0) - at).normalized(); + let a = at - out * off; + drag_in(&mut h, a, a + out * 30.0, 2); + let ctx = format!("{ctx} handle {i} offset {off}"); + assert_eq!(selection(&h), (2, 2), "{ctx}: the caret stays put"); + let (_, _, w2, h2) = super::box_shape(h.state(), id).unwrap(); + // 30 points outward (a corner's diagonal: about 21 per side) is that over + // zoom × layer scale in text units; snapping may shift the release by up to + // its 8 point reach. + let min = 6.0 / (zoom / h.state().canvas_ppp()) / 1.5; + let grew = |was: f32, now: f32, moved: bool| if moved { now - was >= min } else { (now - was).abs() < 1e-3 }; + assert!(grew(w, w2, l || r), "{ctx}: width {w} -> {w2}"); + assert!(grew(bh, h2, t || b), "{ctx}: height {bh} -> {h2}"); } } } diff --git a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs index c3bc50fe94..9d1c96e054 100644 --- a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs @@ -147,21 +147,15 @@ fn caret_font_choices_style_only_subsequent_typing_including_ime() { // One app: each case's text layer goes with Undo before the next case makes its own. // Every acceptance, as each reaches the caret's pending style by its own route through the // family field (ArrowDown applies its row once per step). One original font, as it only decides - // which font is chosen. Every text meets the carets at both ends, where the inserted text and its - // pending font land on a character boundary of that text (a combined emoji, a paragraph break); - // each acceptance runs at both ends too. The acceptance only sets the pending font - // (`type_insertion_style`) before any character is typed, so it need not meet every text. + // which font is chosen. The caret at the start of the text, where any text inserts at byte 0 the same way, + // and at the end of each text, where the inserted text and its pending font land after its last character + // boundary (a plain letter, a joined emoji, a letter after a paragraph break). The acceptance only sets the + // pending font (`type_insertion_style`, checked before anything is typed), wherever the caret is, so each + // acceptance runs once or more and need not meet every caret or text. let mut h = document(); let base = past_len(&h); let original = 0; - for (accept, text, end) in [ - ("enter", "abcdef", false), - ("click", "abcdef", true), - ("arrow-enter", "AéB👩‍💻", false), - ("enter", "AéB👩‍💻", true), - ("click", "ab\ncdé", false), - ("arrow-enter", "ab\ncdé", true), - ] { + for (accept, text, end) in [("enter", "abcdef", false), ("click", "abcdef", true), ("arrow-enter", "AéB👩‍💻", true), ("enter", "ab\ncdé", true)] { let caret = if end { text.chars().count() } else { 0 }; let label = (accept, text, caret); undo_to(&mut h, base); From 7c94182884659e83c2cdfb0c6f42b427a3672674 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 20 Nov 2026 18:18:52 +0530 Subject: [PATCH 087/136] Restore unselected colour components only inside the live damage (#15967) restrict_region now restores only the pixels in the damage rect instead of every pixel of each touched tile. Pinned to one core, the live mixer test drops from 14.69 s to 1.15 s (12.8x faster) and the live retouching test from 16.24 s to 7.93 s (2.0x faster). --- crates/engine/src/color_channels.rs | 36 ++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/color_channels.rs b/crates/engine/src/color_channels.rs index d95007c70f..4212b33187 100644 --- a/crates/engine/src/color_channels.rs +++ b/crates/engine/src/color_channels.rs @@ -200,7 +200,7 @@ fn restrict_surface_impl(before: &Surface, after: &mut Surface, colors: ColorCha .map(|(c, _)| *c) .chain(before.tiles().filter(|(c, _)| after.tile(**c).is_none()).map(|(c, _)| *c)) .collect(); - restrict_coords(before, after, colors, coords)?; + restrict_coords(before, after, colors, coords, None)?; after.prune(); Ok(()) } @@ -218,10 +218,18 @@ pub fn restrict_region(before: &Surface, after: &mut Surface, colors: ColorChann _ => true, }) .collect(); - restrict_coords(before, after, colors, coords) + restrict_coords(before, after, colors, coords, Some(damage)) } -fn restrict_coords(before: &Surface, after: &mut Surface, colors: ColorChannels, coords: BTreeSet) -> Result<()> { +/// Restore the unselected components of each tile in `coords`, inside `area` only, or across the +/// whole tile when `area` is `None`. +fn restrict_coords( + before: &Surface, + after: &mut Surface, + colors: ColorChannels, + coords: BTreeSet, + area: Option, +) -> Result<()> { if before.default_bytes() != after.default_bytes() { return Err(EngineError::Other("a colour-channel edit cannot change unstored pixels".into())); } @@ -231,15 +239,27 @@ fn restrict_coords(before: &Surface, after: &mut Surface, colors: ColorChannels, if stride == 0 { return Err(EngineError::Other("invalid pixel format".into())); } + let row = (photocraft_geom::TILE_SIZE as usize).saturating_mul(stride); for c in coords { let old = before.tile(c); let old_bytes = old.map(|t| t.bytes()); let tile = after.try_tile_mut(c).map_err(|e| EngineError::Other(e.to_string()))?; - for (i, pixel) in tile.bytes_mut().chunks_exact_mut(stride).enumerate() { - let original = old_bytes.as_deref().and_then(|t| t.get(i * stride..(i + 1) * stride)).unwrap_or(before.default_bytes()); - for (ch, (out, src)) in pixel.chunks_exact_mut(bytes).zip(original.chunks_exact(bytes)).enumerate() { - if !colors.contains(ch) { - out.copy_from_slice(src); + let tile_rect = c.rect(); + let part = area.map_or(tile_rect, |a| a.intersect(&tile_rect)); + if !part.is_empty() { + let mut dest = tile.bytes_mut(); + let (x0, x1) = ((part.x0 - tile_rect.x0) as usize, (part.x1 - tile_rect.x0) as usize); + for y in (part.y0 - tile_rect.y0) as usize..(part.y1 - tile_rect.y0) as usize { + let span = y.saturating_mul(row).saturating_add(x0.saturating_mul(stride))..y.saturating_mul(row).saturating_add(x1.saturating_mul(stride)); + let Some(pixels) = dest.get_mut(span.clone()) else { continue }; + let originals = old_bytes.as_deref().and_then(|t| t.get(span)); + for (i, pixel) in pixels.chunks_exact_mut(stride).enumerate() { + let original = originals.and_then(|t| t.get(i * stride..(i + 1) * stride)).unwrap_or(before.default_bytes()); + for (ch, (out, src)) in pixel.chunks_exact_mut(bytes).zip(original.chunks_exact(bytes)).enumerate() { + if !colors.contains(ch) { + out.copy_from_slice(src); + } + } } } } From eb6bd68405e0e92604b5b6446180b4012852d4ae Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 20 Nov 2026 18:28:50 +0530 Subject: [PATCH 088/136] Tests: run the engine mode x depth x command matrices pairwise (#15932) The colour-channel tests looped over every mode, depth, command and target, although the code under test is generic over mode and depth (restrict_coords, scatter_selected, tone::adjust). Each case now runs a rotation that keeps every mode, depth, command and target (and the refusal branches) in at least one case, with all assertions unchanged. - multi_channel_editing: adjustments/filters/drawing (22 commands, one mode and depth each, plus both refusal sides), live brush/eraser, live mixer, live retouching, colour adjustments, desaturate, CMYK grayscale clips, mask view - tone_target_picker: gray tone records, native gray pickers, filter mask picker - tone: the fused-tile oracle keeps the 256 x 256 area only for U16, whose table needs it - tone dialog: one depth per (subset, record) - cmyk_flatten_profile: the synthesised profile uses coarse LUT grids --- crates/engine/src/color_channels/tone.rs | 6 +- .../src/color_channels/tone_dialog_tests.rs | 12 +- .../engine/tests/it/cmyk_flatten_profile.rs | 2 + .../engine/tests/it/multi_channel_editing.rs | 131 +++++++++++------- crates/engine/tests/it/tone_target_picker.rs | 52 ++++--- 5 files changed, 127 insertions(+), 76 deletions(-) diff --git a/crates/engine/src/color_channels/tone.rs b/crates/engine/src/color_channels/tone.rs index 62ecf3174b..5ecc6ebb67 100644 --- a/crates/engine/src/color_channels/tone.rs +++ b/crates/engine/src/color_channels/tone.rs @@ -267,8 +267,10 @@ mod tests { for (si, sample) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { let fmt = PixelFormat::new(mode, sample, true); let mut source = Surface::with_default(fmt, &vec![0.3; fmt.channels()]); - // 256 x 256 is exactly the U16 table's area threshold (`use_table`), so the table path still runs (#15652). - let bounds = Rect::from_xywh(-128, -128, 256, 256); + // 256 x 256 is exactly the U16 table's area threshold (`use_table`), so the table path still runs + // (#15652). U8 builds its table whatever the area and F32 has none, so they use a small area that still + // extends past the data and the masks on every side: default pixels around them are adjusted too. + let bounds = if sample == SampleType::U16 { Rect::from_xywh(-128, -128, 256, 256) } else { Rect::from_xywh(-8, 0, 48, 40) }; let data: Vec<_> = (0..32 * 24 * fmt.channels()) .map(|i| { let v = (i * 37 % 257) as f32 / 256.0; diff --git a/crates/engine/src/color_channels/tone_dialog_tests.rs b/crates/engine/src/color_channels/tone_dialog_tests.rs index c419da9a14..350f970d42 100644 --- a/crates/engine/src/color_channels/tone_dialog_tests.rs +++ b/crates/engine/src/color_channels/tone_dialog_tests.rs @@ -15,13 +15,16 @@ fn tone_dialog_normalization_matches_native_execution() { continue; } let colors = ColorChannels::from_indices((0..count).filter(|k| bits & (1 << k) != 0), count).unwrap(); - for raw in [ + for (ri, raw) in [ json!({"gray":{"gamma":2},"gamma":1.25,"inBlack":8}), json!({"gray":{"gamma":1.234567},"gamma":1.25,"inBlack":8.123456}), json!({"gray":"ignored","points":[[0,20],[255,240]]}), json!({"gray":[[0,0],[100.123456,200.654321],[255,255]]}), json!({"gray":(0..256).map(|i| (i * 37 % 256) as f32).collect::>(),"pencil":true,"smooth":3}), - ] { + ] + .into_iter() + .enumerate() + { let kind = if raw.get("gamma").is_some() { "levels" } else { "curves" }; let mut raw = raw; for (index, key) in keys.iter().enumerate() { @@ -44,7 +47,10 @@ fn tone_dialog_normalization_matches_native_execution() { assert_eq!(canonical_records[*key], original_records[*key], "{mode:?} {bits} {kind}: unselected component {index}"); } let parsed = |p| tone_adjustment(kind, p, crate::adjust_params::from_params(kind, p, None, mode).unwrap(), mode, colors).unwrap(); - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + // One depth per (subset, record), rotating with their sum: every mode and kind still reaches every + // depth across the subsets. + { + let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(bits as usize + ri) % 3]; let bounds = Rect::new(0, 0, 8, 8); let mut original = Surface::new(PixelFormat::new(mode, depth, true)); let values: Vec<_> = (0..count).map(|i| (i as f32 + 1.0) / 7.0).chain([0.65]).collect(); diff --git a/crates/engine/tests/it/cmyk_flatten_profile.rs b/crates/engine/tests/it/cmyk_flatten_profile.rs index bb088ec1a6..0afa7d029e 100644 --- a/crates/engine/tests/it/cmyk_flatten_profile.rs +++ b/crates/engine/tests/it/cmyk_flatten_profile.rs @@ -43,6 +43,8 @@ fn profile() -> Arc> { craft_cms::synth::cmyk_profile(&craft_cms::synth::CmykParams { description: "Test Uncoated".into(), tvi: [0.26, 0.26, 0.26, 0.3], + grid_a2b: 5, + grid_b2a: 9, ..Default::default() }) .unwrap() diff --git a/crates/engine/tests/it/multi_channel_editing.rs b/crates/engine/tests/it/multi_channel_editing.rs index fbb3de72a6..8da4719a85 100644 --- a/crates/engine/tests/it/multi_channel_editing.rs +++ b/crates/engine/tests/it/multi_channel_editing.rs @@ -93,29 +93,35 @@ fn adjustments_filters_and_drawing_preserve_other_encoded_components() { ("paint.artHistoryBrush", json!({"points":[[8,8],[22,12]],"size":9,"tolerance":0})), ("paint.mixerBrush", json!({"points":[[8,8],[22,12]],"size":9,"color":"#ffffff"})), ]; - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for (cmd, p) in &commands { - let mut s = setup(mode, depth); - subset(&mut s); - let before = surface(&s); - // Color Replacement refuses 32-bit RGB (#11923), the Art History Brush every depth - // but 8 bits (#12637), as the reference application does. - if (*cmd == "paint.colorReplacement" && mode == "rgb" && depth == 32) || (*cmd == "paint.artHistoryBrush" && depth != 8) { - assert!(s.execute(cmd, p.clone()).is_err(), "{mode} {depth} {cmd} is refused"); - assert_eq!(surface(&s), before, "{mode} {depth} {cmd}: nothing changed"); - continue; - } - s.execute(cmd, p.clone()).unwrap_or_else(|e| panic!("{mode} {depth} {cmd}: {e}")); - let after = surface(&s); - unchanged(&before, &after); - assert_ne!(before, after, "{mode} {depth} {cmd} must change selected samples"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(surface(&s), before, "undo {cmd}"); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(surface(&s), after, "redo {cmd}"); - } + // Command c runs once, at mode c % 3 and depth (c + c / 3) % 3: the 22 commands cover all nine + // mode and depth pairs, and the four tone adjustments cover every mode and every depth. The two + // extra cases run the other side of each refusal: Color Replacement at RGB 32 bits (refused) and + // the Art History Brush at CMYK 8 bits (allowed). + let modes = ["rgb", "cmyk", "lab"]; + let depths = [8, 16, 32]; + let mut cases: Vec<_> = commands.iter().enumerate().map(|(c, (cmd, p))| (modes[c % 3], depths[(c + c / 3) % 3], *cmd, p.clone())).collect(); + cases.push(("rgb", 32, "paint.colorReplacement", commands[17].1.clone())); + cases.push(("cmyk", 8, "paint.artHistoryBrush", commands[20].1.clone())); + for (mode, depth, cmd, p) in &cases { + let (mode, depth) = (*mode, *depth); + let mut s = setup(mode, depth); + subset(&mut s); + let before = surface(&s); + // Color Replacement refuses 32-bit RGB (#11923), the Art History Brush every depth + // but 8 bits (#12637), as the reference application does. + if (*cmd == "paint.colorReplacement" && mode == "rgb" && depth == 32) || (*cmd == "paint.artHistoryBrush" && depth != 8) { + assert!(s.execute(cmd, p.clone()).is_err(), "{mode} {depth} {cmd} is refused"); + assert_eq!(surface(&s), before, "{mode} {depth} {cmd}: nothing changed"); + continue; } + s.execute(cmd, p.clone()).unwrap_or_else(|e| panic!("{mode} {depth} {cmd}: {e}")); + let after = surface(&s); + unchanged(&before, &after); + assert_ne!(before, after, "{mode} {depth} {cmd} must change selected samples"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(surface(&s), before, "undo {cmd}"); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(surface(&s), after, "redo {cmd}"); } } @@ -150,9 +156,11 @@ fn explicit_target_wins_and_invalid_sets_are_transactional() { #[test] fn live_brush_and_eraser_match_commit_at_all_native_depths() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for erase in [false, true] { + // Depth (mode + erase) % 3: each mode and each depth appears with both erase values. + for (mi, mode) in ["rgb", "cmyk", "lab"].into_iter().enumerate() { + for (ei, erase) in [false, true].into_iter().enumerate() { + { + let depth = [8, 16, 32][(mi + ei) % 3]; let mut s = setup(mode, depth); subset(&mut s); let before = surface(&s); @@ -181,8 +189,9 @@ fn live_mixer_captures_selected_components_and_matches_commit_and_replay() { use photocraft_engine::brush_cmds::mixer_live::LiveMixer; use photocraft_engine::paint::StrokePoint; - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { + // The mixer is generic over mode and depth: one case per mode, each at a different depth. + for (mode, depth) in [("rgb", 8), ("cmyk", 16), ("lab", 32)] { + { let mut s = setup(mode, depth); subset(&mut s); let before = surface(&s); @@ -251,9 +260,21 @@ fn native_float_payloads_survive_unselected_component_restoration() { #[test] fn live_retouching_matches_direct_replay_and_preserves_unselected_bytes() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for cmd in ["paint.dodge", "paint.burn", "paint.blur", "paint.sharpen", "paint.smudge", "paint.cloneStamp", "paint.historyBrush"] { + // The five dab commands (LiveDab) cover every mode and depth, and so do the two retouch commands + // (LiveRetouch). + let cases = [ + ("rgb", 8, "paint.dodge"), + ("cmyk", 16, "paint.burn"), + ("lab", 32, "paint.blur"), + ("cmyk", 8, "paint.sharpen"), + ("rgb", 16, "paint.smudge"), + ("cmyk", 32, "paint.cloneStamp"), + ("lab", 16, "paint.historyBrush"), + ("rgb", 8, "paint.cloneStamp"), + ]; + for (mode, depth, cmd) in cases { + { + { let mut s = setup(mode, depth); subset(&mut s); let original = surface(&s); @@ -627,9 +648,11 @@ fn legacy_cmyk_channel_clips_keep_their_tone_when_pasted_into_a_set_or_single_ch #[test] fn cmyk_grayscale_clips_roundtrip_explicit_and_limited_paste_at_every_depth() { - for depth in [8, 16, 32] { - for explicit_copy in [false, true] { - for command in ["edit.paste", "edit.pasteSpecial.pasteInto", "edit.pasteSpecial.pasteOutside"] { + // Depth (command + explicit copy) % 3: each depth, command and copy kind pairs with the others. + for (ci, command) in ["edit.paste", "edit.pasteSpecial.pasteInto", "edit.pasteSpecial.pasteOutside"].into_iter().enumerate() { + for (ei, explicit_copy) in [false, true].into_iter().enumerate() { + { + let depth = [8, 16, 32][(ci + ei) % 3]; let mut s = setup("cmyk", depth); s.execute("channel.target", json!({"channel":{"color":0}})).unwrap(); let before = surface(&s); @@ -1232,15 +1255,19 @@ fn geometric_filters_on_colour_sets_preserve_background_identity_and_linked_mask #[test] fn colour_adjustments_keep_the_original_cross_component_inputs() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for (cmd, params) in [ - ("image.adjustments.channelMixer", json!({"red":[0,100,0,0]})), - ("image.adjustments.hueSaturation", json!({"saturation":-30})), - ("image.adjustments.vibrance", json!({"vibrance":40})), - ("image.adjustments.colorBalance", json!({"midtones":[20,-10,30]})), - ("image.adjustments.photoFilter", json!({"color":"#ff0000","density":70})), - ] { + // One mode and depth per command; Color Balance runs twice so RGB also sees a second depth. Both + // index sets run in every case. + let cases = [ + ("rgb", 8, "image.adjustments.channelMixer", json!({"red":[0,100,0,0]})), + ("cmyk", 16, "image.adjustments.hueSaturation", json!({"saturation":-30})), + ("lab", 32, "image.adjustments.vibrance", json!({"vibrance":40})), + ("cmyk", 32, "image.adjustments.colorBalance", json!({"midtones":[20,-10,30]})), + ("lab", 8, "image.adjustments.photoFilter", json!({"color":"#ff0000","density":70})), + ("rgb", 16, "image.adjustments.colorBalance", json!({"midtones":[20,-10,30]})), + ]; + for (mode, depth, cmd, params) in cases { + { + { let mut control = setup(mode, depth); let before = surface(&control); control.execute(cmd, params.clone()).unwrap(); @@ -1400,9 +1427,11 @@ fn refused_mask_cut_and_clear_leave_the_pixels_mask_and_clipboard_unchanged() { #[test] fn desaturate_honours_explicit_native_targets_over_the_panel_selection() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for target in [json!({"color":1}), json!({"colors":[1]}), json!("pixels")] { + // Depth (mode + target) % 3: each mode and each target appears at every depth. + for (mi, mode) in ["rgb", "cmyk", "lab"].into_iter().enumerate() { + for (ti, target) in [json!({"color":1}), json!({"colors":[1]}), json!("pixels")].into_iter().enumerate() { + { + let depth = [8, 16, 32][(mi + ti) % 3]; let mut s = setup(mode, depth); let before = surface(&s); let mut control = Session::new(); @@ -1434,10 +1463,14 @@ fn desaturate_honours_explicit_native_targets_over_the_panel_selection() { #[test] fn mask_view_routes_implicit_edits_and_tone_editors_to_the_mask_before_colour_sets() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for view in ["gray", "overlay"] { - for colors in [vec![0], vec![0, 2]] { + // Depth and colour set rotate with (mode + view): each mode and view meets every depth and both + // colour sets across the cases. + for (mi, mode) in ["rgb", "cmyk", "lab"].into_iter().enumerate() { + for (vi, view) in ["gray", "overlay"].into_iter().enumerate() { + { + { + let depth = [8, 16, 32][(mi + vi) % 3]; + let colors = [vec![0], vec![0, 2]][(mi + vi) % 2].clone(); let mut s = setup(mode, depth); s.execute("layer.layerMask.revealAll", json!({})).unwrap(); s.execute("channel.target", json!({"colors":colors})).unwrap(); diff --git a/crates/engine/tests/it/tone_target_picker.rs b/crates/engine/tests/it/tone_target_picker.rs index 9f34868798..54b5a19ca8 100644 --- a/crates/engine/tests/it/tone_target_picker.rs +++ b/crates/engine/tests/it/tone_target_picker.rs @@ -42,11 +42,15 @@ fn plane<'a>(doc: &'a Document, target: &Value) -> &'a Surface { /// Black/white pickers edit only their gray target across colour modes and native depths, including undo/redo. #[test] fn native_gray_pickers_ignore_document_colour_and_preserve_other_data() { - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for target in [json!("mask"), json!("quickMask"), json!({"channel":0})] { - for kind in ["levels", "curves"] { - for point in ["black", "white"] { + // Depth (mode + target) % 3 and, per kind, a point that alternates: each mode and each target meets every depth, + // and each kind runs with both points. + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk].into_iter().enumerate() { + for (ti, target) in [json!("mask"), json!("quickMask"), json!({"channel":0})].into_iter().enumerate() { + let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(mi + ti) % 3]; + for (ki, kind) in ["levels", "curves"].into_iter().enumerate() { + { + { + let point = ["black", "white"][(mi + ti + ki) % 2]; let mut s = session(mode, depth); let before = s.active().unwrap().doc.clone(); let history = s.active().unwrap().history.past_len(); @@ -232,18 +236,21 @@ fn bad_scalar_picker_params_fail_without_changing_pixels() { /// Hidden RGB settings must never affect a gray plane, including pencil curves and sampled edits. #[test] fn gray_tone_records_do_not_leak_from_rgb_channels() { - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for (target, panel) in - [(json!("mask"), ChannelTarget::LayerMask), (json!({"channel":0}), ChannelTarget::Alpha(0)), (json!("quickMask"), ChannelTarget::Composite)] - { - // Each style sees both flags; all four flag pairs occur across the styles. - for (si, style) in ["levels", "points", "pencil"].into_iter().enumerate() { - for (ai, sampled) in [false, true].into_iter().enumerate() { - for (ei, explicit) in [false, true].into_iter().enumerate() { - if (si + ai) % 2 != ei { - continue; - } + // Depth (mode + target) % 3: each mode and each target meets every depth. + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk].into_iter().enumerate() { + for (ti, (target, panel)) in + [(json!("mask"), ChannelTarget::LayerMask), (json!({"channel":0}), ChannelTarget::Alpha(0)), (json!("quickMask"), ChannelTarget::Composite)] + .into_iter() + .enumerate() + { + let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(mi + ti) % 3]; + // Each style runs one (sampled, explicit) pair, rotating with (2 * mode + target + style): every style sees + // all four flag pairs across the cases, and at every depth it sees both sampled and both explicit values. + for (si, style) in ["levels", "points", "pencil"].into_iter().enumerate() { + { + { + let (sampled, explicit) = [(false, false), (false, true), (true, false), (true, true)][(2 * mi + ti + si) % 4]; + { let mut clean = session(mode, depth); clean.active_mut().unwrap().channel_view.target = panel; clean @@ -388,13 +395,14 @@ fn review_picker_reads_the_addressed_mask_layer() { /// A Smart Filter mask is a gray target like a layer mask: the picker reads the stored mask, or the implicit Reveal /// All before anything is stored, without materializing it, and the commit edits only the filter mask, in every -/// colour mode and native depth. (The UI's tone dialogs test only that their pick reaches this target, #15648.) +/// colour mode and, across the cases, every native depth (rotating with mode, stored and kind). (The UI's tone dialogs test only that their pick reaches this target, #15648.) #[test] fn filter_mask_picker_samples_and_edits_only_the_filter_mask() { - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for stored in [false, true] { - for kind in ["levels", "curves"] { + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() { + for (si, stored) in [false, true].into_iter().enumerate() { + for (ki, kind) in ["levels", "curves"].into_iter().enumerate() { + { + let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(mi + si + ki) % 3]; let case = format!("{mode:?} {depth:?} stored={stored} {kind}"); let mut s = session(mode, depth); // A Smart Filter needs the composite selected, not one colour channel, and no Quick Mask (the filter From ccd450ae5a4663031b16e8b146af5160502dcaca Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 20 Nov 2026 18:33:10 +0530 Subject: [PATCH 089/136] Tests: run the fused tone oracle on a small area with a matching table threshold (#15932) tone::adjust now delegates to a private adjust_with that takes the U16 table area threshold (U16_TABLE_AREA, 65_536, unchanged for production). The fused-tile oracle test passes the area of its small bounds, so U16 still takes the table path for the full area and the holes mask and the tiled path for the sparse mask, without 256 x 256 areas. Also drops the empty blocks left by the earlier loop removals in multi_channel_editing, tone_target_picker and the tone dialog test. --- crates/engine/src/color_channels/tone.rs | 31 +- .../src/color_channels/tone_dialog_tests.rs | 22 +- .../engine/tests/it/multi_channel_editing.rs | 324 ++++++++---------- crates/engine/tests/it/tone_target_picker.rs | 257 +++++++------- 4 files changed, 304 insertions(+), 330 deletions(-) diff --git a/crates/engine/src/color_channels/tone.rs b/crates/engine/src/color_channels/tone.rs index 5ecc6ebb67..3e96aa4965 100644 --- a/crates/engine/src/color_channels/tone.rs +++ b/crates/engine/src/color_channels/tone.rs @@ -19,6 +19,10 @@ struct Component { lab_invert: bool, } +/// Building all 65,536 U16 entries amortizes well on large edits. Tiny selections instead use tile-local buffers, +/// avoiding a full table's setup cost for a handful of pixels. +const U16_TABLE_AREA: u64 = 65_536; + struct IntegerTable { adjusted: Vec, encoded: Vec<[u8; 4]>, @@ -27,6 +31,18 @@ struct IntegerTable { /// Evaluate independent tones together, cloning each destination tile once. Untouched native /// samples and the surface default retain their original bytes, including NaN payloads. pub(super) fn adjust(surface: &mut Surface, colors: ColorChannels, adjustment: &Adjustment, selection: Option<&Surface>, bounds: Rect) -> Result<()> { + adjust_with(surface, colors, adjustment, selection, bounds, U16_TABLE_AREA) +} + +/// [`adjust`] with the smallest edit area, in pixels, that builds a U16 table. +fn adjust_with( + surface: &mut Surface, + colors: ColorChannels, + adjustment: &Adjustment, + selection: Option<&Surface>, + bounds: Rect, + table_area: u64, +) -> Result<()> { let fmt = surface.format(); if colors.indices().any(|k| k >= fmt.mode.color_channels()) { return Err(EngineError::Other("invalid colour component".into())); @@ -39,10 +55,8 @@ pub(super) fn adjust(surface: &mut Surface, colors: ColorChannels, adjustment: & (SampleType::F32, _) | (SampleType::U16, Adjustment::Threshold { .. } | Adjustment::Posterize { .. }) => Some(fmt.sample), _ => None, }; - // Building all 65,536 U16 entries amortizes well on large edits. Tiny selections instead - // use tile-local buffers, avoiding a full table's setup cost for a handful of pixels. let area = selection.filter(|s| s.default_pixel().first().is_none_or(|v| *v <= 0.0)).map_or(bounds, |s| s.content_bounds().intersect(&bounds)); - let use_table = fmt.sample == SampleType::U8 || (fmt.sample == SampleType::U16 && u64::from(area.width()) * u64::from(area.height()) >= 65_536); + let use_table = fmt.sample == SampleType::U8 || (fmt.sample == SampleType::U16 && u64::from(area.width()) * u64::from(area.height()) >= table_area); let mut components: Vec = Vec::new(); for index in colors.indices() { let scalar = scalar_adjustment(adjustment, index); @@ -267,10 +281,11 @@ mod tests { for (si, sample) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { let fmt = PixelFormat::new(mode, sample, true); let mut source = Surface::with_default(fmt, &vec![0.3; fmt.channels()]); - // 256 x 256 is exactly the U16 table's area threshold (`use_table`), so the table path still runs - // (#15652). U8 builds its table whatever the area and F32 has none, so they use a small area that still - // extends past the data and the masks on every side: default pixels around them are adjusted too. - let bounds = if sample == SampleType::U16 { Rect::from_xywh(-128, -128, 256, 256) } else { Rect::from_xywh(-8, 0, 48, 40) }; + // A small area that extends past the data and the masks on every side, so default pixels around them are + // adjusted too. The U16 table threshold is exactly its area: the whole area and the holes mask take the + // table path, the sparse mask (content bounds below it) the tiled path (#15652). + let bounds = Rect::from_xywh(-8, 0, 48, 40); + let table_area = u64::from(bounds.width()) * u64::from(bounds.height()); let data: Vec<_> = (0..32 * 24 * fmt.channels()) .map(|i| { let v = (i * 37 % 257) as f32 / 256.0; @@ -293,7 +308,7 @@ mod tests { let mut expected = source.clone(); let mut actual = source.clone(); super::super::adjust_reference(&mut expected, colors, adjustment, selection, bounds).unwrap(); - adjust(&mut actual, colors, adjustment, selection, bounds).unwrap(); + adjust_with(&mut actual, colors, adjustment, selection, bounds, table_area).unwrap(); assert!(expected == actual, "{mode:?} {sample:?} {adjustment:?} selection={}", selection.is_some()); } } diff --git a/crates/engine/src/color_channels/tone_dialog_tests.rs b/crates/engine/src/color_channels/tone_dialog_tests.rs index 350f970d42..057c5c0ddc 100644 --- a/crates/engine/src/color_channels/tone_dialog_tests.rs +++ b/crates/engine/src/color_channels/tone_dialog_tests.rs @@ -49,18 +49,16 @@ fn tone_dialog_normalization_matches_native_execution() { let parsed = |p| tone_adjustment(kind, p, crate::adjust_params::from_params(kind, p, None, mode).unwrap(), mode, colors).unwrap(); // One depth per (subset, record), rotating with their sum: every mode and kind still reaches every // depth across the subsets. - { - let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(bits as usize + ri) % 3]; - let bounds = Rect::new(0, 0, 8, 8); - let mut original = Surface::new(PixelFormat::new(mode, depth, true)); - let values: Vec<_> = (0..count).map(|i| (i as f32 + 1.0) / 7.0).chain([0.65]).collect(); - original.fill_rect(bounds, &values); - let mut expected = original.clone(); - tone::adjust(&mut expected, colors, &parsed(&raw), None, bounds).unwrap(); - let mut actual = original; - tone::adjust(&mut actual, colors, &parsed(&canonical), None, bounds).unwrap(); - assert_eq!(actual, expected, "{mode:?} {depth:?} {bits} {kind}"); - } + let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(bits as usize + ri) % 3]; + let bounds = Rect::new(0, 0, 8, 8); + let mut original = Surface::new(PixelFormat::new(mode, depth, true)); + let values: Vec<_> = (0..count).map(|i| (i as f32 + 1.0) / 7.0).chain([0.65]).collect(); + original.fill_rect(bounds, &values); + let mut expected = original.clone(); + tone::adjust(&mut expected, colors, &parsed(&raw), None, bounds).unwrap(); + let mut actual = original; + tone::adjust(&mut actual, colors, &parsed(&canonical), None, bounds).unwrap(); + assert_eq!(actual, expected, "{mode:?} {depth:?} {bits} {kind}"); } } } diff --git a/crates/engine/tests/it/multi_channel_editing.rs b/crates/engine/tests/it/multi_channel_editing.rs index 8da4719a85..3290897f28 100644 --- a/crates/engine/tests/it/multi_channel_editing.rs +++ b/crates/engine/tests/it/multi_channel_editing.rs @@ -159,27 +159,25 @@ fn live_brush_and_eraser_match_commit_at_all_native_depths() { // Depth (mode + erase) % 3: each mode and each depth appears with both erase values. for (mi, mode) in ["rgb", "cmyk", "lab"].into_iter().enumerate() { for (ei, erase) in [false, true].into_iter().enumerate() { - { - let depth = [8, 16, 32][(mi + ei) % 3]; - let mut s = setup(mode, depth); - subset(&mut s); - let before = surface(&s); - let mut p = json!({"points":[[6,7,1],[23,15,0.7]],"size":9,"color":"#ffffff","erase":erase,"seed":42}); - let live = LiveStroke::begin(&s, &p).unwrap(); - p["seed"] = json!(live.seed); - let st = s.active().unwrap(); - let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); - unchanged(&before, &shown); - s.offer_live_stroke(live).unwrap(); - let result = s.execute("paint.stroke", p).unwrap(); - assert_eq!(result["fromLive"], true, "reuse {mode} {depth} {erase}"); - assert!( - surface(&s) == shown, - "live pixels differ: {mode} {depth} {erase}; shown tiles {}, committed {}", - shown.tile_count(), - surface(&s).tile_count() - ); - } + let depth = [8, 16, 32][(mi + ei) % 3]; + let mut s = setup(mode, depth); + subset(&mut s); + let before = surface(&s); + let mut p = json!({"points":[[6,7,1],[23,15,0.7]],"size":9,"color":"#ffffff","erase":erase,"seed":42}); + let live = LiveStroke::begin(&s, &p).unwrap(); + p["seed"] = json!(live.seed); + let st = s.active().unwrap(); + let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); + unchanged(&before, &shown); + s.offer_live_stroke(live).unwrap(); + let result = s.execute("paint.stroke", p).unwrap(); + assert_eq!(result["fromLive"], true, "reuse {mode} {depth} {erase}"); + assert!( + surface(&s) == shown, + "live pixels differ: {mode} {depth} {erase}; shown tiles {}, committed {}", + shown.tile_count(), + surface(&s).tile_count() + ); } } } @@ -191,33 +189,31 @@ fn live_mixer_captures_selected_components_and_matches_commit_and_replay() { // The mixer is generic over mode and depth: one case per mode, each at a different depth. for (mode, depth) in [("rgb", 8), ("cmyk", 16), ("lab", 32)] { - { - let mut s = setup(mode, depth); - subset(&mut s); - let before = surface(&s); - let params = json!({"points":[[6,7,1]],"size":9,"color":"#ffffff","seed":42,"sampleAllLayers":true}); - let mut live = LiveMixer::begin(&s, ¶ms).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - let first = live.doc.layer(id).unwrap().surface().unwrap(); - unchanged(&before, first); - assert_ne!(&before, first, "the initial dab paints {mode} {depth}"); - live.push(&[StrokePoint::new(23.0, 15.0, 0.7)]).unwrap(); - let shown = live.doc.layer(id).unwrap().surface().unwrap().clone(); - unchanged(&before, &shown); - // The in-flight stroke keeps its original target even if the panel changes. - s.execute("channel.target", json!({"channel":"composite"})).unwrap(); - let params = live.prepare_commit(&mut s).unwrap(); - assert_eq!(params["target"], json!({"colors":[0,2]})); - assert_eq!(s.execute("paint.mixerBrush", params.clone()).unwrap()["fromLive"], true); - assert_eq!(surface(&s), shown, "displayed pixels are committed {mode} {depth}"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(surface(&s), before); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(surface(&s), shown); - let mut replay = setup(mode, depth); - replay.execute("paint.mixerBrush", params).unwrap(); - assert_eq!(surface(&replay), shown, "replay matches {mode} {depth}"); - } + let mut s = setup(mode, depth); + subset(&mut s); + let before = surface(&s); + let params = json!({"points":[[6,7,1]],"size":9,"color":"#ffffff","seed":42,"sampleAllLayers":true}); + let mut live = LiveMixer::begin(&s, ¶ms).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let first = live.doc.layer(id).unwrap().surface().unwrap(); + unchanged(&before, first); + assert_ne!(&before, first, "the initial dab paints {mode} {depth}"); + live.push(&[StrokePoint::new(23.0, 15.0, 0.7)]).unwrap(); + let shown = live.doc.layer(id).unwrap().surface().unwrap().clone(); + unchanged(&before, &shown); + // The in-flight stroke keeps its original target even if the panel changes. + s.execute("channel.target", json!({"channel":"composite"})).unwrap(); + let params = live.prepare_commit(&mut s).unwrap(); + assert_eq!(params["target"], json!({"colors":[0,2]})); + assert_eq!(s.execute("paint.mixerBrush", params.clone()).unwrap()["fromLive"], true); + assert_eq!(surface(&s), shown, "displayed pixels are committed {mode} {depth}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(surface(&s), before); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(surface(&s), shown); + let mut replay = setup(mode, depth); + replay.execute("paint.mixerBrush", params).unwrap(); + assert_eq!(surface(&replay), shown, "replay matches {mode} {depth}"); } } @@ -273,35 +269,31 @@ fn live_retouching_matches_direct_replay_and_preserves_unselected_bytes() { ("rgb", 8, "paint.cloneStamp"), ]; for (mode, depth, cmd) in cases { - { - { - let mut s = setup(mode, depth); - subset(&mut s); - let original = surface(&s); - let p = json!({"points":[[6,7,1],[23,15,0.7]],"size":9,"source":[2,2]}); - let shown = if matches!(cmd, "paint.cloneStamp" | "paint.historyBrush") { - let live = photocraft_engine::retouch_cmds::LiveRetouch::begin(&s, cmd, &p).unwrap(); - let st = s.active().unwrap(); - let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); - s.offer_live_retouch(live).unwrap(); - shown - } else { - let live = photocraft_engine::retouch_cmds::LiveDab::begin(&s, cmd, &p).unwrap(); - let st = s.active().unwrap(); - let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); - s.offer_live_dab(live).unwrap(); - shown - }; - unchanged(&original, &shown); - s.execute(cmd, p.clone()).unwrap(); - let committed = surface(&s); - unchanged(&original, &committed); - let mut replay = setup(mode, depth); - subset(&mut replay); - replay.execute(cmd, p).unwrap(); - assert!(committed == surface(&replay), "{mode} {depth} {cmd}: live reuse differs from replay"); - } - } + let mut s = setup(mode, depth); + subset(&mut s); + let original = surface(&s); + let p = json!({"points":[[6,7,1],[23,15,0.7]],"size":9,"source":[2,2]}); + let shown = if matches!(cmd, "paint.cloneStamp" | "paint.historyBrush") { + let live = photocraft_engine::retouch_cmds::LiveRetouch::begin(&s, cmd, &p).unwrap(); + let st = s.active().unwrap(); + let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); + s.offer_live_retouch(live).unwrap(); + shown + } else { + let live = photocraft_engine::retouch_cmds::LiveDab::begin(&s, cmd, &p).unwrap(); + let st = s.active().unwrap(); + let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); + s.offer_live_dab(live).unwrap(); + shown + }; + unchanged(&original, &shown); + s.execute(cmd, p.clone()).unwrap(); + let committed = surface(&s); + unchanged(&original, &committed); + let mut replay = setup(mode, depth); + subset(&mut replay); + replay.execute(cmd, p).unwrap(); + assert!(committed == surface(&replay), "{mode} {depth} {cmd}: live reuse differs from replay"); } } @@ -651,30 +643,28 @@ fn cmyk_grayscale_clips_roundtrip_explicit_and_limited_paste_at_every_depth() { // Depth (command + explicit copy) % 3: each depth, command and copy kind pairs with the others. for (ci, command) in ["edit.paste", "edit.pasteSpecial.pasteInto", "edit.pasteSpecial.pasteOutside"].into_iter().enumerate() { for (ei, explicit_copy) in [false, true].into_iter().enumerate() { - { - let depth = [8, 16, 32][(ci + ei) % 3]; - let mut s = setup("cmyk", depth); - s.execute("channel.target", json!({"channel":{"color":0}})).unwrap(); - let before = surface(&s); - s.execute("edit.copy", if explicit_copy { json!({"target":{"color":0}}) } else { json!({}) }).unwrap(); - s.edit("clear cyan", |doc, id| { - let surf = doc.layer_mut(id.unwrap()).unwrap().surface_mut().unwrap(); - let mut raw = surf.read_region(Rect::new(0, 0, 32, 24)); - for p in raw.as_chunks_mut::<5>().0 { - p[0] = 0.93; - } - surf.write_region(Rect::new(0, 0, 32, 24), &raw); - Ok(()) - }) - .unwrap(); - if command != "edit.paste" { - s.execute("select.rect", json!({"x":0,"y":0,"width":16,"height":24})).unwrap(); + let depth = [8, 16, 32][(ci + ei) % 3]; + let mut s = setup("cmyk", depth); + s.execute("channel.target", json!({"channel":{"color":0}})).unwrap(); + let before = surface(&s); + s.execute("edit.copy", if explicit_copy { json!({"target":{"color":0}}) } else { json!({}) }).unwrap(); + s.edit("clear cyan", |doc, id| { + let surf = doc.layer_mut(id.unwrap()).unwrap().surface_mut().unwrap(); + let mut raw = surf.read_region(Rect::new(0, 0, 32, 24)); + for p in raw.as_chunks_mut::<5>().0 { + p[0] = 0.93; } - s.execute(command, json!({"target":{"color":0},"center":[16,12]})).unwrap(); - let after = surface(&s); - let x = if command.ends_with("pasteOutside") { 20 } else { 4 }; - assert!((before.pixel(x, 8)[0] - after.pixel(x, 8)[0]).abs() < 2.0 / 255.0, "{depth} {explicit_copy} {command}"); + surf.write_region(Rect::new(0, 0, 32, 24), &raw); + Ok(()) + }) + .unwrap(); + if command != "edit.paste" { + s.execute("select.rect", json!({"x":0,"y":0,"width":16,"height":24})).unwrap(); } + s.execute(command, json!({"target":{"color":0},"center":[16,12]})).unwrap(); + let after = surface(&s); + let x = if command.ends_with("pasteOutside") { 20 } else { 4 }; + assert!((before.pixel(x, 8)[0] - after.pixel(x, 8)[0]).abs() < 2.0 / 255.0, "{depth} {explicit_copy} {command}"); } } } @@ -1266,22 +1256,18 @@ fn colour_adjustments_keep_the_original_cross_component_inputs() { ("rgb", 16, "image.adjustments.colorBalance", json!({"midtones":[20,-10,30]})), ]; for (mode, depth, cmd, params) in cases { - { - { - let mut control = setup(mode, depth); - let before = surface(&control); - control.execute(cmd, params.clone()).unwrap(); - let composite = surface(&control); - for indices in [vec![0], vec![0, 2]] { - let mut s = setup(mode, depth); - s.execute("channel.target", json!({"colors":indices})).unwrap(); - s.execute(cmd, params.clone()).unwrap(); - let mut expected = composite.clone(); - let colors = color_channels::ColorChannels::from_indices(indices, before.format().mode.color_channels()).unwrap(); - color_channels::restrict_surface(&before, &mut expected, colors).unwrap(); - assert!(surface(&s) == expected, "{mode} {depth} {cmd}"); - } - } + let mut control = setup(mode, depth); + let before = surface(&control); + control.execute(cmd, params.clone()).unwrap(); + let composite = surface(&control); + for indices in [vec![0], vec![0, 2]] { + let mut s = setup(mode, depth); + s.execute("channel.target", json!({"colors":indices})).unwrap(); + s.execute(cmd, params.clone()).unwrap(); + let mut expected = composite.clone(); + let colors = color_channels::ColorChannels::from_indices(indices, before.format().mode.color_channels()).unwrap(); + color_channels::restrict_surface(&before, &mut expected, colors).unwrap(); + assert!(surface(&s) == expected, "{mode} {depth} {cmd}"); } } } @@ -1430,30 +1416,24 @@ fn desaturate_honours_explicit_native_targets_over_the_panel_selection() { // Depth (mode + target) % 3: each mode and each target appears at every depth. for (mi, mode) in ["rgb", "cmyk", "lab"].into_iter().enumerate() { for (ti, target) in [json!({"color":1}), json!({"colors":[1]}), json!("pixels")].into_iter().enumerate() { - { - let depth = [8, 16, 32][(mi + ti) % 3]; - let mut s = setup(mode, depth); - let before = surface(&s); - let mut control = Session::new(); - let st = s.active().unwrap(); - control.add_document((*st.doc).clone(), None); - control.select_layer(st.active_layer.unwrap()).unwrap(); - control.execute("image.adjustments.desaturate", json!({})).unwrap(); - let expected = surface(&control); - subset(&mut s); - s.execute("image.adjustments.desaturate", json!({"target":target})).unwrap(); - let actual = surface(&s); - assert_ne!(actual, before, "{mode}@{depth} {target}"); - for y in 0..24 { - for x in 0..32 { - for k in 0..actual.channels() { - let want = if target == "pixels" || k == 1 { &expected } else { &before }; - assert_eq!( - actual.sample_channel(x, y, k).to_bits(), - want.sample_channel(x, y, k).to_bits(), - "{mode}@{depth} {target} component {k}" - ); - } + let depth = [8, 16, 32][(mi + ti) % 3]; + let mut s = setup(mode, depth); + let before = surface(&s); + let mut control = Session::new(); + let st = s.active().unwrap(); + control.add_document((*st.doc).clone(), None); + control.select_layer(st.active_layer.unwrap()).unwrap(); + control.execute("image.adjustments.desaturate", json!({})).unwrap(); + let expected = surface(&control); + subset(&mut s); + s.execute("image.adjustments.desaturate", json!({"target":target})).unwrap(); + let actual = surface(&s); + assert_ne!(actual, before, "{mode}@{depth} {target}"); + for y in 0..24 { + for x in 0..32 { + for k in 0..actual.channels() { + let want = if target == "pixels" || k == 1 { &expected } else { &before }; + assert_eq!(actual.sample_channel(x, y, k).to_bits(), want.sample_channel(x, y, k).to_bits(), "{mode}@{depth} {target} component {k}"); } } } @@ -1467,41 +1447,37 @@ fn mask_view_routes_implicit_edits_and_tone_editors_to_the_mask_before_colour_se // colour sets across the cases. for (mi, mode) in ["rgb", "cmyk", "lab"].into_iter().enumerate() { for (vi, view) in ["gray", "overlay"].into_iter().enumerate() { - { - { - let depth = [8, 16, 32][(mi + vi) % 3]; - let colors = [vec![0], vec![0, 2]][(mi + vi) % 2].clone(); - let mut s = setup(mode, depth); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("channel.target", json!({"colors":colors})).unwrap(); - s.execute("view.layerMask", json!({"mode":view})).unwrap(); - let before = surface(&s); - let st = s.active().unwrap(); - let layer = st.active_layer.unwrap(); - let descriptor = photocraft_engine::channel_cmds::isolated_curve_channel(st).unwrap(); - assert_eq!(descriptor.gray, Some(photocraft_engine::channel_cmds::GraySurface::LayerMask)); - assert!(descriptor.components.is_none()); - s.execute("image.adjustments.invert", json!({})).unwrap(); - assert_eq!(surface(&s), before); - let mask = |s: &Session| s.active().unwrap().doc.layer(layer).unwrap().mask.as_ref().unwrap().surface.clone(); - assert_eq!(mask(&s).sample_channel(8, 8, 0), 0.0); - s.execute("paint.stroke", json!({"points":[[8,8]],"size":6,"hardness":1.0,"color":"#ffffff"})).unwrap(); - assert!(mask(&s).sample_channel(8, 8, 0) > 0.9); - s.execute("filter.blur.gaussianBlur", json!({"radius":2})).unwrap(); - s.execute("image.adjustments.desaturate", json!({})).unwrap(); - assert_eq!(surface(&s), before); - let mask_before = mask(&s); - // An explicit native target can still override the viewed mask. - s.execute("image.adjustments.invert", json!({"target":{"colors":colors}})).unwrap(); - assert_ne!(surface(&s), before); - assert_eq!(mask(&s), mask_before); - s.execute("channel.target", json!({"colors":colors})).unwrap(); - assert!(photocraft_engine::mask_view_cmds::current(s.active().unwrap()).is_none(), "selecting colours leaves mask view"); - s.execute("view.layerMask", json!({"mode":view})).unwrap(); - s.execute("channel.target", json!({"channel":"composite"})).unwrap(); - assert!(photocraft_engine::mask_view_cmds::current(s.active().unwrap()).is_none(), "selecting the composite leaves mask view"); - } - } + let depth = [8, 16, 32][(mi + vi) % 3]; + let colors = [vec![0], vec![0, 2]][(mi + vi) % 2].clone(); + let mut s = setup(mode, depth); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("channel.target", json!({"colors":colors})).unwrap(); + s.execute("view.layerMask", json!({"mode":view})).unwrap(); + let before = surface(&s); + let st = s.active().unwrap(); + let layer = st.active_layer.unwrap(); + let descriptor = photocraft_engine::channel_cmds::isolated_curve_channel(st).unwrap(); + assert_eq!(descriptor.gray, Some(photocraft_engine::channel_cmds::GraySurface::LayerMask)); + assert!(descriptor.components.is_none()); + s.execute("image.adjustments.invert", json!({})).unwrap(); + assert_eq!(surface(&s), before); + let mask = |s: &Session| s.active().unwrap().doc.layer(layer).unwrap().mask.as_ref().unwrap().surface.clone(); + assert_eq!(mask(&s).sample_channel(8, 8, 0), 0.0); + s.execute("paint.stroke", json!({"points":[[8,8]],"size":6,"hardness":1.0,"color":"#ffffff"})).unwrap(); + assert!(mask(&s).sample_channel(8, 8, 0) > 0.9); + s.execute("filter.blur.gaussianBlur", json!({"radius":2})).unwrap(); + s.execute("image.adjustments.desaturate", json!({})).unwrap(); + assert_eq!(surface(&s), before); + let mask_before = mask(&s); + // An explicit native target can still override the viewed mask. + s.execute("image.adjustments.invert", json!({"target":{"colors":colors}})).unwrap(); + assert_ne!(surface(&s), before); + assert_eq!(mask(&s), mask_before); + s.execute("channel.target", json!({"colors":colors})).unwrap(); + assert!(photocraft_engine::mask_view_cmds::current(s.active().unwrap()).is_none(), "selecting colours leaves mask view"); + s.execute("view.layerMask", json!({"mode":view})).unwrap(); + s.execute("channel.target", json!({"channel":"composite"})).unwrap(); + assert!(photocraft_engine::mask_view_cmds::current(s.active().unwrap()).is_none(), "selecting the composite leaves mask view"); } } } diff --git a/crates/engine/tests/it/tone_target_picker.rs b/crates/engine/tests/it/tone_target_picker.rs index 54b5a19ca8..09e98e3501 100644 --- a/crates/engine/tests/it/tone_target_picker.rs +++ b/crates/engine/tests/it/tone_target_picker.rs @@ -48,36 +48,32 @@ fn native_gray_pickers_ignore_document_colour_and_preserve_other_data() { for (ti, target) in [json!("mask"), json!("quickMask"), json!({"channel":0})].into_iter().enumerate() { let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(mi + ti) % 3]; for (ki, kind) in ["levels", "curves"].into_iter().enumerate() { - { - { - let point = ["black", "white"][(mi + ti + ki) % 2]; - let mut s = session(mode, depth); - let before = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - let p = json!({"target":target,"eyedropper":{"point":point,"at":[8,8],"size":3}}); - s.execute(&format!("image.adjustments.{kind}"), p).unwrap(); - let after = s.active().unwrap().doc.clone(); - let expected = if point == "white" { 1.0 } else { 0.0 }; - let actual = plane(&after, &target).sample_channel(8, 8, 0); - assert!((actual - expected).abs() < 0.01, "{mode:?} {depth:?} {target} {kind} {point}: {actual}"); - assert_eq!(before.layers[0].content, after.layers[0].content, "colour pixels and transparency"); - if target != json!("mask") { - assert_eq!(before.layers[0].mask, after.layers[0].mask); - } - if target != json!("quickMask") { - assert_eq!(before.quick_mask, after.quick_mask); - } - if target != json!({"channel":0}) { - assert_eq!(before.channels, after.channels); - } - assert_eq!(before.channels[0].spot, after.channels[0].spot); - assert_eq!(s.active().unwrap().history.past_len(), history + 1); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(plane(&s.active().unwrap().doc, &target), plane(&before, &target)); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(plane(&s.active().unwrap().doc, &target), plane(&after, &target)); - } + let point = ["black", "white"][(mi + ti + ki) % 2]; + let mut s = session(mode, depth); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let p = json!({"target":target,"eyedropper":{"point":point,"at":[8,8],"size":3}}); + s.execute(&format!("image.adjustments.{kind}"), p).unwrap(); + let after = s.active().unwrap().doc.clone(); + let expected = if point == "white" { 1.0 } else { 0.0 }; + let actual = plane(&after, &target).sample_channel(8, 8, 0); + assert!((actual - expected).abs() < 0.01, "{mode:?} {depth:?} {target} {kind} {point}: {actual}"); + assert_eq!(before.layers[0].content, after.layers[0].content, "colour pixels and transparency"); + if target != json!("mask") { + assert_eq!(before.layers[0].mask, after.layers[0].mask); } + if target != json!("quickMask") { + assert_eq!(before.quick_mask, after.quick_mask); + } + if target != json!({"channel":0}) { + assert_eq!(before.channels, after.channels); + } + assert_eq!(before.channels[0].spot, after.channels[0].spot); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(plane(&s.active().unwrap().doc, &target), plane(&before, &target)); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(plane(&s.active().unwrap().doc, &target), plane(&after, &target)); } } } @@ -247,74 +243,65 @@ fn gray_tone_records_do_not_leak_from_rgb_channels() { // Each style runs one (sampled, explicit) pair, rotating with (2 * mode + target + style): every style sees // all four flag pairs across the cases, and at every depth it sees both sampled and both explicit values. for (si, style) in ["levels", "points", "pencil"].into_iter().enumerate() { - { - { - let (sampled, explicit) = [(false, false), (false, true), (true, false), (true, true)][(2 * mi + ti + si) % 4]; - { - let mut clean = session(mode, depth); - clean.active_mut().unwrap().channel_view.target = panel; - clean - .edit("Vary gray samples", |doc, _| { - let patch = Rect::from_xywh(4, 4, 1, 1); - doc.layers[0].mask.as_mut().unwrap().surface.fill_rect(patch, &[0.125]); - doc.channels[0].surface.fill_rect(patch, &[0.125]); - doc.quick_mask.as_mut().unwrap().surface.fill_rect(patch, &[0.125]); - Ok(()) - }) - .unwrap(); - let before = clean.active().unwrap().doc.clone(); - let layer = clean.active().unwrap().active_layer.unwrap(); - let mut dirty = Session::new(); - dirty.add_document((*before).clone(), None); - dirty.select_layer(layer).unwrap(); - dirty.active_mut().unwrap().channel_view.target = panel; - let kind = if style == "levels" { "levels" } else { "curves" }; - let mut params = if kind == "levels" { json!({"gamma":2}) } else { json!({"points":[[0,255],[255,0]],"pencil":style == "pencil"}) }; - if explicit { - params["target"] = target.clone(); - } - if sampled { - params["eyedropper"] = json!({"point":"white","at":[8,8]}); - } - let mut contaminated = params.clone(); - for key in ["red", "green", "blue"] { - contaminated[key] = if kind == "levels" { - json!({"gamma":4}) - } else if style == "pencil" { - json!(vec![255; 256]) - } else { - json!([[0, 255], [255, 255]]) - }; - } - let command = format!("image.adjustments.{kind}"); - clean.execute(&command, params).unwrap(); - dirty.execute(&command, contaminated).unwrap(); - let expected = &clean.active().unwrap().doc; - let actual = &dirty.active().unwrap().doc; - assert!(plane(expected, &target) != plane(&before, &target), "the scalar adjustment really edits the plane"); - assert_eq!( - plane(actual, &target).sample_channel(4, 4, 0), - plane(expected, &target).sample_channel(4, 4, 0), - "{mode:?} {depth:?} {target} {style} sampled={sampled} explicit={explicit}" - ); - assert!( - plane(actual, &target) == plane(expected, &target), - "{mode:?} {depth:?} {target} {style} sampled={sampled} explicit={explicit}" - ); - assert_eq!(actual.layers[0].content, before.layers[0].content); - if target != json!("mask") { - assert_eq!(actual.layers[0].mask, before.layers[0].mask); - } - if target != json!("quickMask") { - assert_eq!(actual.quick_mask, before.quick_mask); - } - if target != json!({"channel":0}) { - assert_eq!(actual.channels, before.channels); - } - assert_eq!(actual.channels[0].spot, before.channels[0].spot); - } - } + let (sampled, explicit) = [(false, false), (false, true), (true, false), (true, true)][(2 * mi + ti + si) % 4]; + let mut clean = session(mode, depth); + clean.active_mut().unwrap().channel_view.target = panel; + clean + .edit("Vary gray samples", |doc, _| { + let patch = Rect::from_xywh(4, 4, 1, 1); + doc.layers[0].mask.as_mut().unwrap().surface.fill_rect(patch, &[0.125]); + doc.channels[0].surface.fill_rect(patch, &[0.125]); + doc.quick_mask.as_mut().unwrap().surface.fill_rect(patch, &[0.125]); + Ok(()) + }) + .unwrap(); + let before = clean.active().unwrap().doc.clone(); + let layer = clean.active().unwrap().active_layer.unwrap(); + let mut dirty = Session::new(); + dirty.add_document((*before).clone(), None); + dirty.select_layer(layer).unwrap(); + dirty.active_mut().unwrap().channel_view.target = panel; + let kind = if style == "levels" { "levels" } else { "curves" }; + let mut params = if kind == "levels" { json!({"gamma":2}) } else { json!({"points":[[0,255],[255,0]],"pencil":style == "pencil"}) }; + if explicit { + params["target"] = target.clone(); } + if sampled { + params["eyedropper"] = json!({"point":"white","at":[8,8]}); + } + let mut contaminated = params.clone(); + for key in ["red", "green", "blue"] { + contaminated[key] = if kind == "levels" { + json!({"gamma":4}) + } else if style == "pencil" { + json!(vec![255; 256]) + } else { + json!([[0, 255], [255, 255]]) + }; + } + let command = format!("image.adjustments.{kind}"); + clean.execute(&command, params).unwrap(); + dirty.execute(&command, contaminated).unwrap(); + let expected = &clean.active().unwrap().doc; + let actual = &dirty.active().unwrap().doc; + assert!(plane(expected, &target) != plane(&before, &target), "the scalar adjustment really edits the plane"); + assert_eq!( + plane(actual, &target).sample_channel(4, 4, 0), + plane(expected, &target).sample_channel(4, 4, 0), + "{mode:?} {depth:?} {target} {style} sampled={sampled} explicit={explicit}" + ); + assert!(plane(actual, &target) == plane(expected, &target), "{mode:?} {depth:?} {target} {style} sampled={sampled} explicit={explicit}"); + assert_eq!(actual.layers[0].content, before.layers[0].content); + if target != json!("mask") { + assert_eq!(actual.layers[0].mask, before.layers[0].mask); + } + if target != json!("quickMask") { + assert_eq!(actual.quick_mask, before.quick_mask); + } + if target != json!({"channel":0}) { + assert_eq!(actual.channels, before.channels); + } + assert_eq!(actual.channels[0].spot, before.channels[0].spot); } } } @@ -401,47 +388,45 @@ fn filter_mask_picker_samples_and_edits_only_the_filter_mask() { for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() { for (si, stored) in [false, true].into_iter().enumerate() { for (ki, kind) in ["levels", "curves"].into_iter().enumerate() { - { - let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(mi + si + ki) % 3]; - let case = format!("{mode:?} {depth:?} stored={stored} {kind}"); - let mut s = session(mode, depth); - // A Smart Filter needs the composite selected, not one colour channel, and no Quick Mask (the filter - // would edit the Quick Mask instead). - s.edit("No Quick Mask", |doc, _| { - doc.quick_mask = None; - Ok(()) - }) - .unwrap(); - s.active_mut().unwrap().channel_view.target = ChannelTarget::Composite; - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("filter.blur.gaussianBlur", json!({"radius": 1})).unwrap(); - if stored { - s.execute("edit.fill", json!({"target": "filterMask", "contents": "color", "color": "#404040"})).unwrap(); - } - let id = s.active().unwrap().active_layer.unwrap(); - let before = s.active().unwrap().doc.clone(); - let p = json!({"target": "filterMask", "eyedropper": {"point": "white", "at": [8, 8]}}); - let picked = adjust_params::destructive_eyedropper(&s, kind, &p).unwrap().unwrap(); - assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "sampling is read-only: {case}"); - let white = if stored { 64.0 } else { 255.0 }; - let sampled = if kind == "levels" { - adjust_params::to_params(&picked)["inWhite"].as_f64().unwrap() - } else { - adjust_params::to_params(&picked)["points"].as_array().unwrap().last().unwrap()[0].as_f64().unwrap() - }; - assert!((sampled - white).abs() < 1.0, "{case}: sampled {sampled}, want {white}"); - s.execute(&format!("image.adjustments.{kind}"), p).unwrap(); - let doc = &s.active().unwrap().doc; - let (LayerContent::Smart(old), LayerContent::Smart(new)) = (&before.layer(id).unwrap().content, &doc.layer(id).unwrap().content) else { - panic!("{case}: not a smart object") - }; - assert!(new.filter_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0) > 0.99, "{case}"); - assert_eq!(new.smart_filters, old.smart_filters, "{case}: the adjustment edits the mask, adds no filter"); - assert_eq!(new.source, old.source, "{case}"); - assert_eq!(doc.layer(id).unwrap().mask, before.layer(id).unwrap().mask, "{case}: the layer mask"); - assert_eq!(doc.channels, before.channels, "{case}"); - assert_eq!(doc.quick_mask, before.quick_mask, "{case}"); + let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(mi + si + ki) % 3]; + let case = format!("{mode:?} {depth:?} stored={stored} {kind}"); + let mut s = session(mode, depth); + // A Smart Filter needs the composite selected, not one colour channel, and no Quick Mask (the filter + // would edit the Quick Mask instead). + s.edit("No Quick Mask", |doc, _| { + doc.quick_mask = None; + Ok(()) + }) + .unwrap(); + s.active_mut().unwrap().channel_view.target = ChannelTarget::Composite; + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 1})).unwrap(); + if stored { + s.execute("edit.fill", json!({"target": "filterMask", "contents": "color", "color": "#404040"})).unwrap(); } + let id = s.active().unwrap().active_layer.unwrap(); + let before = s.active().unwrap().doc.clone(); + let p = json!({"target": "filterMask", "eyedropper": {"point": "white", "at": [8, 8]}}); + let picked = adjust_params::destructive_eyedropper(&s, kind, &p).unwrap().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "sampling is read-only: {case}"); + let white = if stored { 64.0 } else { 255.0 }; + let sampled = if kind == "levels" { + adjust_params::to_params(&picked)["inWhite"].as_f64().unwrap() + } else { + adjust_params::to_params(&picked)["points"].as_array().unwrap().last().unwrap()[0].as_f64().unwrap() + }; + assert!((sampled - white).abs() < 1.0, "{case}: sampled {sampled}, want {white}"); + s.execute(&format!("image.adjustments.{kind}"), p).unwrap(); + let doc = &s.active().unwrap().doc; + let (LayerContent::Smart(old), LayerContent::Smart(new)) = (&before.layer(id).unwrap().content, &doc.layer(id).unwrap().content) else { + panic!("{case}: not a smart object") + }; + assert!(new.filter_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0) > 0.99, "{case}"); + assert_eq!(new.smart_filters, old.smart_filters, "{case}: the adjustment edits the mask, adds no filter"); + assert_eq!(new.source, old.source, "{case}"); + assert_eq!(doc.layer(id).unwrap().mask, before.layer(id).unwrap().mask, "{case}: the layer mask"); + assert_eq!(doc.channels, before.channels, "{case}"); + assert_eq!(doc.quick_mask, before.quick_mask, "{case}"); } } } From 09230a914f1ba7b5c5eeff50855ecea1ebc73bbf Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 20 Nov 2026 18:36:05 +0530 Subject: [PATCH 090/136] Tests: rotate the tone adjustments across sample types in the fused oracle test (#15932) Each adjustment runs once per mode and once per sample type instead of at every pair, which cuts the scalar-oracle calls to a third. --- crates/engine/src/color_channels/tone.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/color_channels/tone.rs b/crates/engine/src/color_channels/tone.rs index 3e96aa4965..06618da39a 100644 --- a/crates/engine/src/color_channels/tone.rs +++ b/crates/engine/src/color_channels/tone.rs @@ -304,7 +304,12 @@ mod tests { if ti != (mi + si) % 3 && !(mode == ColorMode::Rgb && sample == SampleType::U16 && selection.is_none()) { continue; } - for adjustment in &adjustments { + // Each adjustment meets every mode once and every sample type once: Invert at Lab/F32 (`lab_invert`), + // Threshold at RGB/U16 and Posterize at Lab/U16 (the U16 `depth`), Levels and Curves at U16 (table). + for (ai, adjustment) in adjustments.iter().enumerate() { + if (ai + mi) % 3 != si { + continue; + } let mut expected = source.clone(); let mut actual = source.clone(); super::super::adjust_reference(&mut expected, colors, adjustment, selection, bounds).unwrap(); From 5da6827fb2129a86a1883c61b0e84cfe2b1de1b7 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 21 Nov 2026 02:51:20 +0100 Subject: [PATCH 091/136] test(gpu): pay one CPU reference and one render set per parity check The 77 GPU parity tests render the CPU reference and both compositors per check; several tests then rendered the same document again for a ramp or a Stats field, and several documents were far larger than the branches they drive. `diff_rect_full` keeps one pass's pixels and stats so no test renders a document it just compared a second time; the oversized documents shrink to the smallest size that still crosses the 256 px tiles and pages they are about, and the gated Inner Shadow rows compare over the shape instead of the whole 400 x 300 canvas. No branch is dropped: every assertion, tolerance and check count stays, the big-document tests keep their measured documents, and the issue's two mutation checks plus a tile-share mutation still fail against this harness. --- crates/gpu/tests/it/parity.rs | 199 ++++++++++++++++++++++------------ 1 file changed, 128 insertions(+), 71 deletions(-) diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 7dcf5b4ee6..67d100f6ba 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -214,12 +214,25 @@ fn worst_diff(cpu: &[[f32; 4]], gpu: &[[f32; 4]]) -> (f32, usize) { worst } -/// GPU (whole textures, then pages) vs CPU over `rect`: Err with the worst pixel if over the -/// tolerance, else the stats of the unpaged render. -fn diff_rect(g: &mut Gpu, doc: &Document, rect: Rect, what: &str) -> Result { +/// One `diff_rect` pass, kept: the whole-texture compositor's pixels and stats and the paged +/// pass's stats. The CPU reference is computed once and both GPU renders are compared with it; +/// a test that also wants the whole-texture pixels (a measured ramp) or the paged pass's stats +/// (a cell count) reuses them from here instead of paying for a second render of the same +/// document. +struct Diff { + /// The whole-texture compositor's pixels and stats from the pass that checked them. + whole: Vec<[f32; 4]>, + whole_stats: photocraft_gpu::Stats, + paged_stats: photocraft_gpu::Stats, +} + +/// GPU (whole textures, then pages) vs CPU over `rect`, with what a follow-up assert needs: +/// Err with the worst pixel if over the tolerance. +fn diff_rect_full(g: &mut Gpu, doc: &Document, rect: Rect, what: &str) -> Result { let cpu = timed("CPU reference", || photocraft_compose::render(doc, rect)); - let mut first = None; - for (label, comp) in [("", &mut g.comp), (" (paged)", &mut g.paged)] { + let mut whole = None; + let mut paged = None; + for (label, comp, slot) in [("", &mut g.comp, &mut whole), (" (paged)", &mut g.paged, &mut paged)] { let (out, stats) = timed(&format!("{what}{label} GPU render/readback"), || photocraft_gpu::render_to_vec_stats(comp, &g.device, &g.queue, doc, rect)) .map_err(|e| format!("{what}{label}: {e}"))?; let worst = worst_diff(&cpu.px, &out); @@ -228,15 +241,29 @@ fn diff_rect(g: &mut Gpu, doc: &Document, rect: Rect, what: &str) -> Result TOL { return Err(format!("{what}{label}: max diff {:.2}/255 at ({x},{y}): cpu {:?} gpu {:?}", worst.0 * 255.0, cpu.px[worst.1], out[worst.1])); } - first.get_or_insert(stats); + *slot = Some((out, stats)); } - first.ok_or_else(|| format!("{what}: no render")) + match (whole, paged) { + (Some((whole, whole_stats)), Some((_, paged_stats))) => Ok(Diff { whole, whole_stats, paged_stats }), + _ => Err(format!("{what}: no render")), + } +} + +/// GPU vs CPU over `rect`: Err with the worst pixel if over the tolerance, else the stats of +/// the unpaged render. +fn diff_rect(g: &mut Gpu, doc: &Document, rect: Rect, what: &str) -> Result { + diff_rect_full(g, doc, rect, what).map(|pass| pass.whole_stats) } fn check(g: &mut Gpu, doc: &Document, what: &str) { diff_rect(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}")); } +/// [`check`] returning the pass's pixels and stats, for tests that assert more than tolerance. +fn check_full(g: &mut Gpu, doc: &Document, what: &str) -> Diff { + diff_rect_full(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}")) +} + /// Growing a layer's tile footprint keeps the old texels in the overlap (`keep_overlap`) /// while the same update rewrites tiles inside that overlap (#6243): whatever submission /// shape the copy takes, the kept overlap must never overwrite tiles the same update @@ -311,12 +338,11 @@ fn stack_prefix_reuse_matches_uncached_gpu_and_cpu_at_every_depth() { top.fill_opacity = fill; top.blend = blend; top.visible = visible; - let stats = diff_rect(&mut g, &doc, doc.bounds(), "top properties").unwrap(); - assert!(stats.prefix_hits > 0, "{depth:?}"); - assert!(stats.prefix_passes_skipped > 0); - let cached = render_to_vec(&mut g.comp, &g.device, &g.queue, &doc, doc.bounds()).unwrap(); + let pass = diff_rect_full(&mut g, &doc, doc.bounds(), "top properties").unwrap(); + assert!(pass.whole_stats.prefix_hits > 0, "{depth:?}"); + assert!(pass.whole_stats.prefix_passes_skipped > 0); let cold = render_to_vec(&mut uncached, &g.device, &g.queue, &doc, doc.bounds()).unwrap(); - assert_eq!(cached, cold, "reuse preserves the GPU accumulator exactly"); + assert_eq!(pass.whole, cold, "reuse preserves the GPU accumulator exactly"); } let old = doc.clone(); doc.layers[1].surface_mut().unwrap().write_pixel(5, 5, &[0.8, 0.2, 0.6, 0.7]); @@ -349,18 +375,17 @@ fn prefix_follows_an_edit_up_the_stack_and_stays_exact() { doc.layers.push(if batched { l } else { alone(l) }); } let mut exact = |g: &mut Gpu, doc: &Document, what: &str| -> photocraft_gpu::Stats { - let stats = diff_rect(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}")); - let cached = render_to_vec(&mut g.comp, &g.device, &g.queue, doc, doc.bounds()).unwrap(); + let pass = diff_rect_full(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}")); let (cold, cold_stats) = photocraft_gpu::render_to_vec_stats(&mut uncached, &g.device, &g.queue, doc, doc.bounds()).unwrap(); - assert_eq!(cached, cold, "{depth:?} batched {batched} {what}: reuse preserves the GPU accumulator exactly"); + assert_eq!(pass.whole, cold, "{depth:?} batched {batched} {what}: reuse preserves the GPU accumulator exactly"); // Batched and single-layer draws needn't give the same bits on every backend (FXC // on D3D12): a render that captures the prefix groups the layers as an uncached one // does, wherever its checkpoint is. - if stats.prefix_hits == 0 { - assert_eq!(stats.layers_batched, cold_stats.layers_batched, "{depth:?} {what}: capturing changed the batches"); + if pass.whole_stats.prefix_hits == 0 { + assert_eq!(pass.whole_stats.layers_batched, cold_stats.layers_batched, "{depth:?} {what}: capturing changed the batches"); } assert_eq!(cold_stats.layers_batched > 0, batched, "{depth:?} {what}"); - stats + pass.whole_stats }; exact(&mut g, &doc, "populate"); // An edit low in the stack puts the cache there. @@ -473,20 +498,22 @@ fn root_checkpoints_keep_clipping_groups_and_adjustments_whole() { #[test] fn disjoint_partial_damages_admit_whole_chunks_not_damage_rects() { let Some(mut g) = gpu() else { return }; - let mut doc = base_doc(600, 300); + // 300 x 260 (#15927, was 600 x 300): still one 1024 px chunk, so whole-chunk admission is + // what keeps the two stroke series from growing the cache. + let mut doc = base_doc(300, 260); // Each layer in a pass of its own (`alone`): batched into one run, the stack has no // checkpoint below the top layer, so no render would capture and the byte count could not // grow whatever the admission did. doc.layers.push(alone(noise_layer("middle", PixelFormat::RGBA8, doc.bounds(), 2, 0.2))); doc.layers.push(alone(noise_layer("top", PixelFormat::RGBA8, doc.bounds(), 3, 0.2))); check(&mut g, &doc, "warm"); - // Each series paints 8 rectangles. The second series' rectangles are all new (7 px across - // and 65 px down from the first's) but in the same chunk (the 600 x 300 document is one + // Each series paints 8 rectangles. The second series' rectangles are all new (5 px across + // and 65 px down from the first's) but in the same chunk (the 300 x 260 document is one // chunk at `CHUNK`), so a cache entry per damage rectangle would add 8 entries. (The four // series of 24 this replaces painted the same 24 rectangles every time.) let strokes = |g: &mut Gpu, doc: &Document, pass: i32| { for i in 0..8 { - let (x, y) = (40 + i * 60 + pass * 7, 30 + pass * 65); + let (x, y) = (20 + i * 30 + pass * 5, 20 + pass * 65); diff_rect(g, doc, Rect::new(x, y, x + 40, y + 30), "stroke").unwrap(); } }; @@ -514,7 +541,9 @@ fn disjoint_partial_damages_admit_whole_chunks_not_damage_rects() { #[test] fn prefix_partial_damage_context_occlusion_and_budget_are_conservative() { let Some(mut g) = gpu() else { return }; - let mut doc = base_doc(600, 300); + // 300 x 260 (#15927, was 600 x 300): one 1024 px chunk either way; the damage rectangles + // keep their relation to the covered chunk and to the document edge. + let mut doc = base_doc(300, 260); doc.layers.push(alone(noise_layer("middle", PixelFormat::RGBA8, doc.bounds(), 2, 0.2))); doc.layers.push(alone(noise_layer("top", PixelFormat::RGBA8, doc.bounds(), 3, 0.2))); check(&mut g, &doc, "full prefix"); @@ -524,13 +553,13 @@ fn prefix_partial_damage_context_occlusion_and_budget_are_conservative() { let region = Rect::new(10, 10, 50, 45); doc.layers[2].opacity = 0.4; assert!(diff_rect(&mut g, &doc, region, "partial rectangle in a covered chunk").unwrap().prefix_hits > 0); - let outside = Rect::new(10, 310, 50, 345); + let outside = Rect::new(10, 260, 50, 290); assert_eq!(diff_rect(&mut g, &doc, outside, "outside the document").unwrap().prefix_hits, 0); doc.layers[2].opacity = 0.7; assert!(diff_rect(&mut g, &doc, region, "same partial rectangle").unwrap().prefix_hits > 0); - doc.layers[0].surface_mut().unwrap().write_pixel(550, 270, &[1.0, 0.0, 1.0, 0.9]); + doc.layers[0].surface_mut().unwrap().write_pixel(280, 245, &[1.0, 0.0, 1.0, 0.9]); check(&mut g, &doc, "offscreen lower edit"); - diff_rect(&mut g, &doc, Rect::new(500, 250, 580, 290), "disjoint damage after invalidation").unwrap(); + diff_rect(&mut g, &doc, Rect::new(240, 210, 290, 250), "disjoint damage after invalidation").unwrap(); doc.global_light.angle += 15.0; assert_eq!(diff_rect(&mut g, &doc, doc.bounds(), "global context").unwrap().prefix_hits, 0); doc.layers.push(Layer::new("opaque cover", LayerContent::Fill(Fill::Solid(Color::WHITE)))); @@ -1191,8 +1220,10 @@ fn formats_offsets_and_chunks() { #[test] fn incremental_updates_follow_the_document() { let Some(mut g) = gpu() else { return }; - let mut d = base_doc(600, 300); - d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 600, 300), 61, 0.0)); + // 300 x 260 (#15927, was 600 x 300): the painted area is still one 256 px tile at the same + // corner; upload bookkeeping is per tile. + let mut d = base_doc(300, 260); + d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 300, 260), 61, 0.0)); check(&mut g, &d, "initial"); // Paint into one tile of the top layer: only that tile uploads. let top = d.layers[1].surface_mut().unwrap(); @@ -1214,8 +1245,10 @@ fn incremental_updates_follow_the_document() { #[test] fn duplicates_copy_their_source_texture() { let Some(mut g) = gpu() else { return }; - let mut d = base_doc(600, 300); - let mut src = noise_layer("src", PixelFormat::RGBA8, Rect::new(0, 0, 600, 300), 71, 0.0); + // 300 x 260 (#15927, was 600 x 300): four 256 px tiles with one absent from a duplicate — + // the copy and COW paths are per tile, and the two painted tiles stay distinct. + let mut d = base_doc(300, 260); + let mut src = noise_layer("src", PixelFormat::RGBA8, Rect::new(0, 0, 300, 260), 71, 0.0); src.opacity = 0.7; d.layers.push(src); check(&mut g, &d, "source"); @@ -1231,7 +1264,7 @@ fn duplicates_copy_their_source_texture() { dup2.blend = BlendMode::Screen; dup2.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 20, 20), &[1.0, 0.0, 0.0, 1.0]); d.layers.push(dup2); - d.layers[1].surface_mut().unwrap().fill_rect(Rect::new(300, 100, 310, 110), &[0.0, 0.0, 1.0, 1.0]); + d.layers[1].surface_mut().unwrap().fill_rect(Rect::new(260, 100, 270, 110), &[0.0, 0.0, 1.0, 1.0]); check(&mut g, &d, "duplicate and source painted"); // And a tile removed from a duplicate: it reads as transparent again. let mut dup3 = d.layers[1].duplicate(); @@ -1249,10 +1282,12 @@ fn duplicates_copy_their_source_texture() { #[test] fn changed_mask_default_updates_absent_tiles() { let Some(mut g) = gpu() else { return }; - let mut d = base_doc(600, 300); - d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 600, 300), 61, 0.5)); + // 300 x 260 (#15927, was 600 x 300): the opposite-corner tiles still span a 2 x 2 resident + // texture with two absent tiles between them. + let mut d = base_doc(300, 260); + d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 300, 260), 61, 0.5)); // Tiles in opposite corners: the resident texture spans the absent tiles between them. - let corners = [Rect::new(0, 0, 70, 70), Rect::new(530, 230, 600, 300)]; + let corners = [Rect::new(0, 0, 70, 70), Rect::new(230, 190, 300, 260)]; let data = vec![0.5f32; 70 * 70]; for default in [0.0, 1.0] { let mut m = LayerMask::reveal_all(); @@ -1271,7 +1306,10 @@ fn changed_mask_default_updates_absent_tiles() { #[test] fn shared_tiles_upload_once_and_copy() { let Some(mut g) = gpu() else { return }; - let (w, h) = (1100, 700); + // 540 x 540 (#15927, was 1100 x 700): a 3 x 3 grid of 256 px tiles and pages with full + // interior tiles and partial right/bottom ones — every branch here is per tile and page, + // not per document byte. + let (w, h) = (540, 540); for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAYA8 }] { let mut d = base_doc(w, h); let mut l = Layer::raster("fill", fmt); @@ -1309,32 +1347,35 @@ fn shared_tiles_upload_once_and_copy() { #[test] fn growing_layer_keeps_its_resident_tiles() { let Some(mut g) = gpu() else { return }; - let (w, h) = (1100, 700); + // 540 x 540 (#15927, was 1100 x 700): the layer footprint still grows past 256 px tiles in + // all five directions — right, down, towards the origin, inside, and far out — and stays + // within the same 2-tiles-uploaded bound per dab. + let (w, h) = (540, 540); for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA32F] { let mut d = base_doc(w, h); let mut l = Layer::raster("paint", fmt); - l.surface_mut().unwrap().fill_rect(Rect::new(500, 300, 540, 340), &[0.3, 0.6, 0.2, 0.9][..fmt.channels()]); + l.surface_mut().unwrap().fill_rect(Rect::new(260, 260, 300, 300), &[0.3, 0.6, 0.2, 0.9][..fmt.channels()]); let mut m = LayerMask::reveal_all(); m.surface = photocraft_raster::Surface::with_default(PixelFormat::GRAY8, &[0.75]); - m.surface.fill_rect(Rect::new(510, 310, 520, 320), &[0.25]); + m.surface.fill_rect(Rect::new(265, 265, 275, 275), &[0.25]); l.mask = Some(m); d.layers.push(l); check(&mut g, &d, &format!("{fmt:?} initial")); let small = d.clone(); // Dabs right (over a stored tile too, so it changes as the page grows), down, up-left // (the page grows towards the origin), inside, and far out. - for (i, r) in [(480, 320, 760, 380), (520, 560, 580, 620), (60, 40, 120, 100), (505, 305, 535, 335), (1040, 640, 1100, 700)].into_iter().enumerate() { + for (i, r) in [(280, 270, 540, 330), (300, 340, 360, 530), (40, 40, 100, 100), (265, 265, 295, 295), (516, 516, 540, 540)].into_iter().enumerate() { let dab = Rect::new(r.0, r.1, r.2, r.3); d.layers[1].surface_mut().unwrap().fill_rect(dab, &[0.9, 0.1, 0.3, 0.7][..fmt.channels()]); if i == 2 { d.layers[1].mask.as_mut().unwrap().surface.fill_rect(dab, &[0.5]); } let what = format!("{fmt:?} dab {i}"); - let s = diff_rect(&mut g, &d, d.bounds(), &what).unwrap_or_else(|e| panic!("{e}")); - assert!(s.tiles_uploaded <= 2, "{what}: only the dab's tiles upload: {s:?}"); + let pass = diff_rect_full(&mut g, &d, d.bounds(), &what).unwrap_or_else(|e| panic!("{e}")); + assert!(pass.whole_stats.tiles_uploaded <= 2, "{what}: only the dab's tiles upload: {:?}", pass.whole_stats); let mut fresh = g.comp.sibling(); let want = render_to_vec(&mut fresh, &g.device, &g.queue, &d, d.bounds()).unwrap(); - assert!(render_to_vec(&mut g.comp, &g.device, &g.queue, &d, d.bounds()).unwrap() == want, "{what}: same pixels as a fresh upload"); + assert!(pass.whole == want, "{what}: same pixels as a fresh upload"); } // Undo back to the small layer: the pages shrink and show its pixels again. check(&mut g, &small, &format!("{fmt:?} undone")); @@ -1420,8 +1461,9 @@ fn small_layers_composite_over_their_bounds() { pt.opacity = 0.6; d.layers.push(pt); check(&mut g, &d, "small layers"); - // The same over several compositor chunks. - let mut big = base_doc(1500, 1200); + // The same over several compositor chunks. 1080 x 1080 (#15927, was 1500 x 1200): still a + // 2 x 2 grid of 1024 px chunks, and the small layers still straddle the inner chunk border. + let mut big = base_doc(1080, 1080); for (i, mode) in BlendMode::layer_modes().enumerate() { let i = i as i32; big.layers.push(small(400 + i as u32, 1010 + (i % 4) * 5, 1010 + (i / 4) * 5, mode)); @@ -1467,17 +1509,19 @@ fn runs_of_plain_layers_blend_in_one_pass() { // bounds) and clipping groups. Then an edit in the middle, so the prefix cache resumes // part-way up the stack and runs start at its checkpoint. let Some(mut g) = gpu() else { return }; - let mut d = base_doc(96, 64); + // 48 x 32 (#15927, was 96 x 64): batching is decided per layer and per run, not per pixel + // count, and the layers that end inside the canvas still overhang its left edge. + let mut d = base_doc(48, 32); let modes: Vec = BlendMode::layer_modes().collect(); for (i, mode) in modes.iter().copied().cycle().take(90).enumerate() { let i32_ = i as i32; - let rect = if i % 5 == 2 { Rect::from_xywh(-8, 10, 70, 40) } else { Rect::from_xywh(0, 0, 96, 64) }; + let rect = if i % 5 == 2 { Rect::from_xywh(-4, 5, 35, 20) } else { Rect::from_xywh(0, 0, 48, 32) }; let mut l = noise_layer("l", PixelFormat::RGBA8, rect, 900 + i as u32, 0.0); l.blend = mode; l.opacity = 0.35 + 0.05 * (i % 13) as f32; l.fill_opacity = if i % 4 == 1 { 0.6 } else { 1.0 }; if i % 11 == 7 { - l.mask = Some(mask(Rect::from_xywh(i32_ % 30, 0, 50, 64), 70 + i as u32, 0.0)); + l.mask = Some(mask(Rect::from_xywh(i32_ % 15, 0, 25, 32), 70 + i as u32, 0.0)); } if i % 23 == 9 { l.clipped = true; @@ -1489,7 +1533,7 @@ fn runs_of_plain_layers_blend_in_one_pass() { d.layers.push(f); } if i % 17 == 8 { - d.layers.push(noise_layer("small", PixelFormat::RGBA8, Rect::from_xywh(20, 20, 6, 5), 40 + i as u32, 0.5)); + d.layers.push(noise_layer("small", PixelFormat::RGBA8, Rect::from_xywh(10, 10, 6, 5), 40 + i as u32, 0.5)); } } let stats = diff_rect(&mut g, &d, d.bounds(), "plain layer runs").unwrap_or_else(|e| panic!("{e}")); @@ -1510,16 +1554,18 @@ fn runs_of_normal_layers_blend_with_normal_code_alone() { for (mode, depth) in [(ColorMode::Rgb, SampleType::U8), (ColorMode::Rgb, SampleType::U16), (ColorMode::Rgb, SampleType::F32), (ColorMode::Lab, SampleType::U8)] { - let mut d = Document::new("normal", Size::new(96, 64), mode, depth); + // 48 x 32 (#15927, was 96 x 64): the Normal-run shader is picked per layer and mode, not + // per pixel; the runs that end inside the canvas still overhang the left edge. + let mut d = Document::new("normal", Size::new(48, 32), mode, depth); let fmt = d.pixel_format(); - d.layers.push(noise_layer("bg", fmt, Rect::from_xywh(0, 0, 96, 64), 5, 0.0)); + d.layers.push(noise_layer("bg", fmt, Rect::from_xywh(0, 0, 48, 32), 5, 0.0)); for i in 0..40u32 { - let rect = if i % 5 == 3 { Rect::from_xywh(-6, 9, 70, 44) } else { Rect::from_xywh(0, 0, 96, 64) }; + let rect = if i % 5 == 3 { Rect::from_xywh(-3, 5, 35, 22) } else { Rect::from_xywh(0, 0, 48, 32) }; let mut l = noise_layer("n", fmt, rect, 600 + i, if i % 3 == 0 { 0.0 } else { 0.4 }); l.opacity = 0.2 + 0.07 * (i % 11) as f32; l.fill_opacity = [1.0, 0.55, 0.0, 0.8][i as usize % 4]; if i % 7 == 2 { - l.mask = Some(mask(Rect::from_xywh(i as i32 % 25, 0, 60, 64), 50 + i, 0.0)); + l.mask = Some(mask(Rect::from_xywh(i as i32 % 13, 0, 30, 32), 50 + i, 0.0)); } d.layers.push(l); if i % 6 == 4 { @@ -2165,16 +2211,19 @@ fn layer_effects_on_groups_clipping_and_fills() { fn layer_effects_update_incrementally() { let Some(mut g) = gpu() else { return }; let stack = effect_cases().into_iter().find(|(n, _)| *n == "full stack").unwrap().1; - let mut d = fx_doc(700, 600, SampleType::U8); + // 540 x 500 (#15927, was 700 x 600): the effect layer keeps its size — the partial-rebuild + // half-ratio is set by the map area, not by the document margin — and every edit stays on + // canvas. + let mut d = fx_doc(540, 500, SampleType::U8); let mut l = blob("fx", d.pixel_format(), 300.0, 280.0, 200.0, [0.9, 0.4, 0.2]); l.effects.items = stack; d.layers.push(l); - d.layers.push(noise_layer("plain", PixelFormat::RGBA8, Rect::new(500, 20, 650, 120), 5, 0.0)); + d.layers.push(noise_layer("plain", PixelFormat::RGBA8, Rect::new(460, 20, 530, 120), 5, 0.0)); let first = fx_check(&mut g, &d, "initial"); assert!(first.fx_programs > 0 && first.fx_shapes == 1); // An unrelated edit (another layer's pixels, the effect layer's opacity and an effect colour) // reuses every map. - d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(520, 30, 560, 60), &[0.0, 1.0, 0.0, 1.0]); + d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(470, 30, 510, 60), &[0.0, 1.0, 0.0, 1.0]); d.layers[1].opacity = 0.8; if let Effect::ColorOverlay { color, .. } = &mut d.layers[1].effects.items[6] { *color = Color::rgb(0.1, 0.9, 0.9); @@ -3168,14 +3217,13 @@ fn documents_larger_than_the_texture_limit() { let mut d = small_big_doc(); assert!(g.paged.supports(&d).is_ok()); // Every pass sees page borders, and effect maps and blurs crossing them. - check(&mut g, &d, "big document"); - let s = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, d.bounds()).unwrap().1; + let pass = check_full(&mut g, &d, "big document"); + let s = pass.paged_stats; assert!(s.cells >= 9 && s.chunks == s.cells, "{s:?}"); // A viewport off the page grid covers only its cells (3 x 2). let view = Rect::new(200, 230, 530, 430); - diff_rect(&mut g, &d, view, "viewport").unwrap_or_else(|e| panic!("{e}")); - let s = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, view).unwrap().1; - assert_eq!(s.cells, 6, "{s:?}"); + let pass = diff_rect_full(&mut g, &d, view, "viewport").unwrap_or_else(|e| panic!("{e}")); + assert_eq!(pass.paged_stats.cells, 6, "{:?}", pass.paged_stats); // A dab across a page corner on the effect layer, and an edit elsewhere. d.layers[3].surface_mut().unwrap().fill_rect(Rect::new(240, 240, 270, 270), &[0.1, 0.1, 0.9, 1.0]); d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(500, 250, 520, 270), &[0.0, 0.0, 0.0, 0.0]); @@ -3218,9 +3266,11 @@ fn pages_are_evicted_under_the_budget() { #[test] fn layer_pages_are_admitted_under_a_zero_budget_and_stay_on_the_gpu() { let Some(mut g) = gpu() else { return }; - let mut d = base_doc(600, 500); - d.layers.push(noise_layer("mid", PixelFormat::RGBA8, Rect::new(-20, 10, 590, 480), 61, 0.0)); - let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(30, -15, 620, 510), 62, 0.2); + // 540 x 260 (#15927, was 600 x 500): still a 3 x 2 grid of 256 px pages, with the two layers + // overhanging the canvas left, top, right and bottom — the page-admission path is per cell. + let mut d = base_doc(540, 260); + d.layers.push(noise_layer("mid", PixelFormat::RGBA8, Rect::new(-20, 10, 530, 240), 61, 0.0)); + let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(30, -15, 560, 275), 62, 0.2); top.blend = BlendMode::Multiply; d.layers.push(top); // Exercise page residency itself: lower-stack checkpoints could skip binding the pages. @@ -3250,9 +3300,10 @@ fn layer_pages_are_admitted_under_a_zero_budget_and_stay_on_the_gpu() { #[test] fn a_layer_page_out_of_memory_retries_then_ends_only_that_refresh_on_the_cpu() { let Some(mut g) = gpu() else { return }; - let mut d = base_doc(600, 500); - d.layers.push(noise_layer("mid", PixelFormat::RGBA8, Rect::new(-20, 10, 590, 480), 71, 0.0)); - let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(30, -15, 620, 510), 72, 0.2); + // 540 x 260 (#15927, was 600 x 500): the same 3 x 2 page grid the failure counts are set for. + let mut d = base_doc(540, 260); + d.layers.push(noise_layer("mid", PixelFormat::RGBA8, Rect::new(-20, 10, 530, 240), 71, 0.0)); + let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(30, -15, 560, 275), 72, 0.2); top.blend = BlendMode::Multiply; d.layers.push(top); g.paged.set_composite_cache_budget(0); @@ -3673,10 +3724,10 @@ fn anti_aliased_inner_shadow_matches_the_cpu_ramps() { let Some(mut g) = gpu() else { return }; let on = inner_shadow_issue_doc(true); let off = inner_shadow_issue_doc(false); - check(&mut g, &on, "#14934 inner shadow, Anti-aliased"); - check(&mut g, &off, "#14934 inner shadow, Anti-aliased off"); - let gpu_on = render_to_vec(&mut g.comp, &g.device, &g.queue, &on, on.bounds()).expect("gpu render, Anti-aliased"); - let gpu_off = render_to_vec(&mut g.comp, &g.device, &g.queue, &off, off.bounds()).expect("gpu render, Anti-aliased off"); + // `check_full` already rendered both documents on the whole-texture compositor: the ramps + // read those pixels, no second render per document (#15927). + let gpu_on = check_full(&mut g, &on, "#14934 inner shadow, Anti-aliased").whole; + let gpu_off = check_full(&mut g, &off, "#14934 inner shadow, Anti-aliased off").whole; let tl: &[f32] = &[65.0, 89.0, 107.0, 118.0, 124.0, 126.0, 127.0, 127.0, 128.0]; let br: &[f32] = &[49.0, 74.0, 96.0, 112.0, 121.0, 125.0, 126.0, 127.0, 128.0]; for ((side, got), want) in ["top", "left", "bottom", "right"].iter().zip(inner_shadow_ramps(&gpu_on)).zip([tl, tl, br, br]) { @@ -3714,6 +3765,11 @@ fn anti_aliased_inner_shadow_matches_the_cpu_ramps() { #[test] fn anti_aliased_inner_shadow_gated_neighbours_match_the_cpu() { let Some(mut g) = gpu() else { return }; + // #15927: the document stays 400 x 300 (crossing the 256 px page is why it is that size), + // but an Inner Shadow only moves pixels at the shape's edges. The CPU reference and both + // compositors are compared over the shape plus a margin around every measured row — the + // gated shift is inside it for every row below. + let shape = Rect::new(88, 63, 312, 237); for (size, spread, distance, what) in [ (10.0, 0.5, 0.0, "Size 10 Choke 50 %"), (10.0, 0.05, 0.0, "Size 10 Choke 5 %"), @@ -3724,6 +3780,7 @@ fn anti_aliased_inner_shadow_gated_neighbours_match_the_cpu() { (10.0, 0.0, 5.0, "Size 10 Choke 0 at Distance 5 (offset on, whole-pixel light offset)"), (10.0, 0.5, 5.0, "Size 10 Choke 50 % at Distance 5 (still gated)"), ] { - check(&mut g, &inner_shadow_doc(size, spread, distance, true), &format!("#14934 inner shadow, {what}, Anti-aliased")); + diff_rect(&mut g, &inner_shadow_doc(size, spread, distance, true), shape, &format!("#14934 inner shadow, {what}, Anti-aliased")) + .unwrap_or_else(|e| panic!("{e}")); } } From ffad734425abe9fcfc068579c79199a03c0557dd Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 21 Nov 2026 04:49:43 +0100 Subject: [PATCH 092/136] test(gpu): keep absent tiles in the changed-mask-default parity check The 300 x 260 trim put the far mask patch at (230,190,300,260), which touches all four tiles of the mask's 2 x 2 resident span: no tile stayed absent, so the branch #2422 is about (cells.rs: a missing tile in a new resident texture gets the mask default pixel) was unreachable and the check passed with that line neutered. The far patch now starts on the 256 px boundary, (256,256,300,260), so tiles (1,0) and (0,1) stay absent; with cells.rs:431 neutered the test fails again at this geometry ("mask default 1: max diff 246.16/255 at (282,208)", inside the absent tile column). The document stays 300 x 260. Comment truths: the disjoint-damages note called the second stroke series' rectangles "all new" - they are new damage rectangles, not new cached pixels (the chunk they land in is already resident), which is what whole-chunk admission is about; the incremental-updates note called the painted area "one 256 px tile" in a document that spans a 2 x 2 tile grid. --- crates/gpu/tests/it/parity.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 67d100f6ba..02217478cb 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -507,10 +507,11 @@ fn disjoint_partial_damages_admit_whole_chunks_not_damage_rects() { doc.layers.push(alone(noise_layer("middle", PixelFormat::RGBA8, doc.bounds(), 2, 0.2))); doc.layers.push(alone(noise_layer("top", PixelFormat::RGBA8, doc.bounds(), 3, 0.2))); check(&mut g, &doc, "warm"); - // Each series paints 8 rectangles. The second series' rectangles are all new (5 px across - // and 65 px down from the first's) but in the same chunk (the 300 x 260 document is one - // chunk at `CHUNK`), so a cache entry per damage rectangle would add 8 entries. (The four - // series of 24 this replaces painted the same 24 rectangles every time.) + // Each series paints 8 rectangles. The second series' damage rectangles are distinct from + // the first's (5 px across and 65 px down), but their pixels land in the same chunk the + // first series already made resident (the 300 x 260 document is one chunk at `CHUNK`), so + // only admission could grow the cache: an entry per damage rectangle would add 8 entries. + // (The four series of 24 this replaces painted the same 24 rectangles every time.) let strokes = |g: &mut Gpu, doc: &Document, pass: i32| { for i in 0..8 { let (x, y) = (20 + i * 30 + pass * 5, 20 + pass * 65); @@ -1220,8 +1221,9 @@ fn formats_offsets_and_chunks() { #[test] fn incremental_updates_follow_the_document() { let Some(mut g) = gpu() else { return }; - // 300 x 260 (#15927, was 600 x 300): the painted area is still one 256 px tile at the same - // corner; upload bookkeeping is per tile. + // 300 x 260 (#15927, was 600 x 300): the top layer still spans a 2 x 2 grid of 256 px tiles, + // and the paint below still lands in one tile at the same corner; upload bookkeeping is + // per tile. let mut d = base_doc(300, 260); d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 300, 260), 61, 0.0)); check(&mut g, &d, "initial"); @@ -1282,17 +1284,19 @@ fn duplicates_copy_their_source_texture() { #[test] fn changed_mask_default_updates_absent_tiles() { let Some(mut g) = gpu() else { return }; - // 300 x 260 (#15927, was 600 x 300): the opposite-corner tiles still span a 2 x 2 resident - // texture with two absent tiles between them. + // 300 x 260 (#15927, was 600 x 300): the two stored tiles still span a 2 x 2 resident + // texture whose other two tiles stay absent. A patch reaching the opposite corner at + // (230,190) would store all four tiles and leave the default with nothing to cover. let mut d = base_doc(300, 260); d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 300, 260), 61, 0.5)); - // Tiles in opposite corners: the resident texture spans the absent tiles between them. - let corners = [Rect::new(0, 0, 70, 70), Rect::new(230, 190, 300, 260)]; - let data = vec![0.5f32; 70 * 70]; + // Tiles in opposite corners only, the far one starting on the 256 px boundary: the resident + // texture spans the absent tile column and the absent tile row between them. + let corners = [Rect::new(0, 0, 70, 70), Rect::new(256, 256, 300, 260)]; for default in [0.0, 1.0] { let mut m = LayerMask::reveal_all(); m.surface = photocraft_raster::Surface::with_default(PixelFormat::GRAY8, &[default]); for r in corners { + let data = vec![0.5f32; r.width() as usize * r.height() as usize]; m.surface.write_region(r, &data); } d.layers[1].mask = Some(m); From ad2d4ea0826a1302195d5ef3177e713bae694328 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 21 Nov 2026 04:58:38 +0100 Subject: [PATCH 093/136] perf(ui-tests): fire the tool-group step instead of pressing every tool Shift+letter was pressed for every member of every lettered tool group, twice over: 64 tools times two or three whole-app frames, three times (the next tool, the wrap, and entering the group from another tool) = 257 frames of the whole app for a decision `pick_tool` makes in one line from the toolbar table. The per-tool assertions now fire `tools.nextInGroup.`, the command the keymap fires on a Shift+letter press, through `shortcut_dispatch::run_fired` - the same entry a press reaches, with no frame. One press per kind of group stays a real key through the app, and `every_displayed_shortcut_runs_its_menu_item` already presses every `tools.nextInGroup` row's key. Same assertions, same tool-by-tool coverage: the three sweeps cost 22.0 s on this box before and 0.4 s now; the new press test for the representatives adds 1.1 s. --- .../src/tool_shift_cycle_order_tests.rs | 77 +++++++++++++++---- 1 file changed, 64 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs index 67760664bc..d34cdabafe 100644 --- a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs +++ b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs @@ -1,6 +1,7 @@ //! Shift+letter steps through a key's tool group in the toolbar flyout's order, wrapping, and the //! anchor point tools have no letter so P never reaches them. +use craft::ui::runtime::commands::{FirePhase, FireSource, Fired}; use egui::{Key, Modifiers}; use egui_kittest::Harness; use serde_json::json; @@ -63,43 +64,93 @@ fn quick_shift_press(h: &mut Harness<'static, Box>, key: Key) { h.run_steps(2); } +/// The app with the same document as [`app`], but with no harness and no frames: the per-tool assertions below +/// call [`crate::shortcut_dispatch::run_fired`], which is the entry a fired Shift+letter reaches once the runtime +/// has taken the key. One whole-app frame costs more than the pick itself (#15651), and 64 tool members x two frames +/// per press made these three tests the slowest of their file. The keyboard's way to this entry stays pressed for +/// one tool per kind of group in [`a_real_shift_letter_takes_the_next_tool_of_its_group`], and every +/// `tools.nextInGroup` row's binding is pressed by +/// `input::shortcut_dispatch::tests::every_displayed_shortcut_runs_its_menu_item`. +fn bare_app() -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let ctx = app.ctx().clone(); + (app, ctx) +} + +/// Fire `tools.nextInGroup.`, the command Shift+letter is bound to, as a key press fires it. +fn fire_next_in_group(app: &mut PhotocraftApp, ctx: &egui::Context, letter: char) { + let id = crate::shortcut_dispatch::next_in_group_id(letter); + let command = crate::shortcut_dispatch::keymap_command(&id); + crate::shortcut_dispatch::run_fired(app, ctx, &[Fired::new(command, FireSource::Key, FirePhase::Press, 0.0)]); + app.sync_views(); +} + #[test] fn from_every_tool_shift_letter_lands_on_the_next_tool_in_toolbar_order() { - let mut h = app(); + let (mut app, ctx) = bare_app(); for (letter, group) in groups() { for (i, from) in group.iter().enumerate() { - h.state_mut().ui.tool = *from; - quick_shift_press(&mut h, key_for(letter)); + app.ui.tool = *from; + fire_next_in_group(&mut app, &ctx, letter); let want = group[(i + 1) % group.len()]; - assert_eq!(h.state().ui.tool, want, "Shift+{letter} from {from:?}"); + assert_eq!(app.ui.tool, want, "Shift+{letter} from {from:?}"); } } } #[test] fn shift_letter_wraps_from_the_last_tool_to_the_first() { - let mut h = app(); + let (mut app, ctx) = bare_app(); for (letter, group) in groups() { - h.state_mut().ui.tool = *group.last().unwrap(); - shift_press(&mut h, key_for(letter)); - assert_eq!(h.state().ui.tool, group[0], "Shift+{letter} wraps"); + app.ui.tool = *group.last().unwrap(); + fire_next_in_group(&mut app, &ctx, letter); + assert_eq!(app.ui.tool, group[0], "Shift+{letter} wraps"); } } #[test] fn the_first_shift_letter_from_another_tool_lands_on_the_groups_first_tool() { - let mut h = app(); + let (mut app, ctx) = bare_app(); for (letter, group) in groups() { if group.contains(&Tool::Hand) { continue; } - h.state_mut().ui.tool = Tool::Hand; - h.state_mut().ui.group_tools.clear(); - shift_press(&mut h, key_for(letter)); - assert_eq!(h.state().ui.tool, group[0], "Shift+{letter} from the Hand tool"); + app.ui.tool = Tool::Hand; + app.ui.group_tools.clear(); + fire_next_in_group(&mut app, &ctx, letter); + assert_eq!(app.ui.tool, group[0], "Shift+{letter} from the Hand tool"); } } +/// The keyboard route itself, once per kind of group: a shared group's middle tool, the wrap from its last tool, +/// the Pen group (whose flyout holds three anchor tools the letter never reaches), a group entered from a tool +/// outside it, and a single-tool group. Every other member of every group goes through the same `pick_tool` line +/// and is asserted tool by tool in the three tests above. +#[test] +fn a_real_shift_letter_takes_the_next_tool_of_its_group() { + let mut h = app(); + h.state_mut().ui.tool = Tool::PolygonLasso; + quick_shift_press(&mut h, Key::L); + assert_eq!(h.state().ui.tool, Tool::MagneticLasso, "Shift+L from the Polygonal Lasso"); + h.state_mut().ui.tool = Tool::CustomShape; + quick_shift_press(&mut h, Key::U); + assert_eq!(h.state().ui.tool, Tool::Rectangle, "Shift+U wraps to the group's first tool"); + // The Pen group steps its three pens only: the anchor tools are in its flyout but not under its letter. + h.state_mut().ui.tool = Tool::CurvaturePen; + quick_shift_press(&mut h, Key::P); + assert_eq!(h.state().ui.tool, Tool::Pen, "Shift+P wraps the three pens"); + h.state_mut().ui.tool = Tool::Hand; + h.state_mut().ui.group_tools.clear(); + quick_shift_press(&mut h, Key::G); + assert_eq!(h.state().ui.tool, Tool::Gradient, "Shift+G from the Hand picks the group's first tool"); + h.state_mut().ui.tool = Tool::Move; + h.state_mut().ui.group_tools.clear(); + quick_shift_press(&mut h, Key::K); + assert_eq!(h.state().ui.tool, Tool::Frame, "Shift+K picks the only tool of the Frame group"); +} + #[test] fn w_cycles_object_selection_quick_selection_magic_wand() { assert_eq!(sequence('W', 4), vec![Tool::ObjectSelection, Tool::QuickSelection, Tool::MagicWand, Tool::ObjectSelection]); From c6e920c0c081bcbbb9e109018a12c418ca279b58 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 21 Nov 2026 04:58:42 +0100 Subject: [PATCH 094/136] test(ui): one app per row group in the guide-cursor and held-key loops `guide_cursor_tests` built a whole app for each of its 21 rows and dragged through four intermediate points; `hold_keys::tests` built one app per tool in five loops and pressed a stand-in for every tool that shares one family's decision. Both loops re-entered the same production line dozens of times while paying for the app's settle frames each round. - guide cursor: the rows whose press the Move tool takes, and the two locked- guide rows, share one app; a row that moved the guide puts it back with the ruler's own command (`view.moveGuide`). The tools that keep the command for themselves share a second app, Type last and Crop on its own, because their drag leaves an open text edit or a pending crop that would decide the next row. The drag keeps two points instead of four: the guide follows the pointer. - hold keys: one app per loop (`space_right_click...`, `command_or_alt_space...`, `cmd_alt_drag...`, `tilde_erases...`, `space_repositions...`), a fresh layer or an explicit deselect where a case would otherwise see the last one's pixels. - the command-as-Move rule is now also asserted as data for every tool (`the_command_stand_in_rule_is_the_table`), so the drags can press one tool per decision: the vertical type tool, both path tools and the rectangle shape share `is_type` and the `Family::Vector` line with the tools that stayed. --- crates/ui-egui/src/guide_cursor_tests.rs | 62 +++++++++++--- crates/ui-egui/src/input/hold_keys/tests.rs | 94 +++++++++++++++++++-- 2 files changed, 135 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/guide_cursor_tests.rs b/crates/ui-egui/src/guide_cursor_tests.rs index 59ddeed269..81436dd4a5 100644 --- a/crates/ui-egui/src/guide_cursor_tests.rs +++ b/crates/ui-egui/src/guide_cursor_tests.rs @@ -47,8 +47,10 @@ fn drag(h: &mut Harness<'static, Box>, from: f32, to: f32, m: Mod h.run_steps(1); h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: m }); h.run_steps(1); - for k in 1..=4 { - let q = screen(h, from + (to - from) * k as f32 / 4.0, 150.0); + // Two moves: the guide follows the pointer, so one intermediate point is enough to drive the drag and the + // fourth one only cost another whole-app frame each row (#15941). + for k in 1..=2 { + let q = screen(h, from + (to - from) * k as f32 / 2.0, 150.0); h.event(egui::Event::PointerMoved(q)); h.run_steps(1); } @@ -57,20 +59,35 @@ fn drag(h: &mut Harness<'static, Box>, from: f32, to: f32, m: Mod h.run_steps(2); } +/// The vertical guides as they stand. +fn guides(h: &Harness<'static, Box>) -> Vec { + h.state().session.active().unwrap().doc.guides.vertical.clone() +} + +/// Put the guide back at 200 after a row dragged it, through the ruler's own command, so the next row starts +/// where the first one did without paying for another app. +fn put_guide_back(h: &mut Harness<'static, Box>) { + h.state_mut().run("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 200})).unwrap(); + h.run_steps(2); + assert_eq!(guides(h), vec![200.0], "the guide is back at 200 for the next row"); +} + /// The cursor over the guide with ⌘ held (or latched in Window › Modifier Keys, with no key held), -/// and where a ⌘-drag from 200 to 240 leaves it. -fn command_drag(tool: Tool, locked: bool, latched: bool) -> (egui::CursorIcon, Vec) { - let mut h = harness(tool); +/// and where a ⌘-drag from 200 to 240 leaves it, on the shared harness `h`. +fn command_drag(h: &mut Harness<'static, Box>, tool: Tool, locked: bool, latched: bool) -> (egui::CursorIcon, Vec) { + h.state_mut().ui.tool = tool; h.state_mut().ui.extras.lock_guides = locked; let held = if latched { h.state_mut().ui.shell.latched = craft::keymap::Mods::CMD; Modifiers::NONE } else { + h.state_mut().ui.shell.latched = craft::keymap::Mods::NONE; Modifiers::COMMAND }; - let c = hover(&mut h, 200.0, 150.0, held); - drag(&mut h, 200.0, 240.0, held); - (c, h.state().session.active().unwrap().doc.guides.vertical.clone()) + h.run_steps(1); + let c = hover(h, 200.0, 150.0, held); + drag(h, 200.0, 240.0, held); + (c, guides(h)) } const GUIDE: egui::CursorIcon = egui::CursorIcon::ResizeHorizontal; @@ -114,13 +131,34 @@ fn command_over_a_guide_takes_it_where_command_is_the_move_tool() { (Tool::Rectangle, false, false, false), (Tool::Slice, false, false, false), ]; - for (tool, locked, latched, takes_guide) in rows { - let (cursor, guides) = command_drag(tool, locked, latched); + let check = |h: &mut Harness<'static, Box>, tool: Tool, locked: bool, latched: bool, takes_guide: bool| { + let (cursor, moved) = command_drag(h, tool, locked, latched); if takes_guide { - assert_eq!((cursor, guides), (GUIDE, vec![240.0]), "{tool:?} latched={latched}"); + assert_eq!((cursor, moved), (GUIDE, vec![240.0]), "{tool:?} latched={latched}"); + put_guide_back(h); } else { assert_ne!(cursor, GUIDE, "{tool:?} locked={locked}"); - assert_eq!(guides, vec![200.0], "{tool:?} locked={locked}"); + assert_eq!(moved, vec![200.0], "{tool:?} locked={locked}"); + } + }; + // One app for the rows whose ⌘ press the Move tool takes, and for the two rows that ask a locked guide to stay: + // `harness` builds the whole app and its settle frames, while the selected tool, the ⌘ latch and the locked + // guides are state the app reads each frame. Each row that moved the guide puts it back with the ruler's own + // command (`view.moveGuide`), which is what a user does to move it again (#15941). + let mut shared = harness(Tool::Brush); + for (tool, locked, latched, takes_guide) in rows { + if takes_guide || matches!(tool, Tool::Brush | Tool::Frame) { + check(&mut shared, tool, locked, latched, takes_guide); } } + // The tools that keep ⌘ for themselves share an app too. The Type tool goes last: its ⌘-drag leaves an open + // text edit, and `moves_with_command` refuses the guides while one is open, so a later row would be decided by + // that instead of by its tool. The Crop tool keeps an app of its own for the same reason: its drag leaves a + // pending crop frame holding the canvas. + let mut keeps = harness(Tool::Pen); + for tool in [Tool::Pen, Tool::Hand, Tool::Zoom, Tool::Rectangle, Tool::Slice, Tool::Type] { + check(&mut keeps, tool, false, false, false); + } + let mut crop = harness(Tool::Crop); + check(&mut crop, Tool::Crop, false, false, false); } diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index 867bdf7fd5..6114a64d54 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -176,8 +176,13 @@ fn space_repositions_the_drag_being_drawn() { slack: 1, }, ]; + // One app for the three marquee and lasso cases: the tool is state, and each case starts from no selection. + let mut h = harness(Tool::RectMarquee); for c in cases { - let mut h = harness(c.tool); + h.state_mut().run("select.deselect", json!({})).ok(); + assert_eq!(selection(&h), Rect::EMPTY, "{:?}: the case starts with no selection", c.tool); + h.state_mut().ui.tool = c.tool; + h.run_steps(1); press_at(&mut h, c.start.0, c.start.1); for &(x, y) in c.before { move_to(&mut h, x, y); @@ -368,10 +373,11 @@ fn cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd() { } // The Crop and Rotate View tools go last, in an app of their own: they leave a pending crop and // a turned view behind. - let keeps = [ - vec![Tool::Hand, Tool::Zoom, Tool::Pen, Tool::Rectangle, Tool::Type, Tool::VerticalType, Tool::PathSelection, Tool::DirectSelection], - vec![Tool::Crop, Tool::RotateView], - ]; + // One tool per decision the refusal comes from: the Hand, Zoom and Rotate-View families, the vector family's + // shared line (the Pen stands for the shapes and both path tools), and the Type tools' `is_type` line (the + // vertical type tool takes the same branch). Every tool's own decision is asserted in + // `the_command_stand_in_rule_is_the_table`, without a drag. + let keeps = [vec![Tool::Hand, Tool::Zoom, Tool::Pen, Tool::Type], vec![Tool::Crop, Tool::RotateView]]; for group in keeps { let mut h = harness(group[0]); for tool in group { @@ -382,6 +388,61 @@ fn cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd() { } } +/// The ⌘-as-Move rule read as data: `takes_command_stand_in` and the selection family decide which tool hands a ⌘ +/// press to the Move tool, for every tool in the app. The drags above press one tool per decision; this pins each +/// tool by name, so a tool that moves into another family or starts refusing the stand-in fails here. +#[test] +fn the_command_stand_in_rule_is_the_table() { + use crate::canvas::tools::Family; + let hands_to_move = |t: Tool| crate::canvas::tools::takes_command_stand_in(t) || crate::canvas::tools::family(t) == Family::Selection; + let got: Vec = Tool::ALL.into_iter().filter(|t| hands_to_move(*t)).collect(); + let want: Vec = vec![ + Tool::Artboard, + Tool::RectMarquee, + Tool::EllipseMarquee, + Tool::SingleRowMarquee, + Tool::SingleColumnMarquee, + Tool::Lasso, + Tool::PolygonLasso, + Tool::MagneticLasso, + Tool::MagicWand, + Tool::Eyedropper, + Tool::ColorSampler, + Tool::Ruler, + Tool::Note, + Tool::Count, + Tool::Brush, + Tool::Pencil, + Tool::ColorReplacement, + Tool::MixerBrush, + Tool::Eraser, + Tool::BackgroundEraser, + Tool::MagicEraser, + Tool::Gradient, + Tool::PaintBucket, + Tool::SpotHealing, + Tool::Remove, + Tool::Healing, + Tool::Patch, + Tool::ContentAwareMove, + Tool::RedEye, + Tool::CloneStamp, + Tool::PatternStamp, + Tool::HistoryBrush, + Tool::ArtHistoryBrush, + Tool::Blur, + Tool::Sharpen, + Tool::Smudge, + Tool::Dodge, + Tool::Burn, + Tool::Sponge, + Tool::QuickSelection, + Tool::ObjectSelection, + Tool::Frame, + ]; + assert_eq!(got, want, "which tools hand a ⌘ press to the Move tool"); +} + /// A ⌘-drag with `tool`, one that keeps ⌘ for itself, leaves a fresh layer where it is. fn keeps_the_layer(h: &mut Harness<'static, Box>, tool: Tool) { let id = with_layer(h); @@ -397,8 +458,11 @@ fn keeps_the_layer(h: &mut Harness<'static, Box>, tool: Tool) { /// brush to resize, such as the Gradient. #[test] fn cmd_alt_drag_duplicates_the_layer_then_moves_the_copy() { + // One app, one fresh layer per case (the `with_layer` each case already calls). + let mut h = harness(Tool::Brush); for (tool, mods) in [(Tool::Brush, MAC_CMD_ALT), (Tool::Gradient, MAC_CMD_ALT), (Tool::Gradient, CTRL_ALT)] { - let mut h = harness(tool); + h.state_mut().ui.tool = tool; + h.run_steps(1); let orig = with_layer(&mut h); let n0 = h.state().session.active().unwrap().doc.layers.len(); let h0 = h.state().session.active().unwrap().history.past_len(); @@ -486,8 +550,11 @@ fn last_stroke_erases(h: &Harness<'static, Box>) -> Option /// holds across frames (a second pass in a frame does not clear it) and goes with the release. #[test] fn tilde_erases_only_with_the_brush_and_pencil() { + // One app, a fresh layer per tool (`with_layer`), so the strokes of one tool never sit under the next one's. + let mut h = harness(Tool::Brush); for (tool, label, erases) in [(Tool::Brush, "Brush Tool", true), (Tool::Pencil, "Pencil", true), (Tool::CloneStamp, "", false)] { - let mut h = harness(tool); + h.state_mut().ui.tool = tool; + h.run_steps(1); with_layer(&mut h); key(&mut h, Key::Backtick, true, Modifiers::NONE); h.run_steps(3); @@ -559,8 +626,13 @@ fn a_held_key_keeps_a_pending_crop_and_another_tools_key_commits_it() { /// Photoshop, not the held-over tool's menu; the tool comes back on release (#11271). #[test] fn space_right_click_opens_the_hand_view_menu() { + // One app for the four tools: `harness` starts the whole app (its document, panels and settle frames), which is + // most of a case, while the selected tool is state the app takes between frames (#15941). The tool is switched + // the way the ⌘-Move test below does it. + let mut h = harness(Tool::Move); for tool in [Tool::Move, Tool::Brush, Tool::RectMarquee, Tool::Pen] { - let mut h = harness(tool); + h.state_mut().ui.tool = tool; + h.run_steps(1); let p = screen(&h, 200.0, 150.0); h.event(Event::PointerMoved(p)); h.run_steps(1); @@ -611,9 +683,13 @@ fn space_hand_view_menu_closes_when_the_tool_underneath_changes() { /// ⌘/Ctrl+right-click, which lists the layers under the pointer for any tool (#307). #[test] fn command_or_alt_space_right_click_opens_no_view_menu() { + // One app for all four cases, as above; the menu a ⌘+right-click leaves open is closed before the next case. + let mut h = harness(Tool::Move); for mods in [Modifiers::COMMAND, Modifiers::ALT] { for tool in [Tool::Move, Tool::Brush] { - let mut h = harness(tool); + h.state_mut().ui.tool = tool; + h.state_mut().ui.canvas_tool_menu = None; + h.run_steps(1); let p = screen(&h, 200.0, 150.0); h.event(Event::PointerMoved(p)); h.run_steps(1); From 50a45d03188db115b6dc778ff3ab08eade64ed09 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 21 Nov 2026 04:58:47 +0100 Subject: [PATCH 095/136] test(ui): one app for the reset-tip tools and two frames per shortcut press `reset_tip_tests::each_tool_resets_and_first_uses_its_own_tip` started 80 apps: five per painting tool, for two menu commands (`tool.reset`, `tool.resetAll`) and a brush swap that read the state a case had just set. The two commands pick their rule from `fresh_brush` for the tool in front of them, so one app serves all sixteen tools; only the first-use case keeps an app of its own, because a tool that has been picked before is no longer seeing its brush for the first time. Same five scenarios and same sixteen tools: 6.9 s -> 1.0 s on this box. `shortcut_dispatch::tests::press` ran three frames after a press; the runtime takes the key in the first and the app runs the command it fired in the second, which is what `press_in_one_frame` and `quick_shift_press` in this crate already do, so the third frame only drew the app again. `delete_key_targets` shares one app per focus place across its two keys (the delete is undone, the dry-run log is drained, and the mask case puts its selection back), and `keys_run_their_commands` reuses the app whose presses were dry runs. --- .../src/input/shortcut_dispatch/tests.rs | 37 +++++++++++++++---- crates/ui-egui/src/reset_tip_tests.rs | 12 +++--- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index 77163189e0..226a303193 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -84,7 +84,17 @@ pub(crate) fn tap(h: &mut Harness<'_, Box>, key: Key, mods: Modif fn press(h: &mut Harness<'_, Box>, sc: &str) { let sc = parse(sc).unwrap_or_else(|| panic!("unparsable shortcut {sc}")); - tap(h, sc.logical_key, sc.modifiers); + // Two frames, not [`tap`]'s three: the runtime takes the key in the first and the app runs the command it fired + // in the second (`quick_shift_press` in `tool_shift_cycle_order_tests` measures the same for the tool letters). + // The third frame only drew the app again (#15941). + let m = platform(sc.modifiers); + h.input_mut().events.extend([ + egui::Event::ModifiersChanged(m), + egui::Event::Key { key: sc.logical_key, physical_key: None, pressed: true, repeat: false, modifiers: m }, + egui::Event::Key { key: sc.logical_key, physical_key: None, pressed: false, repeat: false, modifiers: m }, + egui::Event::ModifiersChanged(Modifiers::NONE), + ]); + h.run_steps(2); } /// Queue one press/release in one input frame, then let the runtime collect and the app dispatch it. @@ -349,6 +359,8 @@ fn every_displayed_shortcut_runs_its_menu_item() { fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() { let mut failures = Vec::new(); for place in [Place::Canvas, Place::LayersRow, Place::FocusedWidget, Place::OpacityField] { + // One app per place: the presses below include the panel toggles the runtime runs itself, so the next + // place could not count on the Layers panel still being there. let mut h = harness(); set_dry_run(&h.ctx, true); put_focus(&mut h, place); @@ -461,8 +473,8 @@ fn keys_run_their_commands() { set_dry_run(&h.ctx, false); // #352: ⌥[ ⌥] ⌥, ⌥. and ⇧⌥[ walk the Layers panel's rows. Rows, top to bottom: paint, Hello (type), group, - // in-group, Background. - let mut h = harness(); + // in-group, Background. The same app: the dry-run presses above ran no command, so the document is still the + // harness's own (#15941). assert_eq!(active_name(&h), "paint"); for (key, want) in [("Alt+[", "Hello"), ("Alt+[", "group"), ("Alt+[", "in-group"), ("Alt+]", "group"), ("Alt+,", "Background"), ("Alt+.", "paint")] { press(&mut h, key); @@ -512,11 +524,14 @@ fn keys_run_their_commands() { fn delete_key_targets() { // The selected layer, from the canvas or the Layers panel, in one undo step. for place in [Place::Canvas, Place::LayersRow] { + // One app per place: each key's delete is undone by the end of its case, so the next key starts from the + // same document without paying for another whole app (#15941). + let mut h = harness(); + put_focus(&mut h, place); for key in ["Delete", "Backspace"] { - let mut h = harness(); - put_focus(&mut h, place); let s = &mut h.state_mut().session; - s.execute("select.deselect", json!({})).unwrap(); + // The first case of the app deselects the harness's own selection; the ones after it start without one. + s.execute("select.deselect", json!({})).ok(); let adj = photocraft_doc::LayerId(s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()["layer"].as_u64().unwrap()); h.run_steps(2); let before = names(&h); @@ -526,15 +541,21 @@ fn delete_key_targets() { assert_eq!(names(&h).len(), before.len() - 1, "{place:?} {key}: only it"); press(&mut h, "Cmd+Z"); assert_eq!(names(&h), before, "{place:?} {key}: one undo brings it back"); + // The undo's own log entry goes here: the next key of this app starts with an empty log, as the + // app-per-key version did. + take_log(&h.ctx); } } // The layer mask targeted: a selection fills the mask with the background colour, no selection deletes the mask. + // One app for both keys: the first case leaves the layer without a mask and without a selection, and the case + // puts both back before it starts (#15941). + let mut h = harness(); + put_focus(&mut h, Place::Canvas); for key in ["Delete", "Backspace"] { - let mut h = harness(); - put_focus(&mut h, Place::Canvas); let s = &mut h.state_mut().session; let layer = s.active().unwrap().active_layer.unwrap(); + s.execute("select.rect", json!({"x": 20, "y": 20, "width": 80, "height": 60})).unwrap(); s.execute("layer.layerMask.revealAll", json!({})).unwrap(); let sel = s.active().unwrap().doc.selection.as_ref().expect("the harness keeps a selection").content_bounds(); let (x, y) = ((sel.x0 + sel.x1) / 2, (sel.y0 + sel.y1) / 2); diff --git a/crates/ui-egui/src/reset_tip_tests.rs b/crates/ui-egui/src/reset_tip_tests.rs index 44236f1083..9b6e739a74 100644 --- a/crates/ui-egui/src/reset_tip_tests.rs +++ b/crates/ui-egui/src/reset_tip_tests.rs @@ -112,9 +112,13 @@ fn starting(app: &PhotocraftApp, tool: Tool) -> Tip { #[test] fn each_tool_resets_and_first_uses_its_own_tip() { + // One app for the two reset commands of all sixteen tools. Each case picks the tool and scrambles the brush + // before it invokes, and `tool.reset` / `tool.resetAll` work through `fresh_brush` for the tool in front of them, + // so a case never needs an app of its own: starting the app (document, panels, views) was the cost of a case + // here, 80 of them (#15941). + let mut a = app(); for (tool, first_use) in ROWS { // Reset Tool. - let mut a = app(); pick(&mut a, tool); scramble(&mut a); assert_ne!(live(&a), starting(&a, tool), "{tool:?}: the scrambled tip is not its starting tip"); @@ -122,12 +126,10 @@ fn each_tool_resets_and_first_uses_its_own_tip() { assert_eq!(live(&a), starting(&a, tool), "{tool:?}: Reset Tool"); // Reset All Tools with the tool active, then with it picked later. - let mut a = app(); pick(&mut a, tool); scramble(&mut a); invoke(&mut a, "tool.resetAll", json!({"confirmed": true})); assert_eq!(live(&a), starting(&a, tool), "{tool:?}: Reset All Tools, active"); - let mut a = app(); pick(&mut a, tool); scramble(&mut a); pick(&mut a, other(tool)); @@ -136,7 +138,6 @@ fn each_tool_resets_and_first_uses_its_own_tip() { assert_eq!(live(&a), starting(&a, tool), "{tool:?}: Reset All Tools, picked later"); // Other tools keep their brushes through Reset Tool. - let mut a = app(); pick(&mut a, other(tool)); scramble(&mut a); let kept = live(&a); @@ -145,7 +146,8 @@ fn each_tool_resets_and_first_uses_its_own_tip() { let theirs = a.ui.tool_brushes.iter().find(|(t, _)| *t == other(tool)).map(|(_, b)| tip(b)); assert_eq!(theirs, Some(kept), "{tool:?}: {:?} keeps its tip", other(tool)); - // First use, after another tool's tip; its own tip is then kept across tool switches. + // First use, after another tool's tip; its own tip is then kept across tool switches. The tool must not have + // been picked before, so this case keeps an app of its own. let Some(rule) = first_use else { continue }; let mut a = app(); pick(&mut a, other(tool)); From e8b696a6c87885b88fcbb4283ef6fed4e5442b10 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 21 Nov 2026 06:28:54 +0100 Subject: [PATCH 096/136] test(ui): pin the Shift+letter chords of every tool group in one table test The fired sweeps hand the command to run_fired themselves, so no test pressed the Shift+ chords: with the binding for Shift+V dropped at shortcut_dispatch::command_rows the branch stayed green where main fails three. New every_group_letter_shift_chord_reaches_its_group_step asserts the keymap chord of every tools.nextInGroup row over tool_shortcuts::group_letters() on one settled app - one lookup per letter, no frames - the Space anchor row included: its default text `Shift+ ` parses to no chord, so it pins that nothing binds it. Proven red by the temporary Shift+V neuter, green after restoring it. Also in this review round: correct the bare_app comment claiming the menu shortcut test presses these rows (menu_rows lists no tools.nextInGroup id); collapse the byte-identical press and press_in_one_frame in the dispatch tests into one press; split the guide rows by takes_guide || locked instead of tool name, count all 21 rows through the three apps, and guard the keeps app idle (no open text edit) before each row. --- crates/ui-egui/src/guide_cursor_tests.rs | 17 +++++++++--- .../src/input/shortcut_dispatch/tests.rs | 24 +++++------------ .../src/tool_shift_cycle_order_tests.rs | 27 ++++++++++++++++--- 3 files changed, 43 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/guide_cursor_tests.rs b/crates/ui-egui/src/guide_cursor_tests.rs index 81436dd4a5..c972caa80d 100644 --- a/crates/ui-egui/src/guide_cursor_tests.rs +++ b/crates/ui-egui/src/guide_cursor_tests.rs @@ -141,14 +141,17 @@ fn command_over_a_guide_takes_it_where_command_is_the_move_tool() { assert_eq!(moved, vec![200.0], "{tool:?} locked={locked}"); } }; - // One app for the rows whose ⌘ press the Move tool takes, and for the two rows that ask a locked guide to stay: + // One app for the rows whose ⌘ press the Move tool takes and for the rows that ask a locked guide to stay: // `harness` builds the whole app and its settle frames, while the selected tool, the ⌘ latch and the locked - // guides are state the app reads each frame. Each row that moved the guide puts it back with the ruler's own - // command (`view.moveGuide`), which is what a user does to move it again (#15941). + // guides are state the app reads each frame. The split is by what a row expects, not by tool name: a takes-row + // puts the guide back with the ruler's own command (`view.moveGuide`, what a user does to move it again) and a + // locked row moves nothing, so neither leaves state for the rows after it (#15941). let mut shared = harness(Tool::Brush); + let mut ran = 0; for (tool, locked, latched, takes_guide) in rows { - if takes_guide || matches!(tool, Tool::Brush | Tool::Frame) { + if takes_guide || locked { check(&mut shared, tool, locked, latched, takes_guide); + ran += 1; } } // The tools that keep ⌘ for themselves share an app too. The Type tool goes last: its ⌘-drag leaves an open @@ -157,8 +160,14 @@ fn command_over_a_guide_takes_it_where_command_is_the_move_tool() { // pending crop frame holding the canvas. let mut keeps = harness(Tool::Pen); for tool in [Tool::Pen, Tool::Hand, Tool::Zoom, Tool::Rectangle, Tool::Slice, Tool::Type] { + // Cheap guard on the reason this app is ordered: no row so far left an open text edit that would decide + // this one instead of its tool. + assert!(keeps.state().ui.text_edit.is_none(), "no text edit open before {tool:?} in the keeps app"); check(&mut keeps, tool, false, false, false); + ran += 1; } let mut crop = harness(Tool::Crop); check(&mut crop, Tool::Crop, false, false, false); + ran += 1; + assert_eq!(ran, rows.len(), "every row ran once: {} shared, 6 keeps, 1 crop", ran - 7); } diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index 226a303193..cd720d3002 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -82,23 +82,11 @@ pub(crate) fn tap(h: &mut Harness<'_, Box>, key: Key, mods: Modif h.run_steps(3); } +/// A press and release queued in one input frame, then the frames that take it and run its command: two, not +/// [`tap`]'s three - the runtime takes the key in the first and the app runs the command it fired in the second +/// (`quick_shift_press` in `tool_shift_cycle_order_tests` measures the same for the tool letters). The third frame +/// only drew the app again (#15941). fn press(h: &mut Harness<'_, Box>, sc: &str) { - let sc = parse(sc).unwrap_or_else(|| panic!("unparsable shortcut {sc}")); - // Two frames, not [`tap`]'s three: the runtime takes the key in the first and the app runs the command it fired - // in the second (`quick_shift_press` in `tool_shift_cycle_order_tests` measures the same for the tool letters). - // The third frame only drew the app again (#15941). - let m = platform(sc.modifiers); - h.input_mut().events.extend([ - egui::Event::ModifiersChanged(m), - egui::Event::Key { key: sc.logical_key, physical_key: None, pressed: true, repeat: false, modifiers: m }, - egui::Event::Key { key: sc.logical_key, physical_key: None, pressed: false, repeat: false, modifiers: m }, - egui::Event::ModifiersChanged(Modifiers::NONE), - ]); - h.run_steps(2); -} - -/// Queue one press/release in one input frame, then let the runtime collect and the app dispatch it. -fn press_in_one_frame(h: &mut Harness<'_, Box>, sc: &str) { let sc = parse(sc).unwrap_or_else(|| panic!("unparsable shortcut {sc}")); let m = platform(sc.modifiers); h.input_mut().events.extend([ @@ -370,7 +358,7 @@ fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() { // A press the focused component holds (the Layers rows' stacking and visibility keys) // is the component's and reaches no app command. let held = focus_holds(&h.ctx, chord); - press_in_one_frame(&mut h, &sc); + press(&mut h, &sc); let log = take_log(&h.ctx); if typing && !chord.has_command() && !chord.is_function_key() { // A focused text field keeps its typing / editing keys: nothing may fire. @@ -396,7 +384,7 @@ fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() { for t in one.into_iter().chain(many) { let start = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; h.state_mut().ui.tool = start; - press_in_one_frame(&mut h, &t.key().to_string()); + press(&mut h, &t.key().to_string()); let want = if typing { start } else { t }; if h.state().ui.tool.key() != want.key() { failures.push(format!("{place:?}: tool key {} left {:?}, expected a {} tool", t.key(), h.state().ui.tool, want.key())); diff --git a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs index d34cdabafe..2435d1ce02 100644 --- a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs +++ b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs @@ -1,6 +1,7 @@ //! Shift+letter steps through a key's tool group in the toolbar flyout's order, wrapping, and the //! anchor point tools have no letter so P never reaches them. +use craft::keymap::Chord; use craft::ui::runtime::commands::{FirePhase, FireSource, Fired}; use egui::{Key, Modifiers}; use egui_kittest::Harness; @@ -68,9 +69,10 @@ fn quick_shift_press(h: &mut Harness<'static, Box>, key: Key) { /// call [`crate::shortcut_dispatch::run_fired`], which is the entry a fired Shift+letter reaches once the runtime /// has taken the key. One whole-app frame costs more than the pick itself (#15651), and 64 tool members x two frames /// per press made these three tests the slowest of their file. The keyboard's way to this entry stays pressed for -/// one tool per kind of group in [`a_real_shift_letter_takes_the_next_tool_of_its_group`], and every -/// `tools.nextInGroup` row's binding is pressed by -/// `input::shortcut_dispatch::tests::every_displayed_shortcut_runs_its_menu_item`. +/// one tool per kind of group in [`a_real_shift_letter_takes_the_next_tool_of_its_group`], and the chord itself is +/// pinned for every group letter by [`every_group_letter_shift_chord_reaches_its_group_step`] below. These sweeps +/// hand the command to [`crate::shortcut_dispatch::run_fired`] directly, and no menu shows a `tools.nextInGroup` +/// row, so `input::shortcut_dispatch::tests::every_displayed_shortcut_runs_its_menu_item` never takes their branch. fn bare_app() -> (Box, egui::Context) { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); @@ -151,6 +153,25 @@ fn a_real_shift_letter_takes_the_next_tool_of_its_group() { assert_eq!(h.state().ui.tool, Tool::Frame, "Shift+K picks the only tool of the Frame group"); } +/// The chord each group step hangs on: `command_rows` gives every `tools.nextInGroup` row its default +/// `Shift+` binding, and the keymap is what turns the pressed chord into the command the fired sweeps hand to +/// `run_fired` themselves. The sweeps and that entry point pin nothing here, and no menu shows a `tools.nextInGroup` +/// row, so this table - one settled app, one keymap lookup per letter, no frames per letter - is what fails when a +/// row's chord is dropped. The Space group of the Pen flyout's anchor tools (their `key()`, `state::tool`) takes the +/// same loop: its default text is `Shift+ ` with no key name, which `Chord::parse` refuses, so production binds +/// Shift+Space to nothing - pinned too, and this row changes the day a spellable binding for it is added. +#[test] +fn every_group_letter_shift_chord_reaches_its_group_step() { + let h = app(); + for (letter, _) in crate::tool_shortcuts::group_letters() { + let id = crate::shortcut_dispatch::next_in_group_id(letter); + let command = crate::shortcut_dispatch::keymap_command(&id); + let bound = craft::ui::runtime::commands::chord(&h.ctx, &command); + let want = Chord::parse(&format!("Shift+{}", letter.to_ascii_uppercase())).ok(); + assert_eq!(bound, want, "Shift+{letter} reaches {id}"); + } +} + #[test] fn w_cycles_object_selection_quick_selection_magic_wand() { assert_eq!(sequence('W', 4), vec![Tool::ObjectSelection, Tool::QuickSelection, Tool::MagicWand, Tool::ObjectSelection]); From 4ea8bdc8279543eecd61494aaf7f1c095294af2c Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:09:39 +0100 Subject: [PATCH 097/136] Trim the mid-stroke tool-key test to an each-choice set (#16041) pencil_tests::a_tool_key_mid_stroke_paints_what_the_stroke_paints_without_it crossed 4 modes with 5 brush changes (56 apps). The brush is captured once at the press whatever the mode, so History Brush keeps all 5 cases and each Erase to History mode one: Brush and Pencil with the sampled tip, Block with smoothing. 8 cases, 24 apps. --- crates/ui-egui/src/pencil_tests.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/pencil_tests.rs b/crates/ui-egui/src/pencil_tests.rs index 2fbc2c9dba..5b79bf4cc2 100644 --- a/crates/ui-egui/src/pencil_tests.rs +++ b/crates/ui-egui/src/pencil_tests.rs @@ -434,15 +434,15 @@ fn a_tool_key_mid_stroke_paints_what_the_stroke_paints_without_it() { ("no dynamics, then size jitter", round.clone(), json!({"shapeDynamics": {"enabled": true, "size": {"jitter": 1.0}}})), ("no smoothing, then 90 %", round.clone(), json!({"smoothing": {"enabled": true, "amount": 0.9}})), ]; - for mode in ["", "brush", "pencil", "block"] { - for (what, pressed, switched) in &cases { - let plain = history_stroke_pixels(mode, pressed, None); - assert!(history_stroke_pixels(mode, pressed, Some(switched)) == plain, "{mode} {what}: the switch changed the stroke"); - // The switched-to brush paints differently, so the comparison means something; Block - // mode keeps only the brush's smoothing. - if mode != "block" || what.contains("smoothing") { - assert!(history_stroke_pixels(mode, switched, None) != plain, "{mode} {what}: both brushes paint alike"); - } - } + // Each choice, not every mode with every case (#16041): the brush is captured once, at the + // press, whatever the mode, so History Brush takes every case and each Erase to History mode + // one, for its own flags: Brush and Pencil with the sampled tip, Block with smoothing (the only + // brush setting Block keeps). + let runs = cases.iter().map(|c| ("", c)).chain([("brush", &cases[2]), ("pencil", &cases[2]), ("block", &cases[4])]); + for (mode, (what, pressed, switched)) in runs { + let plain = history_stroke_pixels(mode, pressed, None); + assert!(history_stroke_pixels(mode, pressed, Some(switched)) == plain, "{mode} {what}: the switch changed the stroke"); + // The switched-to brush paints differently, so the comparison means something. + assert!(history_stroke_pixels(mode, switched, None) != plain, "{mode} {what}: both brushes paint alike"); } } From bffe7f9ba2c1f197f520cc3b91b3cd16505e641d Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:24:29 +0100 Subject: [PATCH 098/136] First-launch language test: resolve all 14 system tags without an app, draw 3 The test built two whole apps for each of 14 system-tag cases (28 apps). Which language a tag picks is plain logic (`system::resolve` -> `lang_from_tag`), so every case now checks `Lang::from_pref("auto")` under its tags without a harness, including no tags and unsupported tags falling back to English. Drawing only differs by script, so one Latin (fr-CA), one CJK (ja-JP) and one Cyrillic (ru-RU) case still build the app, keep the stored preference at "auto" and find the translated File title in the menu. Part of #15376. Fixes #16039. --- crates/ui-egui/src/i18n/live_tests.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/live_tests.rs b/crates/ui-egui/src/i18n/live_tests.rs index 45cd0cc03c..d40c580558 100644 --- a/crates/ui-egui/src/i18n/live_tests.rs +++ b/crates/ui-egui/src/i18n/live_tests.rs @@ -205,7 +205,8 @@ fn harness_with_services(services: Services) -> egui_kittest::Harness<'static, B } /// Auto draws the detected system language on first launch while keeping the Auto preference; no or -/// unsupported system languages draw English. +/// unsupported system languages draw English. Which language a tag picks is plain logic, checked for +/// every case; drawing differs only by script, so one app each draws Latin, CJK and Cyrillic. #[test] fn first_launch_renders_the_system_language_without_overwriting_auto() { if !needs_catalogs() { @@ -228,6 +229,10 @@ fn first_launch_renders_the_system_language_without_overwriting_auto() { (&["sw-KE", "is-IS"], "en"), ]; for (tags, code) in cases { + assert_eq!(system::with_system_tags(tags, || Lang::from_pref("auto")), lang(code), "{tags:?}"); + } + let drawn: [(&[&str], &str); 3] = [(&["fr-CA"], "fr"), (&["ja-JP"], "ja"), (&["ru-RU"], "ru")]; + for (tags, code) in drawn { system::with_system_tags(tags, || { with_language(Lang::EN, || { let h = harness(); From 9f1b8054ba242dcead9a8e2d0cb287c13240c79e Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:46:37 +0100 Subject: [PATCH 099/136] Check the Erase to History mode flags in the mid-stroke tool-key test (#16041) A dropped pencil or block flag goes from the plain and the switched stroke alike, so the pixel comparisons can't see it; assert the emitted flags, as #16041's mutation list asks. --- crates/ui-egui/src/pencil_tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ui-egui/src/pencil_tests.rs b/crates/ui-egui/src/pencil_tests.rs index 5b79bf4cc2..e7a4d6551a 100644 --- a/crates/ui-egui/src/pencil_tests.rs +++ b/crates/ui-egui/src/pencil_tests.rs @@ -416,6 +416,10 @@ fn history_stroke_pixels(mode: &str, pressed: &serde_json::Value, switched: Opti tool_event(&mut app, ToolEvent::Up { x: pts[4].0, y: pts[4].1 }, Modifiers::NONE); let (id, p) = last(&app); assert_eq!(id, "paint.historyBrush", "{mode}: {p}"); + // The mode's own flags: the pixel comparisons can't see one go, as both strokes would lose it. + for flag in ["pencil", "block"] { + assert_eq!(p.get(flag) == Some(&json!(true)), mode == flag, "{mode}: {flag} in {p}"); + } let st = app.session.active().unwrap(); layer(&app).surface().unwrap().read_region(st.doc.bounds()) } From f27f63b66702def66f9e52c63ffadda59d84824c Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Sat, 21 Nov 2026 13:18:55 +0530 Subject: [PATCH 100/136] Smart Filter tone editor test: an each-choice set of 11 cases instead of the 36-case cross The loop body moves into tone_filter_case. Colour component view 2 keeps all six mode x kind pairs because its forbidden channel name depends on the mode; every other view runs once. target_context returns early for any Smart Filter, so every view reaches the same guard. Co-Authored-By: Claude --- .../src/panels/smart_ui/editor_tests.rs | 178 ++++++++++-------- 1 file changed, 96 insertions(+), 82 deletions(-) diff --git a/crates/ui-egui/src/panels/smart_ui/editor_tests.rs b/crates/ui-egui/src/panels/smart_ui/editor_tests.rs index 154bc60520..4c2821be11 100644 --- a/crates/ui-egui/src/panels/smart_ui/editor_tests.rs +++ b/crates/ui-egui/src/panels/smart_ui/editor_tests.rs @@ -305,92 +305,106 @@ fn assert_tone_preview_is_non_neutral(app: &mut PhotocraftApp, ctx: &egui::Conte crate::canvas::ensure_filter_preview(app, idx, ctx).unwrap(); } +/// Each-choice set: every mode x kind and every view appears. View 2 (`Color(1)`) runs with all six +/// mode x kind pairs because its forbidden channel name (Green, Magenta, a) depends on the mode; the +/// other views run once, spread over modes and kinds, since `target_context` returns early for any +/// Smart Filter, so every view reaches the same guard. +const TONE_FILTER_CASES: [(&str, &str, usize); 11] = [ + ("rgb", "levels", 2), + ("rgb", "curves", 2), + ("lab", "levels", 2), + ("lab", "curves", 2), + ("cmyk", "levels", 2), + ("cmyk", "curves", 2), + ("rgb", "curves", 0), + ("lab", "levels", 1), + ("cmyk", "curves", 3), + ("rgb", "levels", 4), + ("lab", "curves", 5), +]; + +/// One case: `view` 0..5 is the alpha channel, layer mask target, colour component `Color(1)`, smart-object mask UI target, Quick Mask, filter mask UI target. +fn tone_filter_case(mode: &str, kind: &str, view: usize) { + use photocraft_engine::{adjust_params, channel_cmds::ChannelTarget}; + let (mut app, layer) = app(8, mode); + let command = format!("image.adjustments.{kind}"); + let color_mode = app.session.active().unwrap().doc.mode; + let mut recorded = adjust_params::to_params(&adjust_params::default_for(kind, color_mode).unwrap()); + let key = if mode == "lab" { + "lightness" + } else if kind == "curves" { + "points" + } else { + "" + }; + if kind == "levels" { + if key.is_empty() { + recorded["gamma"] = json!(1.4); + } else { + recorded[key]["gamma"] = json!(1.4); + } + } else { + recorded[key] = json!([[0, 0], [128, 180], [255, 255]]); + } + app.run(&command, recorded.clone()).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("channel.new", json!({"name":"Saved sky", "fill":"white"})).unwrap(); + if view == 4 { + app.run("select.editInQuickMaskMode", json!({})).unwrap(); + } + app.session.active_mut().unwrap().channel_view.target = match view { + 0 => ChannelTarget::Alpha(0), + 1 => ChannelTarget::LayerMask, + 2 => ChannelTarget::Color(1), + _ => ChannelTarget::Composite, + }; + app.ui.mask_target = view == 3; + app.ui.filter_mask_target = (view == 5).then_some(layer.0); + let before = app.session.active().unwrap().doc.clone(); + let filters = smart(&app, layer).clone(); + let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1200.0, 900.0)).build_app(|ui, app| crate::dialogs::run(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + let ctx = h.ctx.clone(); + super::open_editor(h.state_mut(), &ctx, layer.0, &filters, 2); + h.run_steps(2); + let values = fields(h.state()); + assert_eq!(values.get("target"), None, "{mode} {kind} view={view}: no channel target is added to a Smart Filter"); + let read = |p: &serde_json::Value| adjust_params::from_params(kind, p, None, color_mode).unwrap(); + assert_eq!(read(&values), read(&recorded), "{mode} {kind} view={view}: recorded colour settings survive reopening"); + h.run_steps(3); + let names: Vec<_> = h.query_all_by_role(egui::accesskit::Role::ComboBox).filter_map(|n| n.value()).collect(); + let expected = match mode { + "lab" => "Lightness", + "cmyk" => "CMYK", + _ => "RGB", + }; + assert!(names.iter().any(|n| n == expected), "{mode} {kind} view={view}: {names:?}"); + assert!( + !names.iter().any(|n| n == "Saved sky" || n == "Quick Mask" || n == "Smart Object Mask" || n == "Green" || n == "Magenta" || n == "a"), + "{names:?}" + ); + let ctx = h.ctx.clone(); + let idx = h.state().session.active_index().unwrap(); + assert!(crate::canvas::ensure_filter_preview(h.state_mut(), idx, &ctx).is_some()); + assert_tone_preview_is_non_neutral(h.state_mut(), &ctx, kind); + assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &before), "preview never writes to the selected plane"); + let shown = photocraft_compose::flatten(h.state().filter_preview.as_ref().unwrap().result.as_ref().unwrap()).px.clone(); + confirm(h.state_mut()); + assert_eq!(shown, photocraft_compose::flatten(&h.state().session.active().unwrap().doc).px, "{mode} {kind} view={view}: preview matches commit"); + assert_eq!(smart(h.state(), layer).smart_filters.len(), 3); + assert_eq!(read(&smart(h.state(), layer).smart_filters[2].params), read(&recorded)); + let after = &h.state().session.active().unwrap().doc; + assert_eq!(after.channels, before.channels); + assert_eq!(after.quick_mask, before.quick_mask); + assert_eq!(after.layer(layer).unwrap().mask, before.layer(layer).unwrap().mask); +} + /// Re-editing a whole-image tone Smart Filter keeps its colour controls and stored records, /// even when a colour component, alpha, Quick Mask or either layer-mask UI target is selected. #[test] fn tone_filter_editor_ignores_current_channel_target() { - use photocraft_engine::{adjust_params, channel_cmds::ChannelTarget}; - for mode in ["rgb", "lab", "cmyk"] { - for kind in ["levels", "curves"] { - for view in 0..6 { - let (mut app, layer) = app(8, mode); - let command = format!("image.adjustments.{kind}"); - let color_mode = app.session.active().unwrap().doc.mode; - let mut recorded = adjust_params::to_params(&adjust_params::default_for(kind, color_mode).unwrap()); - let key = if mode == "lab" { - "lightness" - } else if kind == "curves" { - "points" - } else { - "" - }; - if kind == "levels" { - if key.is_empty() { - recorded["gamma"] = json!(1.4); - } else { - recorded[key]["gamma"] = json!(1.4); - } - } else { - recorded[key] = json!([[0, 0], [128, 180], [255, 255]]); - } - app.run(&command, recorded.clone()).unwrap(); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - app.run("channel.new", json!({"name":"Saved sky", "fill":"white"})).unwrap(); - if view == 4 { - app.run("select.editInQuickMaskMode", json!({})).unwrap(); - } - app.session.active_mut().unwrap().channel_view.target = match view { - 0 => ChannelTarget::Alpha(0), - 1 => ChannelTarget::LayerMask, - 2 => ChannelTarget::Color(1), - _ => ChannelTarget::Composite, - }; - app.ui.mask_target = view == 3; - app.ui.filter_mask_target = (view == 5).then_some(layer.0); - let before = app.session.active().unwrap().doc.clone(); - let filters = smart(&app, layer).clone(); - let mut h = - Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1200.0, 900.0)).build_app(|ui, app| crate::dialogs::run(app, ui), app); - PhotocraftApp::setup_context(&h.ctx, Default::default()); - let ctx = h.ctx.clone(); - super::open_editor(h.state_mut(), &ctx, layer.0, &filters, 2); - h.run_steps(2); - let values = fields(h.state()); - assert_eq!(values.get("target"), None, "{mode} {kind} view={view}: no channel target is added to a Smart Filter"); - let read = |p: &serde_json::Value| adjust_params::from_params(kind, p, None, color_mode).unwrap(); - assert_eq!(read(&values), read(&recorded), "{mode} {kind} view={view}: recorded colour settings survive reopening"); - h.run_steps(3); - let names: Vec<_> = h.query_all_by_role(egui::accesskit::Role::ComboBox).filter_map(|n| n.value()).collect(); - let expected = match mode { - "lab" => "Lightness", - "cmyk" => "CMYK", - _ => "RGB", - }; - assert!(names.iter().any(|n| n == expected), "{mode} {kind} view={view}: {names:?}"); - assert!( - !names.iter().any(|n| n == "Saved sky" || n == "Quick Mask" || n == "Smart Object Mask" || n == "Green" || n == "Magenta" || n == "a"), - "{names:?}" - ); - let ctx = h.ctx.clone(); - let idx = h.state().session.active_index().unwrap(); - assert!(crate::canvas::ensure_filter_preview(h.state_mut(), idx, &ctx).is_some()); - assert_tone_preview_is_non_neutral(h.state_mut(), &ctx, kind); - assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &before), "preview never writes to the selected plane"); - let shown = photocraft_compose::flatten(h.state().filter_preview.as_ref().unwrap().result.as_ref().unwrap()).px.clone(); - confirm(h.state_mut()); - assert_eq!( - shown, - photocraft_compose::flatten(&h.state().session.active().unwrap().doc).px, - "{mode} {kind} view={view}: preview matches commit" - ); - assert_eq!(smart(h.state(), layer).smart_filters.len(), 3); - assert_eq!(read(&smart(h.state(), layer).smart_filters[2].params), read(&recorded)); - let after = &h.state().session.active().unwrap().doc; - assert_eq!(after.channels, before.channels); - assert_eq!(after.quick_mask, before.quick_mask); - assert_eq!(after.layer(layer).unwrap().mask, before.layer(layer).unwrap().mask); - } - } + for (mode, kind, view) in TONE_FILTER_CASES { + tone_filter_case(mode, kind, view); } } From 0cb5be967af0aeefb125e0246d2782dbc2e0beeb Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Sat, 21 Nov 2026 08:55:10 +0100 Subject: [PATCH 101/136] test(ui): start each Hand view-menu case at its own zoom input/hold_keys/tests.rs The four cases share one app, so the first case's 200 % was the zoom the next three started from: their "200% from {before}" assert could pass on a view that was already there, and a row that closed the menu without applying the command would not have been caught. Each case now puts the shared view at 100 % before it opens the menu, and the case asserts that the zoom it starts from is not 200 %, so the row's own action is the only thing that can move the view - for Brush, RectMarquee and Pen as well as Move. The assert alone is not a red test on the parent commit: with only the assert added and the 100 % start left out, the case fails at "Brush: the case starts away from 200 %", which is the inherited zoom. With both, all four tools' rows do apply 200 %, so this pins the routes rather than fixing a wrong one. --- crates/ui-egui/src/input/hold_keys/tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index 6114a64d54..ffd8bf95de 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -632,6 +632,11 @@ fn space_right_click_opens_the_hand_view_menu() { let mut h = harness(Tool::Move); for tool in [Tool::Move, Tool::Brush, Tool::RectMarquee, Tool::Pen] { h.state_mut().ui.tool = tool; + // Every case starts at 100 %, not where the case before it left the shared view: the first + // case ends at 200 %, and a later case whose row applied nothing would still read 200 %. + let view = &mut h.state_mut().ui.views[0]; + view.zoom = 1.0; + view.clear_pending(); h.run_steps(1); let p = screen(&h, 200.0, 150.0); h.event(Event::PointerMoved(p)); @@ -649,6 +654,7 @@ fn space_right_click_opens_the_hand_view_menu() { assert_eq!(h.state().ui.tool, tool, "{tool:?}: the tool is kept"); // Its rows work as the selected Hand's do. let before = zoom(&h); + assert!(before != 2.0, "{tool:?}: the case starts away from 200 % ({before}), so the row has to move the view"); let ctx = h.ctx.clone(); crate::canvas_tool_menu::choose(h.state_mut(), &ctx, "view.twoHundredPercent"); h.run_steps(2); From d369052bc6e33c05366853f00f3dac7e3bf7b151 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:58:14 +0100 Subject: [PATCH 102/136] Damaged-preference test: one app per load-only case (#16040) The load-only cases of a_damaged_remembered_value_resets_only_itself built a second, restarted app to read the repaired file. They now use one app: check what it loaded, tick (the repair writes the file), then reread the file through a settings store and require it to load without section errors and to equal what the app holds. A repair that drops other keys still fails. The cases that set state keep the restart. --- crates/ui-egui/src/prefs/prefs_ui/tests.rs | 42 ++++++++++++++++++---- 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index fe6902bb93..b915f2c136 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -723,8 +723,34 @@ fn run_cases(cases: Vec) { } /// A case that only seeds a file and checks what the app loads from it. -fn loaded(name: &'static str, seed: Value, check: impl Fn(&PhotocraftApp) + 'static) -> Case { - Case { name, seed: Some(seed), set: Box::new(|_, _| {}), check: Box::new(move |app, _, _| check(app)) } +struct Loaded { + name: &'static str, + seed: Value, + check: Box, +} + +fn loaded(name: &'static str, seed: Value, check: impl Fn(&PhotocraftApp) + 'static) -> Loaded { + Loaded { name, seed, check: Box::new(check) } +} + +/// One app per case: what it loads, then what its first tick leaves in the file. A load that reset values writes the +/// repaired preferences on that tick, so the file must read back cleanly as what the app holds; a repair that drops +/// other keys fails here without a restarted app. +fn run_loaded(cases: Vec) { + for case in cases { + eprintln!("case: {}", case.name); + let files = Arc::new(MemoryFiles::new()); + seed(&files, &case.seed, Some(::SCHEMA_VERSION)); + let mut app = app_on(&files); + (case.check)(&app); + let ctx = app.ctx().clone(); + tick(&mut app, &ctx); + let (reread, report) = services_on(&files).settings.unwrap(); + assert!(report.section_errors.is_empty(), "{}: {:?}", case.name, report.section_errors); + // As written: the file has no nulls, which the preset libraries hold in memory. + let written = |p: &prefs::SavedPrefs| serde_json::to_value(p).unwrap(); + assert_eq!(written(reread.get()), written(&app.session.saved_prefs()), "{}", case.name); + } } fn restart_cases() -> Vec { @@ -982,7 +1008,8 @@ fn remembered_state_survives_a_restart() { run_cases(restart_cases()); } -fn damaged_cases() -> Vec { +/// The load-only cases, and the cases that set state in a first app and restart. +fn damaged_cases() -> (Vec, Vec) { use crate::state::Tool; let d = crate::state::ToolOptions::default; let mut cases = Vec::new(); @@ -1080,8 +1107,9 @@ fn damaged_cases() -> Vec { assert_eq!(app.session.tools.background, [1.0; 4]); })); // A tool-colour preset with an invalid channel is refused and leaves the remembered colours alone. + let mut restarts = Vec::new(); for bad_channel in [json!(1e100), json!("red"), json!(true), json!({}), json!([])] { - cases.push(Case { + restarts.push(Case { name: "tool colours after an invalid preset", seed: None, set: Box::new(move |app, _| { @@ -1099,12 +1127,14 @@ fn damaged_cases() -> Vec { }), }); } - cases + (cases, restarts) } #[test] fn a_damaged_remembered_value_resets_only_itself() { - run_cases(damaged_cases()); + let (loaded, restarts) = damaged_cases(); + run_loaded(loaded); + run_cases(restarts); } #[test] From f22516a68013d13cfd41277329374d342bfb8950 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:58:36 +0100 Subject: [PATCH 103/136] Damaged-preference test: clearer comment on the as-written comparison (#16040) --- crates/ui-egui/src/prefs/prefs_ui/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index b915f2c136..7d662bcc6c 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -747,7 +747,7 @@ fn run_loaded(cases: Vec) { tick(&mut app, &ctx); let (reread, report) = services_on(&files).settings.unwrap(); assert!(report.section_errors.is_empty(), "{}: {:?}", case.name, report.section_errors); - // As written: the file has no nulls, which the preset libraries hold in memory. + // Compared as written: the file has no nulls, while the preset libraries hold some in memory. let written = |p: &prefs::SavedPrefs| serde_json::to_value(p).unwrap(); assert_eq!(written(reread.get()), written(&app.session.saved_prefs()), "{}", case.name); } From d56bf759c43afa2cc0b3d63a8e79d9e9efa8570d Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:16:02 +0100 Subject: [PATCH 104/136] Live-dab replay tests cross commands, cases and depths pairwise (#15931) Each command still meets every stroke case, colour mode and mask target once, and every command and every case, mode or target still runs at 8, 16 and 32 bits: 90 -> 30, 72 -> 24 and 54 -> 18 strokes. --- .../tests/it/live_dab_matches_replay.rs | 108 ++++++++++-------- 1 file changed, 60 insertions(+), 48 deletions(-) diff --git a/crates/engine/tests/it/live_dab_matches_replay.rs b/crates/engine/tests/it/live_dab_matches_replay.rs index a7fca39818..d8d2fb65fd 100644 --- a/crates/engine/tests/it/live_dab_matches_replay.rs +++ b/crates/engine/tests/it/live_dab_matches_replay.rs @@ -31,54 +31,66 @@ fn pixels(s: &Session) -> Vec { st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(st.doc.bounds()) } +/// The six sequential-dab commands every test here strokes with. +const CMDS: [&str; 6] = ["paint.smudge", "paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge"]; + +/// The tests cross commands with one more axis (stroke case, colour mode or target) and depth +/// pairwise: each command meets each value of the axis once, at the depth `(i + j) % 3` picks, so +/// every command and every value of the axis still runs at 8, 16 and 32 bits (32 is the float path). +const DEPTHS: [u32; 3] = [8, 16, 32]; + +/// The commands that meet value `i` of the other axis at `DEPTHS[d]`. +fn cmds_at(i: usize, d: usize) -> impl Iterator { + CMDS.into_iter().enumerate().filter(move |(j, _)| (i + j) % 3 == d).map(|(_, cmd)| cmd) +} + #[test] fn pressure_shape_and_smoothing_match_replay() { let mut failures = Vec::new(); - for cmd in ["paint.smudge", "paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge"] { - for case in ["pressure", "locked", "ellipse", "smoothing", "scattering"] { - for depth in [8, 16, 32] { - let mut s = setup(depth, "rgb"); - match case { - "locked" => { - s.edit("lock alpha", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; - Ok(()) - }) - .unwrap(); - } - "ellipse" => { - s.tools.brush.roundness = 0.2; - s.tools.brush.angle = 37.0; - } - "smoothing" => { - s.tools.brush.smoothing.amount = 0.6; - } - "scattering" => { - s.tools.brush.scattering.enabled = true; - s.tools.brush.scattering.scatter.jitter = 1.0; - } - _ => {} + for (i, cmd) in CMDS.into_iter().enumerate() { + for (j, case) in ["pressure", "locked", "ellipse", "smoothing", "scattering"].into_iter().enumerate() { + let depth = DEPTHS[(i + j) % 3]; + let mut s = setup(depth, "rgb"); + match case { + "locked" => { + s.edit("lock alpha", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; + Ok(()) + }) + .unwrap(); } - let points = [[40.0, 40.0, 0.1], [65.0, 50.0, 0.4], [100.0, 60.0, 1.0], [140.0, 70.0, 0.7], [60.0, 40.0, 0.2]]; - let params = json!({"points":points,"size":40,"hardness":70,"strength":80,"opacity":55,"spacing":25}); - s.execute(cmd, params.clone()).unwrap(); - let want = pixels(&s); - s.execute("edit.undo", json!({})).unwrap(); - let mut start = params.clone(); - start["points"] = json!([points[0]]); - let mut live = LiveDab::begin(&s, cmd, &start).unwrap(); - for q in &points[1..] { - live.push(&[StrokePoint::new(q[0], q[1], q[2] as f32)]).unwrap(); + "ellipse" => { + s.tools.brush.roundness = 0.2; + s.tools.brush.angle = 37.0; } - s.offer_live_dab(live).unwrap(); - let result = s.execute(cmd, params).unwrap(); - assert_eq!(result["fromLive"], true); - let got = pixels(&s); - let count = got.iter().zip(&want).filter(|(a, b)| a != b).count(); - let max = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - if count > 0 { - failures.push(format!("{cmd} {case} depth={depth}: {count} channels differ, max={max}")); + "smoothing" => { + s.tools.brush.smoothing.amount = 0.6; } + "scattering" => { + s.tools.brush.scattering.enabled = true; + s.tools.brush.scattering.scatter.jitter = 1.0; + } + _ => {} + } + let points = [[40.0, 40.0, 0.1], [65.0, 50.0, 0.4], [100.0, 60.0, 1.0], [140.0, 70.0, 0.7], [60.0, 40.0, 0.2]]; + let params = json!({"points":points,"size":40,"hardness":70,"strength":80,"opacity":55,"spacing":25}); + s.execute(cmd, params.clone()).unwrap(); + let want = pixels(&s); + s.execute("edit.undo", json!({})).unwrap(); + let mut start = params.clone(); + start["points"] = json!([points[0]]); + let mut live = LiveDab::begin(&s, cmd, &start).unwrap(); + for q in &points[1..] { + live.push(&[StrokePoint::new(q[0], q[1], q[2] as f32)]).unwrap(); + } + s.offer_live_dab(live).unwrap(); + let result = s.execute(cmd, params).unwrap(); + assert_eq!(result["fromLive"], true); + let got = pixels(&s); + let count = got.iter().zip(&want).filter(|(a, b)| a != b).count(); + let max = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + if count > 0 { + failures.push(format!("{cmd} {case} depth={depth}: {count} channels differ, max={max}")); } } } @@ -87,8 +99,8 @@ fn pressure_shape_and_smoothing_match_replay() { #[test] fn native_modes_selection_and_lock_match_replay() { - for mode in ["rgb", "gray", "cmyk", "lab"] { - for depth in [8, 16, 32] { + for (i, mode) in ["rgb", "gray", "cmyk", "lab"].into_iter().enumerate() { + for (d, depth) in DEPTHS.into_iter().enumerate() { let mut s = setup(depth, mode); s.edit("lock alpha", |doc, active| { doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; @@ -97,7 +109,7 @@ fn native_modes_selection_and_lock_match_replay() { .unwrap(); s.execute("select.rect", json!({"x":30,"y":20,"width":110,"height":60})).unwrap(); let points = [[-10.0, 30.0], [80.0, 50.0], [160.0, 80.0], [60.0, 60.0]]; - for cmd in ["paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge", "paint.smudge"] { + for cmd in cmds_at(i, d) { let params = json!({"points":points,"size":30,"hardness":40,"strength":70,"opacity":37}); let expected_damage = s.execute(cmd, params.clone()).unwrap()["damage"].clone(); let want = pixels(&s); @@ -178,7 +190,7 @@ fn pressure_sized_live_dabs_commit_only_the_requested_mask_or_channel() { let values: Vec = (0..120).flat_map(|y| (0..200).map(move |x| ((x * 7 + y * 3) % 31) as f32 / 31.0)).collect(); surface.write_region(photocraft_geom::Rect::new(0, 0, 200, 120), &values); }; - for depth in [8, 16, 32] { + for (d, depth) in DEPTHS.into_iter().enumerate() { let mut s = setup(depth, "rgb"); s.execute("layer.new.layer", json!({})).unwrap(); s.execute("layer.layerMask.revealAll", json!({})).unwrap(); @@ -192,8 +204,8 @@ fn pressure_sized_live_dabs_commit_only_the_requested_mask_or_channel() { }) .unwrap(); let before = s.active().unwrap().doc.clone(); - for target in [json!("mask"), json!({"channel":0}), json!("quickMask")] { - for cmd in ["paint.smudge", "paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge"] { + for (i, target) in [json!("mask"), json!({"channel":0}), json!("quickMask")].into_iter().enumerate() { + for cmd in cmds_at(i, d) { let points = [[40.0, 40.0, 0.1], [65.0, 50.0, 0.4], [100.0, 60.0, 1.0], [140.0, 70.0, 0.7], [60.0, 40.0, 0.2]]; let params = json!({"target":target,"points":points,"size":40,"hardness":70,"strength":80,"opacity":55,"spacing":25}); s.execute(cmd, params.clone()).unwrap(); From eb809af5bb7e3e0f87952568836a2106e66664f7 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:31:13 +0100 Subject: [PATCH 105/136] raw hostile tests: a fixed sample by default, the full sweep under PHOTOCRAFT_FULL_SWEEP=1 (#15938) every_truncation_fails_cleanly tried every 3rd length of every seed and random_corruption_never_panics 400 corruptions per seed. They now take the first and last 16 lengths, every 7th length in the first 2 KiB and about 300 lengths per seed past it, and 40 corruptions per seed from a stream of its own. PHOTOCRAFT_FULL_SWEEP=1 runs every length and 400 corruptions. Most of the truncation time went to the RW2 seed, whose data is padded to a 16 KiB block: about 2,300 cuts in the padding that decode the same zeros. --- crates/raw/tests/it/hostile.rs | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/crates/raw/tests/it/hostile.rs b/crates/raw/tests/it/hostile.rs index 7ae2287b69..b04d93ce9f 100644 --- a/crates/raw/tests/it/hostile.rs +++ b/crates/raw/tests/it/hostile.rs @@ -157,10 +157,23 @@ fn a_seed_states_a_maker_note_colour_space() { assert!(samples().iter().any(|b| embedded_preview_color_space(b) == Some(PreviewColorSpace::AdobeRgb))); } +/// Whether the fuzz tests below run every case instead of their fixed sample: `PHOTOCRAFT_FULL_SWEEP=1`, +/// the switch `photocraft_testkit::Sweep` reads (this standalone crate cannot depend on the testkit). +fn full_sweep() -> bool { + std::env::var_os("PHOTOCRAFT_FULL_SWEEP").is_some_and(|v| v == "1") +} + #[test] fn every_truncation_fails_cleanly() { + // The fixed sample: the first and last 16 lengths, which cut the header and the last bytes of + // the sensor data, every 7th length in the first 2 KiB, and about 300 lengths per file past it. + // Only the RW2 seed is much longer: RW2 pads its data to a 16 KiB block, so its cuts past 2 KiB + // all decode the same zeros, and every 7th of them cost more than the rest of the test. + // The full sweep tries every length. + let full = full_sweep(); for b in samples() { - for n in (0..b.len()).step_by(3) { + let step = |n: usize| if n < 2048 { 7 } else { (b.len() / 300).max(7) }; + for n in (0..b.len()).filter(|&n| full || n % step(n) == 0 || n < 16 || n + 16 >= b.len()) { exercise(&b[..n]); } } @@ -168,13 +181,15 @@ fn every_truncation_fails_cleanly() { #[test] fn random_corruption_never_panics() { - let mut s = 0xDEAD_BEEF_u64; - let mut next = || { - s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - s >> 33 - }; - for b in samples() { - for _ in 0..400 { + let cases = if full_sweep() { 400 } else { 40 }; + for (i, b) in samples().iter().enumerate() { + // A stream per file, so the fixed sample is the start of the full sweep's. + let mut s = 0xDEAD_BEEF_u64 ^ (i as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15); + let mut next = || { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + s >> 33 + }; + for _ in 0..cases { let mut c = b.clone(); for _ in 0..1 + next() % 6 { let at = next() as usize % c.len(); From 76c42a4808c7cc5542c553efdc09b79c0be91e06 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:38:34 +0100 Subject: [PATCH 106/136] Custom-domain lookup test: each container takes one domain spelling (#15936) custom_domain_lookup_warns_and_round_trips_verbatim crossed 3 LUT domain spellings with 6 PSD/PSB x depth containers (18 open/save chains). The spelling only decides read_lookup's default-domain check; after that the block is raw bytes whose stored lengths are all multiples of four, so no spelling reaches a different container path. Each of the 6 containers now takes the spellings in turn: every container and every spelling still runs the whole open, native round trip and PSD/PSB re-save chain, with the same assertions. adjust_map's unit tests still parse every spelling. --- crates/io/tests/it/adjust_warnings.rs | 74 ++++++++++++++------------- 1 file changed, 39 insertions(+), 35 deletions(-) diff --git a/crates/io/tests/it/adjust_warnings.rs b/crates/io/tests/it/adjust_warnings.rs index 55220bb251..d74ffde1e6 100644 --- a/crates/io/tests/it/adjust_warnings.rs +++ b/crates/io/tests/it/adjust_warnings.rs @@ -177,45 +177,49 @@ fn short_color_lookup_table_warns_on_open() { #[test] fn custom_domain_lookup_warns_and_round_trips_verbatim() { + // The domain spelling only decides whether the LUT reads as default (`read_lookup`); from + // there the block is kept as raw bytes, whose stored lengths are all a multiple of four, so + // no spelling changes the containers' padding. Each container takes the spellings in turn: + // every spelling still crosses PSD and PSB, and `adjust_map`'s unit tests parse each one. let domains = ["DOMAIN_MIN 0 0 0\nDOMAIN_MAX 0.5 0.5 0.5\n", "DOMAIN_MIN 0 0.25 0\nDOMAIN_MAX 1 0.75 1\n", "LUT_3D_INPUT_RANGE 0 0.5\n"]; - for domain in domains { + let containers = [ + (Version::Psd, 8, "psd"), + (Version::Psd, 16, "psd"), + (Version::Psd, 32, "psd"), + (Version::Psb, 8, "psb"), + (Version::Psb, 16, "psb"), + (Version::Psb, 32, "psb"), + ]; + for (i, (version, depth, extension)) in containers.into_iter().enumerate() { + let domain = domains[i % domains.len()]; let cube = identity_cube(domain); - for (version, depth, extension) in [ - (Version::Psd, 8, "psd"), - (Version::Psd, 16, "psd"), - (Version::Psd, 32, "psd"), - (Version::Psb, 8, "psb"), - (Version::Psb, 16, "psb"), - (Version::Psb, 32, "psb"), - ] { - let input = synthetic_lookup_psd(version, depth, &cube); - let (_, source_block) = parsed_lookup_block(&input); - let name = format!("input.{extension}"); - let opened = import(&name, &input).expect("open synthetic PSD/PSB"); - assert_eq!(unsupported_lookup_raw(&opened.document), source_block, "{extension}, {depth}-bit, {domain:?}"); - let warnings: Vec<_> = opened.warnings.iter().filter(|warning| warning.contains("Custom-domain LUT")).collect(); - assert_eq!(warnings.len(), 1, "{extension}, {depth}-bit: {:?}", opened.warnings); - assert!( - warnings[0].contains("Color Lookup") - && warnings[0].contains("DOMAIN_MIN") - && warnings[0].contains("DOMAIN_MAX") - && warnings[0].to_ascii_lowercase().contains("not supported"), - "{}", - warnings[0] - ); + let input = synthetic_lookup_psd(version, depth, &cube); + let (_, source_block) = parsed_lookup_block(&input); + let name = format!("input.{extension}"); + let opened = import(&name, &input).expect("open synthetic PSD/PSB"); + assert_eq!(unsupported_lookup_raw(&opened.document), source_block, "{extension}, {depth}-bit, {domain:?}"); + let warnings: Vec<_> = opened.warnings.iter().filter(|warning| warning.contains("Custom-domain LUT")).collect(); + assert_eq!(warnings.len(), 1, "{extension}, {depth}-bit: {:?}", opened.warnings); + assert!( + warnings[0].contains("Color Lookup") + && warnings[0].contains("DOMAIN_MIN") + && warnings[0].contains("DOMAIN_MAX") + && warnings[0].to_ascii_lowercase().contains("not supported"), + "{}", + warnings[0] + ); - let native = export(&opened.document, "preserved.pcraft", &ExportOptions::default()).expect("save native document"); - let native_open = import("preserved.pcraft", &native.bytes).expect("reopen native document"); - assert_eq!(unsupported_lookup_raw(&native_open.document), source_block, "native preservation, {extension}, {depth}-bit"); + let native = export(&opened.document, "preserved.pcraft", &ExportOptions::default()).expect("save native document"); + let native_open = import("preserved.pcraft", &native.bytes).expect("reopen native document"); + assert_eq!(unsupported_lookup_raw(&native_open.document), source_block, "native preservation, {extension}, {depth}-bit"); - let output_name = format!("roundtrip.{extension}"); - let options = ExportOptions { force_psb: version.is_psb(), ..Default::default() }; - let saved = export(&native_open.document, &output_name, &options).expect("re-export PSD/PSB"); - let (_, output_block) = parsed_lookup_block(&saved.bytes); - assert_eq!(output_block, source_block, "saved block, {extension}, {depth}-bit, {domain:?}"); - let reopened = import(&output_name, &saved.bytes).expect("reopen re-exported PSD/PSB"); - assert_eq!(unsupported_lookup_raw(&reopened.document), source_block, "reopened block, {extension}, {depth}-bit"); - } + let output_name = format!("roundtrip.{extension}"); + let options = ExportOptions { force_psb: version.is_psb(), ..Default::default() }; + let saved = export(&native_open.document, &output_name, &options).expect("re-export PSD/PSB"); + let (_, output_block) = parsed_lookup_block(&saved.bytes); + assert_eq!(output_block, source_block, "saved block, {extension}, {depth}-bit, {domain:?}"); + let reopened = import(&output_name, &saved.bytes).expect("reopen re-exported PSD/PSB"); + assert_eq!(unsupported_lookup_raw(&reopened.document), source_block, "reopened block, {extension}, {depth}-bit"); } } From c877585a7fe89bbcb60044b3ee5ff5b343129092 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:20:50 +0100 Subject: [PATCH 107/136] #15928: Camera Raw GPU tests run one integer depth and float per case 8 and 16 bits both develop with `float = false`, so they share every line of the CPU develop and the pass; cases alternate between them so both quantizations still run. Tiny frames run one depth per size, flat frames and the dehaze tower (not quantized) drop the identical 16-bit run, the dehaze cache test runs on an 858-wide strip (the cache key doesn't hold the size), and the shadows-only 858-wide strip is left to the clarity test's strip, whose case has Shadows and Highlights too. --- crates/gpu/tests/it/camera_raw.rs | 90 +++++++++++++++++-------------- 1 file changed, 51 insertions(+), 39 deletions(-) diff --git a/crates/gpu/tests/it/camera_raw.rs b/crates/gpu/tests/it/camera_raw.rs index d85a2fac52..7d5904fd29 100644 --- a/crates/gpu/tests/it/camera_raw.rs +++ b/crates/gpu/tests/it/camera_raw.rs @@ -1,8 +1,9 @@ -//! Camera Raw's GPU preview pass against the CPU develop (the oracle), stage by stage, at 8, 16 -//! and 32 bits. Skips, with a message, when there is no adapter or device or it can't render -//! `Rgba32Float`; with `WGPU_BACKEND` set those fail instead, as in `parity.rs`. A pipeline that -//! doesn't build on an adapter that can run it fails. The shader itself is validated without a -//! GPU ([`the_shader_validates_without_a_gpu`]), so a WGSL error fails on every runner. +//! Camera Raw's GPU preview pass against the CPU develop (the oracle), stage by stage, at an +//! integer depth (8 or 16 bits) and at 32 bits (see [`depths`]). Skips, with a message, when +//! there is no adapter or device or it can't render `Rgba32Float`; with `WGPU_BACKEND` set those +//! fail instead, as in `parity.rs`. A pipeline that doesn't build on an adapter that can run it +//! fails. The shader itself is validated without a GPU ([`the_shader_validates_without_a_gpu`]), +//! so a WGSL error fails on every runner. use photocraft_algo::camera_raw::{self as raw, CameraRaw, DevelopInputs, StoredVignetteStyle, Wheel}; use photocraft_gpu::{CameraRawDevelop, DeviceHealth, Fault}; @@ -135,6 +136,15 @@ enum Depth { const DEPTHS: [Depth; 3] = [Depth::Eight, Depth::Sixteen, Depth::Float]; +/// The depths the `i`th case of a set runs at: one integer depth and 32 bits. 8 and 16 bits both +/// develop with `float = false` (the dialog hands the develop only `float`, see +/// `crates/ui-egui/src/dialogs/camera_raw_gpu.rs`), so they share every line of the CPU develop +/// and the pass and differ only in how [`image`] quantizes the input; cases alternate between +/// them so both quantizations still run. +fn depths(i: usize) -> [Depth; 2] { + [DEPTHS[i % 2], Depth::Float] +} + fn hash(i: usize, c: u64) -> f32 { let mut z = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ c.wrapping_mul(0xC2B2_AE3D_27D4_EB4F); z = (z ^ (z >> 29)).wrapping_mul(0xBF58_476D_1CE4_E5B9); @@ -208,8 +218,8 @@ fn check(name: &str, sets: &[Case]) { fn check_at(name: &str, sets: &[Case], size: (usize, usize)) { let Some(mut g) = gpu() else { return }; - for p in sets { - for depth in DEPTHS { + for (i, p) in sets.iter().enumerate() { + for depth in depths(i) { let d = compare_at(&mut g, p, depth, size); eprintln!("{name} {depth:?}: max |GPU - CPU| = {d:.2e}"); } @@ -439,15 +449,17 @@ fn shadows_and_highlights_on_tiny_odd_and_flat_frames() { let stages = per_pixel(&p, 3, 3, false, None).unwrap(); assert!(g.dev.develop(&g.device, &g.queue, None, &image(w, h, Depth::Eight), None, [w as u32, h as u32], &stages).is_err()); } - for size in [(3, 3), (5, 3), (37, 23), (300, 7)] { - for depth in DEPTHS { - let d = compare_at(&mut g, &p, depth, size); - eprintln!("shadows/highlights {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}"); - } + // One depth per size, in turn: the size decides the pyramid and the edges, the depth only the + // input's quantization and whether the result clips, which `shadows_and_highlights` checks + // at every depth. + for (i, size) in [(3, 3), (5, 3), (37, 23), (300, 7)].into_iter().enumerate() { + let depth = DEPTHS[i % DEPTHS.len()]; + let d = compare_at(&mut g, &p, depth, size); + eprintln!("shadows/highlights {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}"); } - // A flat frame has no range to filter. + // A flat frame has no range to filter. It isn't quantized, so one integer depth. let flat = vec![[0.4, 0.35, 0.3, 1.0]; 64 * 48]; - for depth in DEPTHS { + for depth in depths(0) { compare_image(&mut g, &p, depth, &flat, (64, 48)); } } @@ -480,7 +492,7 @@ fn shadows_and_highlights_with_per_pixel_stages() { check_at( "shadows/highlights + per pixel", &[ - all.clone(), + all, // Whites and Blacks measured after the filter, both directions. cr! { shadows: 60.0, whites: 70.0, blacks: -45.0}, cr! { highlights: -60.0, whites: -60.0, blacks: 50.0, exposure: -0.4}, @@ -488,13 +500,9 @@ fn shadows_and_highlights_with_per_pixel_stages() { ], (171, 48), ); - // At the dialog's proxy width, at one depth: the depth only changes how the input is - // quantized (8 and 16 bits both develop with `float = false`), and every depth already ran - // above at 171×48. The long side is what matters here (subsampled pyramid levels); the short - // one only needs to keep several levels, so the frame is a strip. - let Some(mut g) = gpu() else { return }; - let d = compare_at(&mut g, &all, Depth::Sixteen, (858, 120)); - eprintln!("shadows/highlights + per pixel 858x120: max |GPU - CPU| = {d:.2e}"); + // The dialog's proxy width (the pyramid levels and range cells at that size) runs in + // `clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages`, whose first set + // has Shadows and Highlights too. } /// Asserts that each of `sets` moves some pixel of the test image by over 2 %, so a comparison @@ -584,21 +592,22 @@ fn clarity_texture_and_dehaze_on_tiny_and_odd_frames() { let Some(mut g) = gpu() else { return }; let p = cr! { dehaze: 45.0, clarity: 50.0, texture: 60.0, whites: 20.0, blacks: -20.0}; // Without Shadows and Highlights even 1 and 2 pixel frames develop on the GPU. - for size in [(1, 1), (2, 2), (40, 2), (3, 3), (5, 3), (37, 23), (300, 7)] { - for depth in DEPTHS { - let d = compare_at(&mut g, &p, depth, size); - eprintln!("clarity/texture/dehaze {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}"); - } + // One depth per size, in turn, as in `shadows_and_highlights_on_tiny_odd_and_flat_frames`; + // `clarity_texture_and_dehaze` checks the stages at every depth. + for (i, size) in [(1, 1), (2, 2), (40, 2), (3, 3), (5, 3), (37, 23), (300, 7)].into_iter().enumerate() { + let depth = DEPTHS[i % DEPTHS.len()]; + let d = compare_at(&mut g, &p, depth, size); + eprintln!("clarity/texture/dehaze {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}"); } // Texture's blur on a small proxy is too narrow to change anything; the stage still runs. let narrow = cr! { texture: 80.0, contrast: 10.0, pixel_scale: 0.1}; assert!(per_pixel(&narrow, 64, 48, true, None).and_then(|s| s.texture).is_some_and(|t| t.radii.is_empty())); - for depth in DEPTHS { + for depth in depths(1) { compare_at(&mut g, &narrow, depth, (64, 48)); } - // A flat frame: no haze to find, no detail to raise. + // A flat frame: no haze to find, no detail to raise. Not quantized, so one integer depth. let flat = vec![[0.4, 0.35, 0.3, 1.0]; 64 * 48]; - for depth in DEPTHS { + for depth in depths(0) { compare_image(&mut g, &p, depth, &flat, (64, 48)); } } @@ -620,25 +629,28 @@ fn dehaze_opens_the_dark_channel_like_the_cpu() { [c[0], c[1], c[2], 1.0] }) .collect(); - for dehaze in [100.0, 60.0, -40.0] { - for depth in DEPTHS { - let d = compare_image(&mut g, &cr! { dehaze: dehaze }, depth, &src, (w, h)); - eprintln!("dehaze {dehaze} on the tower {depth:?}: max |GPU - CPU| = {d:.2e}"); - } + // The scene isn't quantized, so the depth only picks `float` (whether the result clips); one + // per strength, both in turn. + for (dehaze, depth) in [(100.0, Depth::Float), (60.0, Depth::Eight), (-40.0, Depth::Float)] { + let d = compare_image(&mut g, &cr! { dehaze: dehaze }, depth, &src, (w, h)); + eprintln!("dehaze {dehaze} on the tower {depth:?}: max |GPU - CPU| = {d:.2e}"); } } #[test] fn dehaze_remakes_its_copy_when_the_white_balance_changes() { let Some(mut g) = gpu() else { return }; - let src = image(858, 572, Depth::Eight); + // The dialog's proxy width, so the copy is subsampled as there; the cache key doesn't hold the + // size, so the frame is a strip. + let (w, h) = (858, 120); + let src = image(w, h, Depth::Eight); // Same source key throughout: the copy is cached by it and by the white balance. for temperature in [25.0, -40.0, -40.0, 0.0] { let p = cr! { dehaze: 50.0, temperature}; let mut cpu = src.clone(); - develop(&mut cpu, 858, 572, &p, false); - let stages = per_pixel(&p, 858, 572, false, None).unwrap(); - let out = g.dev.develop(&g.device, &g.queue, None, &src, Some(3), [858, 572], &stages).unwrap(); + develop(&mut cpu, w, h, &p, false); + let stages = per_pixel(&p, w, h, false, None).unwrap(); + let out = g.dev.develop(&g.device, &g.queue, None, &src, Some(3), [w as u32, h as u32], &stages).unwrap(); let d = out.iter().zip(&cpu).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max); assert!(d <= TOL, "temperature {temperature}: off by {d}"); } From 03561a189d93c60e8e3bec1a6522cd94e13a734f Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:38:34 +0100 Subject: [PATCH 108/136] #15930: compute the measured structure-continue fill once The six measured `structure_continue_tests` (Auto and Rectangular x samples, boundary, phase) all filled the same document with the same options, and `measured_auto_area_is_the_rectangular_one` asserts that Auto gives `fill` the Rectangular area there. One test now fills once and checks the nine samples, the blue / green boundary and the phase through the whole hole, reporting every check that is off. --- .../content_aware/structure_continue_tests.rs | 73 +++++++------------ 1 file changed, 25 insertions(+), 48 deletions(-) diff --git a/crates/algo/src/content_aware/structure_continue_tests.rs b/crates/algo/src/content_aware/structure_continue_tests.rs index 895e9f5d02..62a097d5d8 100644 --- a/crates/algo/src/content_aware/structure_continue_tests.rs +++ b/crates/algo/src/content_aware/structure_continue_tests.rs @@ -67,14 +67,11 @@ fn window_buffers() -> (Vec, Vec, usize) { (img, hole, ww) } -/// Fill the measured document the way the command does with `opts` and Auto or Rectangular -/// sampling, and return the filled window. -fn fill_measured_document(sampling: &str, opts: &FillOptions) -> Vec { +/// Fill the measured document the way the command does with `opts` and Auto sampling, and return +/// the filled window. +fn fill_measured_document(opts: &FillOptions) -> Vec { let (img, hole, ww) = window_buffers(); - let source = match sampling { - "auto" => auto_sampling(ww, 400, 3, &img, &hole), - _ => hole.iter().map(|h| !h).collect(), - }; + let source = auto_sampling(ww, 400, 3, &img, &hole); fill(ww, 400, 3, &img, &hole, &source, opts) } @@ -169,49 +166,29 @@ fn boundary_mismatches(out: &[f32]) -> (usize, usize) { (green_above, cold_below) } +/// The measured fill, computed once: Auto and Rectangular give `fill` the same area on this +/// document ([`measured_auto_area_is_the_rectangular_one`]), so one fill stands for both. The +/// checks are collected first, so a failure reports every one that is off. #[test] -fn auto_fill_continues_the_bands_and_stripes_at_the_measured_samples() { +fn measured_fill_continues_the_bands_and_stripes_and_keeps_the_boundary_at_y_200() { assert_eq!(window(), Rect::new(100, 0, 500, 400), "the sampling window #14191 measured"); - let out = fill_measured_document("auto", &FillOptions::default()); + let out = fill_measured_document(&FillOptions::default()); + let mut failures = Vec::new(); let off = samples_off(&out); - assert!(off.is_empty(), "Auto sampling: {} of 9 samples off\n{}", off.len(), off.join("\n")); -} - -#[test] -fn rectangular_fill_continues_the_bands_and_stripes_at_the_measured_samples() { - let out = fill_measured_document("rectangular", &FillOptions::default()); - let off = samples_off(&out); - assert!(off.is_empty(), "Rectangular sampling: {} of 9 samples off\n{}", off.len(), off.join("\n")); -} - -#[test] -fn auto_fill_keeps_the_blue_green_boundary_at_y_200() { - let out = fill_measured_document("auto", &FillOptions::default()); + if !off.is_empty() { + failures.push(format!("{} of 9 samples off\n{}", off.len(), off.join("\n"))); + } let (green_above, cold_below) = boundary_mismatches(&out); - assert_eq!(green_above, 0, "pixels above y 200 that took a colour of the green half"); - assert_eq!(cold_below, 0, "pixels below y 200 that took a colour of the blue half"); -} - -#[test] -fn rectangular_fill_keeps_the_blue_green_boundary_at_y_200() { - let out = fill_measured_document("rectangular", &FillOptions::default()); - let (green_above, cold_below) = boundary_mismatches(&out); - assert_eq!(green_above, 0, "pixels above y 200 that took a colour of the green half"); - assert_eq!(cold_below, 0, "pixels below y 200 that took a colour of the blue half"); -} - -#[test] -fn auto_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() { - let out = fill_measured_document("auto", &FillOptions::default()); + if (green_above, cold_below) != (0, 0) { + failures.push(format!( + "the blue / green boundary moved: {green_above} pixels above y 200 took a colour of the green half, {cold_below} below it one of the blue half" + )); + } let (worst, within, n) = phase_through_the_hole(&out); - assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})"); -} - -#[test] -fn rectangular_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() { - let out = fill_measured_document("rectangular", &FillOptions::default()); - let (worst, within, n) = phase_through_the_hole(&out); - assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})"); + if within != n { + failures.push(format!("{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})")); + } + assert!(failures.is_empty(), "{}", failures.join("\n")); } /// Per-channel slack for the unmeasured pins below. The exact values hold bit for bit on Windows @@ -273,7 +250,7 @@ fn unmeasured_geometric_adaptation() -> Vec<(&'static str, FillOptions, [i32; 27 } fn check_unmeasured(what: &str, opts: &FillOptions, want: &[i32; 27]) { - let out = fill_measured_document("auto", opts); + let out = fill_measured_document(opts); let got: Vec = SAMPLES.iter().flat_map(|((x, y), _)| filled_at(&out, *x, *y)).collect(); let off: Vec = SAMPLES .iter() @@ -307,8 +284,8 @@ fn unmeasured_geometric_adaptation_keeps_todays_fill() { #[test] fn measured_auto_area_is_the_rectangular_one() { - // What the measured Auto and Rectangular fills above rest on: on this document Auto keeps the - // whole window, as in the reference application. + // What the measured fill above rests on: on this document Auto keeps the whole window, as in + // the reference application, so the Auto fill is the Rectangular one. let (img, hole, ww) = window_buffers(); assert_eq!(auto_sampling(ww, 400, 3, &img, &hole), hole.iter().map(|h| !h).collect::>()); } From e22a775246a2ab4b6ebe740a7afd14d851134039 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:19:55 +0100 Subject: [PATCH 109/136] #15929: build the compositor pipelines with FXC once, not twice `pipelines::every_compositor_pipeline_builds` builds every pipeline with FXC on DX12, then again on every backend with `Dx12Compiler::Auto`. Without `dxcompiler.dll` on the search path, as on the Windows runners, `Auto` falls back to FXC, so the second DX12 pass repeated the first. The second pass now names DXC, so DX12 drops out of it when DXC does not load and is built through DXC when it does. The Windows adapter and device checks stay on the FXC pass. --- crates/gpu/tests/it/pipelines.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/gpu/tests/it/pipelines.rs b/crates/gpu/tests/it/pipelines.rs index fa4b684ad9..7d7cde044b 100644 --- a/crates/gpu/tests/it/pipelines.rs +++ b/crates/gpu/tests/it/pipelines.rs @@ -32,21 +32,24 @@ fn every_compositor_pipeline_builds() { // One instance per backend: `Backends::all()` only enables the others on one instance, and // `request_adapter` then returns the single default adapter, so the other backends' own // translation went untested. One adapter per backend keeps a second, unrelated adapter of the - // same backend (a dual-GPU laptop's integrated GPU) out of the run. - for (backends, compiler) in [(wgpu::Backends::DX12, wgpu::Dx12Compiler::Fxc), (wgpu::Backends::all(), wgpu::Dx12Compiler::Auto)] { + // same backend (a dual-GPU laptop's integrated GPU) out of the run. The second pass names DXC + // rather than `Auto`: without `dxcompiler.dll`, as on the Windows runners, `Auto` falls back to + // FXC and built every pipeline with FXC a second time (half of this test's time, #15929), while + // a DXC that does not load leaves DX12 out of that pass. + for (backends, compiler) in [(wgpu::Backends::DX12, wgpu::Dx12Compiler::Fxc), (wgpu::Backends::all(), wgpu::Dx12Compiler::default_dynamic_dxc())] { + let required = cfg!(windows) && matches!(compiler, wgpu::Dx12Compiler::Fxc); for backend in backends.iter() { let instance = wgpu::Instance::new(describe(backend, compiler.clone())); // The Windows runners always have a WARP adapter on DX12, so a missing one there means // the check this test exists for silently did not run. Any other backend is a plain - // skip: `Backends::all()` also names backends this platform does not provide. + // skip: `Backends::all()` also names backends this platform does not provide, and + // DX12 through DXC needs a `dxcompiler.dll`. let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { - #[cfg(windows)] - assert!(backend != wgpu::Backends::DX12, "no adapter on Windows: the DX12/FXC pipeline check did not run"); + assert!(!required, "no adapter on Windows: the DX12/FXC pipeline check did not run"); continue; }; let Ok((device, _queue)) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())) else { - #[cfg(windows)] - assert!(backend != wgpu::Backends::DX12, "no device on Windows: the DX12/FXC pipeline check did not run"); + assert!(!required, "no device on Windows: the DX12/FXC pipeline check did not run"); continue; }; let info = adapter.get_info(); From 63253358bc4c94cf23b160405057fb3f08eb8559 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:47:00 +0100 Subject: [PATCH 110/136] #15929: drop the time share from the second-pass comment The CI runners saved about a quarter of the test, not half. --- crates/gpu/tests/it/pipelines.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/gpu/tests/it/pipelines.rs b/crates/gpu/tests/it/pipelines.rs index 7d7cde044b..8313213c4d 100644 --- a/crates/gpu/tests/it/pipelines.rs +++ b/crates/gpu/tests/it/pipelines.rs @@ -34,8 +34,8 @@ fn every_compositor_pipeline_builds() { // translation went untested. One adapter per backend keeps a second, unrelated adapter of the // same backend (a dual-GPU laptop's integrated GPU) out of the run. The second pass names DXC // rather than `Auto`: without `dxcompiler.dll`, as on the Windows runners, `Auto` falls back to - // FXC and built every pipeline with FXC a second time (half of this test's time, #15929), while - // a DXC that does not load leaves DX12 out of that pass. + // FXC and built every pipeline with FXC a second time (#15929), while a DXC that does not load + // leaves DX12 out of that pass. for (backends, compiler) in [(wgpu::Backends::DX12, wgpu::Dx12Compiler::Fxc), (wgpu::Backends::all(), wgpu::Dx12Compiler::default_dynamic_dxc())] { let required = cfg!(windows) && matches!(compiler, wgpu::Dx12Compiler::Fxc); for backend in backends.iter() { From d7f8f1c170bb7e900c00a02dc442ac6cff7023a8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 15:41:00 +0100 Subject: [PATCH 111/136] WIP: Crop previews the grown area in the background colour (#16185) From 8367f93c1666671a17f3229f88a36ceea0da5f6f Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 15:56:25 +0100 Subject: [PATCH 112/136] Crop previews the area a crop adds past the canvas in the background colour, and Classic Mode shows nothing past it (#16185) Needs the craft-libs pin with RasterDisplay::region_fill. --- crates/ui-egui/src/canvas/document_display.rs | 14 ++++++- crates/ui-egui/src/tools/crop_ui.rs | 14 ++++++- crates/ui-egui/src/tools/crop_ui/tests.rs | 41 +++++++++++++++++++ 3 files changed, 66 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 446295699e..9e1ea6b806 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -392,6 +392,12 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, let r = frame.turned_bounds(); PixelRect::new(r.x0.floor() as i32, r.y0.floor() as i32, r.x1.ceil() as i32, r.y1.ceil() as i32) }); + // What a crop that grows the canvas adds to a Background previews in its fill colour, as on the monitor. + let region_fill = region.and_then(|_| crate::crop_ui::grown_fill(app, doc)).and_then(|c| { + let (display, _) = super::display::canvas_display(app, doc, output); + let one = photocraft_compose::Buffer::filled(DRect::from_xywh(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + super::display::display_image(display.as_deref(), &one).pixels.first().copied() + }); let app: &PhotocraftApp = app; let (gpu, composite) = match prepared { Some(Prepared::Gpu(picture)) => (Some(picture), None), @@ -401,7 +407,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, let overlay = overlay.map(|prep| prep.source(app)); let bounds = gpu.as_ref().map(GpuPicture::bounds).or_else(|| composite.as_ref().map(|c| c.bounds())).unwrap_or_else(|| doc.bounds()); let mapping = (bounds != doc.bounds()).then(|| placement(bounds)); - let frame = Frame { checker: checker.as_ref(), edge, mapping, pattern, region }; + let frame = Frame { checker: checker.as_ref(), edge, mapping, pattern, region, region_fill }; if let Some(picture) = &gpu { frame.apply(RasterDisplay::painted(label.clone(), size, picture.clone().into_paint())).picture().show_at(ui, body.rect); } else if let Some(composite) = &composite { @@ -577,6 +583,8 @@ struct Frame<'c> { mapping: Option, pattern: bool, region: Option, + /// The colour of the region past the document (a crop's grown Background), over the checkerboard. + region_fill: Option, } impl Frame<'_> { @@ -594,6 +602,10 @@ impl Frame<'_> { Some(region) => display.extent(Extent::Region(region)), None => display, }; + let display = match self.region_fill { + Some(fill) => display.region_fill(fill), + None => display, + }; if self.pattern { display.extent(Extent::Tiled) } else { display } } } diff --git a/crates/ui-egui/src/tools/crop_ui.rs b/crates/ui-egui/src/tools/crop_ui.rs index 23828a19c6..c7d1945d05 100644 --- a/crates/ui-egui/src/tools/crop_ui.rs +++ b/crates/ui-egui/src/tools/crop_ui.rs @@ -217,9 +217,19 @@ pub fn frame(app: &PhotocraftApp) -> Option { app.canvas_tools.crop.tool.frame() } -/// The canvas shows the pixels past its edges under the shield. +/// The canvas shows the pixels past its edges under the shield. Default mode only: in Classic Mode the frame lies over +/// the pasteboard and the layers stop at the canvas edge, as in Photoshop. pub(crate) fn shows_beyond_canvas(app: &PhotocraftApp) -> bool { - app.ui.tool == Tool::Crop && app.canvas_tools.crop.tool.shows_beyond_canvas() + app.ui.tool == Tool::Crop && app.ui.tool_options.crop.image_mode() && app.canvas_tools.crop.tool.shows_beyond_canvas() +} + +/// The colour the area a crop adds past the canvas previews in (`shows_beyond_canvas`), as the commit fills it: the +/// background colour on a visible Background with Delete Cropped Pixels on and Fill: Background. `None` previews +/// transparency (Delete off turns the Background into a layer; Content-Aware Fill makes its own pixels). +pub(crate) fn grown_fill(app: &PhotocraftApp, doc: &photocraft_doc::Document) -> Option<[f32; 4]> { + let crop = &app.ui.tool_options.crop; + let fills = crop.delete_pixels && crop.fill == CropFill::Background && doc.background().is_some_and(|layer| layer.visible); + fills.then_some(app.session.tools.background) } /// Show Cropped Area is off with the Crop tool showing a frame: nothing outside it shows. diff --git a/crates/ui-egui/src/tools/crop_ui/tests.rs b/crates/ui-egui/src/tools/crop_ui/tests.rs index 95a1ea379f..11d8883160 100644 --- a/crates/ui-egui/src/tools/crop_ui/tests.rs +++ b/crates/ui-egui/src/tools/crop_ui/tests.rs @@ -417,3 +417,44 @@ fn drawing_a_new_crop_snaps_its_corner_not_the_default_frame() { assert!((frame.rect.x1 - 300.0).abs() < 1e-6, "classic {classic}: {frame:?}"); } } + +/// #16185: as in Photoshop, the pixels past the canvas show while a frame is edited in the default mode only; in Classic +/// Mode the frame lies over the pasteboard and the layers stop at the canvas edge. +#[test] +fn classic_mode_shows_nothing_past_the_canvas() { + let mut app = app(SampleType::U8); + drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); + assert!(tool(&mut app).shows_beyond_canvas(), "the drawn frame is being edited"); + assert!(!crop_ui::shows_beyond_canvas(&app), "Classic Mode: no preview past the canvas"); + app.ui.tool_options.crop.shield.classic_mode = false; + assert!(crop_ui::shows_beyond_canvas(&app), "default mode: the canvas shows past its edges"); +} + +/// #16185: the area a crop adds past the canvas previews in the colour the commit fills a Background's new area with, +/// and as transparency where the commit leaves it transparent. +#[test] +fn the_grown_area_previews_in_the_background_colour_the_crop_fills_it_with() { + let mut app = app(SampleType::U8); + app.ui.tool_options.crop.shield.classic_mode = false; + let red = [1.0, 0.0, 0.0, 1.0]; + app.session.tools.background = red; + let doc = (*app.session.active().unwrap().doc).clone(); + assert_eq!(crop_ui::grown_fill(&app, &doc), Some(red), "Delete Cropped Pixels on, Fill: Background"); + + app.ui.tool_options.crop.delete_pixels = false; + assert_eq!(crop_ui::grown_fill(&app, &doc), None, "Delete off turns the Background into a layer: transparency"); + app.ui.tool_options.crop.delete_pixels = true; + + app.ui.tool_options.crop.fill = CropFill::ContentAware; + assert_eq!(crop_ui::grown_fill(&app, &doc), None, "Content-Aware Fill makes its own pixels"); + app.ui.tool_options.crop.fill = CropFill::Background; + + let mut hidden = doc.clone(); + hidden.layers[0].visible = false; + assert_eq!(crop_ui::grown_fill(&app, &hidden), None, "a hidden Background shows nothing"); + + app.session.execute("layer.new.layerFromBackground", json!({})).unwrap(); + let layered = (*app.session.active().unwrap().doc).clone(); + assert!(layered.background().is_none()); + assert_eq!(crop_ui::grown_fill(&app, &layered), None, "no Background: the other layers stay transparent there"); +} From f0f09d33f3cdeca04cd8d40f5a40d1dd726ff71d Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:31:49 +0100 Subject: [PATCH 113/136] docs: remove unavailable Windows x86 downloads --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 04508f9637..380fa11989 100644 --- a/README.md +++ b/README.md @@ -353,7 +353,6 @@ sha256-verified. Fetch them with `cargo xtask corpus --all` and run the tests wi |---|---|---| | x64 (64-bit Intel/AMD) | `photocraft--windows-x64.msi` | `photocraft--windows-x64-portable.zip` | | arm64 (Snapdragon and other ARM PCs) | `photocraft--windows-arm64.msi` | `photocraft--windows-arm64-portable.zip` | -| x86 (32-bit) | `photocraft--windows-x86.msi` | `photocraft--windows-x86-portable.zip` | Installers and executables are code-signed. From 7a6dba8fe932706af85938b3aeff5d82ca14cb83 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:55:18 +0100 Subject: [PATCH 114/136] CLI: accept a UTF-8 BOM in recorded action files --- apps/photocraft-cli/src/actions.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/apps/photocraft-cli/src/actions.rs b/apps/photocraft-cli/src/actions.rs index f8b900e49a..faad175a17 100644 --- a/apps/photocraft-cli/src/actions.rs +++ b/apps/photocraft-cli/src/actions.rs @@ -90,7 +90,8 @@ pub fn load_actions_file(path: &Path, name: Option<&str>) -> Result<(Steps, Vec< let is_atn = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("atn")) || matches!(bytes.get(..4), Some([0, 0, 0, 12 | 16])); if !is_atn { let text = String::from_utf8(bytes).map_err(|source| ActionsError::Utf8 { path: path.to_path_buf(), source })?; - let (steps, set) = load_actions(&text, name)?; + let text = text.strip_prefix('\u{feff}').unwrap_or(&text); + let (steps, set) = load_actions(text, name)?; return Ok((steps, set, Vec::new())); } let imp = photocraft_engine::atn_cmds::import(&bytes).map_err(|message| ActionsError::Atn { path: path.to_path_buf(), message })?; @@ -114,3 +115,23 @@ pub fn load_actions_file(path: &Path, name: Option<&str>) -> Result<(Steps, Vec< let play = vec![("actions.play".to_string(), json!({"action": action.name}))]; Ok((play, imp.actions, warnings)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn load_actions_file_accepts_utf8_bom() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("actions.json"); + + std::fs::write(&path, b"\xEF\xBB\xBF[\"image.adjustments.invert\"]").unwrap(); + let (steps, set, warnings) = load_actions_file(&path, None).unwrap(); + assert_eq!(steps, vec![("image.adjustments.invert".to_owned(), json!({}))]); + assert!(set.is_empty()); + assert!(warnings.is_empty()); + + std::fs::write(&path, b"\xEF\xBB\xBF[").unwrap(); + assert!(matches!(load_actions_file(&path, None), Err(ActionsError::Json(_)))); + } +} From aedf6224f0408ff186b1ec7641e1b130d4330d53 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:03:18 +0100 Subject: [PATCH 115/136] fix(batch): reject non-path entries in explicit input lists --- crates/engine/src/cmd/file_cmds/batch_run.rs | 26 +++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 680d5e404f..7b92b586fa 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -7,12 +7,36 @@ use super::{Arc, Document, EngineError, Result, Session, Value, batch_naming, js /// Inputs of a batch command: `"input"` is a folder or an array of files. pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result> { match p.get("input").or_else(|| p.get("files")) { - Some(Value::Array(a)) => Ok(a.iter().filter_map(Value::as_str).map(str::to_string).collect()), + Some(Value::Array(a)) => a + .iter() + .enumerate() + .map(|(i, v)| { + v.as_str() + .map(str::to_string) + .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("input file {} must be a path string", i + 1) }) + }) + .collect(), Some(Value::String(dir)) => list_images(dir), _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"input\" (folder or array of files)".into() }), } } +#[test] +fn batch_rejects_a_non_path_input_before_writing() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("source.png"); + let image = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, vec![255; 48]).unwrap(); + let bytes = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + std::fs::write(&input, bytes).unwrap(); + for (cmd, format) in [("file.automate.batch", "png"), ("file.scripts.imageProcessor", "jpg")] { + let output = dir.path().join(format); + let mut s = Session::new(); + let err = s.execute(cmd, json!({"steps": [], "input": [&input, 17], "output": &output, "format": format})).unwrap_err(); + assert!(matches!(&err, EngineError::BadParams { cmd: name, msg } if name == cmd && msg == "input file 2 must be a path string"), "{err}"); + assert!(!output.exists()); + } +} + /// One input of a batch run: the file, and the folder it sits in relative to the input folder /// (`""` at the top level, `"a/b"` two levels down), which its result keeps under `output`. #[derive(Clone, Debug, PartialEq)] From a9edadc0ba11f958f5c955d3b68d516934bec1e8 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:15:43 +0100 Subject: [PATCH 116/136] docs: explain automatic masks on new adjustment layers --- .../guides/adjust-colors-with-adjustment-layers.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/docs/user/guides/adjust-colors-with-adjustment-layers.md b/docs/user/guides/adjust-colors-with-adjustment-layers.md index 500ff3521c..760a3db7a9 100644 --- a/docs/user/guides/adjust-colors-with-adjustment-layers.md +++ b/docs/user/guides/adjust-colors-with-adjustment-layers.md @@ -2,7 +2,7 @@ title: Adjust colors without changing your pixels description: Add a Curves, Levels or other adjustment layer in PhotoCraft so you can change or switch it off later. order: 20 -verified: 0.8.2 +verified: 0.23.1 --- Use **Layer › New Adjustment Layer** and pick an adjustment. The change sits on its own layer above your image, so your original pixels stay as they were and you can edit or hide the adjustment later. @@ -13,20 +13,19 @@ Use **Layer › New Adjustment Layer** and pick an adjustment. The change sits o 2. Choose **Layer › New Adjustment Layer**, then an adjustment such as **Curves…**, **Levels…**, **Vibrance…** or **Hue/Saturation…**. 3. Change the settings in the **Properties** panel, which shows the settings of the new layer. -The same list is behind the button at the bottom of the **Layers** panel, labelled **Create new fill or adjustment layer** when you hover over it. +The fill and adjustment button at the bottom of **Layers** offers the same choices. The adjustments in the menu are **Brightness/Contrast**, **Levels**, **Curves**, **Exposure**, **Vibrance**, **Hue/Saturation**, **Color Balance**, **Black & White**, **Photo Filter**, **Channel Mixer**, **Color Lookup**, **Invert**, **Posterize**, **Threshold**, **Gradient Map** and **Selective Color**. ## Limit it to one area 1. Select the area first, for example with the **Elliptical Marquee Tool**. See [Select part of an image and mask it](select-and-mask.md). -2. Add the adjustment layer as above. -3. With the adjustment layer active, choose **Layer › Layer Mask › Reveal Selection**. The adjustment now shows only inside the selection. +2. Add the adjustment layer as above. PhotoCraft uses the selection as the new layer’s mask, so the adjustment affects only that area. ## Change it later -Click the adjustment layer in the **Layers** panel and edit its settings in **Properties**. Every step you take is also listed in the **History** panel. +Click the adjustment thumbnail in **Layers**, then edit its settings in **Properties**. Every step you take is also listed in the **History** panel. ## Apply an adjustment straight to the pixels -If you do not need to change it later, use **Image › Adjustments**, for example **Image › Adjustments › Curves…**. These change the pixels of the layer directly and are not kept as a separate layer. +To adjust a pixel layer directly, use **Image › Adjustments**, for example **Image › Adjustments › Curves…**. On a Smart Object, supported adjustments appear as Smart Filters. From eb790f5b8213518b01573d7ff4552d9a3f1ea82b Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:28:42 +0100 Subject: [PATCH 117/136] fix(batch): protect the actions file from the error log --- apps/photocraft-cli/src/batch.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index d64f3318d1..676226fada 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -104,6 +104,9 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> photocraft_engine::file_cmds::validate_flat_outputs(&plan).map_err(|error| CliError::Naming(error.to_string()))?; if let Some(log) = &a.error_log { let same = |path: &Path| photocraft_engine::file_cmds::same_destination(log, path); + if same(&a.actions) { + return Err(CliError::BatchOption("--error-log must not replace the --actions file".into())); + } if inputs.iter().any(|input| same(Path::new(&input.path))) || targets.iter().any(|target| same(target)) { return Err(CliError::BatchOption("--error-log must not replace an input or batch output".into())); } From bd6f4055f59de1e90b6ff510ba1ce5b6a0a54268 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:28:53 +0100 Subject: [PATCH 118/136] test: cover equivalent actions and error-log paths --- apps/photocraft-cli/tests/it/cli.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index c572c460fa..be29d2b862 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -715,6 +715,22 @@ fn batch_with(d: &Path, input: &Path, name: &str, actions: &str, extra: &[&str]) bin().args(["batch", "--actions"]).arg(&file).arg("--in").arg(input).arg("--out").arg(d.join(name)).args(extra).output().unwrap() } +#[test] +fn batch_error_log_cannot_replace_its_actions_file() { + let d = tmp("batch-log-actions-collision"); + let input = d.join("in"); + std::fs::create_dir_all(&input).unwrap(); + let actions = r#"[{"command":"image.adjustments.invert"}]"#; + let log = input.join("../actions.json"); + + let result = batch_with(&d, &input, "actions", actions, &["--error-log", &log.to_string_lossy()]); + let error = String::from_utf8_lossy(&result.stderr); + assert!(!result.status.success(), "{error}"); + assert!(error.contains("--error-log") && error.contains("--actions"), "{error}"); + assert_eq!(std::fs::read(d.join("actions.json")).unwrap(), actions.as_bytes()); + assert!(!d.join("actions").exists(), "the output folder must not be created"); +} + /// #489: `batch --actions` takes `[id, params]` steps and a droplet's steps, with the same results /// as the object form; a malformed step fails before anything is written. #[test] From 76312b153bd6cd259594338352c2de5528f429a2 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:46:51 +0100 Subject: [PATCH 119/136] Duplicate Layer: the dialog title drops the menu item's ellipsis (#16349) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Layer › Duplicate Layer… opened a window titled "Duplicate Layer…" ("Duplicate Layers…" for several layers, "Duplicate Group…" on a group). The titles now read without the ellipsis, as #15541 did for Stroke and New Group; the shared title test covers the three cases. --- crates/ui-egui/src/dialog_title_ellipsis_tests.rs | 15 ++++++++++++++- crates/ui-egui/src/dialogs/duplicate_layer_ui.rs | 9 +++++---- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs index 014c7dc1c5..6865848d8b 100644 --- a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs +++ b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs @@ -25,7 +25,7 @@ fn harness() -> Harness<'static, Box> { #[test] fn dialog_titles_drop_the_menu_ellipsis() { - let cases: [(&str, Open); 4] = [ + let cases: [(&str, Open); 7] = [ ("Stroke", |app| { crate::stroke_ui::open(app); }), @@ -38,6 +38,19 @@ fn dialog_titles_drop_the_menu_ellipsis() { ("New Brush Preset", |app| { crate::brush_preset_dialog::open(app, None); }), + // Layer › Duplicate Layer… names its window after what is selected (#16349). + ("Duplicate Layer", |app| { + crate::duplicate_layer_ui::open(app).unwrap(); + }), + ("Duplicate Layers", |app| { + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.allLayers", json!({})).unwrap(); + crate::duplicate_layer_ui::open(app).unwrap(); + }), + ("Duplicate Group", |app| { + app.run("layer.groupLayers", json!({})).unwrap(); + crate::duplicate_layer_ui::open(app).unwrap(); + }), ]; for (title, open) in cases { let mut h = harness(); diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs index 59e6ace51c..dd47475180 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs @@ -52,13 +52,14 @@ pub fn open(app: &mut PhotocraftApp) -> Result { let selected = st.selected_layers(); let layer = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("no active layer")?; let captured = json!({"document": st.doc.id.0, "selected": selected.iter().map(|id| id.0).collect::>()}); - // Several selected layers keep their names, as in Photoshop's Duplicate Layers. + // Several selected layers keep their names, as in Photoshop's Duplicate Layers. The window + // title is the menu item's name without its ellipsis (#16349). let (title, name) = if selected.len() > 1 { - (tl!("Duplicate Layers…"), None) + (tl!("Duplicate Layers"), None) } else if layer.is_group() { - (tl!("Duplicate Group…"), Some(st.doc.copy_name(&layer.name))) + (tl!("Duplicate Group"), Some(st.doc.copy_name(&layer.name))) } else { - (tl!("Duplicate Layer…"), Some(st.doc.copy_name(&layer.name))) + (tl!("Duplicate Layer"), Some(st.doc.copy_name(&layer.name))) }; let mut options: Vec<(String, Label)> = destinations(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect(); options.push(("new".to_string(), Label::from(tl!("New")))); From 2657da41b19d57d2bfbf7588faf1cbcdf90d0210 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 00:40:05 +0100 Subject: [PATCH 120/136] Integration: port the ATN tests of #11536 and #11548 to ActionStep Both PRs predate main's switch from (id, params) tuples to ActionStep { command, params }; their new tests no longer compiled on main. Co-authored-by: MMexicann <44814932+MMexicann@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/tests.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index e6c6515ad1..8e959cdc5a 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -2454,13 +2454,13 @@ fn black_white_fractional_coefficients_refuse_lossy_export() { if id == "layer.setAdjustment" { params["kind"] = json!("blackWhite"); } - let action = Action::new("Fractional BW", vec![(id.into(), params.clone())]); + let action = Action::new("Fractional BW", vec![ActionStep::new(id, params.clone())]); let error = export("BW", &[&action], &[], false).unwrap_err(); assert!(error.contains(id) && error.contains("skipUnsupported"), "{id} {key}: {error}"); let (bytes, skipped) = export("BW", &[&action], &[], true).unwrap(); assert_eq!(skipped, vec![Skipped { action: "Fractional BW".into(), step: 0, id: id.into() }]); assert!(import(&bytes).unwrap().actions[0].steps.is_empty()); - assert_eq!(action.steps[0].1, params, "export must preserve the native action"); + assert_eq!(action.steps[0].params, params, "export must preserve the native action"); } } } @@ -2479,12 +2479,13 @@ fn black_white_whole_coefficients_and_defaults_round_trip() { if id == "layer.setAdjustment" { params["kind"] = json!("blackWhite"); } - let action = Action::new("Whole BW", vec![(id.into(), params.clone())]); + let action = Action::new("Whole BW", vec![ActionStep::new(id, params.clone())]); let (bytes, skipped) = export("BW", &[&action], &[], false).unwrap(); assert!(skipped.is_empty()); let imported = import(&bytes).unwrap(); assert!(imported.unsupported.is_empty() && imported.warnings.is_empty()); - let (back_id, back) = &imported.actions[0].steps[0]; + let step = &imported.actions[0].steps[0]; + let (back_id, back) = (&step.command, &step.params); assert_eq!(back_id, id); for key in ["reds", "yellows", "greens", "cyans", "blues", "magentas"] { assert_eq!(back.get(key).and_then(Value::as_f64), params.get(key).and_then(Value::as_f64), "{id} {key}: {back}"); @@ -3588,7 +3589,7 @@ fn image_size_explicit_sides_keep_precedence_over_percent() { assert_eq!((size.width, size.height), expected, "native {params} at {depth} bits"); let mut recorded = Session::new(); - recorded.actions.list.push(Action::new("Resize", vec![("image.imageSize".into(), params.clone())])); + recorded.actions.list.push(Action::new("Resize", vec![ActionStep::new("image.imageSize", params.clone())])); let before = recorded.actions.list.clone(); let saved = recorded.execute("actions.save", json!({"action": "Resize"})).unwrap(); assert_eq!(saved["skipped"], json!([])); @@ -3614,7 +3615,7 @@ fn image_size_explicit_sides_do_not_hide_invalid_percent() { let mut native = Session::new(); native.execute("file.new", json!({"width": 32, "height": 24})).unwrap(); assert!(native.execute("image.imageSize", params.clone()).is_err(), "{params}"); - let action = Action::new("Resize", vec![("image.imageSize".into(), params.clone())]); + let action = Action::new("Resize", vec![ActionStep::new("image.imageSize", params.clone())]); assert!(export("Size", &[&action], &[], false).is_err(), "{params}"); let (_, skipped) = export("Size", &[&action], &[], true).unwrap(); assert_eq!(skipped.len(), 1, "{params}"); @@ -3629,7 +3630,7 @@ fn image_size_dimensions_have_unique_atn_keys() { (json!({"width": 20, "height": 18, "percent": 50}), D::UnitFloat { unit: PX, value: 20.0 }, D::UnitFloat { unit: PX, value: 18.0 }, None), (json!({"percent": 50}), pct(50.0), pct(50.0), Some(true)), ] { - let action = Action::new("Resize", vec![("image.imageSize".into(), params.clone())]); + let action = Action::new("Resize", vec![ActionStep::new("image.imageSize", params.clone())]); let (bytes, skipped) = export("Size", &[&action], &[], false).unwrap(); assert!(skipped.is_empty()); let file = atn::parse(&bytes).unwrap(); From c74906bdddd565dc72c18ad6798782f2c47edea7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 00:42:19 +0100 Subject: [PATCH 121/136] Integration: use the Result of ActionList::push in the #11548 test Co-authored-by: MMexicann <44814932+MMexicann@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 8e959cdc5a..057a14dd71 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3589,7 +3589,7 @@ fn image_size_explicit_sides_keep_precedence_over_percent() { assert_eq!((size.width, size.height), expected, "native {params} at {depth} bits"); let mut recorded = Session::new(); - recorded.actions.list.push(Action::new("Resize", vec![ActionStep::new("image.imageSize", params.clone())])); + recorded.actions.list.push(Action::new("Resize", vec![ActionStep::new("image.imageSize", params.clone())])).unwrap(); let before = recorded.actions.list.clone(); let saved = recorded.execute("actions.save", json!({"action": "Resize"})).unwrap(); assert_eq!(saved["skipped"], json!([])); From 69252058d75241971d2e42415d48f56d21d34d77 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 01:51:55 +0100 Subject: [PATCH 122/136] Repin craft-libs to next cec6d87ff and egui to 72cb386ac Brings storytold/craft-libs#2919 (layer eye stays empty, #16321), #2929 (About tab spacing, #16325), #2931 (Space after an Alt tap, #16327), #2932 (scroll bar range and drag, #16328, #16329), #2934 (grip ticks and the toolbar grip, #16332, #16333) and #2939 (About stays inside the window, #16326). The Overscroll scroll bar test follows the new range: the document plus, on each side, the visible length less 100 screen points. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 198 +++++++++--------- Cargo.toml | 106 +++++----- crates/engine/Cargo.toml | 2 +- crates/ipp/Cargo.toml | 2 +- crates/ui-egui/src/canvas/document_display.rs | 5 +- 5 files changed, 158 insertions(+), 155 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 84b7b8e6fe..e97745a678 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1365,7 +1365,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-automation", "craft-behavior", @@ -1406,7 +1406,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "crc32fast", "flate2", @@ -1427,7 +1427,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "rustix 1.1.5", ] @@ -1435,7 +1435,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "base64 0.22.1", "craft-behavior", @@ -1460,7 +1460,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1478,7 +1478,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-docpath", @@ -1496,7 +1496,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "egui", ] @@ -1504,7 +1504,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "md-5", "rayon", @@ -1513,12 +1513,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-cms", @@ -1538,7 +1538,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1553,7 +1553,7 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-metadata", "craft-xml", @@ -1563,7 +1563,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "thiserror 2.0.21", ] @@ -1571,7 +1571,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "rayon", ] @@ -1579,7 +1579,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "block2 0.6.2", "craft-atomic", @@ -1604,7 +1604,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "serde", ] @@ -1612,7 +1612,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1631,12 +1631,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-eps", "craft-idml", @@ -1654,7 +1654,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-atomic", "dirs", @@ -1664,7 +1664,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1679,7 +1679,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1698,7 +1698,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "cap-primitives", "craft-atomic", @@ -1719,12 +1719,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "heic-rs", "rayon", @@ -1733,7 +1733,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1746,7 +1746,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "chrono", "fixed_decimal", @@ -1774,7 +1774,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-xml", "craft-zip", @@ -1784,7 +1784,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-dds", "craft-heif", @@ -1812,7 +1812,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1830,12 +1830,12 @@ dependencies = [ [[package]] name = "craft-ipp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "thiserror 2.0.21", ] @@ -1843,7 +1843,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-host", "craft-i18n", @@ -1858,7 +1858,7 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-xml", "craft-zip", @@ -1868,7 +1868,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-i18n", @@ -1882,7 +1882,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-host", @@ -1900,7 +1900,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1912,7 +1912,7 @@ dependencies = [ [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-xml", "craft-zip", @@ -1922,7 +1922,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-keymap", @@ -1937,7 +1937,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "blake3", "craft-atomic", @@ -1950,7 +1950,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "flate2", "serde", @@ -1961,7 +1961,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "bytemuck", "flate2", @@ -1976,7 +1976,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "flate2", "thiserror 2.0.21", @@ -1985,7 +1985,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "async-channel", "async-io", @@ -2015,7 +2015,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "thiserror 2.0.21", ] @@ -2023,7 +2023,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-host", @@ -2046,7 +2046,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "encoding_rs", "flate2", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "dispatch2", "egui", @@ -2068,7 +2068,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "chrono", "craft-crw", @@ -2086,7 +2086,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-host", @@ -2104,7 +2104,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-atomic", "craft-host", @@ -2121,7 +2121,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2142,7 +2142,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-keymap", @@ -2154,7 +2154,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2177,7 +2177,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2192,7 +2192,7 @@ dependencies = [ [[package]] name = "craft-theme-editor" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-theme", @@ -2203,7 +2203,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-atomic", "craft-behavior", @@ -2218,7 +2218,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "serde", "thiserror 2.0.21", @@ -2227,7 +2227,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "serde", "thiserror 2.0.21", @@ -2236,7 +2236,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-keymap", @@ -2251,7 +2251,7 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "serde", ] @@ -2259,7 +2259,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2273,7 +2273,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-i18n", @@ -2289,7 +2289,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "accesskit", "craft-behavior", @@ -2329,7 +2329,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2340,7 +2340,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-host", @@ -2358,7 +2358,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-host", @@ -2379,7 +2379,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-host", @@ -2398,7 +2398,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-behavior", "craft-host", @@ -2415,7 +2415,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "chrono", "craft-host", @@ -2444,7 +2444,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "winsafe", ] @@ -2452,7 +2452,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "craft-atomic", "craft-behavior", @@ -2482,7 +2482,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2491,7 +2491,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2501,7 +2501,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2891,7 +2891,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "emath", @@ -2901,7 +2901,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -2938,7 +2938,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "accesskit", "ahash", @@ -2959,7 +2959,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -2978,7 +2978,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "accesskit_winit", "arboard", @@ -3004,7 +3004,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "egui", @@ -3018,7 +3018,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "egui", @@ -3031,7 +3031,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "dify", "eframe", @@ -3057,7 +3057,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "serde", @@ -3150,7 +3150,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -3177,7 +3177,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[package]] name = "equivalent" @@ -3964,7 +3964,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "bytemuck", "hayro-interpret", @@ -3994,7 +3994,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -4012,7 +4012,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -4036,7 +4036,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "flate2", "hayro-ccitt", @@ -5120,7 +5120,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -9521,7 +9521,7 @@ dependencies = [ [[package]] name = "vello_common" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "bytemuck", "fearless_simd", @@ -9569,7 +9569,7 @@ dependencies = [ [[package]] name = "vello_cpu" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" dependencies = [ "bytemuck", "glifo 0.1.1", @@ -11190,29 +11190,29 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" [[patch.unused]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531#cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" diff --git a/Cargo.toml b/Cargo.toml index 0bbdcba3f8..50ba4b7032 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,21 +12,21 @@ rust-version = "1.95" [workspace.dependencies] # The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match # `craft::egui_fork::REV` (checked by `cargo xtask ci`). -craft = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", default-features = false } -craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531", default-features = false } +craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -45,34 +45,34 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } # Keep the shared embedded-image validation API until the framework revision includes it. -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531", features = ["tree-render", "tree-render-system-fonts"] } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531", features = ["ui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -337,30 +337,30 @@ opt-level = 3 # Keep the complete egui family and native event bridge on reviewed fork commits. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -vello_common = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -emath = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +vello_common = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +emath = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 6cf1a53a76..0d7a0779d3 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -19,7 +19,7 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } craft-cms = { workspace = true } # PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide. -craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } diff --git a/crates/ipp/Cargo.toml b/crates/ipp/Cargo.toml index f9480715c4..9f2abc3d32 100644 --- a/crates/ipp/Cargo.toml +++ b/crates/ipp/Cargo.toml @@ -7,7 +7,7 @@ license.workspace = true rust-version.workspace = true [dependencies] -craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "cec6d87ff276cd8629f8c9ff36cd6b9ef1de2531" } [lints] workspace = true diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 052581d13d..f89029a987 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -678,7 +678,10 @@ mod tests { view.rect.top() ); } - let room = |length: f32, document: f64| if overscroll { f64::from(length) - document } else { 0.0 }; + // With Overscroll the track reaches into the pasteboard until 100 screen points of the document (all of a + // shorter one) stay in view at the opposite edge (#16328): the document plus, on each side, the visible + // length less those points. The scroll room is that less the visible length. + let room = |length: f32, document: f64| if overscroll { f64::from(length) + document - 2.0 * document.min(100.0) } else { 0.0 }; let x_room = room(view.rect.width(), 400.0); let y_room = room(view.rect.height(), 300.0); assert_eq!(horizontal.accesskit_node().max_numeric_value(), Some(x_room), "horizontal scroll room with Overscroll {overscroll}"); From a5eb7da5917ad0734d431a15120e417299d18626 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 23:27:15 +0100 Subject: [PATCH 123/136] Tests: Space after an Alt tap or F10 pans and opens no menu (#16327) Lands with the craft-libs pin bump that carries storytold/craft-libs#2931; it fails on the current pin (Space opens File). Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/input/hold_keys/tests.rs | 41 +++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index 867bdf7fd5..f40bb4dd3d 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -720,3 +720,44 @@ fn space_hand_pasteboard_menu_opens_outside_the_image_and_outlives_space() { h.run_steps(2); assert!(h.state().ui.canvas_tool_menu.is_none(), "another tool selected closes it"); } + +/// A lone Alt tap or F10 puts the keyboard on the menu bar. Space then opens no menu (it used to open File, and a held +/// Space ran File > New) and is the Hand in the same press: the drag pans, as it always does in the reference +/// application (#16327). +#[test] +fn space_after_an_alt_tap_or_f10_pans_and_opens_no_menu() { + for (f10, clicked) in [(false, false), (true, false), (false, true), (true, true)] { + let mut h = harness(Tool::Brush); + let p = screen(&h, 200.0, 150.0); + if clicked { + // A dab first, so the canvas holds the keyboard when the bar takes it. + click(&mut h, 100.0, 80.0, Modifiers::NONE); + } + h.event(Event::PointerMoved(p)); + h.run_steps(2); + if f10 { + key(&mut h, Key::F10, true, Modifiers::NONE); + key(&mut h, Key::F10, false, Modifiers::NONE); + } else { + h.event(Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(1); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + } + assert!(craft::ui::menu::bar::is_focused(&h.ctx), "f10 {f10}, clicked {clicked}: the keyboard is on the bar"); + let before = center(&h); + key(&mut h, Key::Space, true, Modifiers::NONE); + assert!(!craft::ui::menu::bar::is_open(&h.ctx), "f10 {f10}, clicked {clicked}: Space opens no menu"); + assert!(!craft::ui::menu::bar::is_focused(&h.ctx), "f10 {f10}, clicked {clicked}: Space takes the keyboard off the bar"); + button(&mut h, p, true, Modifiers::NONE); + move_to(&mut h, 250.0, 180.0); + let q = screen(&h, 250.0, 180.0); + button(&mut h, q, false, Modifiers::NONE); + key(&mut h, Key::Space, false, Modifiers::NONE); + h.run_steps(2); + assert!(!craft::ui::menu::bar::is_open(&h.ctx), "f10 {f10}, clicked {clicked}: no menu after the drag"); + assert_ne!(center(&h), before, "f10 {f10}, clicked {clicked}: Space and a drag pan the view"); + assert_eq!(h.state().session.documents().len(), 1, "f10 {f10}, clicked {clicked}: no new document"); + assert_eq!(h.state().ui.tool, Tool::Brush, "f10 {f10}, clicked {clicked}: the tool comes back"); + } +} From a0b92a8abaef4ed0e0f4b39251dd38c3f0386270 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 02:29:14 +0100 Subject: [PATCH 124/136] Conditional Mode Change: lay the source checkboxes out with the framework's grid On craft-libs next the framework's checkboxes inside an egui Grid take the whole height left in the dialog, one row each, so All, None and the Target Mode section ended up far below and under other rows. The source checkboxes are now a two-column craft Grid with All and None in a Row under them, in a Stack. Co-Authored-By: Claude Opus 5.5 --- .../dialogs/conditional_mode_change_dialog.rs | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/dialogs/conditional_mode_change_dialog.rs b/crates/ui-egui/src/dialogs/conditional_mode_change_dialog.rs index 52d2e840bd..aff07c6d8b 100644 --- a/crates/ui-egui/src/dialogs/conditional_mode_change_dialog.rs +++ b/crates/ui-egui/src/dialogs/conditional_mode_change_dialog.rs @@ -5,9 +5,12 @@ //! The checkboxes are one custom row of the command's form: `from` is the list of ticked source //! ids and `to` the target id, so OK, Reset and `ui.dialog.set` work as for every form. +use craft::behavior::ColumnWidth; use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Props as _, Show as _}; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::layout::GridFit; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind}; use craft::ui::runtime::env::Label; use serde_json::{Value, json}; @@ -66,29 +69,33 @@ fn ticked(from: &Value, id: &str) -> bool { } } -/// The eight checkboxes in two columns, All and None under them. +/// The two columns of checkboxes, each as wide as its widest label. +const COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content]; + +/// The eight checkboxes in two columns, All and None under them. Laid out by the framework's grid and row: in an egui +/// `Grid` the framework's checkboxes took the whole height left in the dialog, one row each. fn sources_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut craft::ui::patterns::form_dialogs::CustomContext) -> egui::Response { let from = from_value(fields); let mut on = SOURCES.map(|(id, _)| ticked(&from, id)); let before = on; - let response = egui::Grid::new("conditional-mode-sources") - .num_columns(2) - .spacing([24.0, 6.0]) - .show(ui, |ui| { - for row in 0..4 { - for i in [row, row + 4] { - Checkbox::new(Bind::bound(&mut on[i])).label(tl!(SOURCES[i].1)).show(ui); + let response = Stack::new() + .show(ui, |ui, _| { + Grid::new(COLUMNS).fit(GridFit::Fixed).show(ui, |ui, _| { + for row in 0..4 { + for i in [row, row + 4] { + Checkbox::new(Bind::bound(&mut on[i])).label(tl!(SOURCES[i].1)).show(ui); + } } - ui.end_row(); - } - for (label, all) in [(tl!("All"), true), (tl!("None"), false)] { - if Button::new(label).show(ui).clicked() { - on = [all; 8]; + }); + Row::new().show(ui, |ui, _| { + for (label, all) in [(tl!("All"), true), (tl!("None"), false)] { + if Button::new(label).show(ui).clicked() { + on = [all; 8]; + } } - } - ui.end_row(); + }); }) - .response; + .output; if on != before { let ticked: Vec<&str> = SOURCES.iter().zip(on).filter(|(_, on)| *on).map(|((id, _), _)| *id).collect(); fields.set("from", FieldValue::Json(json!(ticked))); From d618b49186c28e6695ed7ce62a661259ac3d35e5 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 02:37:01 +0100 Subject: [PATCH 125/136] UI: key pixel pictures and cached bounds on the scratch read-error generation (#16364) A tile that fails to read shows zeros and its pixels again once it reads, without moving its surface's generation or its document's revision. The Channels and History snapshot thumbnails, the Patterns swatches and Styles thumbnails, the Navigator, the Print and filter previews, the bounds cache and the selection outline now key on the read-error generation through one helper (crate::scratch_reads), as the Layers thumbnails and the menu rule facts already did. A test-only seam simulates a transition; tests cover each cache, the rule facts and the Layers thumbnails. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/app/thumbs.rs | 25 ++-- crates/ui-egui/src/canvas/navigator.rs | 4 +- crates/ui-egui/src/canvas/outline.rs | 4 +- crates/ui-egui/src/canvas/tool_feedback.rs | 2 +- crates/ui-egui/src/dialogs/file_ui/print.rs | 20 ++- .../ui-egui/src/dialogs/filter_preview_ui.rs | 29 ++++- crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/menus/facts.rs | 2 +- crates/ui-egui/src/panels/layers_tree.rs | 2 +- crates/ui-egui/src/panels/preset_browser.rs | 9 +- .../src/panels/preset_browser/tests.rs | 18 +++ crates/ui-egui/src/scratch_read_keys_tests.rs | 116 ++++++++++++++++++ crates/ui-egui/src/scratch_reads.rs | 48 ++++++++ 13 files changed, 261 insertions(+), 21 deletions(-) create mode 100644 crates/ui-egui/src/scratch_read_keys_tests.rs create mode 100644 crates/ui-egui/src/scratch_reads.rs diff --git a/crates/ui-egui/src/app/thumbs.rs b/crates/ui-egui/src/app/thumbs.rs index 0677b17c23..f8b25d555a 100644 --- a/crates/ui-egui/src/app/thumbs.rs +++ b/crates/ui-egui/src/app/thumbs.rs @@ -26,7 +26,8 @@ impl<'a> SnapshotThumbs<'a> { impl ThumbSource for SnapshotThumbs<'_> { fn revision(&self, key: &u64, _request: &ThumbRequest) -> Revision { let shown = self.snapshots.iter().find(|s| s.id == *key).map(|s| std::sync::Arc::as_ptr(&s.doc) as usize); - Revision::of(&(self.doc.0, *key, shown)) + // A snapshot's tiles can fail to read and recover without a new `Arc` (`crate::scratch_reads`). + Revision::of(&(self.doc.0, *key, shown, crate::scratch_reads::generation())) } fn render(&self, key: &u64, request: &ThumbRequest) -> ThumbRender { @@ -36,6 +37,12 @@ impl ThumbSource for SnapshotThumbs<'_> { } } +/// What the bounds cache keys `surface`'s bounds by: its generation and the scratch read-error generation, as a tile +/// that fails to read scans as empty and moves neither (`crate::scratch_reads`). +pub(crate) fn bounds_revision(surface: &photocraft_raster::Surface) -> u64 { + crate::scratch_reads::with(surface.generation()) +} + /// The document area a layer thumbnail frames: the canvas, or with `clip` the layer's pixels on /// it (the canvas again when it has none there, so an empty layer still shows the page shape). pub(crate) fn layer_thumb_frame(layer: &photocraft_doc::Layer, canvas: photocraft_geom::Rect, clip: bool) -> photocraft_geom::Rect { @@ -47,9 +54,10 @@ pub(crate) fn layer_thumb_frame(layer: &photocraft_doc::Layer, canvas: photocraf } impl PhotocraftApp { - /// Cached `Surface::content_bounds` keyed by an id and the surface's generation. + /// Cached `Surface::content_bounds` keyed by an id and the surface's generation with the scratch read-error + /// generation ([`bounds_revision`]). pub fn cached_bounds(&mut self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { - let rev = surface.generation(); + let rev = bounds_revision(surface); if let Some((r, b)) = self.bounds_cache.get(&key) && *r == rev { @@ -67,7 +75,7 @@ impl PhotocraftApp { /// hasn't changed since, else a scan (not cached). pub fn known_bounds(&self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { match self.bounds_cache.get(&key) { - Some((r, b)) if *r == surface.generation() => *b, + Some((r, b)) if *r == bounds_revision(surface) => *b, _ => surface.content_bounds(), } } @@ -79,7 +87,7 @@ impl PhotocraftApp { match &layer.content { photocraft_doc::LayerContent::Shape(sh) if sh.has_soft_mask() => { // Cached per rendering, like the pixel bounds: the frame renders strips of the shape. - let (key, rev) = (layer.id.0 | 1 << 63, surface.generation()); + let (key, rev) = (layer.id.0 | 1 << 63, bounds_revision(surface)); if let Some((r, b)) = self.bounds_cache.get(&key) && *r == rev { @@ -176,10 +184,13 @@ impl ThumbSource for ChannelThumbs<'_> { fn revision(&self, key: &Row, _request: &ThumbRequest) -> Revision { let doc = &self.st.doc; let size = (doc.size.width, doc.size.height); + // A tile that fails to read and recovers moves neither the document's revision nor its surface's generation + // (`crate::scratch_reads`). + let scratch = crate::scratch_reads::generation(); match key { - Row::Composite | Row::Color(_) => Revision::of(&(doc.id.0, self.st.pixel_revision, self.show_color, size)), + Row::Composite | Row::Color(_) => Revision::of(&(doc.id.0, self.st.pixel_revision, self.show_color, size, scratch)), // A channel-list change with empty damage still refreshes these: they follow their own surface. - _ => Revision::of(&(doc.id.0, self.st.active_layer, self.surface(key).map(photocraft_raster::Surface::generation), size)), + _ => Revision::of(&(doc.id.0, self.st.active_layer, self.surface(key).map(photocraft_raster::Surface::generation), size, scratch)), } } diff --git a/crates/ui-egui/src/canvas/navigator.rs b/crates/ui-egui/src/canvas/navigator.rs index 8253334baa..88e53640c7 100644 --- a/crates/ui-egui/src/canvas/navigator.rs +++ b/crates/ui-egui/src/canvas/navigator.rs @@ -74,7 +74,9 @@ pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id, st.revision, st.damage_from(), st.last_damage))?; let (doc, preview_key) = display_doc(app, idx); let (display, display_key) = canvas_display(app, &doc, None); - let preview_key = preview_key ^ display_key; + // A tile that fails to read and recovers keeps the snapshot and its revision: the picture and its partial updates + // follow the scratch read-error generation too (`crate::scratch_reads`). + let preview_key = crate::scratch_reads::with(preview_key ^ display_key); let cached = app.navigator_textures.get(&id).cloned(); if let Some((r, p, _, t)) = &cached && r.ptr_eq(&snapshot) diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 8e2e18bac0..cb46af475c 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -24,8 +24,10 @@ impl MaskSource for SurfaceMask<'_> { self.size } + /// The mask's revision with the scratch read-error generation: a selection tile that fails to read traces as + /// empty, and as its pixels once it reads, without a new revision (`crate::scratch_reads`). fn revision(&self) -> u64 { - self.revision + crate::scratch_reads::with(self.revision) } /// The allocated tiles: every pixel that differs from the default lies in one, and the union of their rects is diff --git a/crates/ui-egui/src/canvas/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs index 38bc614cf0..22821a53a2 100644 --- a/crates/ui-egui/src/canvas/tool_feedback.rs +++ b/crates/ui-egui/src/canvas/tool_feedback.rs @@ -102,7 +102,7 @@ mod tests { assert!(has_selection(&app), "nothing cached: scanned"); assert_eq!(selection_op(Tool::Lasso, 0, ALT, has_selection(&app)), SelectionOperation::Subtract); let st = app.session.active().unwrap(); - let (key, fingerprint) = (u64::MAX - st.doc.id.0, st.doc.selection.as_ref().unwrap().generation()); + let (key, fingerprint) = (u64::MAX - st.doc.id.0, crate::app::thumbs::bounds_revision(st.doc.selection.as_ref().unwrap())); // An empty box cached for this very selection is believed, so nothing is scanned. app.bounds_cache.insert(key, (fingerprint, photocraft_geom::Rect::EMPTY)); assert!(!has_selection(&app), "the cached bounds are used"); diff --git a/crates/ui-egui/src/dialogs/file_ui/print.rs b/crates/ui-egui/src/dialogs/file_ui/print.rs index 1ba51ac4e8..3da1ad4e52 100644 --- a/crates/ui-egui/src/dialogs/file_ui/print.rs +++ b/crates/ui-egui/src/dialogs/file_ui/print.rs @@ -402,9 +402,9 @@ fn fields_set_position(f: &mut DialogFields, left: f64, top: f64) { /// The document's flattened picture at the preview size, mirrored for Emulsion Down (the sheet /// draws the picture unmirrored in the box). The texture lives in the context's memory under the -/// document's id and revision. +/// document's id and revision, and the scratch read-error generation (`crate::scratch_reads`). fn picture(ctx: &egui::Context, doc: &photocraft_doc::Document, revision: u64, mirror: bool) -> egui::load::SizedTexture { - let key = egui::Id::unique(("print-thumb", doc.id.0, revision, mirror)); + let key = egui::Id::unique(("print-thumb", doc.id.0, revision, mirror, crate::scratch_reads::generation())); let tex: Option> = ctx.data(|d| d.get_temp(key)); let tex = tex.unwrap_or_else(|| { let th = photocraft_compose::thumbnail(doc, 400); @@ -570,3 +570,19 @@ pub(crate) fn print_status(app: &mut PhotocraftApp, r: &Value) { }; app.ui.status_error = false; } + +#[cfg(test)] +mod scratch_tests { + /// A tile that fails to read and recovers keeps the document's revision; the preview picture still draws again, + /// so it does not keep the zeros it read during the error. + #[test] + fn the_preview_picture_draws_again_after_a_scratch_read_error_transition() { + use photocraft_doc::{ColorMode, Document, SampleType}; + let ctx = egui::Context::default(); + let doc = Document::new("Print", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let first = super::picture(&ctx, &doc, 3, false).id; + assert_eq!(super::picture(&ctx, &doc, 3, false).id, first, "the same revision keeps its picture"); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_ne!(super::picture(&ctx, &doc, 3, false).id, first, "the picture draws again after the transition"); + } +} diff --git a/crates/ui-egui/src/dialogs/filter_preview_ui.rs b/crates/ui-egui/src/dialogs/filter_preview_ui.rs index f0aaeb9f21..8bf8be5577 100644 --- a/crates/ui-egui/src/dialogs/filter_preview_ui.rs +++ b/crates/ui-egui/src/dialogs/filter_preview_ui.rs @@ -94,9 +94,10 @@ fn picture(app: &PhotocraftApp, ctx: &egui::Context, id: DialogId) -> Option(cache_id))); - // Channel visibility and the active mask can change without a document revision. Both the - // original (press-and-hold) and filtered textures must follow the canvas's current view. - let view = (st.channel_view.clone(), app.session.prefs().interface.show_channels_in_color, st.active_layer); + // Channel visibility and the active mask can change without a document revision, and so can a tile that fails + // to read and recovers (`crate::scratch_reads`). Both the original (press-and-hold) and filtered textures must + // follow the canvas's current view. + let view = (st.channel_view.clone(), app.session.prefs().interface.show_channels_in_color, st.active_layer, crate::scratch_reads::generation()); if cache.view.as_ref() != Some(&view) { cache = Cache { view: Some(view), ..Default::default() }; } @@ -221,7 +222,7 @@ struct CachedTex { struct Cache { filtered: Option, original: Option, - view: Option<(photocraft_engine::channel_cmds::ChannelView, bool, Option)>, + view: Option<(photocraft_engine::channel_cmds::ChannelView, bool, Option, u64)>, } #[cfg(test)] @@ -358,6 +359,26 @@ mod tests { assert!(pixels.unwrap().iter().all(|p| *p == Color32::BLACK)); } + /// A tile that fails to read and recovers moves no revision; the unfiltered texture still draws again then, so it + /// does not keep the zeros it read during the error. + #[test] + fn original_texture_refreshes_after_a_scratch_read_error_transition() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let id = top_dialog(&app); + let ctx = app.ctx().clone(); + let cache_id = egui::Id::unique(("filter-preview-ui", id.value())); + let original = |ctx: &egui::Context| ctx.data(|d| d.get_temp::(cache_id).unwrap().original.unwrap().tex.id()); + ctx.run_ui(Default::default(), |ui| feed(&mut app, ui.ctx())).textures_delta.clear(); + let before = original(&ctx); + ctx.run_ui(Default::default(), |ui| feed(&mut app, ui.ctx())).textures_delta.clear(); + assert_eq!(original(&ctx), before, "an unchanged picture is not uploaded again"); + crate::scratch_reads::tests::simulate_read_error_transition(); + ctx.run_ui(Default::default(), |ui| feed(&mut app, ui.ctx())).textures_delta.clear(); + assert_ne!(original(&ctx), before, "the picture draws again after the transition"); + } + #[test] fn only_filter_dialogs_get_the_preview_pane() { for (command, pane) in [ diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c1b338620f..4ce0306dd4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -56,6 +56,7 @@ pub mod panels; pub mod preset_files_ui; pub mod proxy; pub mod render_path; +pub(crate) mod scratch_reads; pub mod state; pub mod texel_guard; pub mod theme; @@ -972,6 +973,8 @@ mod layer_thumb_bounds_tests; mod mask_thumb_refresh_tests; #[cfg(test)] mod menu_floor_trials; +#[cfg(test)] +mod scratch_read_keys_tests; #[cfg(test)] mod new_doc_remember_tests; diff --git a/crates/ui-egui/src/menus/facts.rs b/crates/ui-egui/src/menus/facts.rs index 4732b7800b..aacc54fdfc 100644 --- a/crates/ui-egui/src/menus/facts.rs +++ b/crates/ui-egui/src/menus/facts.rs @@ -205,7 +205,7 @@ impl<'a> RuleFacts<'a> { active_index: s.active_index(), active: s.active_tracked(), all: all_revisions(s.documents()), - scratch: photocraft_raster::spill::read_error_generation(), + scratch: crate::scratch_reads::generation(), jobs: (s.has_jobs(), s.active_job().map(|job| job.id.0)), smart_child: active.is_some_and(|d| s.smart_links.iter().any(|link| link.child == d.doc.id)), fade: s.edit_state.fade.as_ref().map(|fade| (fade.doc, fade.revision)), diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 25e10df30d..4a6f0b42af 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -746,7 +746,7 @@ impl ThumbSource> for PhotoThumbs<'_> { }; // A tile that fails to read shows zeros, and its pixels again once it reads, without moving its surface's // generation: the scratch read-error generation moves with both (#16252). - let scratch = photocraft_raster::spill::read_error_generation(); + let scratch = crate::scratch_reads::generation(); Revision::of(&(shown, clip, self.doc.size.width, self.doc.size.height, scratch)) } diff --git a/crates/ui-egui/src/panels/preset_browser.rs b/crates/ui-egui/src/panels/preset_browser.rs index 242b9a3d23..3b8cc76f2e 100644 --- a/crates/ui-egui/src/panels/preset_browser.rs +++ b/crates/ui-egui/src/panels/preset_browser.rs @@ -160,9 +160,12 @@ type HeldPatterns = Arc<[Arc]>; type StylesStamp = (Revision, u64); /// A number for the library's patterns and their pixels: equal stamps mean the same patterns with the same pixels -/// (`Surface::generation` names a pixel state, and is shared by clones). +/// (`Surface::generation` names a pixel state, and is shared by clones). It also moves with the scratch read-error +/// generation: a pattern tile that fails to read draws zeros and its pixels again once it reads, under the same +/// generation (`crate::scratch_reads`), and the style thumbnails drawn over the patterns follow it through this. fn patterns_stamp(library: &PatternLibrary) -> u64 { let mut hasher = DefaultHasher::new(); + crate::scratch_reads::generation().hash(&mut hasher); for pattern in &library.items { (&pattern.id, &pattern.name, pattern.surface.generation()).hash(&mut hasher); } @@ -302,9 +305,9 @@ fn pattern_image(pattern: &photocraft_doc::Pattern) -> ColorImage { } /// The texture store key of `pattern`'s swatch: its id and its pixels, so a pattern replaced under the same id draws -/// anew. +/// anew, and a swatch drawn while a tile failed to read draws again once it reads (`crate::scratch_reads`). fn pattern_key(pattern: &photocraft_doc::Pattern) -> PictureKey { - ("pattern", pattern.id.clone(), pattern.surface.generation()) + ("pattern", pattern.id.clone(), crate::scratch_reads::with(pattern.surface.generation())) } /// A texture of `pattern`'s swatch that its holder owns: it stays while the handle lives, where a cached texture diff --git a/crates/ui-egui/src/panels/preset_browser/tests.rs b/crates/ui-egui/src/panels/preset_browser/tests.rs index ee3c9c6613..6044d8c57e 100644 --- a/crates/ui-egui/src/panels/preset_browser/tests.rs +++ b/crates/ui-egui/src/panels/preset_browser/tests.rs @@ -172,6 +172,24 @@ fn a_pattern_replaced_under_its_id_keys_a_new_picture() { assert_eq!(pattern_key(&first), pattern_key(&first.clone()), "a clone holds the same pixels"); } +/// A pattern swatch drawn while a pattern tile failed to read shows zeros: once the tile reads again (no new +/// generation), the swatch keys a new picture, and so do the style thumbnails drawn over the patterns. +#[test] +fn pattern_and_style_pictures_follow_a_scratch_read_error_transition() { + let mut app = app(); + let pattern = app.session.patterns.items[0].clone(); + let (swatch, library) = (pattern_key(&pattern), StyleLibrary::held(&mut app)); + assert_eq!(pattern_key(&pattern), swatch); + assert!(Arc::ptr_eq(&library, &StyleLibrary::held(&mut app))); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_ne!(pattern_key(&pattern), swatch, "the swatch draws again"); + let after = StyleLibrary::held(&mut app); + assert!(!Arc::ptr_eq(&library, &after), "the style library is taken again"); + let stamps = |library: &StyleLibrary| library.styles.iter().map(|(stamp, _)| *stamp).collect::>(); + assert!(!stamps(&library).is_empty()); + assert!(stamps(&library).iter().zip(stamps(&after)).all(|(before, now)| *before != now), "every style thumbnail draws again"); +} + /// The flat list of the app's style presets. fn styles(app: &PhotocraftApp) -> Vec { app.session.presets.styles.iter().flat_map(|group| group.items.iter().cloned()).collect() diff --git a/crates/ui-egui/src/scratch_read_keys_tests.rs b/crates/ui-egui/src/scratch_read_keys_tests.rs new file mode 100644 index 0000000000..186d3a1033 --- /dev/null +++ b/crates/ui-egui/src/scratch_read_keys_tests.rs @@ -0,0 +1,116 @@ +//! The UI's pictures and derived values of document pixels follow the scratch read-error generation: a tile that +//! fails to read shows zeros and its real pixels again once it reads, without moving its surface's generation or its +//! document's revision (`crate::scratch_reads`). Each test simulates one such transition and checks that the key a +//! cache is held by moves with it, and stays put without it. + +use craft::imaging::trace::MaskSource; +use craft::layers::ui::thumbs::{LayerThumb, ThumbContents}; +use craft::ui::primitives::textures::{ThumbRequest, ThumbSource}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::channels_panel::Row; +use crate::scratch_reads::tests::simulate_read_error_transition; + +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({"name": "Paint"})).unwrap(); + app.run("paint.stroke", json!({"points": [[4, 4], [40, 30]], "size": 8, "color": "#2060c0"})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("channel.new", json!({"name": "Alpha", "fill": "white"})).unwrap(); + app.run("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + app +} + +fn request() -> ThumbRequest { + ThumbRequest::for_cell(32.0, 1.0) +} + +/// Calls `revision` before, again without a change, and after one transition: the key must hold, then move. +fn holds_then_moves(what: &str, mut revision: impl FnMut() -> T) { + let before = revision(); + assert_eq!(revision(), before, "{what}: nothing changed, the same key"); + simulate_read_error_transition(); + assert_ne!(revision(), before, "{what}: a read error or its recovery moves the key"); +} + +#[test] +fn layer_thumbnails_follow_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + let layer = st.active_layer.unwrap(); + let keys = [LayerThumb::pixels(layer, ThumbContents::EntireDocument), LayerThumb::mask(layer)]; + holds_then_moves("layer thumbnails", || { + let thumbs = crate::panels::layers_tree::PhotoThumbs::new(&app, &st.doc); + keys.iter().map(|key| thumbs.revision(key, &request()).get()).collect::>() + }); +} + +#[test] +fn the_rule_facts_follow_a_scratch_read_error_transition() { + let app = app(); + holds_then_moves("rule facts", || crate::menus::facts::key(&app)); +} + +#[test] +fn channel_thumbnails_follow_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + holds_then_moves("channel thumbnails", || { + let thumbs = crate::app::thumbs::ChannelThumbs::new(&app, st); + [Row::Composite, Row::Color(0), Row::Alpha(0), Row::LayerMask].iter().map(|row| thumbs.revision(row, &request()).get()).collect::>() + }); +} + +#[test] +fn snapshot_thumbnails_follow_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + let snapshot = st.snapshots().first().map(|s| s.id).expect("a new document has its first snapshot"); + holds_then_moves("snapshot thumbnails", || crate::app::thumbs::SnapshotThumbs::new(&app, st.doc.id).revision(&snapshot, &request()).get()); +} + +/// A selection whose tile read as zeros scans as empty: once it reads again, the cached bounds are scanned anew. +#[test] +fn cached_bounds_are_scanned_again_after_a_scratch_read_error_transition() { + let mut app = app(); + let (doc, selection) = { + let st = app.session.active().unwrap(); + (st.doc.id, st.doc.selection.clone().unwrap()) + }; + let key = u64::MAX - doc.0; + let bounds = app.cached_bounds(key, &selection); + assert!(!bounds.is_empty()); + // The box a scan during the read error would have cached. + let fingerprint = crate::app::thumbs::bounds_revision(&selection); + app.bounds_cache.insert(key, (fingerprint, photocraft_geom::Rect::EMPTY)); + assert!(app.known_bounds(key, &selection).is_empty(), "without a transition the cached box is believed"); + simulate_read_error_transition(); + assert_eq!(app.known_bounds(key, &selection), bounds, "after it, the bounds are scanned again"); + assert_eq!(app.cached_bounds(key, &selection), bounds); +} + +#[test] +fn the_selection_outline_follows_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + let selection = st.doc.selection.as_ref().unwrap(); + let size = [st.doc.size.width, st.doc.size.height]; + holds_then_moves("selection outline", || crate::canvas::outline::SurfaceMask::new(selection, selection.generation(), size).revision()); +} + +#[test] +fn the_navigator_picture_draws_again_after_a_scratch_read_error_transition() { + let mut app = app(); + let ctx = app.ctx().clone(); + let doc = app.session.active().unwrap().doc.id; + crate::canvas::navigator_texture(&mut app, &ctx, 0).unwrap(); + let held = |app: &PhotocraftApp| app.navigator_textures.get(&doc).map(|(_, key, _, texture)| (*key, texture.id())).unwrap(); + let before = held(&app); + crate::canvas::navigator_texture(&mut app, &ctx, 0).unwrap(); + assert_eq!(held(&app), before, "nothing changed: the same picture"); + simulate_read_error_transition(); + crate::canvas::navigator_texture(&mut app, &ctx, 0).unwrap(); + assert_ne!(held(&app).0, before.0, "the picture is drawn again for the new generation"); +} diff --git a/crates/ui-egui/src/scratch_reads.rs b/crates/ui-egui/src/scratch_reads.rs new file mode 100644 index 0000000000..014eb823f3 --- /dev/null +++ b/crates/ui-egui/src/scratch_reads.rs @@ -0,0 +1,48 @@ +//! The scratch read-error generation as the UI's caches key on it. +//! +//! A tile whose scratch bytes fail to read shows a zero placeholder through `&self`, and its real pixels again once +//! a reload succeeds, without moving its surface's generation or its document's revision (the `PlainData` comment on +//! `photocraft_raster::Tile`). Both transitions move `spill::read_error_generation`, so every picture or derived +//! value the UI keeps of document or preset pixels keys on [`generation`] too; otherwise a thumbnail drawn during a +//! read error keeps its zeros after the tile recovers. + +/// The scratch read-error generation now: it moves when a tile fails to read and when it reads again. +pub(crate) fn generation() -> u64 { + let real = photocraft_raster::spill::read_error_generation(); + #[cfg(test)] + let real = real.wrapping_add(tests::BUMPS.with(std::cell::Cell::get)); + real +} + +/// [`generation`] folded with `revision`: one number for a cache keyed by a single `u64` that must follow both. +pub(crate) fn with(revision: u64) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::hash::DefaultHasher::new(); + (revision, generation()).hash(&mut hasher); + hasher.finish() +} + +#[cfg(test)] +pub(crate) mod tests { + use std::cell::Cell; + + thread_local! { + /// Read-error transitions simulated on this test's thread, so a test sees one without setting up the + /// process-wide scratch file, and tests on other threads never do. + pub(super) static BUMPS: Cell = const { Cell::new(0) }; + } + + /// Simulates one read-error transition (a tile failing, or one recovering) as the caches see it. + pub(crate) fn simulate_read_error_transition() { + BUMPS.with(|bumps| bumps.set(bumps.get().wrapping_add(1))); + } + + #[test] + fn a_simulated_transition_moves_the_generation_and_the_folded_key() { + let (generation, folded) = (super::generation(), super::with(7)); + assert_eq!(super::with(7), folded, "the same state folds to the same key"); + simulate_read_error_transition(); + assert_ne!(super::generation(), generation); + assert_ne!(super::with(7), folded); + } +} From cf5347b545ce65554cbf1378cfe0d161d8576a7c Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 02:46:35 +0100 Subject: [PATCH 126/136] Integration: fix the batch 27 CI failures (fmt, null Image Size percent) - cargo fmt for the merged Tool list in paint_mouse.rs. - The #11516 fix refused an exported Image Size step with "percent": null, which main's review test treats as omitted. Native playback now omits a null percent like a null side or resolution, and export follows it, so both still agree. The null case moves from the invalid-percent test to a new native + round-trip test. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/steps_doc.rs | 2 +- crates/engine/src/cmd/atn_cmds/tests.rs | 2 +- crates/engine/src/cmd/image_cmds.rs | 3 ++- .../engine/tests/it/atn_mapped_identifiers.rs | 25 +++++++++++++++++++ crates/ui-egui/src/canvas/paint_mouse.rs | 10 +++++++- 5 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/steps_doc.rs b/crates/engine/src/cmd/atn_cmds/steps_doc.rs index caa3393de6..2625254fb0 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_doc.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_doc.rs @@ -529,7 +529,7 @@ pub(super) fn image_size_to(_: &str, p: &Value) -> Option { }; // Native playback validates a supplied percentage even when explicit sides override it. // Dropping an invalid percentage would turn a refused action into a different, valid edit. - if p.get("percent").is_some_and(|value| value.as_f64().is_none_or(|pc| !pc.is_finite() || pc <= 0.0)) { + if p.get("percent").is_some_and(|value| !value.is_null() && value.as_f64().is_none_or(|pc| !pc.is_finite() || pc <= 0.0)) { return None; } // Resolution only with Resample on imports as keep-print-size; a command without it cannot be told apart. diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 057a14dd71..59a7a66b16 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3610,7 +3610,7 @@ fn image_size_explicit_sides_keep_precedence_over_percent() { #[test] fn image_size_explicit_sides_do_not_hide_invalid_percent() { - for percent in [json!(0), json!(-1), json!("50"), json!(false), json!(null)] { + for percent in [json!(0), json!(-1), json!("50"), json!(false)] { let params = json!({"width": 20, "height": 18, "percent": percent, "resample": "nearest"}); let mut native = Session::new(); native.execute("file.new", json!({"width": 32, "height": 24})).unwrap(); diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index c87de3a02a..7aa0608111 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -257,7 +257,8 @@ fn image_size(s: &mut Session, p: &Value) -> Result { ph = scaled_dimension(p, "height", scale, "image.imageSize")?; } // `percent` scales both sides (what a Photoshop action records as "200%"); an explicit side wins. - if let Some(pc) = p.get("percent") { + // A null `percent` is omitted, like a null side or resolution. + if let Some(pc) = p.get("percent").filter(|value| !value.is_null()) { let pc = pc.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad("image.imageSize", "`percent` must be a positive number"))?; pw = pw.or(Some(ow as f64 * pc / 100.0)); ph = ph.or(Some(oh as f64 * pc / 100.0)); diff --git a/crates/engine/tests/it/atn_mapped_identifiers.rs b/crates/engine/tests/it/atn_mapped_identifiers.rs index daed23a2e6..6fb8097bb2 100644 --- a/crates/engine/tests/it/atn_mapped_identifiers.rs +++ b/crates/engine/tests/it/atn_mapped_identifiers.rs @@ -94,6 +94,31 @@ fn review_point_resize_exports_with_null_optional_values() { } } +/// A null percentage is omitted at playback too, so an exported step and the native command agree. +#[test] +fn review_null_percent_is_omitted_by_the_native_resize() { + for params in + [json!({"width":72,"units":"pt","resample":"nearest","scaleStyles":false,"percent":null}), json!({"width":30,"resample":"nearest","percent":null})] + { + let mut without = params.clone(); + without.as_object_mut().unwrap().remove("percent"); + let mut expected = sized_document(20, 10, 144); + expected.execute("image.imageSize", without).unwrap(); + let mut actual = sized_document(20, 10, 144); + actual.execute("image.imageSize", params.clone()).expect("a null percent must not refuse the resize"); + assert_eq!(actual.active().unwrap().doc.size, expected.active().unwrap().doc.size); + let action = Action::new("Recorded", vec![ActionStep::new("image.imageSize", params)]); + let (bytes, skipped) = atn_cmds::export("Identifiers", &[&action], &[], false).unwrap(); + assert!(skipped.is_empty()); + let imported = atn_cmds::import(&bytes).unwrap(); + let mut replayed = sized_document(20, 10, 144); + replayed.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + let result = replayed.execute("actions.play", json!({"action":"Recorded"})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(replayed.active().unwrap().doc.size, expected.active().unwrap().doc.size); + } +} + /// The native default resampler must be explicit in a physical-size recording. #[test] fn review_point_resize_exports_the_default_resampler() { diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index 9d99724f22..cd58e26268 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -54,7 +54,15 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // start at 0° and off too, whatever the outgoing brush has (#12629). None if matches!( tool, - Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge | Tool::AdjustmentBrush | Tool::ArtHistoryBrush + Tool::BackgroundEraser + | Tool::Healing + | Tool::Burn + | Tool::Dodge + | Tool::Sponge + | Tool::CloneStamp + | Tool::Smudge + | Tool::AdjustmentBrush + | Tool::ArtHistoryBrush ) => { fresh_brush(tool, ¤t) From b9a3c22aab9689dd04c5ed889644f3489fe27674 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 03:04:43 +0100 Subject: [PATCH 127/136] UI: key the histogram, Export As preview and Layer Style swatch on the scratch read-error generation (#16364) The Histogram panel folds the generation into its key, so its counts go stale and are counted again; the Export As preview asks again for the same revision when the generation moves, as it does for a working-profile change; the Layer Style dialog's preview swatch, drawn over the patterns' pixels, keys on it too. Each has a test that fails without its key change. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/export_dialog.rs | 18 ++++++++------- .../src/dialogs/export_dialog/tests.rs | 23 +++++++++++++++++++ crates/ui-egui/src/dialogs/layer_style.rs | 9 +++++++- .../ui-egui/src/dialogs/layer_style/tests.rs | 13 +++++++++++ crates/ui-egui/src/panels/histogram_panel.rs | 4 +++- .../src/panels/histogram_panel/tests.rs | 18 +++++++++++++++ 6 files changed, 75 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 8b695b3525..21b5a651c2 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -203,9 +203,10 @@ pub(crate) struct ExportOpen { picking: bool, /// The newest preview the dialog asked for that is not fully answered yet. work: Option, - /// The newest request made, with the working profile it was made under: a change of the working - /// profile alters the preview of an untagged document without changing the settings. - last: Option<(u64, ExportOptions, Option)>, + /// The newest request made, with the working profile and the scratch read-error generation it was made under: a + /// change of the working profile alters the preview of an untagged document without changing the settings, and a + /// tile that fails to read and recovers alters the pixels without a new revision (`crate::scratch_reads`). + last: Option<(u64, ExportOptions, Option, u64)>, } /// One preview request being answered: the proxy preview first, then the exact size estimate. @@ -881,13 +882,14 @@ fn drive(app: &mut PhotocraftApp, ctx: &egui::Context, open: &mut ExportOpen) -> dialog.cancel_requests(); } } - // The settings did not change but the working profile did: ask again for the same revision. + // The settings did not change but the working profile or the scratch read-error generation did: ask again for the + // same revision. let wanted = wanted.or_else(|| { - let (revision, options, hash) = open.last.as_ref()?; - (working_profile_hash(app) != *hash).then(|| PreviewRequest::new(*revision, options.clone())) + let (revision, options, hash, scratch) = open.last.as_ref()?; + (working_profile_hash(app) != *hash || crate::scratch_reads::generation() != *scratch).then(|| PreviewRequest::new(*revision, options.clone())) }); if let Some(request) = wanted { - open.last = Some((request.revision, request.options.clone(), working_profile_hash(app))); + open.last = Some((request.revision, request.options.clone(), working_profile_hash(app), crate::scratch_reads::generation())); open.work = start_preview(app, open, request); } answer_preview(app, ctx, open); @@ -940,7 +942,7 @@ fn start_preview(app: &PhotocraftApp, open: &ExportOpen, request: PreviewRequest let profile = effective_source_profile(app, &doc); let signature = format!("{}:{}", Value::Object(settings.clone()), profile.content_hash()); let layer = open.layers.first().map(|layer| layer.0); - let key = egui::Id::unique(("export-preview", doc.id.0, st.revision, layer)); + let key = egui::Id::unique(("export-preview", doc.id.0, st.revision, layer, crate::scratch_reads::generation())); Some(PreviewWork { revision: request.revision, settings, signature, key, doc, profile, answered: None }) } diff --git a/crates/ui-egui/src/dialogs/export_dialog/tests.rs b/crates/ui-egui/src/dialogs/export_dialog/tests.rs index 24c1b0f6ab..ccbc1244db 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/tests.rs @@ -924,6 +924,29 @@ fn preview_cache_tracks_working_profiles_but_prefers_embedded_profiles() { } } +/// A tile that fails to read and recovers alters the pixels without a new revision or other settings: the preview +/// is made again, so it does not keep the zeros it read during the error (`crate::scratch_reads`). +#[test] +fn the_preview_is_made_again_after_a_scratch_read_error_transition() { + let app = export_app(20, 10); + let revision = app.session.active().unwrap().revision; + let mut h = harness(app); + open(h.state_mut()).unwrap(); + settle_preview(&mut h); + let texture = + |h: &AppHarness| h.state().export_open.as_ref().and_then(|open| open.texture.as_ref().map(egui::TextureHandle::id)).expect("a preview was made"); + let before = texture(&h); + let options = dialog_options(&h); + h.run_steps(3); + settle_preview(&mut h); + assert_eq!(texture(&h), before, "nothing changed: the same preview"); + crate::scratch_reads::tests::simulate_read_error_transition(); + settle_preview(&mut h); + assert_eq!(h.state().session.active().unwrap().revision, revision); + assert_eq!(dialog_options(&h), options, "the settings did not change"); + assert_ne!(texture(&h), before, "the preview is made again"); +} + /// The dialog's requests are taken once: a second take in the same frame (a frame can run two /// passes) starts no second preview and files no second save request. #[test] diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index de856173ae..5b956a5347 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -641,11 +641,18 @@ fn paint_picture(cx: &ContentPainterCx, rect: Rect, key: impl std::hash::Hash + cx.picture(texture, rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), 0.0); } +/// The texture store key of the preview swatch: the draft's render hash and the scratch read-error generation, as the +/// swatch draws over the patterns' pixels, which a tile that fails to read shows as zeros until it reads again +/// (`crate::scratch_reads`). +fn swatch_key(draft: &LayerStyleDraft) -> (&'static str, u64, u64) { + ("layer-style-swatch", draft.render_hash(), crate::scratch_reads::generation()) +} + /// Paints the preview swatch: the draft's style on a sample square, rebuilt when its render hash changes. fn preview_thumb(app: &PhotocraftApp) -> impl Fn(&ContentPainterCx, Rect, &LayerStyleDraft) + Send + Sync + 'static { let patterns = app.session.patterns.clone(); move |cx, rect, draft| { - paint_picture(cx, rect, ("layer-style-swatch", draft.render_hash()), || { + paint_picture(cx, rect, swatch_key(draft), || { let mut scratch = Session::new(); scratch.patterns = patterns.clone(); match pending_style(&patterns, &draft.style) { diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 7d83620208..3ee114f20c 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -790,3 +790,16 @@ fn an_existing_outer_glow_is_edited_with_its_own_values() { let FxPaint::Color(c) = &g.paint else { panic!("{:?}", g.paint) }; assert_eq!(hex(c), "#ffffbe", "OK kept the colour"); } + +/// The preview swatch draws over the patterns' pixels: a tile that fails to read and recovers keeps the draft's render +/// hash, and the swatch still keys a new picture, so it does not keep the zeros it read during the error. +#[test] +fn the_preview_swatch_follows_a_scratch_read_error_transition() { + let mut app = app_with_layer(32); + let id = open(&mut app, Some(EffectKind::PatternOverlay.key())).unwrap(); + let key = swatch_key(draft(&app, id)); + assert_eq!(swatch_key(draft(&app, id)), key, "nothing changed: the same picture"); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_eq!(draft(&app, id).render_hash(), key.1, "the draft is unchanged"); + assert_ne!(swatch_key(draft(&app, id)), key, "the swatch draws again"); +} diff --git a/crates/ui-egui/src/panels/histogram_panel.rs b/crates/ui-egui/src/panels/histogram_panel.rs index 65cb782240..7a241651c7 100644 --- a/crates/ui-egui/src/panels/histogram_panel.rs +++ b/crates/ui-egui/src/panels/histogram_panel.rs @@ -351,7 +351,9 @@ fn committed_key(app: &PhotocraftApp) -> Option<(HistKey, ToneSpace, HistSource) Some((d, r, k)) if d == doc && r == revision => k, _ => tone::selection_key(&st.doc), }; - let source_tag = tone::tag(source, space, HistScope::Selection, sel); + // A tile that fails to read counts as zeros, and as its pixels again once it reads, without a new revision: the + // key follows the scratch read-error generation too (`crate::scratch_reads`). + let source_tag = crate::scratch_reads::with(tone::tag(source, space, HistScope::Selection, sel)); Some((HistKey { doc, revision, source: source_tag, preview: 0, max_level }, space, source)) } diff --git a/crates/ui-egui/src/panels/histogram_panel/tests.rs b/crates/ui-egui/src/panels/histogram_panel/tests.rs index fe53966526..0a85f3b077 100644 --- a/crates/ui-egui/src/panels/histogram_panel/tests.rs +++ b/crates/ui-egui/src/panels/histogram_panel/tests.rs @@ -447,3 +447,21 @@ fn the_tone_histogram_cache_ignores_selection_changes() { app.run("select.deselect", json!({})).unwrap(); assert!(Arc::ptr_eq(&first, &tone::histograms(&mut app, src, ToneSpace::Rgb)), "deselecting keeps it too"); } + +/// A tile that fails to read counts as zeros, and as its pixels again once it reads, without a new revision or +/// selection: the panel's histogram goes stale and is counted again (`crate::scratch_reads`). +#[test] +fn the_panel_recounts_after_a_scratch_read_error_transition() { + let mut app = app_with(json!({"width": 64, "height": 48})); + settle(&mut app); + let counted = app.doc_hist.clone().expect("landed"); + frame(&mut app); + assert_eq!(inspect(&app)["current"], true, "nothing changed: still current"); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_eq!(inspect(&app)["current"], false, "stale after the transition"); + settle(&mut app); + let recounted = app.doc_hist.clone().expect("landed"); + assert_eq!(recounted.key.revision, counted.key.revision, "no new revision"); + assert_ne!(recounted.key.source, counted.key.source, "counted again for the new generation"); + assert_eq!(inspect(&app)["current"], true); +} From d4c630df0ec1775bcadbfec87d729fc797d26584 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 03:31:31 +0100 Subject: [PATCH 128/136] Integration: drop #14714 from the batch The book's relative links to docs/mcp.md follow the branch they are read on; pinning them to main would send readers of a fork, a branch or an older release to the wrong version. Co-Authored-By: Claude Opus 5.5 --- book/src/automation/mcp.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 4528b56576..57a76c5c5d 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -6,9 +6,9 @@ - **Bridge:** `BridgeClient` forwards tools to a desktop application started with `photocraft --control `. - **The open window:** plain `photocraft-cli mcp` finds the desktop application through the connection file it publishes while the person lets agents use it (ArtCraft Launcher › Settings › AI agents), before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen in Preferences › AI Integrations. Without that consent, or with `--headless`, it is the headless session above. -The simplest setup needs no terminal: turn on ArtCraft Launcher › Settings › AI agents and click *Add* next to the AI app; that one entry reaches every Craft app. See [`docs/mcp.md`](https://github.com/storytold/photocraft/blob/main/docs/mcp.md#connecting-the-desktop-app-no-terminal). +The simplest setup needs no terminal: turn on ArtCraft Launcher › Settings › AI agents and click *Add* next to the AI app; that one entry reaches every Craft app. See [`docs/mcp.md`](../../../docs/mcp.md#connecting-the-desktop-app-no-terminal). -For a source checkout, first [install the CLI on PATH and register the server](https://github.com/storytold/photocraft/blob/main/docs/mcp.md#install-and-register). +For a source checkout, first [install the CLI on PATH and register the server](../../../docs/mcp.md#install-and-register). The installed binary survives `cargo clean`; a symlink into `target/release` does not. Start the headless server with (without `--headless`, `mcp` works in the open PhotoCraft window @@ -77,4 +77,4 @@ listed. `photocraft://document` and `photocraft://commands` expose live JSON. Lo that are waited on report progress and stop when the request is cancelled, headless and in bridge mode (where they may also outlast the bridge's reply timeout), and direct headless Render Video does too, using the granted write root; see -[`docs/mcp.md`](https://github.com/storytold/photocraft/blob/main/docs/mcp.md) for arguments, cleanup and transport behavior. +[`docs/mcp.md`](../../../docs/mcp.md) for arguments, cleanup and transport behavior. From bda7872bea5f4100ce059ed4f0c8dda0d824182a Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:10:26 +0100 Subject: [PATCH 129/136] fix(ui): Select Data Points draws each check box's name (#16345) The data point check boxes sat in a labelled "Data Points" row. A check box named by its row's label scope draws no text of its own, so all 36 boxes showed without names, and the column titles stood on the line of "Data Points:". The row is now full width with "Data Points:" drawn above the three titled columns, so each box draws its name beside it. --- .../analysis/data_points_labels_tests.rs | 97 +++++++++++++++++++ crates/ui-egui/src/tools/analysis/dialogs.rs | 40 +++++--- 2 files changed, 122 insertions(+), 15 deletions(-) create mode 100644 crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs diff --git a/crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs b/crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs new file mode 100644 index 0000000000..236a071a3a --- /dev/null +++ b/crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs @@ -0,0 +1,97 @@ +//! #16345: Image › Analysis › Select Data Points draws every check box with its data point's name, and each column's +//! title above its boxes. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_engine::analysis_cmds; +use serde_json::json; + +use super::sources; +use crate::PhotocraftApp; + +type H = Harness<'static, Box>; + +fn open_dialog() -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).with_context(app.ctx().clone()).build_ui_state( + |ui, app: &mut Box| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::dialogs::run(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "image.analysis.selectDataPoints", json!({})).unwrap(); + h.run_steps(6); + h +} + +/// The shown name of data point `column`, as the engine lists it. +fn name(column: &str) -> &str { + analysis_cmds::COLUMNS.iter().find(|c| c.0 == column).map_or(column, |c| c.1) +} + +/// A check box of the dialog: where it is, its name, and where the text that names it is drawn. +struct Shown { + rect: egui::Rect, + name: String, + text: Option, +} + +fn rect(r: egui::accesskit::Rect) -> egui::Rect { + egui::Rect::from_min_max(egui::pos2(r.x0 as f32, r.y0 as f32), egui::pos2(r.x1 as f32, r.y1 as f32)) +} + +#[test] +fn every_check_box_draws_its_data_point_name_and_each_column_its_title_above() { + let h = open_dialog(); + let mut boxes: Vec = h + .query_all_by_role(Role::CheckBox) + .map(|b| { + let node = b.accesskit_node(); + let name = node.label().unwrap_or_default(); + let text = + node.labelled_by().find(|l| l.role() == Role::Label && l.value().as_deref() == Some(name.as_str())).and_then(|l| l.bounding_box()).map(rect); + Shown { rect: b.rect(), name, text } + }) + .collect(); + // In columns by their left edge, each column top to bottom. + boxes.sort_by(|a, b| a.rect.left().total_cmp(&b.rect.left()).then(a.rect.top().total_cmp(&b.rect.top()))); + let mut columns: Vec> = Vec::new(); + for shown in boxes { + match columns.last_mut() { + Some(column) if (column[0].rect.left() - shown.rect.left()).abs() < 0.5 => column.push(shown), + _ => columns.push(vec![shown]), + } + } + let names: Vec> = columns.iter().map(|c| c.iter().map(|s| s.name.as_str()).collect()).collect(); + assert_eq!(columns.len(), sources().len(), "one column of boxes per source: {names:?}"); + for (((source, title), column), shown) in sources().into_iter().zip(&columns).zip(&names) { + let want: Vec<&str> = analysis_cmds::available(source).into_iter().map(name).collect(); + assert_eq!(shown, &want, "{source}: each box is named after its data point, in order"); + // Each box draws its name: the text that names it stands after the box, on its line. + for b in column { + let text = b.text.unwrap_or_else(|| panic!("{source}: {:?} draws no name", b.name)); + assert!( + text.left() >= b.rect.right() - 0.5 && text.top() < b.rect.bottom() && text.bottom() > b.rect.top(), + "{source}: {:?} is named beside its box", + b.name + ); + } + // The title sits over its column's first box, under the dialog's "Data Points:" rather than on its line. + let heading = h.query_by_label("Data Points:").expect("\"Data Points:\" is drawn").rect(); + let first = column[0].rect; + let title = h + .query_all_by_label(title) + .find(|n| n.accesskit_node().role() != Role::CheckBox && n.rect().left() <= first.center().x && n.rect().right() >= first.center().x) + .unwrap_or_else(|| panic!("{title} heads its column")) + .rect(); + assert!(title.bottom() <= first.top() + 0.5, "{source}: the title {title:?} is above the first box {first:?}"); + assert!(heading.bottom() <= title.top() + 0.5, "{source}: \"Data Points:\" {heading:?} is above the title {title:?}"); + } +} diff --git a/crates/ui-egui/src/tools/analysis/dialogs.rs b/crates/ui-egui/src/tools/analysis/dialogs.rs index 9285426605..8247e31ac5 100644 --- a/crates/ui-egui/src/tools/analysis/dialogs.rs +++ b/crates/ui-egui/src/tools/analysis/dialogs.rs @@ -170,26 +170,32 @@ fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> { }) } Kind::DataPoints => { + // Full width, with the title over the columns: in a labelled row every check box is named by the row and + // draws no name of its own. let row = Param::custom("columns", tl!("Data Points"), |ui, fields, _| { - Row::new() + Stack::new() .show(ui, |ui, _| { - for (source, title) in sources() { - Stack::new().show(ui, |ui, _| { - Text::new(Label::from(title)).show(ui); - for column in analysis_cmds::available(source) { - let name = analysis_cmds::COLUMNS.iter().find(|c| c.0 == column).map_or(column, |c| c.1); - let field = point_key(source, column); - let mut on = fields.bool(&field).unwrap_or(false); - Checkbox::new(Bind::bound(&mut on)).label(name.to_owned()).show(ui); - if fields.bool(&field) != Some(on) { - fields.set(field, on); + Text::new(Label::from(tl!("Data Points:"))).show(ui); + Row::new().show(ui, |ui, _| { + for (source, title) in sources() { + Stack::new().show(ui, |ui, _| { + Text::new(Label::from(title)).show(ui); + for column in analysis_cmds::available(source) { + let name = analysis_cmds::COLUMNS.iter().find(|c| c.0 == column).map_or(column, |c| c.1); + let field = point_key(source, column); + let mut on = fields.bool(&field).unwrap_or(false); + Checkbox::new(Bind::bound(&mut on)).label(name.to_owned()).show(ui); + if fields.bool(&field) != Some(on) { + fields.set(field, on); + } } - } - }); - } + }); + } + }); }) .output - }); + }) + .full_width(); ParamDialog::command(key, tl!("Select Data Points"), vec![row]) } Kind::ScaleMarker => { @@ -211,3 +217,7 @@ fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> { }; dialog.values(Bind::bound(fields)) } + +#[cfg(test)] +#[path = "data_points_labels_tests.rs"] +mod data_points_labels_tests; From 73b38a6fad8aeae9de5a8d1d99aef45ed0c89caa Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Sun, 22 Nov 2026 09:49:02 +0000 Subject: [PATCH 130/136] UI: show the Limits, Curve Fit, Author and Color labels in the options bar (#16338) Background Eraser's Limits dropdown, Freeform Pen's Curve Fit field and the Note tool's Author field and Color swatch were bare controls whose label only named them for accessibility. Wrap each in a Field, as the labelled bar cells (Color Replacement's Limits, the frame Stroke field) already do, so the label is drawn in front of the control. Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- crates/ui-egui/src/tools.rs | 3 ++ crates/ui-egui/src/tools/analysis/bars.rs | 9 +++-- crates/ui-egui/src/tools/eraser_ui.rs | 21 +++++++---- .../tools/options_bar_field_labels_tests.rs | 37 +++++++++++++++++++ crates/ui-egui/src/tools/vector_ui/options.rs | 13 +++++-- 5 files changed, 70 insertions(+), 13 deletions(-) create mode 100644 crates/ui-egui/src/tools/options_bar_field_labels_tests.rs diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index d23b04cd3b..4b9009cfb2 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -82,3 +82,6 @@ mod art_history_reset_tip_tests; #[cfg(test)] mod object_selection_not_found_tests; + +#[cfg(test)] +mod options_bar_field_labels_tests; diff --git a/crates/ui-egui/src/tools/analysis/bars.rs b/crates/ui-egui/src/tools/analysis/bars.rs index baca8837ae..15d34f36e8 100644 --- a/crates/ui-egui/src/tools/analysis/bars.rs +++ b/crates/ui-egui/src/tools/analysis/bars.rs @@ -7,8 +7,9 @@ use craft::draw::ui::measure::{RulerBar, RulerLine}; use craft::theme::Srgba; use craft::ui::buttons::{Button, IconButton, ToggleButton}; use craft::ui::choice::Swatch; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::{Divider, Text}; +use craft::ui::form::Field; use craft::ui::pickers::Select; use craft::ui::runtime::env::Label; use craft::ui::text::TextField; @@ -180,9 +181,11 @@ fn count(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &photocraft_doc::Docum } fn note(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &photocraft_doc::Document) { - TextField::new(Label::from(tl!("Author")), Bind::bound(&mut app.ui.analysis.note_author)).show(ui); + // In `Field`s: a bare control's label only names it, it is not drawn (#16338). + Field::new(Label::from(tl!("Author"))).show(ui, |ui, _| TextField::new(Label::from(tl!("Author")), Bind::bound(&mut app.ui.analysis.note_author)).show(ui)); let rgb = app.ui.analysis.note_color; - if Swatch::new(Label::from(tl!("Color")), Srgba::from_rgb_array(rgb)).show(ui).clicked + let swatch = Field::new(Label::from(tl!("Color"))).show(ui, |ui, _| Swatch::new(Label::from(tl!("Color")), Srgba::from_rgb_array(rgb)).show(ui).clicked); + if swatch.inner == Some(true) && let Err(message) = crate::color_picker_ui::open_for_target(app, "noteColor", &crate::color_picker_ui::title_for(tl!("Color")), rgb) { crate::notices::error(app, message); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 2ebed238af..12fd03a433 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -7,8 +7,9 @@ use craft::behavior::IconId; use craft::ui::buttons::ToggleButton; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::Divider; +use craft::ui::form::Field; use craft::ui::pickers::Select; use craft::ui::primitives::IconSpec; use photocraft_engine::eraser_cmds::{MAGIC_ERASER_BITMAP_ERROR, MAGIC_ERASER_INDEXED_ERROR}; @@ -197,12 +198,18 @@ fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { Entry::new("contiguous".to_string(), tl!("Contiguous")), Entry::new("findEdges".to_string(), tl!("Find Edges")), ]; - let picked = Select::new(tl!("Limits:"), Bind::given(o.bg_limits.clone()), &limits) - .tooltip(tl!("How far to let the erasing spread").to_owned()) - .show(ui) - .events - .committed() - .cloned(); + // In a `Field`, as Color Replacement's Limits: a bare control's label only names it (#16338). + let picked = Field::new(tl!("Limits:")) + .show(ui, |ui, _| { + Select::new(tl!("Limits:"), Bind::given(o.bg_limits.clone()), &limits) + .tooltip(tl!("How far to let the erasing spread").to_owned()) + .show(ui) + .events + .committed() + .cloned() + }) + .inner + .flatten(); if let Some(limits) = picked { o.bg_limits = limits; } diff --git a/crates/ui-egui/src/tools/options_bar_field_labels_tests.rs b/crates/ui-egui/src/tools/options_bar_field_labels_tests.rs new file mode 100644 index 0000000000..0f5c8c4195 --- /dev/null +++ b/crates/ui-egui/src/tools/options_bar_field_labels_tests.rs @@ -0,0 +1,37 @@ +//! #16338: Background Eraser's "Limits:", Freeform Pen's "Curve Fit:" and the Note tool's "Author:" and "Color:" +//! are drawn in front of their controls, not only given to them as accessible names. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The options bar of `tool` on a new document, rendered through the real host. +fn bar(tool: Tool) -> Harness<'static, Box> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + let mut h = + Harness::builder().with_size(vec2(1600.0, 200.0)).with_context(app.ctx().clone()).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + h +} + +#[test] +fn bare_bar_controls_show_their_labels() { + let cases: [(Tool, &[&str]); 3] = [(Tool::BackgroundEraser, &["Limits:"]), (Tool::FreeformPen, &["Curve Fit:"]), (Tool::Note, &["Author", "Color"])]; + for (tool, labels) in cases { + let h = bar(tool); + let shown: Vec = h.query_all_by_role(Role::Label).filter_map(|n| n.accesskit_node().label()).collect(); + for label in labels { + let node = h.query_all_by_role(Role::Label).find(|n| n.accesskit_node().label().as_deref() == Some(label)); + let node = node.unwrap_or_else(|| panic!("{tool:?}: label {label:?} is drawn; labels shown: {shown:?}")); + let r = node.rect(); + assert!(r.width() > 0.0 && r.height() > 0.0 && r.top() >= 0.0, "{tool:?}: {label:?} has a visible rect: {r:?}"); + } + } +} diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index 5668bd24ac..face470c71 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -7,6 +7,7 @@ use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked}; use craft::ui::display::{Divider, Text}; +use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::runtime::env::{Label, UnitKind}; use craft::ui::text::NumberField; @@ -205,9 +206,15 @@ fn pen_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, open: &mut Ba match tool { Tool::FreeformPen => { Divider::vertical().show(ui); - let field = - NumberField::new(label(tl!("Curve Fit:")), Bind::given(Some(f64::from(o.curve_fit)))).range(0.5..=10.0).unit_kind(UnitKind::Pixels).show(ui); - if let Some(Some(v)) = field.value().copied() { + // In a `Field`: a bare control's label only names it, it is not drawn (#16338). + let picked = Field::new(label(tl!("Curve Fit:"))) + .show(ui, |ui, _| { + let field = NumberField::new(label(tl!("Curve Fit:")), Bind::given(Some(f64::from(o.curve_fit)))); + field.range(0.5..=10.0).unit_kind(UnitKind::Pixels).show(ui).value().copied() + }) + .inner + .flatten(); + if let Some(Some(v)) = picked { o.curve_fit = v as f32; } let alt = crate::shortcuts::pretty("Alt"); From 6e0e587d9680c7151985c6fa67de1169523ae4e6 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:26:25 +0700 Subject: [PATCH 131/136] test(raw): verify Camera Raw exposure migration after native reopen (#16387) * test(raw): verify Camera Raw exposure migration after native reopen * style(test): format native Camera Raw migration fixture --- .../tests/it/camera_raw_baseline_pin.rs | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/engine/tests/it/camera_raw_baseline_pin.rs b/crates/engine/tests/it/camera_raw_baseline_pin.rs index a7152da043..e0e26cd252 100644 --- a/crates/engine/tests/it/camera_raw_baseline_pin.rs +++ b/crates/engine/tests/it/camera_raw_baseline_pin.rs @@ -148,6 +148,50 @@ fn camera_raw_smart_filter_migrates_to_shared_develop_settings() { assert_eq!(migrated.settings.vignette.style, craft_develop_model::VignetteStyle::HighlightPriority); } +#[test] +fn camera_raw_migration_preserves_exposure_presence_after_native_reopen() { + use std::sync::Arc; + + use craft_develop_model::{DevelopSettings, Process}; + use photocraft_color::{BlendMode, ColorMode, SampleType}; + use photocraft_doc::{Document, Layer, Size, SmartFilter, SmartObject, SmartSource}; + use photocraft_geom::Affine; + + // Original synthetic content. Exercise the native serializer, not the PSD importer. + let size = Size::new(2, 2); + let mut source = Session::new(); + source.execute("file.new", json!({"width": 2, "height": 2, "depth": 16})).unwrap(); + let embedded = Arc::new(photocraft_format::save_to_bytes(&source.active().unwrap().doc, &Default::default()).unwrap()); + let mut base = DevelopSettings { process: Process::V8.version(), ..Default::default() }; + base.light.exposure = -0.75; + base.light.contrast = 12.0; + for (params, expected) in [(json!({"encodingGamma": 1.8}), -0.75), (json!({"encodingGamma": 1.8, "exposure": 0.0}), 0.0)] { + let source = SmartSource::Embedded { file_name: "generated.pcraft".into(), bytes: embedded.clone() }; + let mut smart = SmartObject::new(source, Affine::IDENTITY, None); + smart.smart_filters.push(SmartFilter { + command: "filter.cameraRaw".into(), + params: params.clone(), + blend: BlendMode::Normal, + opacity: 1.0, + visible: true, + }); + let mut doc = Document::new("Saved Camera Raw exposure", size, ColorMode::Rgb, SampleType::U16); + doc.layers.push(Layer::new("Stored filter", LayerContent::Smart(smart))); + + let saved = photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap(); + let reopened = photocraft_format::load_from_bytes(&saved).unwrap(); + let LayerContent::Smart(smart) = &reopened.layers[0].content else { panic!("expected reopened Smart Object") }; + let [filter] = smart.smart_filters.as_slice() else { panic!("expected one stored Camera Raw filter") }; + assert_eq!(filter.command, "filter.cameraRaw"); + assert_eq!(filter.params, params); + let migrated = photocraft_algo::camera_raw::migrate_to_develop_settings(&base, &filter.params).unwrap(); + assert!(migrated.unmapped_fields.is_empty(), "{:?}", migrated.unmapped_fields); + assert_eq!(migrated.settings.process, base.process); + assert_eq!(migrated.settings.light.exposure, expected); + assert_eq!(migrated.settings.light.contrast, base.light.contrast); + } +} + #[test] fn reopened_camera_raw_smart_filter_keeps_legacy_close_curve_knots() { use std::sync::Arc; From 7c105d873d1bd26ee39cb030acd1f50d78762af5 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 12:23:00 +0100 Subject: [PATCH 132/136] Revert "Merge PR #14699: web: allow browser zoom on both host pages" This reverts commit 66fcded47294bf138cb52e8366a1abaf55ba14d0, reversing changes made to fbe6b1e594a5686f6c119181949dbb9c8cdb2098. --- apps/photocraft-web-boot/index.html | 2 +- apps/photocraft-web/index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/photocraft-web-boot/index.html b/apps/photocraft-web-boot/index.html index c527f8d78f..ff3e548534 100644 --- a/apps/photocraft-web-boot/index.html +++ b/apps/photocraft-web-boot/index.html @@ -2,7 +2,7 @@ - + PhotoCraft