Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Curves: apply to masks, alpha, and Quick Mask (#5335) (#5448)

Vikram Bhaskaran0f8c1a410635
diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/adjust_cmds/tests.rs
index 9f614732d..80e97b9f3 100644
--- a/crates/engine/src/adjust_cmds/tests.rs
+++ b/crates/engine/src/adjust_cmds/tests.rs
@@ -527,6 +527,106 @@ fn a_targeted_mask_enables_editing_it_on_any_layer() {
assert_eq!(rgba(&s, 23, 3), pixels);
}
+/// #5335: Curves (⌘M) edits the targeted layer mask, saved channel or Quick Mask at every depth.
+#[test]
+fn curves_apply_to_non_colour_targets_at_every_depth() {
+ let area = photocraft_geom::Rect::from_xywh(0, 0, 48, 32);
+ for depth in DEPTHS {
+ for target in ["mask", "alpha", "quickMask"] {
+ let mut s = session(depth, "rgb");
+ s.execute("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap();
+ let p = match target {
+ "mask" => {
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ json!({"points": [[0, 0], [128, 200], [255, 255]], "target": "mask"})
+ }
+ "alpha" => {
+ s.execute("channel.new", json!({"name": "Sky sel", "fill": "white"})).unwrap();
+ json!({"points": [[0, 0], [128, 200], [255, 255]], "target": {"channel": 0}})
+ }
+ _ => {
+ s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap();
+ json!({"points": [[0, 0], [128, 200], [255, 255]], "target": "quickMask"})
+ }
+ };
+ let edit_target = p.get("target").cloned().unwrap_or(json!(null));
+ s.edit("levels", |doc, active| {
+ let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &json!({ "target": edit_target })).unwrap();
+ surf.fill_rect(area, &[0.5]);
+ Ok(())
+ })
+ .unwrap();
+ let read = |s: &Session| {
+ let d = s.active().unwrap();
+ let layer = d.doc.layer(d.active_layer.unwrap()).unwrap();
+ let t = match target {
+ "quickMask" => d.doc.quick_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0),
+ "alpha" => d.doc.channels[0].surface.sample_channel(8, 8, 0),
+ _ => layer.mask.as_ref().unwrap().surface.sample_channel(8, 8, 0),
+ };
+ (rgba(s, 8, 8), t)
+ };
+ let ((pixels, before), past) = (read(&s), s.active().unwrap().history.past_len());
+ s.execute("image.adjustments.curves", p).unwrap();
+ let (pixels_after, after) = read(&s);
+ let case = format!("{target} at {depth}");
+ assert_eq!(pixels_after, pixels, "{case}: colour pixels stay put");
+ assert!(after > before + 0.1, "{case}: the curve lifted the midtone ({before} → {after})");
+ assert_eq!(s.active().unwrap().history.past_len(), past + 1, "{case}");
+ s.undo();
+ assert!((read(&s).1 - before).abs() < 1e-5, "{case}: undo restores the target");
+ }
+ }
+}
+
+/// #5335: a layer mask, saved channel or Quick Mask holds gray levels whatever the document's
+/// colour mode: inverting 25% grey gives 75% grey in Lab and CMYK, not an untouched plane (Lab
+/// ignores the composite) or an ink-separated result (CMYK curves the inks).
+#[test]
+fn curves_on_grey_targets_ignore_the_document_colour_mode() {
+ let area = photocraft_geom::Rect::from_xywh(0, 0, 48, 32);
+ for mode in ["lab", "cmyk"] {
+ for depth in [8u64, 16] {
+ for target in ["mask", "alpha", "quickMask"] {
+ let mut s = session(depth, mode);
+ let p = match target {
+ "mask" => {
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ json!("mask")
+ }
+ "alpha" => {
+ s.execute("channel.new", json!({"name": "Sky sel", "fill": "white"})).unwrap();
+ json!({"channel": 0})
+ }
+ _ => {
+ s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap();
+ json!("quickMask")
+ }
+ };
+ s.edit("levels", |doc, active| {
+ let (surf, _) = crate::channel_cmds::target_surface(doc, *active, &json!({ "target": p })).unwrap();
+ surf.fill_rect(area, &[0.25]);
+ Ok(())
+ })
+ .unwrap();
+ let read = |s: &Session| match target {
+ "quickMask" => doc(s).quick_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0),
+ "alpha" => doc(s).channels[0].surface.sample_channel(8, 8, 0),
+ _ => mask_at(s, 8, 8),
+ };
+ let before = read(&s);
+ let pixels = rgba(&s, 8, 8);
+ s.execute("image.adjustments.curves", json!({"points": [[0, 255], [255, 0]], "target": p})).unwrap();
+ let after = read(&s);
+ let case = format!("{mode} {depth}-bit {target}");
+ assert!((before - 0.25).abs() < 0.01, "{case}: filled with 25% grey ({before})");
+ assert!((after - 0.75).abs() < 0.02, "{case}: inverting 25% grey gives 75% grey ({after})");
+ assert_eq!(rgba(&s, 8, 8), pixels, "{case}: colour pixels stay put");
+ }
+ }
+ }
+}
+
#[test]
fn replace_color_localized_clusters_only_change_the_colour_near_the_sample() {
// The same cream on the left (x < 8) and the right (x ≥ 40), grey between.
diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs
index 00f3ec4e3..6dac6f2a6 100644
--- a/crates/engine/src/channel_cmds.rs
+++ b/crates/engine/src/channel_cmds.rs
@@ -182,6 +182,87 @@ pub fn composite_name(mode: ColorMode) -> &'static str {
}
}
+/// The Curves dialog's Channel popup lists only this channel when the Channels panel has a
+/// single non-composite target (a colour component, layer mask, saved channel or Quick Mask).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct IsolatedCurveChannel {
+ /// Channels-panel name, including a custom alpha name or "{layer} Mask".
+ pub name: String,
+ /// Curves param key: empty = composite `points`; otherwise `red`/`green`/…
+ pub key: &'static str,
+ /// Index into the tone-space histograms (composite = 0 for RGB/CMYK).
+ pub hist: usize,
+ /// Colour components keep their curve tint; masks and alphas do not.
+ pub tint: bool,
+ /// Built-in labels (colour channels, Quick Mask) follow the interface language; a custom
+ /// alpha name or a "{layer} Mask" keeps the layer name, so it stays exactly as entered (#5335).
+ pub translate: bool,
+ /// The gray plane this target edits, whatever the document's colour mode; its surface is
+ /// what the dialog's histogram must describe (#5335). None for colour components.
+ pub gray: Option<GraySurface>,
+}
+
+/// A grayscale plane Curves can target: the dialog parses and previews its curves in gray levels
+/// even in Lab and CMYK documents (#5335).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum GraySurface {
+ /// The active layer's layer mask.
+ LayerMask,
+ /// A saved channel, as an index into [`Document::channels`].
+ Alpha(usize),
+ /// The Quick Mask.
+ QuickMask,
+}
+
+/// Isolated Curves channel for the active document, matching [`inject_target`].
+pub fn isolated_curve_channel(st: &DocState) -> Option<IsolatedCurveChannel> {
+ isolated_curve_channel_for(st, false)
+}
+
+/// [`isolated_curve_channel`] with the Layers panel's mask target added: clicking a mask
+/// thumbnail targets it without touching the Channels panel, and both ways of selecting the mask
+/// must give the same Curves dropdown (#5335).
+pub fn isolated_curve_channel_for(st: &DocState, layers_panel_mask: bool) -> Option<IsolatedCurveChannel> {
+ let doc = &st.doc;
+ let mode = edit_mode(doc);
+ match st.channel_view.target {
+ ChannelTarget::Color(k) => {
+ let names = color_names(mode);
+ let keys = crate::adjust_params::channel_keys(crate::adjust_params::default_space(mode));
+ let name = names.get(k)?.to_string();
+ let key = *keys.get(k)?;
+ let hist = if matches!(mode, ColorMode::Lab) { k } else { k.saturating_add(1) };
+ Some(IsolatedCurveChannel { name, key, hist, tint: true, translate: true, gray: None })
+ }
+ ChannelTarget::Alpha(i) => doc.channels.get(i).map(|c| IsolatedCurveChannel {
+ name: c.name.clone(),
+ key: "",
+ hist: 0,
+ tint: false,
+ translate: false,
+ gray: Some(GraySurface::Alpha(i)),
+ }),
+ ChannelTarget::Composite if doc.quick_mask.is_some() => Some(IsolatedCurveChannel {
+ name: "Quick Mask".into(),
+ key: "",
+ hist: 0,
+ tint: false,
+ translate: true,
+ gray: Some(GraySurface::QuickMask),
+ }),
+ ChannelTarget::LayerMask => layer_mask_curve_channel(st),
+ ChannelTarget::Composite if crate::mask_view_cmds::current(st).is_some() || layers_panel_mask => layer_mask_curve_channel(st),
+ _ => None,
+ }
+}
+
+fn layer_mask_curve_channel(st: &DocState) -> Option<IsolatedCurveChannel> {
+ let layer = st.active_layer.and_then(|id| st.doc.layer(id))?;
+ layer.mask.as_ref()?;
+ let name = format!("{} Mask", layer.name);
+ Some(IsolatedCurveChannel { name, key: "", hist: 0, tint: false, translate: false, gray: Some(GraySurface::LayerMask) })
+}
+
fn edit_mode(doc: &Document) -> ColorMode {
doc.pixel_format().mode
}
diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs
index 1d721ee5c..d63dc5fd0 100644
--- a/crates/engine/src/channel_cmds/tests.rs
+++ b/crates/engine/src/channel_cmds/tests.rs
@@ -867,3 +867,51 @@ fn thumbnail_selection_shape_without_pixel_cache_uses_its_transparency() {
assert_eq!((b.x0, b.y0, b.width(), b.height()), (20, 10, 40, 30));
}
}
+
+/// #5335: a single targeted channel is the only Curves popup entry, named as in the Channels panel.
+#[test]
+fn isolated_curve_channel_matches_the_channels_panel() {
+ let mut s = session();
+ assert!(isolated_curve_channel(s.active().unwrap()).is_none(), "composite lists every colour channel");
+ s.execute("channel.target", json!({"channel": {"color": 1}})).unwrap();
+ let green = isolated_curve_channel(s.active().unwrap()).expect("green");
+ assert_eq!((green.name.as_str(), green.key, green.tint), ("Green", "green", true));
+ assert!(green.translate && green.gray.is_none(), "built-in colour labels follow the language");
+
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ s.execute("channel.target", json!({"channel": "mask"})).unwrap();
+ let mask = isolated_curve_channel(s.active().unwrap()).expect("mask");
+ assert_eq!(mask.key, "");
+ assert!(!mask.tint);
+ assert_eq!(mask.name, format!("{} Mask", doc(&s).layer(s.active().unwrap().active_layer.unwrap()).unwrap().name));
+
+ s.execute("channel.new", json!({"name": "Green", "fill": "white"})).unwrap();
+ s.execute("channel.target", json!({"channel": 0})).unwrap();
+ let alpha = isolated_curve_channel(s.active().unwrap()).expect("alpha");
+ assert_eq!((alpha.name.as_str(), alpha.key, alpha.tint), ("Green", "", false));
+ assert!(!alpha.translate, "a custom channel name stays exactly as entered");
+ assert_eq!(alpha.gray, Some(GraySurface::Alpha(0)));
+
+ let mut qm = session();
+ qm.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap();
+ let row = isolated_curve_channel(qm.active().unwrap()).expect("quick mask");
+ assert_eq!((row.name.as_str(), row.tint), ("Quick Mask", false));
+ assert_eq!(row.gray, Some(GraySurface::QuickMask));
+}
+
+/// #5335: selecting the mask in the Layers panel gives the same isolated Curves channel as
+/// selecting it in the Channels panel; the Quick Mask keeps priority.
+#[test]
+fn layers_panel_mask_target_isolates_the_curve_channel() {
+ let mut s = session();
+ assert!(isolated_curve_channel_for(s.active().unwrap(), true).is_none(), "a layer without a mask is not targeted");
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ s.execute("channel.target", json!({"channel": "mask"})).unwrap();
+ let by_panel = isolated_curve_channel(s.active().unwrap()).expect("mask targeted from the Channels panel");
+ s.execute("channel.target", json!({"channel": "composite"})).unwrap();
+ let by_layers = isolated_curve_channel_for(s.active().unwrap(), true).expect("mask targeted from the Layers panel");
+ assert_eq!(by_panel, by_layers, "both ways of selecting the mask give the same dropdown");
+ s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap();
+ let row = isolated_curve_channel_for(s.active().unwrap(), true).expect("quick mask wins");
+ assert_eq!((row.name.as_str(), row.gray), ("Quick Mask", Some(GraySurface::QuickMask)));
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 68d00a7da..7ddad8073 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -4,7 +4,7 @@ use photocraft_color::{BlendMode, Color, ColorMode, SampleType};
use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent, LayerId, LayerMask, Size};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
-use serde_json::{Value, json};
+use serde_json::{Map, Value, json};
use crate::{EngineError, Result, Session, inspect, pixels};
@@ -414,6 +414,31 @@ fn doc_mode(s: &Session) -> ColorMode {
s.active().map_or(ColorMode::Rgb, |d| d.doc.mode)
}
+/// The colour mode a destructive adjustment parses its tone space in: a targeted layer mask,
+/// saved channel or Quick Mask holds gray levels whatever the document's mode, so Curves and
+/// Levels stay in the neutral space instead of Lab (where the composite is ignored) or CMYK
+/// (where the curve runs on the inks) (#5335).
+fn adjust_mode(s: &Session, p: &Value) -> ColorMode {
+ if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) { ColorMode::Grayscale } else { doc_mode(s) }
+}
+
+/// 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).
+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") {
+ o.insert(k.clone(), v.clone());
+ }
+ }
+ Value::Object(o)
+ }
+ other => other.clone(),
+ }
+}
+
// ---------- the table ----------
#[allow(clippy::too_many_lines)]
@@ -1269,7 +1294,16 @@ fn build() -> Vec<CommandSpec> {
});
let adj = match eyedropped {
Some(adj) => adj,
- None => crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?,
+ None => {
+ // A gray plane target keeps the neutral tone space even over params
+ // carrying 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") { gray_tone_params(p) } else { p.clone() }
+ } else {
+ p.clone()
+ };
+ crate::adjust_params::from_params(&kind, &tone, None, adjust_mode(s, p))?
+ }
};
let label = adj.label().to_string();
// A smart object records the adjustment as a smart filter (Photoshop), which
diff --git a/crates/ui-egui/src/adjust_dialog.rs b/crates/ui-egui/src/adjust_dialog.rs
index eb8f89a68..cabf9fbde 100644
--- a/crates/ui-egui/src/adjust_dialog.rs
+++ b/crates/ui-egui/src/adjust_dialog.rs
@@ -146,7 +146,7 @@ pub fn reset(app: &PhotocraftApp, ctx: &egui::Context, fields: &mut Map<String,
return;
}
let kind = fields.get("__adjust").and_then(Value::as_str).unwrap_or_default().to_string();
- let mode = app.session.active().map_or(photocraft_doc::ColorMode::Rgb, |s| s.doc.mode);
+ let mode = curve_mode(app, &kind);
// Color Balance: Photoshop keeps the user's Preserve Luminosity across Reset.
let preserve = if kind == "colorBalance" { fields.get("preserveLuminosity").cloned() } else { None };
let Ok(defaults) = photocraft_engine::adjust_params::default_for(&kind, mode) else { return };
@@ -170,7 +170,7 @@ pub fn reset(app: &PhotocraftApp, ctx: &egui::Context, fields: &mut Map<String,
pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
let kind = command.strip_prefix(PREFIX).filter(|k| adjust_editors::has_editor(k))?;
let spec = photocraft_engine::commands::find(command)?;
- let mode = app.session.active().map_or(photocraft_doc::ColorMode::Rgb, |s| s.doc.mode);
+ let mode = curve_mode(app, kind);
let defaults = photocraft_engine::adjust_params::default_for(kind, mode).ok()?;
let mut fields = Map::new();
fields.insert("__command".into(), json!(command));
@@ -184,19 +184,49 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
Some(app.ui.open_dialog(crate::state::DialogKind::Command, fields))
}
+/// The Curves dialog's single-channel target: the Channels panel's, plus the Layers panel's mask
+/// selection — both ways of selecting a mask must give the same dropdown (#5335).
+fn isolated(app: &PhotocraftApp) -> Option<photocraft_engine::channel_cmds::IsolatedCurveChannel> {
+ let mask = app.layer_mask_targeted();
+ app.session.active().and_then(|st| photocraft_engine::channel_cmds::isolated_curve_channel_for(st, mask))
+}
+
+/// The colour mode the Levels/Curves dialog seeds and parses in: a mask, saved channel or
+/// Quick Mask holds gray levels whatever the document's mode, so its curve is a neutral one
+/// and the fields carry no Lab or CMYK records (#5335).
+fn curve_mode(app: &PhotocraftApp, kind: &str) -> photocraft_doc::ColorMode {
+ let mode = app.session.active().map_or(photocraft_doc::ColorMode::Rgb, |s| s.doc.mode);
+ if kind == "curves" && isolated(app).is_some_and(|c| c.gray.is_some()) {
+ photocraft_doc::ColorMode::Grayscale
+ } else {
+ mode
+ }
+}
+
/// Dialog body: the kind's editor over the fields, then the Preview checkbox.
pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String, Value>) {
let kind = fields.get("__adjust").and_then(Value::as_str).unwrap_or_default().to_string();
- let mode = app.session.active().map_or(photocraft_doc::ColorMode::Rgb, |s| s.doc.mode);
+ let mode = curve_mode(app, &kind);
if matches!(kind.as_str(), "levels" | "curves") {
picker_controls(ui, fields, mode);
ui.add_space(4.0);
}
let mut values = crate::filter_dialog::params_of(fields);
let active = app.session.active().and_then(|s| s.active_layer);
- let gray = app.session.active().is_some_and(|s| adjust_editors::is_gray(s.doc.mode));
+ let isolated_curve = isolated(app);
+ // Only Curves gets an isolated single-channel target here; Levels keeps its usual fields.
+ let gray_plane = (kind == "curves").then(|| isolated_curve.as_ref().and_then(|c| c.gray)).flatten();
+ let gray = gray_plane.is_some() || app.session.active().is_some_and(|s| adjust_editors::is_gray(s.doc.mode));
let hist = match active {
- Some(id) if adjust_editors::needs_histogram(&kind) => Some(tone::histograms(app, HistSource::Layer(id), adjust_editors::space_of(&values))),
+ Some(id) if adjust_editors::needs_histogram(&kind) => {
+ // A mask or saved channel's curve edits that plane's own levels: the histogram
+ // describes it, not the colour layers beneath (#5335).
+ let source = match gray_plane {
+ Some(surface) => HistSource::Channel { layer: id, surface },
+ None => HistSource::Layer(id),
+ };
+ Some(tone::histograms(app, source, adjust_editors::space_of(&values)))
+ }
_ => None,
};
let cx = EditorCx {
@@ -207,6 +237,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String,
gradients: adjust_editors::gradient_presets(app, &kind),
dialog: true,
dynamic_color_sliders: app.session.prefs().interface.dynamic_color_sliders,
+ isolated_curve,
};
let e = adjust_editors::editor(ui, &kind, &mut values, &cx);
if e.import_gradients {
@@ -762,4 +793,89 @@ mod tests {
assert_eq!(channel_points(&app, "red"), red, "pointer up does not sample again");
assert!(picker_armed(&app));
}
+
+ /// #5335: a targeted mask, saved channel or colour component is the only Channel popup entry.
+ #[test]
+ fn curves_channel_popup_lists_only_the_targeted_channel() {
+ let mut app = app_with_image();
+ app.run("layer.layerMask.revealAll", json!({})).unwrap();
+ app.run("channel.target", json!({"channel": "mask"})).unwrap();
+ let mut h = curves_harness(app);
+ let names = popup_channels(&mut h);
+ assert!(names.iter().any(|n| n.contains("Mask")), "{names:?}");
+ assert!(!names.iter().any(|n| n == "RGB" || n == "Red" || n == "Green" || n == "Blue"), "{names:?}");
+ }
+
+ /// #5335: selecting the mask in the Layers panel gives the same Curves dropdown as selecting
+ /// it in the Channels panel.
+ #[test]
+ fn curves_channel_popup_lists_only_the_mask_selected_in_the_layers_panel() {
+ let mut app = app_with_image();
+ app.run("layer.layerMask.revealAll", json!({})).unwrap();
+ app.ui.mask_target = true; // clicking the mask thumbnail in the Layers panel
+ assert!(app.layer_mask_targeted(), "the Layers panel mask thumbnail is targeted");
+ let mut h = curves_harness(app);
+ let names = popup_channels(&mut h);
+ assert_eq!(names.len(), 1, "only the mask: {names:?}");
+ assert!(names[0].contains("Mask"), "{names:?}");
+ }
+
+ /// #5335: in a Lab document, Curves over a gray target keeps neutral fields: no Lab records
+ /// to overwrite the mask's own curve or pick the wrong tone space.
+ #[test]
+ fn curves_on_a_gray_target_seeds_neutral_fields_in_a_lab_document() {
+ for via_layers_panel in [false, true] {
+ let mut app = app_in_mode("lab");
+ app.run("layer.layerMask.revealAll", json!({})).unwrap();
+ if via_layers_panel {
+ app.ui.mask_target = true;
+ } else {
+ app.run("channel.target", json!({"channel": "mask"})).unwrap();
+ }
+ let id = open(&mut app, "image.adjustments.curves").expect("opens");
+ let values = crate::filter_dialog::params_of(&app.ui.dialog_mut(id).unwrap().fields.clone());
+ assert!(values.get("points").is_some(), "{values:?}");
+ for key in ["lightness", "a", "b", "cyan", "magenta", "yellow", "black"] {
+ assert!(values.get(key).is_none(), "{key} in a gray target's curves: {values:?}");
+ }
+ }
+ }
+
+ /// #5335: in Italian the built-in labels translate, but a channel the user named "Green"
+ /// stays exactly "Green".
+ #[test]
+ fn curves_channel_popup_keeps_custom_names_verbatim_in_italian() {
+ let it = crate::i18n::Lang::from_code("it").expect("it registered");
+ assert_eq!(crate::i18n::tr(it, "Green"), "Verde", "the test relies on the built-in label");
+ let _lang = crate::i18n::language_scope(it);
+ let mut app = app_with_image();
+ app.run("channel.new", json!({"name": "Green", "fill": "white"})).unwrap();
+ app.run("channel.target", json!({"channel": 0})).unwrap();
+ let mut h = curves_harness(app);
+ let names = popup_channels(&mut h);
+ assert!(names.iter().any(|n| n == "Green"), "custom names stay as entered: {names:?}");
+ assert!(!names.iter().any(|n| n == "Verde"), "not translated: {names:?}");
+ // A targeted colour component keeps its translated built-in label.
+ let mut colour = app_with_image();
+ colour.run("channel.target", json!({"channel": {"color": 1}})).unwrap();
+ let mut h = curves_harness(colour);
+ let names = popup_channels(&mut h);
+ assert!(names.iter().any(|n| n == "Verde"), "built-in labels follow the language: {names:?}");
+ }
+
+ /// Curves open in a harness over `app`.
+ fn curves_harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> {
+ let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app);
+ PhotocraftApp::setup_context(&h.ctx, Default::default());
+ open(h.state_mut(), "image.adjustments.curves").unwrap();
+ h.run_steps(4);
+ h
+ }
+
+ /// The Channel popup's selected value (its option labels are what it shows).
+ fn popup_channels(h: &mut Harness<'static, PhotocraftApp>) -> Vec<String> {
+ h.query_all_by_role(egui::accesskit::Role::ComboBox)
+ .filter_map(|n| n.value().map(|s| s.to_string()))
+ .collect()
+ }
}
diff --git a/crates/ui-egui/src/adjust_editors.rs b/crates/ui-egui/src/adjust_editors.rs
index 2678cc65f..87a81b8c3 100644
--- a/crates/ui-egui/src/adjust_editors.rs
+++ b/crates/ui-egui/src/adjust_editors.rs
@@ -92,6 +92,8 @@ pub struct EditorCx {
/// Preferences ▸ Interface ▸ Dynamic Color Sliders: colour tracks on the colour sliders
/// (off: the plain track).
pub dynamic_color_sliders: bool,
+ /// Image › Curves with a single Channels-panel target: that channel only (#5335).
+ pub isolated_curve: Option<photocraft_engine::channel_cmds::IsolatedCurveChannel>,
}
/// The Levels/Curves channel space the values address.
@@ -291,14 +293,26 @@ pub fn tone_channels(space: ToneSpace, gray: bool) -> &'static [ToneChannel] {
}
fn channel_picker(ui: &mut egui::Ui, id: egui::Id, chans: &[ToneChannel], text: &str) -> usize {
+ let opts: Vec<(usize, &str)> = chans.iter().enumerate().map(|(i, c)| (i, c.label)).collect();
+ channel_picker_opts(ui, id, &opts, text, true)
+}
+
+/// The popup, with `translate` for whether the built-in labels follow the interface language;
+/// a user-typed channel name is shown exactly as entered (#5335).
+fn channel_picker_opts(ui: &mut egui::Ui, id: egui::Id, opts: &[(usize, &str)], text: &str, translate: bool) -> usize {
let mut ch: usize = ui.data(|d| d.get_temp(id)).unwrap_or(0);
- if ch >= chans.len() {
+ if ch >= opts.len() {
ch = 0;
}
ui.horizontal(|ui| {
label(ui, text);
- let opts: Vec<(usize, &str)> = chans.iter().enumerate().map(|(i, c)| (i, c.label)).collect();
- widgets::dropdown(ui, &format!("{id:?}-ch"), &mut ch, &opts, 110.0);
+ let width = if opts.len() == 1 { 160.0 } else { 110.0 };
+ let key = format!("{id:?}-ch");
+ if translate {
+ widgets::dropdown(ui, &key, &mut ch, opts, width);
+ } else {
+ widgets::dropdown_literal(ui, &key, &mut ch, opts, width);
+ }
});
ui.data_mut(|d| d.insert_temp(id, ch));
ch
@@ -428,11 +442,20 @@ fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
let chans = tone_channels(space, cx.gray);
let state_id = cx.mem.with("curves");
let mut st: CurveUi = ui.data(|d| d.get_temp(state_id)).unwrap_or_default();
- let ch = channel_picker(ui, cx.mem.with("curves-ch"), chans, tl!("Channel:"));
+ let isolated = cx.isolated_curve.as_ref();
+ let ch = if let Some(iso) = isolated {
+ channel_picker_opts(ui, cx.mem.with("curves-ch"), &[(0, iso.name.as_str())], tl!("Channel:"), iso.translate)
+ } else {
+ channel_picker(ui, cx.mem.with("curves-ch"), chans, tl!("Channel:"))
+ };
if ch != st.channel {
st = CurveUi { channel: ch, ..Default::default() };
}
- let chan = chans.get(ch).copied().unwrap_or(ToneChannel { key: "", label: "" });
+ let chan =
+ if let Some(iso) = isolated { ToneChannel { key: iso.key, label: "" } } else { chans.get(ch).copied().unwrap_or(ToneChannel { key: "", label: "" }) };
+ let overlay_others = isolated.is_none();
+ let tinted = isolated.is_some_and(|c| c.tint) || (isolated.is_none() && ch != 0);
+ let hist_i = isolated.map_or(ch, |c| c.hist);
let key = curve_key(&chan);
let mut e = curves_mode_row(ui, v, key, cx.gray);
let pencil = v.get("pencil").and_then(Value::as_bool).unwrap_or(false);
@@ -477,7 +500,7 @@ fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
let p = ui.painter_at(full.expand(2.0));
p.rect_filled(graph, 0.0, t.field);
if let Some(h) = &cx.hist {
- tone::draw_histogram(&p, graph, &h[ch], Color32::from_gray(if t.pro { 88 } else { 190 }).gamma_multiply(0.75));
+ tone::draw_histogram(&p, graph, &h[hist_i], Color32::from_gray(if t.pro { 88 } else { 190 }).gamma_multiply(0.75));
}
for i in 1..4 {
let f = i as f32 / 4.0;
@@ -510,7 +533,7 @@ fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
let line: Vec<Pos2> = map.iter().enumerate().map(|(k, o)| to_scr([k as f32 / last * 255.0, *o])).collect();
p.add(egui::Shape::line(line, Stroke::new(width, color)));
};
- if ch == 0 {
+ if overlay_others && ch == 0 {
// Photoshop overlays the edited channel curves on the composite.
for c in chans.iter().skip(1) {
if pencil {
@@ -526,7 +549,7 @@ fn curves(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
}
}
}
- let color = if ch == 0 { t.text } else { bar_color(&chan, &t) };
+ let color = if tinted { bar_color(&chan, &t) } else { t.text };
if pencil {
draw_map(&map, color, 1.5);
} else {
@@ -1623,6 +1646,7 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj
gradients: gradient_presets(app, kind),
dialog: false,
dynamic_color_sliders: app.session.prefs().interface.dynamic_color_sliders,
+ isolated_curve: None,
};
if matches!(kind, "levels" | "curves") {
crate::layer_picker::controls(app, ui, id);
@@ -1676,6 +1700,7 @@ mod tests {
gradients: Vec::new(),
dialog: false,
dynamic_color_sliders: dynamic,
+ isolated_curve: None,
};
let stops = [Color32::BLACK, Color32::RED];
assert_eq!(track_stops(&cx(true), &stops), Some(&stops[..]));
diff --git a/crates/ui-egui/src/adjust_editors_tests.rs b/crates/ui-egui/src/adjust_editors_tests.rs
index 9c39088be..d8c6e7953 100644
--- a/crates/ui-egui/src/adjust_editors_tests.rs
+++ b/crates/ui-egui/src/adjust_editors_tests.rs
@@ -566,6 +566,7 @@ fn gradient_map_stop_controls_fit_a_narrow_properties_panel_in_every_theme() {
gradients: Vec::new(),
dialog: false,
dynamic_color_sliders: true,
+ isolated_curve: None,
};
editor(ui, "gradientMap", values, &cx);
},
@@ -774,6 +775,7 @@ fn editor_harness(kind: &'static str, params: serde_json::Value) -> Harness<'sta
gradients: Vec::new(),
dialog: true,
dynamic_color_sliders: true,
+ isolated_curve: None,
};
editor(ui, kind, values, &cx);
},
diff --git a/crates/ui-egui/src/tone.rs b/crates/ui-egui/src/tone.rs
index 0eacc731a..5cd04d4f0 100644
--- a/crates/ui-egui/src/tone.rs
+++ b/crates/ui-egui/src/tone.rs
@@ -40,12 +40,20 @@ pub enum HistSource {
BelowLayer(LayerId),
/// One layer on its own (the target of a destructive Image › Adjustments command).
Layer(LayerId),
+ /// The gray plane a Curves target edits: a layer mask, a saved channel or the Quick Mask.
+ /// The dialog shows this plane's own levels, not the colour layers beneath (#5335).
+ Channel { layer: LayerId, surface: photocraft_engine::channel_cmds::GraySurface },
}
fn tag(source: HistSource, space: ToneSpace) -> u64 {
let (k, id) = match source {
HistSource::BelowLayer(l) => (1u64, l.0),
HistSource::Layer(l) => (2, l.0),
+ HistSource::Channel { layer, surface } => match surface {
+ photocraft_engine::channel_cmds::GraySurface::LayerMask => (3, layer.0),
+ photocraft_engine::channel_cmds::GraySurface::Alpha(i) => (4, i as u64),
+ photocraft_engine::channel_cmds::GraySurface::QuickMask => (5, layer.0),
+ },
};
let s = match space {
ToneSpace::Rgb => 0u64,
@@ -68,6 +76,35 @@ fn isolate(layers: &mut [Layer], id: LayerId) -> bool {
/// Histograms of `doc` as seen by `source`, in the channels of `space`.
pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace) -> Histograms {
+ let mut h = vec![[0u32; 256]; match space {
+ ToneSpace::Rgb => 4,
+ ToneSpace::Cmyk => 5,
+ ToneSpace::Lab => 3,
+ }];
+ match source {
+ // The gray plane itself: its levels are what the curve edits, whatever the document's
+ // colour mode (#5335).
+ HistSource::Channel { layer, surface } => {
+ let surf = match surface {
+ photocraft_engine::channel_cmds::GraySurface::LayerMask => doc.layer(layer).and_then(|l| l.mask.as_ref()).map(|m| &m.surface),
+ photocraft_engine::channel_cmds::GraySurface::Alpha(i) => doc.channels.get(i).map(|c| &c.surface),
+ photocraft_engine::channel_cmds::GraySurface::QuickMask => doc.quick_mask.as_ref().map(|c| &c.surface),
+ };
+ if let Some(s) = surf
+ && let Some(bin) = h.first_mut()
+ {
+ *bin = gray_bins(s, doc.bounds());
+ }
+ }
+ HistSource::BelowLayer(_) | HistSource::Layer(_) => {
+ composite_bins(doc, source, space, &mut h);
+ }
+ }
+ Histograms { tag: tag(source, space), ch: h }
+}
+
+/// Bins of the composited image below (`BelowLayer`) or of one layer alone (`Layer`), in `space`.
+fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, h: &mut [[u32; 256]]) {
let mut d = doc.clone();
match source {
HistSource::BelowLayer(hide) => {
@@ -78,14 +115,9 @@ pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace)
HistSource::Layer(id) => {
isolate(&mut d.layers, id);
}
+ HistSource::Channel { .. } => {}
}
let img = photocraft_compose::thumbnail(&d, 384);
- let n = match space {
- ToneSpace::Rgb => 4,
- ToneSpace::Cmyk => 5,
- ToneSpace::Lab => 3,
- };
- let mut h = vec![[0u32; 256]; n];
let bin = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as usize;
for p in img.pixels.as_chunks::<4>().0 {
if p[3] == 0 {
@@ -115,7 +147,26 @@ pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace)
}
}
}
- Histograms { tag: tag(source, space), ch: h }
+}
+
+/// 256-bin histogram of a gray plane: its levels in 0–255, sampled like the engine's auto-tone
+/// histograms so a big canvas costs no more than about a megapixel here (#5335).
+fn gray_bins(surf: &photocraft_raster::Surface, area: photocraft_geom::Rect) -> [u32; 256] {
+ let mut h = [0u32; 256];
+ let step = ((u64::from(area.width()) * u64::from(area.height())) / 1_000_000).max(1).isqrt().max(1) as i32;
+ let mut y = area.y0;
+ while y < area.y1 {
+ let mut x = area.x0;
+ while x < area.x1 {
+ let v = (surf.sample_channel(x, y, 0).clamp(0.0, 1.0) * 255.0).round() as usize;
+ if let Some(bin) = h.get_mut(v) {
+ *bin += 1;
+ }
+ x += step;
+ }
+ y += step;
+ }
+ h
}
/// Cached histograms for a tone editor; recomputed only when something other than the editor's
@@ -126,6 +177,7 @@ pub fn histograms(app: &mut PhotocraftApp, source: HistSource, space: ToneSpace)
let want = tag(source, space);
let layer = match source {
HistSource::BelowLayer(l) | HistSource::Layer(l) => l,
+ HistSource::Channel { layer, .. } => layer,
};
let pixels_kept = view_only(st);
if let Some((d, l, r, h)) = app.tone_hist.as_mut()
@@ -362,6 +414,39 @@ mod tests {
assert_eq!(compute_histograms(&st.doc, HistSource::Layer(bg), ToneSpace::Cmyk).ch.len(), 5);
assert_eq!(compute_histograms(&st.doc, HistSource::Layer(bg), ToneSpace::Lab).ch.len(), 3);
}
+
+ /// #5335: the Curves histogram of a targeted gray plane describes that plane, not the
+ /// colour layers beneath it: a channel filled with 25% grey over a black layer shows a
+ /// spike at 25% grey, not at black.
+ #[test]
+ fn channel_histogram_describes_the_gray_plane() {
+ use photocraft_engine::channel_cmds::GraySurface;
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); // white background
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 32})).unwrap();
+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();
+ s.execute("channel.new", json!({"name": "Sky sel", "fill": "white"})).unwrap();
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ let b = photocraft_geom::Rect::from_xywh(0, 0, 32, 32);
+ s.edit("fill-planes", |doc, active| {
+ doc.channels[0].surface.fill_rect(b, &[0.25]);
+ doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap().surface.fill_rect(b, &[0.0]);
+ Ok(())
+ })
+ .unwrap();
+ let st = s.active().unwrap();
+ let layer = st.active_layer.unwrap();
+ let h = compute_histograms(&st.doc, HistSource::Channel { layer, surface: GraySurface::Alpha(0) }, ToneSpace::Rgb);
+ assert!(h[0][64] > 0, "a spike at 25% grey, got {:?}", &h[0][0..80]);
+ assert_eq!(h[0][0], 0, "not the black layer beneath");
+ let m = compute_histograms(&st.doc, HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb);
+ assert!(m[0][0] > 0, "the hidden mask is black");
+ // Each plane keeps its own cache entry: switching targets recomputes.
+ assert_ne!(tag(HistSource::Channel { layer, surface: GraySurface::Alpha(0) }, ToneSpace::Rgb),
+ tag(HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb));
+ assert_ne!(tag(HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb), tag(HistSource::Layer(layer), ToneSpace::Rgb));
+ }
}
#[cfg(test)]
diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs
index 49bcf0978..39c063baa 100644
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@ -1296,9 +1296,16 @@ pub fn dropdown<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, op
dropdown_hovered(ui, id, current, options, width).0
}
+/// [`dropdown`] whose option labels are shown exactly as given: names the user typed (a channel
+/// or layer name) must not be translated, unlike the built-in labels [`dropdown`] translates (#5335).
+pub fn dropdown_literal<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool {
+ let (chosen, _) = dropdown_with(ui, id, current, options, width, false, false);
+ !chosen.is_empty()
+}
+
/// [`dropdown`], also returning the option under the pointer in its open list (live previews).
pub fn dropdown_hovered<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option<T>) {
- let (chosen, hovered) = dropdown_with(ui, id, current, options, width, false);
+ let (chosen, hovered) = dropdown_with(ui, id, current, options, width, false, true);
(!chosen.is_empty(), hovered)
}
@@ -1309,11 +1316,13 @@ pub fn dropdown_hovered<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &m
/// in order (one per notch; the last is `current`) and the option under the pointer in the open
/// list, none while the pointer rests where the wheel last stepped.
pub fn dropdown_wheel_hovered<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (Vec<T>, Option<T>) {
- dropdown_with(ui, id, current, options, width, true)
+ dropdown_with(ui, id, current, options, width, true, true)
}
-fn dropdown_with<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32, wheel: bool) -> (Vec<T>, Option<T>) {
- let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| tl!(l)).unwrap_or("—");
+#[allow(clippy::too_many_arguments)]
+fn dropdown_with<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, options: &[(T, &str)], width: f32, wheel: bool, translate: bool) -> (Vec<T>, Option<T>) {
+ let shown = |l: &str| if translate { tl!(l).to_string() } else { l.to_string() };
+ let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| shown(l)).unwrap_or_else(|| "—".into());
let (mut chosen, mut hovered) = (Vec::new(), None);
// The wheel's notches add up over the button and the open list alike.
let wheel_id = ui.make_persistent_id(id).with("wheel");
@@ -1325,11 +1334,12 @@ fn dropdown_with<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, o
let mut reveal = wheel && ui.data_mut(|d| d.remove_temp::<bool>(reveal_id)).unwrap_or(false);
// The list opens on the press: press, drag onto an option and release to choose it (#2735).
let (press, close) = crate::press_menu::PressCombo::before(ui, id);
+ let texts: Vec<String> = options.iter().map(|(_, l)| shown(l)).collect();
let response =
egui::ComboBox::from_id_salt(id).selected_text(label).width(width).height(420.0).icon(chevron_icon).close_behavior(close).show_ui(ui, |ui| {
- fit_widest_option(ui, options.iter().map(|(_, l)| tl!(l)));
+ fit_widest_option(ui, texts.iter().map(|l| l.as_str()));
// A typed letter jumps to the next option starting with it, ↩ closes the list (#1481).
- let labels: Vec<&str> = options.iter().map(|(_, l)| tl!(l)).collect();
+ let labels: Vec<&str> = texts.iter().map(|l| l.as_str()).collect();
let shown = options.iter().position(|(v, _)| v == current);
if let Some((v, _)) = type_ahead::keys(ui, ui.make_persistent_id(id), shown, &labels).and_then(|i| options.get(i)) {
*current = v.clone();
@@ -1348,8 +1358,8 @@ fn dropdown_with<T: PartialEq + Clone>(ui: &mut Ui, id: &str, current: &mut T, o
// The row nearest the pointer, by its distance to each row.
let pointer = ui.ctx().pointer_hover_pos().filter(|_| ui.rect_contains_pointer(ui.clip_rect()));
let mut nearest: Option<(f32, &T)> = None;
- for (v, l) in options {
- let item = ui.selectable_label(v == current, tl!(l));
+ for ((v, _), text) in options.iter().zip(texts.iter()) {
+ let item = ui.selectable_label(v == current, text.as_str());
if reveal && v == current {
item.scroll_to_me(None);
}