Apply Image: keep mask alphas and layers named like built-ins apart

The mask group (#14489) listed an alpha channel by its name and a layer by its name, so an alpha named "Red" shared the
id of the red colour channel and resolved to it, and a pixel layer named "merged" was hidden behind the Merged entry.
Such an alpha now has the id alpha#<index> and is sent as {"alpha": index}; such a layer keeps its own option, with the
id layer#<name>, and is sent as {"name": ...}. Names the engine reads as themselves keep their plain ids.
This commit is contained in:
qvest-ssels committed 2026-11-25 09:10:55 +01:00
1 parent ce3e497188
commit 807de92bbb
2 files changed
+136 -16

No files matched your search

@@ -218,3 +218,72 @@ fn a_mask_from_another_document() {
assert_eq!(rgb(&app, 50, 50), [55, 155, 205]);
assert_eq!(rgb(&app, 300, 50), [50, 150, 250]);
}
/// "clash" (RGB 8 bit, 400 x 300, Background 200/100/50): an alpha channel named "Red" white on the left half, and a
/// pixel layer named "merged" white on the right half above the Background, which is targeted.
fn names_like_the_built_in_choices() -> (Box<PhotocraftApp>, egui::Context, usize) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
run(&mut app, "file.new", json!({"width": 400, "height": 300, "background": "#c86432", "name": "clash"}));
run(&mut app, "select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300}));
run(&mut app, "select.saveSelection", json!({"name": "Red"}));
run(&mut app, "select.deselect", json!({}));
run(&mut app, "layer.new.layer", json!({"name": "merged"}));
fill(&mut app, [200, 0, 200, 300], "#ffffff");
run(&mut app, "layer.select", json!({"name": "Background"}));
app.sync_views();
let ctx = app.ctx().clone();
let clash = index_of(&app, "clash");
(app, ctx, clash)
}
/// The option id of row `key` at `position` of its list, after checking the list's labels and that no two options
/// share an id.
fn option_at(app: &mut PhotocraftApp, key: &str, labels: &[&str], position: usize) -> String {
let list = options(app, key);
assert_eq!(list.iter().map(|(_, label)| label.as_str()).collect::<Vec<_>>(), labels, "{key}");
let mut unique: Vec<&String> = list.iter().map(|(id, _)| id).collect();
unique.sort();
unique.dedup();
assert_eq!(unique.len(), list.len(), "{key} options share an id: {list:?}");
list[position].0.clone()
}
#[test]
fn a_mask_alpha_named_like_a_colour_channel_reads_the_alpha() {
let (mut app, ctx, clash) = names_like_the_built_in_choices();
let alpha = option_at(&mut app, &mask_channel_key(clash), &["Gray", "Red", "Green", "Blue", "Red"], 4);
let d = open(&mut app, &ctx);
set(&mut app, &ctx, d, "blending", json!("normal"));
set(&mut app, &ctx, d, "sourceInvert", json!(true));
set(&mut app, &ctx, d, MASK_ON, json!(true));
set(&mut app, &ctx, d, MASK_SOURCE, json!(clash.to_string()));
set(&mut app, &ctx, d, &mask_channel_key(clash), json!(alpha));
assert_eq!(fields(&app, d)["maskChannel"], json!({"alpha": 0}), "an explicit alpha selector");
crate::dialogs::confirm(&mut app, &ctx, d).unwrap();
// The alpha masks the left half in and the right half out; the red plane (200 everywhere) would mix both.
assert_eq!(rgb(&app, 50, 50), [55, 155, 205]);
assert_eq!(rgb(&app, 300, 50), [200, 100, 50]);
}
#[test]
fn a_mask_layer_named_merged_is_that_layer_not_the_composite() {
let (mut app, ctx, clash) = names_like_the_built_in_choices();
let layer = option_at(&mut app, &mask_layer_key(clash), &["Merged", "merged", "Background"], 1);
let d = open(&mut app, &ctx);
set(&mut app, &ctx, d, "blending", json!("normal"));
set(&mut app, &ctx, d, "sourceInvert", json!(true));
set(&mut app, &ctx, d, MASK_ON, json!(true));
set(&mut app, &ctx, d, MASK_SOURCE, json!(clash.to_string()));
set(&mut app, &ctx, d, &mask_layer_key(clash), json!(layer));
assert_eq!(fields(&app, d)["maskLayer"], json!({"name": "merged"}), "an explicit layer name selector");
crate::dialogs::confirm(&mut app, &ctx, d).unwrap();
let through_dialog = [rgb(&app, 50, 50), rgb(&app, 300, 50)];
run(&mut app, "edit.undo", json!({}));
// The same as the command with the layer named explicitly, and not the result of the composite as mask.
let mask = |layer: Value| json!({"sourceInvert": true, "blending": "normal", "mask": {"document": clash, "layer": layer, "channel": "RGB"}});
run(&mut app, APPLY, mask(json!({"name": "merged"})));
assert_eq!([rgb(&app, 50, 50), rgb(&app, 300, 50)], through_dialog);
run(&mut app, "edit.undo", json!({}));
run(&mut app, APPLY, mask(json!("merged")));
assert_ne!([rgb(&app, 50, 50), rgb(&app, 300, 50)], through_dialog, "the composite masks differently");
}
+67 -16
View File
@@ -705,17 +705,68 @@ pub(crate) fn apply_image_documents(app: &PhotocraftApp) -> Vec<(usize, &photocr
documents
}
/// The option id prefix of a layer the engine would not read by its plain name: one named "merged" (the composite) or
/// with no name, and so that no plain name is mistaken for one, any name with this prefix. The rest of the id is the
/// name, sent as `{"name": …}` ([`apply_image_layer_selector`]).
const LAYER_NAMED: &str = "layer#";
/// The option id prefix of an alpha channel the engine would not read by its plain name: one named as a built-in
/// channel ("Red", "RGB", "selection"…), a later one of a repeated name, or one with this prefix. The rest of the id is
/// its index, sent as `{"alpha": index}` ([`apply_image_channel_selector`]).
const ALPHA_AT: &str = "alpha#";
/// The option id of the layer `name`: the name itself, unless the engine would read it as something else.
fn apply_image_layer_option(name: &str) -> String {
if name.is_empty() || name == "merged" || name.starts_with(LAYER_NAMED) { format!("{LAYER_NAMED}{name}") } else { name.to_owned() }
}
/// The layer selector an Apply Image Layer option sends: `{"name": …}` for a [`LAYER_NAMED`] id, else the id.
fn apply_image_layer_selector(id: &str) -> Value {
id.strip_prefix(LAYER_NAMED).map_or_else(|| json!(id), |name| json!({"name": name}))
}
/// The channel selector an Apply Image Channel option sends: `{"alpha": index}` for an [`ALPHA_AT`] id, else the id.
fn apply_image_channel_selector(id: &str) -> Value {
id.strip_prefix(ALPHA_AT).and_then(|i| i.parse::<u64>().ok()).map_or_else(|| json!(id), |i| json!({"alpha": i}))
}
/// A selector as a dialog field: a plain id as text, an explicit selector as JSON.
fn selector_field(selector: Value) -> FieldValue {
match selector {
Value::String(id) => FieldValue::Text(id),
other => FieldValue::Json(other),
}
}
/// The alpha channel options of a source document, labelled by name: an alpha whose name the engine reads as itself
/// keeps it as its id, any other is [`ALPHA_AT`] and its index, so no option shares an id with a built-in channel or
/// another alpha.
fn apply_image_alpha_options(doc: &photocraft_doc::Document) -> Vec<(String, Label)> {
use photocraft_engine::channel_cmds::{ChanRef, parse_ref};
doc.channels
.iter()
.enumerate()
.map(|(i, c)| {
let plain = !c.name.starts_with(ALPHA_AT) && parse_ref(&json!(c.name), doc) == Some(ChanRef::Alpha(i));
(if plain { c.name.clone() } else { format!("{ALPHA_AT}{i}") }, Label::from(c.name.clone()))
})
.collect()
}
/// The Layer list of a source document and its default: Merged, then its pixel layers top to bottom (the engine takes
/// the topmost layer of a name), Merged first; a single-layer document lists only that layer.
fn apply_image_layers(doc: &photocraft_doc::Document) -> (Vec<String>, String) {
/// the topmost layer of a name), Merged first; a single-layer document lists only that layer. A layer keeps its own
/// option beside Merged whatever its name ([`apply_image_layer_option`]).
fn apply_image_layers(doc: &photocraft_doc::Document) -> (Vec<(String, Label)>, String) {
let all = doc.walk();
if let [(_, _, only)] = all.as_slice() {
return (vec![only.name.clone()], only.name.clone());
let id = apply_image_layer_option(&only.name);
return (vec![(id.clone(), Label::from(only.name.clone()))], id);
}
let mut layers = vec!["merged".to_string()];
for (_, _, l) in all.into_iter().rev() {
if l.surface().is_some() && !layers.contains(&l.name) {
layers.push(l.name.clone());
let mut names: Vec<&str> = Vec::new();
let mut layers = vec![("merged".to_string(), Label::from(tl!("Merged")))];
for (_, _, l) in all.iter().rev() {
if l.surface().is_some() && !names.contains(&l.name.as_str()) {
names.push(&l.name);
layers.push((apply_image_layer_option(&l.name), Label::from(l.name.clone())));
}
}
(layers, "merged".to_string())
@@ -737,11 +788,10 @@ fn apply_image_mask_channels(doc: &photocraft_doc::Document) -> (Vec<(String, La
}
list.extend(colors.iter().map(|n| (n.to_string(), Label::from(n.to_string()))));
}
let mut rest: Vec<String> = doc.channels.iter().map(|c| c.name.clone()).collect();
list.extend(apply_image_alpha_options(doc));
if doc.selection.is_some() {
rest.push("selection".into());
list.extend(channels(&["selection".to_string()]));
}
list.extend(channels(&rest));
(list, default)
}
@@ -756,7 +806,7 @@ fn apply_image_mask_rows(app: &PhotocraftApp) -> Vec<Param> {
for (i, doc) in documents {
let (layers, layer) = apply_image_layers(doc);
let (list, channel) = apply_image_mask_channels(doc);
rows.push(choice(&mask_layer_key(i), tl!("Layer"), channels(&layers), &layer).visible_when(mask_shown_key(i), true));
rows.push(choice(&mask_layer_key(i), tl!("Layer"), layers, &layer).visible_when(mask_shown_key(i), true));
rows.push(choice(&mask_channel_key(i), tl!("Channel"), list, &channel).visible_when(mask_shown_key(i), true));
}
rows.push(shown(Param::new(MASK_INVERT, tl!("Invert"), ParamKind::bool(false))));
@@ -765,7 +815,8 @@ fn apply_image_mask_rows(app: &PhotocraftApp) -> Vec<Param> {
/// Brings the mask group's shell keys and the `mask*` parameters of `image.applyImage` up to date: the chosen
/// document's Layer and Channel rows are shown, and OK sends `maskDocument`, `maskLayer`, `maskChannel` and, only when
/// Invert is ticked, `maskInvert`. With Mask unticked it sends no mask at all.
/// Invert is ticked, `maskInvert`. With Mask unticked it sends no mask at all. A layer or alpha the engine would read as
/// something else by its name goes as an explicit selector.
fn apply_image_mask_derive(fields: &mut DialogFields) {
let on = fields.bool(MASK_ON) == Some(true);
let source = fields.text(MASK_SOURCE).and_then(|s| s.parse::<usize>().ok());
@@ -777,11 +828,11 @@ fn apply_image_mask_derive(fields: &mut DialogFields) {
fields.remove(key);
}
let Some(i) = source.filter(|_| on) else { return };
let Some(channel) = fields.text(&mask_channel_key(i)).map(str::to_owned) else { return };
let layer = fields.text(&mask_layer_key(i)).unwrap_or("merged").to_owned();
let Some(channel) = fields.text(&mask_channel_key(i)).map(apply_image_channel_selector) else { return };
let layer = apply_image_layer_selector(fields.text(&mask_layer_key(i)).unwrap_or("merged"));
fields.set("maskDocument", FieldValue::Int(i64::try_from(i).unwrap_or(i64::MAX)));
fields.set("maskLayer", layer);
fields.set("maskChannel", channel);
fields.set("maskLayer", selector_field(layer));
fields.set("maskChannel", selector_field(channel));
if fields.bool(MASK_INVERT) == Some(true) {
fields.set("maskInvert", true);
}