Isolate scalar tone parameters and normalize recorded gray aliases

This commit is contained in:
Vlad Grankovsky committed 2026-10-23 20:23:13 +02:00
1 parent 7b89bc637a
commit 36944dfbaa
7 files changed
+176 -8

No files matched your search

+3 -3
View File
@@ -69,14 +69,14 @@ pub fn default_for(kind: &str, mode: ColorMode) -> Result<Adjustment> {
from_params(kind, &json!({}), None, mode)
}
/// Tone params for a gray plane target: the document-space channel records are dropped, because
/// those keys select the Lab or CMYK tone space and a plane only holds levels (#5335).
/// Tone params for a gray plane target: drop RGB, CMYK and Lab component records so only the
/// composite (or `gray` alias) can affect the plane. Hidden colour curves must stay neutral (#5335).
pub fn gray_tone_params(p: &Value) -> Value {
match p {
Value::Object(m) => {
let mut o = Map::new();
for (k, v) in m {
if !matches!(k.as_str(), "cyan" | "magenta" | "yellow" | "black" | "lightness" | "a" | "b") {
if !matches!(k.as_str(), "red" | "green" | "blue" | "cyan" | "magenta" | "yellow" | "black" | "lightness" | "a" | "b") {
o.insert(k.clone(), v.clone());
}
}
+1 -1
View File
@@ -1447,7 +1447,7 @@ fn build() -> Vec<CommandSpec> {
Some(adj) => adj,
None => {
// A gray plane target keeps the neutral tone space even over params
// carrying Lab or CMYK records (#5335).
// carrying RGB, Lab or CMYK records (#5335).
let tone = if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) {
if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::gray_tone_params(p) } else { p.clone() }
} else {
@@ -228,3 +228,83 @@ fn bad_scalar_picker_params_fail_without_changing_pixels() {
assert!(s.execute(&format!("image.adjustments.{kind}"), json!({"target":{"channel":999},"eyedropper":{"point":"white","at":[8,8]}})).is_err());
}
}
/// 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)]
{
for style in ["levels", "points", "pencil"] {
for sampled in [false, true] {
for explicit in [false, true] {
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);
}
}
}
}
}
}
}
+18 -2
View File
@@ -309,17 +309,33 @@ fn open_fields(app: &mut PhotocraftApp, command: &str, mut fields: Map<String, V
let spec = photocraft_engine::commands::find(command)?;
let mode = curve_mode(app, kind, &fields);
let defaults = photocraft_engine::adjust_params::default_for(kind, mode).ok()?;
let supplied = if matches!(kind, "levels" | "curves") && isolated(app, &fields).is_some_and(|c| c.gray.is_some()) {
let gray_target = matches!(kind, "levels" | "curves") && isolated(app, &fields).is_some_and(|c| c.gray.is_some());
let mut supplied = if gray_target {
photocraft_engine::adjust_params::gray_tone_params(&Value::Object(std::mem::take(&mut fields))).as_object().cloned().unwrap_or_default()
} else {
std::mem::take(&mut fields)
};
// Resolve a recorded gray alias before adding defaults: Levels' alias would otherwise
// override visible control edits, while Curves' default points would hide the alias entirely.
if gray_target
&& supplied.contains_key("gray")
&& let Ok(adjustment) = photocraft_engine::adjust_params::from_params(kind, &Value::Object(supplied.clone()), None, mode)
&& let Value::Object(canonical) = photocraft_engine::adjust_params::to_params(&adjustment)
{
supplied.remove("gray");
supplied.extend(canonical);
}
fields.insert("__command".into(), json!(command));
fields.insert("__label".into(), json!(spec.label));
fields.insert("__adjust".into(), json!(kind));
fields.insert("__filter".into(), json!(true));
fields.insert("__preview".into(), json!(true));
if let Value::Object(p) = photocraft_engine::adjust_params::to_params(&defaults) {
if let Value::Object(mut p) = photocraft_engine::adjust_params::to_params(&defaults) {
// An invalid gray alias must reach engine validation: seeded identity points would
// otherwise override it. Valid aliases were already canonicalized above.
if gray_target && kind == "curves" && supplied.get("gray").is_some_and(|v| !v.is_null()) && supplied.get("points").is_none_or(Value::is_null) {
p.remove("points");
}
fields.extend(p);
}
fields.extend(supplied);
+64
View File
@@ -284,6 +284,9 @@ fn action_dialog(mode: ColorMode, target: Value, panel: ChannelTarget, kind: &st
// grayscale target. Those records must not leak back into the dialog after normalization.
let mut recorded = photocraft_engine::adjust_params::to_params(&photocraft_engine::adjust_params::default_for(kind, mode).unwrap());
recorded["target"] = target;
for key in ["red", "green", "blue"] {
recorded[key] = if kind == "levels" { json!({"gamma": 4}) } else { json!([[0, 255], [255, 255]]) };
}
app.run(&format!("image.adjustments.{kind}"), recorded).unwrap();
app.run("actions.stop", json!({})).unwrap();
app.run("actions.dialog", json!({"action": "Tone step", "step": 0, "enabled": true})).unwrap();
@@ -302,6 +305,10 @@ fn action_dialog_uses_recorded_alpha_instead_of_current_red_channel() {
let mut h = action_dialog(mode, json!({"channel": 0}), ChannelTarget::Color(0), kind);
assert_eq!(names(&h), ["Saved sky"]);
assert_eq!(params(&h)["target"], json!({"channel": 0}));
let neutral = photocraft_engine::adjust_params::to_params(&photocraft_engine::adjust_params::default_for(kind, ColorMode::Grayscale).unwrap());
for key in ["red", "green", "blue"] {
assert_eq!(params(&h)[key], neutral[key], "hidden {key} starts neutral");
}
for key in ["cyan", "black", "lightness", "a", "b"] {
assert!(params(&h).get(key).is_none());
}
@@ -371,6 +378,9 @@ fn explicit_channel_action_uses_channel_preview_even_with_composite_selected() {
fn explicit_pixels_action_bypasses_current_alpha_target() {
let mut h = action_dialog(ColorMode::Rgb, json!("pixels"), ChannelTarget::Alpha(0), "curves");
assert_eq!(names(&h), ["RGB"]);
for key in ["red", "green", "blue"] {
assert_eq!(params(&h)[key], json!([[0, 255], [255, 255]]), "pixel targets retain their recorded {key} curve");
}
h.get_by_label("Set White Point").click();
h.run_steps(2);
assert!(adjust_dialog::sample_at(h.state_mut(), 8.0, 8.0));
@@ -431,3 +441,57 @@ fn missing_explicit_channel_cannot_preview_as_a_colour_layer() {
assert_eq!(h.state().session.active().unwrap().doc.channels, original.channels);
assert_eq!(h.state().session.active().unwrap().doc.layers, original.layers);
}
/// A recorded `gray` alias must seed editable composite controls, rather than override them invisibly.
#[test]
fn scalar_action_gray_alias_seeds_the_visible_controls() {
for kind in ["levels", "curves"] {
let mut app = fixture(ColorMode::Lab, SampleType::U8, ChannelTarget::Color(0));
let gray = if kind == "levels" { json!({"gamma":2}) } else { json!([[0, 255], [255, 0]]) };
let mut action = photocraft_engine::actions_cmds::Action::new(
"Gray alias",
vec![(format!("image.adjustments.{kind}"), json!({"target":{"channel":0},"gray":gray}))],
);
action.dialogs.insert(0);
app.session.actions.list.push(action);
let mut h = harness(app);
h.state_mut().run("actions.play", json!({"action":"Gray alias"})).unwrap();
h.run_steps(4);
assert_eq!(names(&h), ["Saved sky"]);
let id = h.state().ui.dialogs.last().unwrap().id;
if kind == "levels" {
assert_eq!(params(&h)["gamma"].as_f64(), Some(2.0), "the visible gamma agrees with the recorded gray gamma");
edit_gamma(&mut h, "1.0");
} else {
assert_eq!(params(&h)["points"], json!([[0.0, 255.0], [255.0, 0.0]]), "the visible curve is the recorded gray curve");
h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("points".into(), json!([[0, 0], [255, 255]]));
}
assert!(params(&h).get("gray").is_none(), "a hidden alias must not override subsequent control edits");
let before = h.state().session.active().unwrap().doc.clone();
dialogs::confirm(h.state_mut(), id).unwrap();
assert!((value(h.state(), ChannelTarget::Alpha(0)) - 0.25).abs() < 0.005, "editing the visible controls back to neutral is effective");
assert_eq!(h.state().session.active().unwrap().doc.layers[0].content, before.layers[0].content);
}
}
/// Malformed aliases remain command errors; neutral dialog defaults must not conceal them.
#[test]
fn invalid_scalar_action_gray_alias_cannot_commit() {
for (kind, gray) in [("levels", json!({"gamma":"invalid"})), ("curves", json!("invalid")), ("curves", json!([[0, 0]]))] {
let mut app = fixture(ColorMode::Lab, SampleType::U8, ChannelTarget::Color(0));
let command = format!("image.adjustments.{kind}");
let mut action = photocraft_engine::actions_cmds::Action::new("Invalid alias", vec![(command.clone(), json!({"target":{"channel":0},"gray":gray}))]);
action.dialogs.insert(0);
app.session.actions.list.push(action);
let mut h = harness(app);
h.state_mut().run("actions.play", json!({"action":"Invalid alias"})).unwrap();
h.run_steps(4);
let original = h.state().session.active().unwrap().doc.clone();
let layer = h.state().session.active().unwrap().active_layer;
assert!(filter_dialog::preview_document(&original, layer, &command, &params(&h), 1).is_none());
let id = h.state().ui.dialogs.last().unwrap().id;
assert!(dialogs::confirm(h.state_mut(), id).is_err());
assert!(std::sync::Arc::ptr_eq(&original, &h.state().session.active().unwrap().doc));
assert!(h.state().ui.dialogs.is_empty());
}
}
+1 -1
View File
@@ -79,7 +79,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- Magnetic Lasso (`tool: "magneticLasso"`): a `down`/`up` pair is a click. The first sets the first fastening point (its modifiers set the selection mode); later clicks fasten a point, or close the border on the first point. `move` events trace the border with or without a button held, fastening points by themselves; with `alt: true` a click draws a straight segment and a drag a freehand one. `ui.inspect` shows the border in progress under `magnetic` (`path`, `anchors`, `live`, `mode`). `ui.key` Enter closes it along the edges, Backspace removes the last fastening point, Escape cancels. To select along edges in one call instead, use the `select.magneticLasso` command with rough points around the shape.
- Image › Adjustments › Curves on top, no eyedropper armed (#7325): a `down` with `command: true` adds a point on the curve the dialog shows (its Channel popup), at the pixel's tone (RGB: Rec. 709 luma; Gray: the mean) and at the curve's current output there, so the preview does not change; with `shift: true` as well, one point on each of Red, Green and Blue at that channel's value. It samples the merged image like the eyedroppers, never moves an existing point (a point already within 2 levels is selected instead, a 16-point curve takes no more), and the tool is not driven. Nothing is added with a pencil-drawn curve, in Lab or CMYK, or with a mask, saved channel or Quick Mask targeted.
- Levels or Curves adjustment layer, Properties eyedropper armed (`layerPicker` in `ui.inspect`: `{layer, point, tool}`, set by the panel's Set Black/Neutral Gray/White Point buttons): a `down` sets that point from the image below the layer as one `layer.setAdjustment {"layer", "eyedropper": {"point", "at": [x, y], "size"}}` (send that command directly to skip the UI) and the tool is not driven; Esc, another tool or another layer disarms it.
- Image › Adjustments › Levels/Curves on a raster mask, saved alpha/spot channel or Quick Mask uses grayscale controls in every document colour mode. Both dialogs list only the isolated target by its actual name (custom alpha/spot and mask names stay literal), with the matching channel controls and histogram; Levels Auto uses that histogram too. Black/White Point samples that plane's own values, including unstored defaults, with the Eyedropper's Sample Size clipped at the canvas edge; Neutral Gray is unavailable. Direct commands accept `{"target":"mask"|"quickMask"|{"channel":index}, "eyedropper":{"point":"black|white","at":[x,y],"size":1|3|5|11|31|51|101}}`. Sampling updates dialog parameters until OK; Cancel keeps the pixels. An Action step's explicit target takes precedence over the currently selected channel when choosing its dialog defaults, Levels/Curves channel name, histogram and preview. Reset, pencil editing and sampling retain that explicit target. Adjustment-layer Properties keep sampling the colour image below the layer. Reopening an existing whole-image Smart Filter keeps its recorded colour controls regardless of the current channel or mask target.
- Image › Adjustments › Levels/Curves on a raster mask, saved alpha/spot channel or Quick Mask uses grayscale controls in every document colour mode. Both dialogs list only the isolated target by its actual name (custom alpha/spot and mask names stay literal), with the matching channel controls and histogram; Levels Auto uses that histogram too. Black/White Point samples that plane's own values, including unstored defaults, with the Eyedropper's Sample Size clipped at the canvas edge; Neutral Gray is unavailable. Direct commands accept `{"target":"mask"|"quickMask"|{"channel":index}, "eyedropper":{"point":"black|white","at":[x,y],"size":1|3|5|11|31|51|101}}`. Sampling updates dialog parameters until OK; Cancel keeps the pixels. An Action step's explicit target takes precedence over the currently selected channel when choosing its dialog defaults, Levels/Curves channel name, histogram and preview. Reset, pencil editing and sampling retain that explicit target. Scalar targets discard RGB/CMYK/Lab component records from recorded parameters, and a recorded `gray` alias seeds the visible composite controls so subsequent edits remain effective. Adjustment-layer Properties keep sampling the colour image below the layer. Reopening an existing whole-image Smart Filter keeps its recorded colour controls regardless of the current channel or mask target.
- `ui.click {x, y, button?, count?}` / `ui.move {x, y}`: synthetic pointer input in screen points (`button`: `left` (default), `right` (or `secondary`) or `middle`). `count` (default 1, `2` for a double-click) is at most 256; a larger one is an error and queues nothing
- `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`. `{"key": "AltLeft"}` is a tap on Alt, which puts the keyboard on the in-window menu bar (then `ArrowRight`, `ArrowDown`, `Enter`, `Escape` or a menu's letter drive it); `{"key": "F", "alt": true}` opens the menu with that mnemonic (#4988)
- `ui.pointer`, `ui.click`, `ui.move`, `ui.key` and `ui.screenshot` validate every parameter before acting, as `ui.set` does: an unknown field (top-level, under `modifiers` or in an event), a value of the wrong JSON type (`"x": "abc"`, `"ctrl": "yes"`), a `button`, `kind`, `tool` or `key` outside the accepted set, or a number outside its range (`pressure`, tilt, `rotation`, `count`) is an error naming the parameter, and nothing is queued or applied. A `null` field counts as omitted and takes its default
+9 -1
View File
@@ -27,7 +27,15 @@ Ctrl/Cmd-click point insertion now uses the shared context-preservation helper,
A further review found that reopening a whole-image Levels/Curves Smart Filter could inherit the current channel's isolation, or a Layers-panel mask target and grayscale defaults. Reopening now resolves the captured Smart Filter before seeding its colour controls. A new regression covers RGB/Lab/CMYK, both tone dialogs, and five current targets (alpha, Channels-panel mask, individual component, Layers-panel mask and Quick Mask): 30 reopening/preview/commit cases preserving recorded non-neutral curves, masks and saved channels. Action private-field sanitization also checks that a recorded step cannot forge the Smart Filter marker.
Final current-head validation: full engine/UI `cargo test` **6,221 passed, 0 failed, 36 normally ignored**; the ignored full-registry adversarial command test passed separately. Strict engine/UI all-target Clippy, formatting, layering and wasm passed. Offscreen Smart Filter captures are retained with the review logs. The last general quick-perf attempt (2026-10-22) stopped at an upstream `layout_bench` fixture that converts already imported Smart Objects a second time; four earlier suites passed and the layout benchmark's `--direct` path completed. This dialog-setup follow-up does not change the historical CPU benchmark workload below.
Validation of `7b89bc637`: full engine/UI `cargo test` **6,221 passed, 0 failed, 36 normally ignored**; the ignored full-registry adversarial command test passed separately. Strict engine/UI all-target Clippy, formatting, layering and wasm passed. Offscreen Smart Filter captures are retained with the review logs. The last general quick-perf attempt (2026-10-22) stopped at an upstream `layout_bench` fixture that converts already imported Smart Objects a second time; four earlier suites passed and the layout benchmark's `--direct` path completed. This dialog-setup follow-up does not change the historical CPU benchmark workload below.
## Further parameter review (2026-10-23)
CodeRabbit's next review identified retained non-neutral RGB channel records in scalar parameters. The shared gray-target filter now drops RGB as well as CMYK/Lab component records. A regression first failed on the previous implementation, then passed across 432 cases: RGB/Gray/Lab/CMYK, U8/U16/F32, masks/alpha/spot/Quick Mask, Levels/point Curves/pencil Curves, direct/sampled edits and implicit/explicit targets. Whole target surfaces match an independent clean-parameter command; colour pixels, other planes and spot metadata remain unchanged. Action tests now carry non-neutral RGB records and check neutral hidden controls for scalar targets and preserved records for pixel targets.
A further local review reproduced a recorded `gray` alias seeding bug: Levels could display Gamma 1 for recorded Gamma 2 and let the hidden alias override later edits, while default Curves points could conceal the recorded curve. Scalar dialogs now resolve valid aliases through the checked parser/serializer before merging defaults. Invalid aliases remain preview/commit errors and leave document data unchanged. Offscreen Lab alpha Action captures show the recorded Gamma 2 and inverted curve under `Saved sky` while Lightness is selected.
Validation of this follow-up: full engine/UI `cargo test` **6,224 passed, 0 failed, 36 normally ignored**; the ignored adversarial command test passed separately. Strict engine/UI all-target Clippy, formatting, layering and wasm passed. A third local review found no further actionable issues in scope. No proxy or pixel-processing algorithm changed; no fresh timing comparison is claimed for parameter filtering and dialog initialization.
## 24 MP release comparison