Skip to content

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

Fade the alpha channel or Quick Mask an edit changed (#7382)

Hector Villarreald1003c6191cc
diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs
index f9fab33e3..4cb4b2e60 100644
--- a/crates/engine/src/edit_menu_cmds.rs
+++ b/crates/engine/src/edit_menu_cmds.rs
@@ -13,6 +13,7 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
+use crate::channel_cmds::ChannelTarget;
use crate::commands::{CommandSpec, blend_from_str, int, layer_param};
use crate::{EngineError, Result, Session};
@@ -24,11 +25,23 @@ pub struct FadeSource {
pub doc: DocId,
/// Document revision right after the command; any later change disables Fade.
pub revision: u64,
- pub layer: LayerId,
- pub mask: bool,
+ pub target: FadeTarget,
pub label: String,
}
+/// What the faded command changed, and so what Fade blends back.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum FadeTarget {
+ /// A layer's pixels.
+ Pixels(LayerId),
+ /// A layer's layer mask.
+ Mask(LayerId),
+ /// An alpha or spot channel (index into [`Document::channels`]).
+ Channel(usize),
+ /// The Quick Mask.
+ QuickMask,
+}
+
/// A custom shape (Edit › Define Custom Shape), usable by the Custom Shape tool.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CustomShape {
@@ -60,8 +73,18 @@ pub(crate) fn after_command(s: &mut Session, id: &str) {
return;
}
let Some(st) = s.active() else { return };
- let Some(layer) = st.active_layer else { return };
let label = st.history.undo_label().unwrap_or(id).to_string();
+ // A targeted alpha channel, or the Quick Mask, takes the edit instead of the layer (#7382).
+ let channel = match st.channel_view.target {
+ ChannelTarget::Alpha(i) if i < st.doc.channels.len() => Some(FadeTarget::Channel(i)),
+ ChannelTarget::Composite if st.doc.quick_mask.is_some() => Some(FadeTarget::QuickMask),
+ _ => None,
+ };
+ if let Some(target) = channel {
+ s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, target, label });
+ return;
+ }
+ let Some(layer) = st.active_layer else { return };
let mask = st.doc.layer(layer).is_some_and(|l| l.mask.is_some())
&& st.history.state(st.history.past_len().wrapping_sub(1)).is_some_and(|prev| {
// The mask changed and the pixels didn't: the command painted the mask.
@@ -75,7 +98,8 @@ pub(crate) fn after_command(s: &mut Session, id: &str) {
surf_eq(now.and_then(|l| l.surface()), was.and_then(|l| l.surface()))
&& !surf_eq(now.and_then(|l| l.mask.as_ref().map(|m| &m.surface)), was.and_then(|l| l.mask.as_ref().map(|m| &m.surface)))
});
- s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, layer, mask, label });
+ let target = if mask { FadeTarget::Mask(layer) } else { FadeTarget::Pixels(layer) };
+ s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, target, label });
}
/// Tile identity of a surface (pointer equality of its COW tiles).
@@ -144,15 +168,31 @@ fn can_fade(s: &Session) -> std::result::Result<(), String> {
if f.doc != st.doc.id || f.revision != st.revision || !st.history.can_undo() {
return Err("Fade is only available right after a filter, adjustment or painting step".into());
}
- if st.doc.layer(f.layer).is_none() {
- return Err("the faded layer no longer exists".into());
+ if surface_of(&st.doc, f.target).is_none() {
+ return Err(match f.target {
+ FadeTarget::Pixels(_) | FadeTarget::Mask(_) => "the faded layer no longer exists".into(),
+ FadeTarget::Channel(_) | FadeTarget::QuickMask => "the faded channel no longer exists".into(),
+ });
}
Ok(())
}
-fn surface_of(doc: &Document, id: LayerId, mask: bool) -> Option<&Surface> {
- let l = doc.layer(id)?;
- if mask { l.mask.as_ref().map(|m| &m.surface) } else { l.surface() }
+fn surface_of(doc: &Document, target: FadeTarget) -> Option<&Surface> {
+ match target {
+ FadeTarget::Pixels(id) => doc.layer(id)?.surface(),
+ FadeTarget::Mask(id) => doc.layer(id)?.mask.as_ref().map(|m| &m.surface),
+ FadeTarget::Channel(i) => doc.channels.get(i).map(|c| &c.surface),
+ FadeTarget::QuickMask => doc.quick_mask.as_ref().map(|c| &c.surface),
+ }
+}
+
+fn surface_of_mut(doc: &mut Document, target: FadeTarget) -> Option<&mut Surface> {
+ match target {
+ FadeTarget::Pixels(id) => doc.layer_mut(id)?.surface_mut(),
+ FadeTarget::Mask(id) => doc.layer_mut(id)?.mask.as_mut().map(|m| &mut m.surface),
+ FadeTarget::Channel(i) => doc.channels.get_mut(i).map(|c| &mut c.surface),
+ FadeTarget::QuickMask => doc.quick_mask.as_mut().map(|c| &mut c.surface),
+ }
}
/// Blend `after` back towards `before` over `area`: `before + opacity × (B(before, after) − before)`
@@ -209,8 +249,8 @@ fn fade(s: &mut Session, p: &Value) -> Result<Value> {
let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let prev = st.history.state(st.history.past_len() - 1).ok_or_else(|| bad(cmd, "no previous state"))?;
- let before = surface_of(&prev, src.layer, src.mask).cloned().ok_or_else(|| EngineError::Other("the layer did not exist before this step".into()))?;
- let now = surface_of(&st.doc, src.layer, src.mask).ok_or(EngineError::NoLayer(src.layer))?;
+ let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?;
+ let now = surface_of(&st.doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?;
if now.format() != before.format() {
return Err(EngineError::Other("can't fade a step that changed the layer's pixel format".into()));
}
@@ -219,8 +259,7 @@ fn fade(s: &mut Session, p: &Value) -> Result<Value> {
let area = if before.default_pixel() != now.default_pixel() { st.doc.bounds() } else { before.content_bounds().union(&now.content_bounds()) };
let label = format!("Fade {}", src.label);
s.edit(&label, |doc, _| {
- let l = doc.layer_mut(src.layer).ok_or(EngineError::NoLayer(src.layer))?;
- let surf = if src.mask { l.mask.as_mut().map(|m| &mut m.surface) } else { l.surface_mut() }.ok_or(EngineError::NoLayer(src.layer))?;
+ let surf = surface_of_mut(doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?;
fade_surface(&before, surf, area, mode, opacity)?;
surf.prune();
Ok(())
diff --git a/crates/engine/src/edit_menu_cmds/tests.rs b/crates/engine/src/edit_menu_cmds/tests.rs
index 873061e46..34b42a3a4 100644
--- a/crates/engine/src/edit_menu_cmds/tests.rs
+++ b/crates/engine/src/edit_menu_cmds/tests.rs
@@ -72,7 +72,7 @@ fn fade_uniform_layer_mask_invert_at_all_depths() {
assert!((mask_pixel(&s) - 1.0).abs() < 0.01);
s.execute("image.adjustments.invert", json!({})).unwrap();
assert!(mask_pixel(&s) < 0.01, "depth {depth}: invert changed the mask");
- assert!(s.edit_state.fade.as_ref().is_some_and(|f| f.mask), "depth {depth}: Fade must target the mask");
+ assert!(s.edit_state.fade.as_ref().is_some_and(|f| matches!(f.target, FadeTarget::Mask(_))), "depth {depth}: Fade must target the mask");
let history_before_fade = s.active().unwrap().history.past_len();
s.execute("edit.fade", json!({"opacity": opacity})).unwrap();
@@ -89,6 +89,45 @@ fn fade_uniform_layer_mask_invert_at_all_depths() {
}
}
+/// #7382: with an alpha channel or the Quick Mask targeted, the edit changes it, not the layer, and
+/// Fade blends it back: at 0 % to the channel as it was, at every depth.
+#[test]
+fn fade_an_alpha_channel_or_the_quick_mask_at_all_depths() {
+ for depth in [8, 16, 32] {
+ for quick_mask in [false, true] {
+ for (opacity, k) in [(0, 0.0), (25, 0.25), (100, 1.0)] {
+ let mut s = session(depth);
+ if quick_mask {
+ s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap();
+ } else {
+ s.execute("channel.new", json!({"fill": "black"})).unwrap();
+ s.execute("channel.target", json!({"channel": 0})).unwrap();
+ }
+ let channel = |s: &Session, x, y| {
+ let doc = &s.active().unwrap().doc;
+ let c = if quick_mask { doc.quick_mask.as_ref() } else { doc.channels.first() };
+ c.unwrap().surface.pixel(x, y)[0]
+ };
+ let was = channel(&s, 5, 5);
+ s.execute("image.adjustments.invert", json!({})).unwrap();
+ assert!((channel(&s, 5, 5) - (1.0 - was)).abs() < 0.01, "depth {depth}, quick mask {quick_mask}: inverted");
+ let expected = was + (1.0 - 2.0 * was) * k;
+ let steps = s.active().unwrap().history.past_len();
+ s.execute("edit.fade", json!({"opacity": opacity})).unwrap();
+ for (x, y) in [(0, 0), (5, 5), (63, 47)] {
+ let v = channel(&s, x, y);
+ assert!((v - expected).abs() < 0.02, "depth {depth}, quick mask {quick_mask}, {opacity} %, ({x}, {y}): {v}");
+ }
+ assert_eq!(px(&s, 5, 5)[0], 1.0, "the layer is left alone");
+ let st = s.active().unwrap();
+ assert_eq!((st.history.past_len(), st.history.undo_label()), (steps + 1, Some("Fade Invert")));
+ assert!(s.undo());
+ assert!((channel(&s, 5, 5) - (1.0 - was)).abs() < 0.01, "undo puts the inverted channel back");
+ }
+ }
+ }
+}
+
#[test]
fn purge_commands() {
let mut s = session(8);