Invert (⌘I) inverts the targeted layer mask (#780) (#838)

* Invert (⌘I) inverts the targeted layer mask (#780)

With the layer mask targeted (its thumbnail clicked, or viewed with
Alt-click), Image > Adjustments and the filters now edit the mask instead
of the layer's pixels, as in Photoshop. Without a selection Invert also
flips the mask's default, so a reveal-all mask becomes hide-all, past the
canvas too. A targeted mask enables these commands on layers without
pixels (adjustment and fill layers), and dialog previews show the mask.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* rustfmt

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Brandon Thomas <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-10-07 23:30:53 -04:00
1 parent e694208a06
commit a93fb88064
15 files changed
+236 -27

No files matched your search

+5 -4
View File
@@ -167,19 +167,20 @@ fn process_surface(surf: &mut Surface, selection: Option<&Surface>, f: &mut dyn
surf.write_region(r, &out);
}
/// One history step running `f` on the active pixel layer (or targeted channel).
/// One history step running `f` on the active pixel layer (or targeted channel or layer mask).
fn rgba_edit(s: &mut Session, label: &str, p: &Value, mut f: impl FnMut(&mut Vec<[f32; 4]>, Rect)) -> Result<Value> {
if crate::channel_cmds::is_channel_target(p) {
let id = crate::commands::layer_param(s, &Value::Null).ok();
if crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels {
return s.edit(label, |doc, _| {
let sel = doc.selection.clone();
if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, p)? {
if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, id, p)? {
process_surface(surf, sel.as_ref(), &mut f);
surf.prune();
}
Ok(Value::Null)
});
}
let id = crate::commands::layer_param(s, &Value::Null)?;
let id = id.ok_or_else(|| EngineError::Other("no active layer".into()))?;
s.edit(label, |doc, _| {
let sel = doc.selection.clone();
let surf = crate::commands::paint_surface(doc, id, &Value::Null)?;
+66
View File
@@ -223,3 +223,69 @@ fn new_kinds_round_trip_through_psd_and_pcraft() {
assert_eq!(a.content, b.content);
}
}
fn mask_at(s: &Session, x: i32, y: i32) -> f32 {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0)
}
/// #780: with the layer mask targeted, Invert (⌘I) inverts the mask, past the canvas too, and
/// leaves the layer's pixels alone; one history step.
#[test]
fn invert_with_the_mask_targeted_inverts_the_mask() {
for depth in DEPTHS {
let mut s = session(depth, "rgb");
s.execute("select.rect", json!({"x": 24, "y": 0, "width": 24, "height": 32})).unwrap();
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
let (pixels, off_canvas) = (rgba(&s, 3, 3), mask_at(&s, -500, 3));
let steps = s.active().unwrap().history.past_len();
s.execute("image.adjustments.invert", json!({"target": "mask"})).unwrap();
assert_eq!((mask_at(&s, 3, 3), mask_at(&s, 30, 3)), (1.0, 0.0), "depth {depth}");
assert_eq!(mask_at(&s, -500, 3), 1.0 - off_canvas, "the mask's untouched area inverts too");
assert_eq!(rgba(&s, 3, 3), pixels, "the layer is untouched");
assert_eq!(s.active().unwrap().history.past_len(), steps + 1);
// Through a selection, only the selected part.
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 32})).unwrap();
s.execute("image.adjustments.invert", json!({"target": "mask"})).unwrap();
assert_eq!((mask_at(&s, 3, 3), mask_at(&s, 12, 3), mask_at(&s, 30, 3)), (0.0, 1.0, 0.0));
for _ in 0..3 {
s.undo(); // invert, select, invert
}
assert_eq!((mask_at(&s, 3, 3), mask_at(&s, 30, 3), mask_at(&s, -500, 3)), (0.0, 1.0, off_canvas));
}
}
/// #780: a targeted mask enables Invert (and filters) on layers without pixels, such as an
/// adjustment layer; viewing the mask (⌥-click) targets it too.
#[test]
fn a_targeted_mask_enables_editing_it_on_any_layer() {
let mut s = session(8, "rgb");
s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap();
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
let mask = json!({"target": "mask"});
assert!(!s.is_enabled("image.adjustments.invert"), "no pixels to invert");
assert!(s.is_enabled_with("image.adjustments.invert", &mask));
assert!(s.is_enabled_with("filter.blur.gaussianBlur", &mask));
assert!(!s.is_enabled_with("image.adjustments.desaturate", &mask), "only what edits the mask");
s.execute("image.adjustments.invert", mask.clone()).unwrap();
assert_eq!((mask_at(&s, 3, 3), mask_at(&s, -500, -500)), (0.0, 0.0), "reveal all → hide all");
s.execute("view.layerMask", json!({"mode": "gray"})).unwrap();
assert!(s.is_enabled("image.adjustments.invert"), "the mask view targets the mask");
s.execute("image.adjustments.invert", json!({})).unwrap();
assert_eq!(mask_at(&s, 3, 3), 1.0);
// A filter on a pixel layer's targeted mask leaves the pixels alone.
s.execute("layer.delete", json!({})).unwrap();
s.execute("select.rect", json!({"x": 24, "y": 0, "width": 24, "height": 32})).unwrap();
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
let pixels = rgba(&s, 23, 3);
s.execute("filter.blur.gaussianBlur", json!({"radius": 3, "target": "mask"})).unwrap();
assert!(mask_at(&s, 23, 3) > 0.0 && mask_at(&s, 23, 3) < 1.0, "the mask's edge is blurred");
assert_eq!(rgba(&s, 23, 3), pixels);
// No mask: an error, not the layer's pixels.
s.execute("layer.layerMask.delete", json!({})).unwrap();
assert!(!s.is_enabled_with("image.adjustments.invert", &mask));
assert!(s.execute("image.adjustments.invert", mask).is_err());
assert_eq!(rgba(&s, 23, 3), pixels);
}
+29 -5
View File
@@ -520,18 +520,42 @@ pub(crate) fn target_surface<'a>(doc: &'a mut Document, layer: Option<LayerId>,
}
}
/// Channel surface for filters and adjustments (made explicit over the canvas), if the params
/// target a channel.
pub(crate) fn channel_surface_for_filter<'a>(doc: &'a mut Document, p: &Value) -> Result<Option<&'a mut Surface>> {
if !is_channel_target(p) {
/// The grayscale surface filters and adjustments edit instead of the layer's pixels (made explicit
/// over the canvas), if the params target one: an alpha channel, the Quick Mask, or the mask of
/// `layer`.
pub(crate) fn channel_surface_for_filter<'a>(doc: &'a mut Document, layer: Option<LayerId>, p: &Value) -> Result<Option<&'a mut Surface>> {
if target_of(p) == Target::Pixels {
return Ok(None);
}
let b = doc.bounds();
let (surf, _) = target_surface(doc, None, p)?;
let (surf, _) = target_surface(doc, layer, p)?;
materialize(surf, b);
Ok(Some(surf))
}
/// Commands that edit a targeted layer mask in place of the layer: the Image › Adjustments table
/// and the filters. A mask target enables them on any layer with a mask, so ⌘I inverts an
/// adjustment layer's mask as in Photoshop (#780).
fn edits_mask(id: &str) -> bool {
id.strip_prefix("image.adjustments.").is_some_and(|kind| crate::adjust_params::default_for(kind, ColorMode::Rgb).is_ok())
|| crate::filters::params_for(id, &Value::Null).is_some()
}
/// The precondition of `id` when `p` targets the active layer's mask (`"target":"mask"`): the
/// layer needs a mask. None when another precondition applies.
pub(crate) fn mask_target_enabled(s: &Session, id: &str, p: &Value) -> Option<std::result::Result<(), String>> {
if target_of(p) != Target::Mask || !edits_mask(id) {
return None;
}
Some(crate::active_layer_of(s).and_then(|l| if l.mask.is_some() { Ok(()) } else { Err("the active layer has no layer mask".into()) }))
}
/// Whether command `id` edits the targeted channel or mask when its params name no `"target"`
/// (filters, adjustments, paint and fill commands); the shell adds its mask target to these.
pub fn follows_target(id: &str) -> bool {
routed(id)
}
/// Commands whose target follows the Channels panel.
fn routed(id: &str) -> bool {
id.starts_with("filter.")
+12 -1
View File
@@ -192,11 +192,22 @@ fn new_adjustment(s: &mut Session, adj: Adjustment) -> Result<Value> {
}
fn destructive_adjust(s: &mut Session, label: &str, adj: Adjustment, p: &Value) -> Result<Value> {
if is_mask_target(p) {
// The targeted layer mask (#780): ⌘I inverts it, as in Photoshop.
let id = layer_param(s, &Value::Null)?;
return s.edit(label, |doc, _| {
let sel = doc.selection.clone();
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
let mask = l.mask.as_mut().ok_or_else(|| EngineError::Other("layer has no mask".into()))?;
pixels::adjust_mask(&mut mask.surface, &adj, sel.as_ref());
Ok(Value::Null)
});
}
if crate::channel_cmds::is_channel_target(p) {
// Alpha channel / Quick Mask target: the adjustment runs on the grayscale channel.
return s.edit(label, |doc, _| {
let sel = doc.selection.clone();
if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, p)? {
if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, None, p)? {
pixels::adjust_surface(surf, &adj, sel.as_ref(), ColorMode::Grayscale);
surf.prune();
}
+1 -1
View File
@@ -226,7 +226,7 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value>
let bounds = sel_bounds.filter(|b| !b.is_empty()).unwrap_or(doc_bounds);
// Neighbourhood filters repeat edge pixels at the canvas edge (or past it, where the
// layer has off-canvas pixels) instead of fading in transparency, as Photoshop does.
if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, &p)? {
if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, Some(layer), &p)? {
let content = surf.content_bounds();
let area = algo::output_area(&fp, content, bounds, sel_bounds);
*surf = filter(surf, &fp, area, bounds, selection.as_ref(), doc_bounds.union(&content))?;
+3 -3
View File
@@ -598,15 +598,15 @@ impl Session {
if let Some(v) = crate::float_cmds::before_command(self, id)? {
return Ok(Started::Done(v));
}
if let Err(why) = crate::smart_cmds::target_enabled(self, spec, &params).unwrap_or_else(|| (spec.enabled)(self)) {
// Pixel commands follow the Channels panel target unless the caller names one.
let run_params = crate::channel_cmds::inject_target(self, id, crate::commands::inject_kind(id, params.clone()));
if let Err(why) = crate::smart_cmds::target_enabled(self, spec, &params).unwrap_or_else(|| self.precondition(spec, &run_params)) {
return Err(EngineError::Disabled(id.to_string(), why));
}
if let Some(why) = self.job_conflict(id, spec.journal) {
return Err(EngineError::Disabled(id.to_string(), why));
}
self.coalesce_request = params.get("coalesce").and_then(Value::as_str).map(str::to_string);
// Pixel commands follow the Channels panel target unless the caller names one.
let run_params = crate::channel_cmds::inject_target(self, id, crate::commands::inject_kind(id, params.clone()));
self.color_restrict = crate::channel_cmds::color_restriction(self, id, &run_params);
self.jobs.spawn = background;
// Last-resort guard (AGENTS.md, Never crash): a command that panics anyway fails with an
+18 -2
View File
@@ -405,14 +405,30 @@ impl Session {
/// Is the command currently runnable? (drives menu enablement)
pub fn is_enabled(&self, id: &str) -> bool {
commands::find(id).is_some_and(|s| (s.enabled)(self).is_ok() && self.job_conflict(id, s.journal).is_none())
self.is_enabled_with(id, &Value::Null)
}
/// [`Self::is_enabled`] for a call with `params`: their `"target"` can enable a command, as a
/// targeted layer mask enables Image › Adjustments › Invert on an adjustment layer (#780).
pub fn is_enabled_with(&self, id: &str, params: &Value) -> bool {
self.disabled_reason_with(id, params).is_none()
}
/// Why the command can't run now (None = it can): its own precondition, or a background job
/// running on the active document.
pub fn disabled_reason(&self, id: &str) -> Option<String> {
self.disabled_reason_with(id, &Value::Null)
}
/// [`Self::disabled_reason`] for a call with `params`.
pub fn disabled_reason_with(&self, id: &str, params: &Value) -> Option<String> {
let Some(s) = commands::find(id) else { return Some(format!("unknown command `{id}`")) };
(s.enabled)(self).err().or_else(|| self.job_conflict(id, s.journal))
self.precondition(s, &channel_cmds::inject_target(self, id, params.clone())).err().or_else(|| self.job_conflict(id, s.journal))
}
/// The command's own precondition for a call with `params` (their target filled in).
fn precondition(&self, spec: &commands::CommandSpec, params: &Value) -> std::result::Result<(), String> {
channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self))
}
/// Apply an undoable edit to the active document.
+32 -1
View File
@@ -13,6 +13,37 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surf
if r.is_empty() {
return;
}
let out = adjusted(s, r, adj, selection, mode);
s.write_region(r, &out);
}
/// Applies `adj` to a layer mask through the selection. Untouched mask pixels count (they read as
/// the mask's default value), and without a selection the default changes too, since a mask
/// reaches past the canvas: Invert turns a reveal-all mask into a hide-all one (#780).
pub fn adjust_mask(s: &mut Surface, adj: &Adjustment, selection: Option<&Surface>) {
let mode = photocraft_color::ColorMode::Grayscale;
if let Some(sel) = selection {
let r = sel.content_bounds();
if !r.is_empty() {
let out = adjusted(s, r, adj, Some(sel), mode);
s.write_region(r, &out);
s.prune();
}
return;
}
let fmt = s.format();
let unit = Rect::from_xywh(0, 0, 1, 1);
let mut out = Surface::with_default(fmt, &adjusted(&Surface::with_default(fmt, &s.default_pixel()), unit, adj, None, mode));
let r = s.tile_bounds();
if !r.is_empty() {
out.write_region(r, &adjusted(s, r, adj, None, mode));
}
out.prune();
*s = out;
}
/// `s`'s pixels over `r` (untouched ones included) with `adj` applied through the selection, encoded.
fn adjusted(s: &Surface, r: Rect, adj: &Adjustment, selection: Option<&Surface>, mode: photocraft_color::ColorMode) -> Vec<f32> {
let fmt = s.format();
let n = fmt.channels();
let raw = s.read_region(r);
@@ -31,7 +62,7 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surf
let m = photocraft_raster::from_rgba_into(&fmt, mixed, &mut enc);
out.extend_from_slice(&enc[..m]);
}
s.write_region(r, &out);
out
}
/// Fill (respecting selection coverage) with a straight RGBA colour.
+1 -1
View File
@@ -73,7 +73,7 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
s.edit(&label, |doc, _| {
let selection = doc.selection.clone();
let canvas = doc.bounds();
if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, p)? {
if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, Some(layer), p)? {
*surf = plugin.apply(surf, canvas, selection.as_ref(), &resolved).map_err(err)?;
return Ok(());
}
+5 -2
View File
@@ -218,8 +218,11 @@ fn update(app: &mut PhotocraftApp, idx: usize) -> Option<&AdjustPreview> {
};
let st = app.session.documents().get(idx)?;
let (doc_id, revision, target) = (st.doc.id, st.revision, st.active_layer?);
// Commands that target a channel (Channels panel / Quick Mask) keep the proxy preview.
let channel_target = st.channel_view.target != photocraft_engine::channel_cmds::ChannelTarget::Composite || st.doc.quick_mask.is_some();
// Commands that target a channel (Channels panel / Quick Mask) or a layer mask keep the proxy
// preview.
let channel_target = st.channel_view.target != photocraft_engine::channel_cmds::ChannelTarget::Composite
|| st.doc.quick_mask.is_some()
|| !app.with_mask_target(&format!("image.adjustments.{kind}"), Value::Null).is_null();
let session = hash(&[&doc_id.0.to_le_bytes(), &revision.to_le_bytes(), &target.0.to_le_bytes(), &[u8::from(channel_target)]]);
let h = hash(&[kind.as_bytes(), params.to_string().as_bytes(), &[u8::from(preview)]]);
if let Some(p) = &app.adjust_preview
+2 -1
View File
@@ -819,7 +819,8 @@ fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u6
return None;
}
let cmd = d.fields.get("__command")?.as_str()?.to_string();
let params = crate::filter_dialog::params_of(&d.fields);
// Previews edit what the command will: a targeted layer mask included (#780).
let params = app.with_mask_target(&cmd, crate::filter_dialog::params_of(&d.fields));
let (doc_id, revision, doc, active) = {
let st = app.session.documents().get(idx)?;
(st.doc.id, st.revision, st.doc.clone(), st.active_layer)
+23
View File
@@ -640,6 +640,7 @@ impl PhotocraftApp {
}
}
// Long commands become background jobs when enabled (`jobs_ui`); the rest run inline.
let params = self.with_mask_target(id, params);
let r = jobs_ui::run(self, id, params);
if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") {
self.clip_external = false;
@@ -1115,6 +1116,28 @@ fn read_dropped(_f: &dyn egui::DroppedFile) -> Result<Vec<u8>, String> {
}
impl PhotocraftApp {
/// `params` aimed at the active layer's mask (`"target":"mask"`) when the Layers panel targets
/// it and command `id` edits the target (adjustments, filters, fills) without naming one:
/// ⌘I then inverts the mask, as in Photoshop (#780). A targeted alpha channel or Quick Mask
/// mode wins, as the engine routes those itself.
pub fn with_mask_target(&self, id: &str, params: Value) -> Value {
if !self.ui.mask_target || !photocraft_engine::channel_cmds::follows_target(id) || params.get("target").is_some() {
return params;
}
let Some(st) = self.session.active() else { return params };
let composite = st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::Composite && st.doc.quick_mask.is_none();
if !composite || st.active_layer.and_then(|id| st.doc.layer(id)).is_none_or(|l| l.mask.is_none()) {
return params;
}
match params {
Value::Object(mut m) => {
m.insert("target".into(), Value::from("mask"));
Value::Object(m)
}
_ => serde_json::json!({ "target": "mask" }),
}
}
/// Viewing a layer mask (#196) targets it; a vector-mask target needs a vector mask on the
/// active layer (a shape layer's path is its content, not a mask).
fn sync_mask_targets(&mut self) {
@@ -384,3 +384,33 @@ fn mask_view_gestures_fail_gracefully_without_a_mask() {
assert_eq!(mask_view(&h), serde_json::Value::Null);
assert_eq!(crate::canvas::paint_target(h.state()), json!("pixels"));
}
/// #780: clicking the mask thumbnail targets the mask, and ⌘I (Image › Adjustments › Invert)
/// then inverts the mask instead of the layer; on an adjustment layer the menu item is live.
#[test]
fn command_i_inverts_the_targeted_mask() {
let (s, masked, _) = dotted();
let mut h = harness(s, 0, 1.0, 290.0);
let pixels = layer(&h, masked).content;
let r = mask_rect(&h, masked, MaskKind::Pixel);
click_with(&mut h, r.center(), Modifiers::NONE);
assert!(h.state().ui.mask_target);
h.key_press_modifiers(Modifiers::COMMAND, egui::Key::I);
h.run_steps(2);
let l = layer(&h, masked);
let mask = &l.mask.as_ref().unwrap().surface;
assert_eq!((mask.sample_channel(50, 50, 0), mask.sample_channel(150, 10, 0)), (1.0, 0.0), "the mask inverted");
assert!(l.content == pixels, "the layer's pixels are untouched");
// An adjustment layer's mask: Invert is enabled only through the mask target.
let app = h.state_mut();
app.run("layer.newAdjustmentLayer.curves", json!({})).unwrap();
app.run("layer.layerMask.revealAll", json!({})).unwrap();
app.ui.mask_target = false;
assert!(!crate::menus::is_enabled(app, "image.adjustments.invert"));
app.ui.mask_target = true;
assert!(crate::menus::is_enabled(app, "image.adjustments.invert"));
app.run("image.adjustments.invert", json!({})).unwrap();
let st = app.session.active().unwrap();
let mask = &st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface;
assert_eq!(mask.sample_channel(10, 10, 0), 0.0, "reveal all → hide all");
}
+2 -1
View File
@@ -518,7 +518,8 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
Some(t) => t.warp.is_none(),
None => app.session.active().and_then(|s| s.active_layer).is_some(),
},
i => app.session.is_enabled(i),
// A targeted layer mask enables what edits it (Invert on an adjustment layer's mask).
i => app.session.is_enabled_with(i, &app.with_mask_target(i, Value::Null)),
}
}
+7 -5
View File
@@ -201,11 +201,13 @@ pub fn dispatch_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, focus: Foc
/// Why `id` can't run now (the engine's reason when it has one).
pub fn disabled_reason(app: &PhotocraftApp, id: &str) -> String {
photocraft_engine::commands::find(id).and_then(|_| app.session.disabled_reason(id)).unwrap_or_else(|| match id {
"tools.decreaseBrushHardness" | "tools.increaseBrushHardness" => "the current tool has no brush tip".into(),
_ if app.session.active().is_none() => "no document open".into(),
_ => "not available in the current state".into(),
})
photocraft_engine::commands::find(id).and_then(|_| app.session.disabled_reason_with(id, &app.with_mask_target(id, serde_json::Value::Null))).unwrap_or_else(
|| match id {
"tools.decreaseBrushHardness" | "tools.increaseBrushHardness" => "the current tool has no brush tip".into(),
_ if app.session.active().is_none() => "no document open".into(),
_ => "not available in the current state".into(),
},
)
}
fn label(id: &str) -> String {