Skip to content

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

Masks: target a new layer mask and keep separate colour pairs for mask and pixels (#2166) (#2200)

David Manneb20f83654c9
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index c13571199..69cc04b86 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -257,6 +257,33 @@ pub struct ToolState {
/// preset stays "the current brush" so `brush.presets.update` can overwrite it); cleared when
/// the brush is reset or the preset is gone.
pub current_preset: Option<String>,
+ /// A layer mask is the edit target ([`ToolState::target_mask`]).
+ pub mask_targeted: bool,
+ /// The foreground/background pair of the edit target that isn't current: the layer pixels'
+ /// colours while a mask is targeted, the mask's while the pixels are (#2166).
+ pub other_colors: [[f32; 4]; 2],
+}
+
+impl ToolState {
+ /// Photoshop's colour pair for a layer mask that has none yet: white foreground, black
+ /// background (reveal-paint first).
+ pub const MASK_COLORS: [[f32; 4]; 2] = [[1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]];
+
+ /// Switch the edit target between layer pixels and a layer mask. Like Photoshop, the mask and
+ /// the pixels keep separate app-wide foreground/background pairs: changing the target puts
+ /// the current pair aside and brings back the other one, so colours picked while a mask is
+ /// targeted are remembered for masks (#2166). The mask pair starts at [`Self::MASK_COLORS`].
+ /// Returns whether the target changed.
+ pub fn target_mask(&mut self, mask: bool) -> bool {
+ if self.mask_targeted == mask {
+ return false;
+ }
+ self.mask_targeted = mask;
+ let [fg, bg] = std::mem::replace(&mut self.other_colors, [self.foreground, self.background]);
+ self.foreground = fg;
+ self.background = bg;
+ true
+ }
}
impl Default for ToolState {
@@ -274,6 +301,8 @@ impl Default for ToolState {
mixer: Default::default(),
brush_gesture: None,
current_preset: None,
+ mask_targeted: false,
+ other_colors: Self::MASK_COLORS,
}
}
}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 4d76ddcef..3827ad9a3 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -1285,6 +1285,42 @@ fn document_inspect_and_activate_invalid_index() {
assert_eq!(err_act.to_string(), "no document at index 9");
}
+/// #2166, measured in Photoshop 25.1: a layer mask and the layer pixels keep separate
+/// foreground/background pairs, swapped when the edit target changes.
+#[test]
+fn mask_and_pixels_keep_their_own_colour_pair() {
+ const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
+ const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
+ const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
+ const GRAY: [f32; 4] = [0.5, 0.5, 0.5, 1.0];
+ let [white, black] = ToolState::MASK_COLORS;
+ let mut s = session_with_doc();
+ s.execute("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap();
+ let pair = |s: &Session| (s.tools.foreground, s.tools.background);
+ assert!(!s.tools.target_mask(false), "already on the pixels: nothing changes");
+ assert_eq!(pair(&s), (RED, BLUE));
+ assert!(s.tools.target_mask(true));
+ assert_eq!(pair(&s), (white, black), "a mask starts at white/black");
+ assert!(!s.tools.target_mask(true), "targeting it again changes nothing");
+ assert_eq!(pair(&s), (white, black));
+ s.tools.target_mask(false);
+ assert_eq!(pair(&s), (RED, BLUE), "the pixels get their colours back");
+ s.execute("tools.setColors", json!({"foreground": "#00ff00"})).unwrap();
+ s.tools.target_mask(true);
+ assert_eq!(pair(&s), (white, black));
+ s.tools.target_mask(false);
+ assert_eq!(pair(&s), (GREEN, BLUE), "a colour picked on the pixels is remembered");
+ // A colour picked while the mask is targeted is remembered for masks.
+ s.tools.target_mask(true);
+ s.execute("tools.setColors", json!({"foreground": "#808080"})).unwrap();
+ let mask_fg = s.tools.foreground;
+ assert!((mask_fg[0] - GRAY[0]).abs() < 0.01);
+ s.tools.target_mask(false);
+ assert_eq!(pair(&s), (GREEN, BLUE));
+ s.tools.target_mask(true);
+ assert_eq!(pair(&s), (mask_fg, black));
+}
+
#[test]
fn delete_layer_selects_neighbour_and_undo_restores_layer() {
for deleted_index in 0..3 {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index a17c67c05..3c6a3832b 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -785,6 +785,11 @@ impl PhotocraftApp {
} else {
jobs_ui::run(self, id, params)
};
+ if r.is_ok() && ADDS_LAYER_MASK.contains(&id) {
+ // Adding a layer mask targets it, as in Photoshop (#2166).
+ self.ui.mask_target = true;
+ self.ui.vector_mask_target = false;
+ }
if r.is_ok() && id == "select.toWorkPath" {
// Make Work Path selects the new work path in the Paths panel, as in Photoshop.
self.ui.selected_path = Some("work".into());
@@ -1125,6 +1130,8 @@ impl PhotocraftApp {
self.pending_screenshots.push((token, path, reply));
}
}
+ // `ui.set` may have changed the edit target: the next request sees its colours.
+ self.sync_mask_targets();
}
self.control_rx = Some(rx);
}
@@ -1382,12 +1389,7 @@ impl PhotocraftApp {
/// ⌘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()) {
+ if !photocraft_engine::channel_cmds::follows_target(id) || params.get("target").is_some() || !self.layer_mask_targeted() {
return params;
}
match params {
@@ -1399,20 +1401,32 @@ impl PhotocraftApp {
}
}
+ /// The Layers panel targets the active layer's mask, and no alpha channel or Quick Mask
+ /// takes over (the engine routes those itself).
+ pub fn layer_mask_targeted(&self) -> bool {
+ let Some(st) = self.session.active().filter(|_| self.ui.mask_target) else { return false };
+ let composite = st.channel_view.target == photocraft_engine::channel_cmds::ChannelTarget::Composite && st.doc.quick_mask.is_none();
+ composite && st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some())
+ }
+
/// 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).
+ /// active layer (a shape layer's path is its content, not a mask). Targeting a mask or the
+ /// pixels brings back that target's foreground/background pair, as in Photoshop (#2166).
fn sync_mask_targets(&mut self) {
- let Some(st) = self.session.active() else { return };
- if photocraft_engine::mask_view_cmds::current(st).is_some() {
- self.ui.mask_target = true;
- self.ui.vector_mask_target = false;
- }
- if self.ui.vector_mask_target && !mask_thumbs_ui::has_vector_mask(st) {
- self.ui.vector_mask_target = false;
- }
- if self.ui.mask_target && !st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some()) {
- self.ui.mask_target = false;
+ if let Some(st) = self.session.active() {
+ if photocraft_engine::mask_view_cmds::current(st).is_some() {
+ self.ui.mask_target = true;
+ self.ui.vector_mask_target = false;
+ }
+ if self.ui.vector_mask_target && !mask_thumbs_ui::has_vector_mask(st) {
+ self.ui.vector_mask_target = false;
+ }
+ if self.ui.mask_target && !st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| l.mask.is_some()) {
+ self.ui.mask_target = false;
+ }
}
+ let mask = self.layer_mask_targeted();
+ self.session.tools.target_mask(mask);
}
fn prune_thumbs(&mut self) {
@@ -1687,6 +1701,15 @@ impl PhotocraftApp {
}
}
+/// Layer › Layer Mask commands that add a layer mask: Photoshop targets the new mask (#2166).
+const ADDS_LAYER_MASK: [&str; 5] = [
+ "layer.layerMask.revealAll",
+ "layer.layerMask.hideAll",
+ "layer.layerMask.revealSelection",
+ "layer.layerMask.hideSelection",
+ "layer.layerMask.fromTransparency",
+];
+
/// The New Document dialog's key in the preferences' `dialogs` map.
const NEW_DOCUMENT: &str = "file.new";
@@ -2038,6 +2061,49 @@ mod clipboard_tests {
assert!((mask.value(32, 32) - 128.0 / 255.0).abs() < 2.0 / 255.0, "the grey, centred in the view: {}", mask.value(32, 32));
assert_eq!(mask.value(0, 0), 0.0, "the rest of the mask is unchanged");
}
+
+ /// #2166, measured in Photoshop 25.1: adding a layer mask targets it with white/black, and
+ /// the pixels and the mask each keep their own foreground/background pair.
+ #[test]
+ fn targeting_a_mask_swaps_to_its_own_colour_pair() {
+ use serde_json::json;
+ const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
+ const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
+ const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
+ const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
+ const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
+ let mut app = PhotocraftApp::new(Session::new(), Services::default());
+ app.run("file.new", json!({"width": 32, "height": 32})).unwrap();
+ let masked = app.run("layer.new.layer", json!({})).unwrap()["layer"].clone();
+ app.run("tools.setColors", json!({"foreground": "#ff0000", "background": "#0000ff"})).unwrap();
+ let pair = |app: &PhotocraftApp| (app.session.tools.foreground, app.session.tools.background);
+ let target = |app: &mut PhotocraftApp, mask: bool| {
+ app.ui.mask_target = mask;
+ app.sync_views();
+ };
+ app.run("layer.layerMask.revealAll", json!({})).unwrap();
+ assert!(app.ui.mask_target, "the new mask is targeted");
+ assert_eq!(pair(&app), (WHITE, BLACK));
+ target(&mut app, false);
+ assert_eq!(pair(&app), (RED, BLUE), "the pixels get their colours back");
+ target(&mut app, true);
+ assert_eq!(pair(&app), (WHITE, BLACK));
+ target(&mut app, false);
+ app.run("tools.setColors", json!({"foreground": "#00ff00"})).unwrap();
+ target(&mut app, true);
+ assert_eq!(pair(&app), (WHITE, BLACK));
+ target(&mut app, false);
+ assert_eq!(pair(&app), (GREEN, BLUE));
+ // A layer without a mask edits its pixels: their pair.
+ target(&mut app, true);
+ app.run("layer.new.layer", json!({})).unwrap();
+ assert_eq!(pair(&app), (GREEN, BLUE));
+ app.run("layer.select", json!({"layer": masked})).unwrap();
+ target(&mut app, true);
+ assert_eq!(pair(&app), (WHITE, BLACK));
+ app.run("layer.layerMask.delete", json!({})).unwrap();
+ assert_eq!(pair(&app), (GREEN, BLUE), "deleting the targeted mask goes back to the pixels");
+ }
}
#[cfg(test)]
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 068d6c9f5..6ec63f554 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -37,7 +37,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- `engine.execute {command, params}`: run any engine or UI command by id. Engine commands run directly with their default params and never open a dialog. Use `ui.menu.invoke` for menu-click behaviour, which opens a command's dialog when no params are given. `params` must be a JSON object (omit it or pass `null` for none); an array, string, number or boolean is an error naming the command, in every transport (control channel, `serve`, MCP and the CLI)
- `engine.commands`: list commands with enablement
- `ui.inspect`: full UI state (tool, panels, views, dialogs, windows, window size). The menu tree is not included; use `ui.menu.list`. `brushPicker` is `null` while closed and `{pos: [x, y], list: {collapsed, filter, view, renaming}}` while the Brush Preset picker is open (coordinates in screen points). `view` holds the View/Window/Type preferences: `screen_mode`, `extras`, `show` and `snap_to` flags, `flip_horizontal`, `arrange` (Window › Arrange layout), pixel aspect, font preview size, language options. `perf.timings.gpuInfo` holds the graphics adapter, backend, driver, the backend chosen at launch and why, the canvas renderer (`gpu`/`cpu`) and, after a device loss, `lost` (`help.systemInfo` returns the same as `info`)
-- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, rotation?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerView?, gradientBlendMode?, gradientClassic?}`: change UI state; any other field is an error, checked before anything changes (`zoom` is the canvas zoom where 1 = 100%, one document pixel per physical display pixel, so a scaled display doesn't magnify the image; `theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `brushesView` and `brushPickerView` are `list` or `grid` for the Brushes panel and the Brush Preset picker; `brushPicker` is `[x, y]` in screen points to open the Brush Preset picker there (as a right-click with a painting tool does) or `null` to close it, and picking a preset in it is `tools.setBrush {"preset": name}`; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"]}`, the right-dock groups top to bottom, their heights in points and the groups collapsed to their tab strip; `dockWidth` sets the right dock width in points, clamped to 250..520; `colorPanel` is `{background}`, whether the Color panel edits the background colour)
+- `ui.set {tool?, panels?, dockTabs?, dock?, dockWidth?, colorPanel?, maskTarget?, vectorMaskTarget?, selectionMode?, zoom?, center?, rotation?, fit?, theme?, brushSize?, brushSection?, brushTab?, brushesView?, brushPicker?, brushPickerView?, gradientBlendMode?, gradientClassic?}`: change UI state; any other field is an error, checked before anything changes (`zoom` is the canvas zoom where 1 = 100%, one document pixel per physical display pixel, so a scaled display doesn't magnify the image; `theme` is `pro`, `proMedium`, `studio`, `studioLight` or `classic`; `selectionMode` is the selection tools' options-bar mode, 0 New, 1 Add, 2 Subtract, 3 Intersect; `brushSection` indexes the Brush Settings sections, `brushTab` 0 = Brush Settings, 1 = Brushes; `brushesView` and `brushPickerView` are `list` or `grid` for the Brushes panel and the Brush Preset picker; `brushPicker` is `[x, y]` in screen points to open the Brush Preset picker there (as a right-click with a painting tool does) or `null` to close it, and picking a preset in it is `tools.setBrush {"preset": name}`; `dock` is `{order: ["layers", …], heights: {"properties": 180}, collapsed: ["color"]}`, the right-dock groups top to bottom, their heights in points and the groups collapsed to their tab strip; `dockWidth` sets the right dock width in points, clamped to 250..520; `colorPanel` is `{background}`, whether the Color panel edits the background colour; `maskTarget` targets the active layer's mask, which, like Photoshop, swaps in the foreground/background pair kept for masks (white/black until one is picked) and swaps the pixels' pair back when the pixels are targeted again)
- `typeTransform` is `null` outside a temporary Ctrl/Cmd Type-tool drag. During a drag it reports its source document/revision, original affine, oriented `frame` (layer, local bounds, document-space corners and pivot), and captured `gesture`. Drive it with `ui.pointer` and `command: true` at `down`; `move`/`up` may release the modifier. The document/history remain unchanged during preview, and `up` applies one `type.edit` within `textEdit`'s session. Pressing Escape during the drag cancels only the preview. This pointer state is never restored from saved UI state.
- `ui.menu.invoke {id, params?, wait?}` / `ui.menu.list`: activate a menu item by id; list the menu tree. A menu item that starts a background job (a filter without a dialog, such as Blur More) replies with the job's result once it has been applied; with `"wait": false` the reply is `{job, pending: true}` at once
- `ui.set` also accepts `gradientBlendMode` (a layer blend mode name, such as `Difference`) and `gradientClassic` (boolean) for the Gradient tool options bar.