Skip to content

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

Stamp Visible (Cmd+Alt+Shift+E) and Stamp Down; Alt+Merge keeps the originals (#217) (#356) (#356)

Brandon Thomas90a46d3f8914
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 8be97f207..79fff5b2d 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -962,6 +962,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::prefs::specs());
v.extend(crate::edit_menu_cmds::specs());
v.extend(crate::fill_key_cmds::specs());
+ v.extend(crate::stamp_cmds::specs());
v.extend(crate::align_cmds::specs());
v.extend(crate::photo_cmds::specs());
v.extend(crate::lens_cmds::specs());
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index dbbe92ac1..6143ad366 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -69,6 +69,7 @@ pub mod slice_cmds;
pub mod smart_cmds;
pub mod smartselect_cmds;
pub mod snap;
+pub mod stamp_cmds;
mod timeline_cmds;
pub mod transform_cmds;
mod trap_cmds;
diff --git a/crates/engine/src/stamp_cmds.rs b/crates/engine/src/stamp_cmds.rs
new file mode 100644
index 000000000..918c249c3
--- /dev/null
+++ b/crates/engine/src/stamp_cmds.rs
@@ -0,0 +1,356 @@
+//! Stamping (#217): merge layers into a layer while keeping the originals.
+//!
+//! - **Stamp Visible** (⌘⌥⇧E, or ⌥ + Layer › Merge Visible): every visible layer composited into a
+//! new layer above the active one.
+//! - **Stamp Down** (⌘⌥E, or ⌥ + Layer › Merge Down): a copy of the active layer merged into the
+//! pixel layer below it; with several layers selected, a copy of them merged into a new layer
+//! above the top one.
+//!
+//! Photoshop has no menu items for these (they are the ⌥ variants of the merge commands), so they
+//! are commands with default shortcuts: rebindable in Edit › Keyboard Shortcuts (Layer), recorded
+//! in actions and drivable by agents. The composite is rendered in bands
+//! ([`photocraft_compose::flatten_to_surface`]), so no full-size float copy of a large document is
+//! held, and tiles left fully transparent are pruned.
+
+use photocraft_color::PixelFormat;
+use photocraft_doc::{Document, Layer, LayerContent, LayerId};
+use serde_json::{Value, json};
+
+use crate::commands::CommandSpec;
+use crate::{EngineError, Result, Session};
+
+fn has_doc(s: &Session) -> std::result::Result<(), String> {
+ s.active().map(|_| ()).ok_or_else(|| "no document".into())
+}
+
+fn has_layer(s: &Session) -> std::result::Result<(), String> {
+ let st = s.active().ok_or("no document")?;
+ st.active_layer.filter(|id| st.doc.layer(*id).is_some()).map(|_| ()).ok_or_else(|| "no active layer".into())
+}
+
+fn object(p: &Value, cmd: &str) -> Result<()> {
+ match p {
+ Value::Object(_) | Value::Null => Ok(()),
+ _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: "expected an object".into() }),
+ }
+}
+
+/// The document's pixel format with an alpha channel (a stamp has transparency).
+fn with_alpha(doc: &Document) -> PixelFormat {
+ let f = doc.pixel_format();
+ PixelFormat::new(f.mode, f.sample, true)
+}
+
+/// A new pixel layer holding the composite of `doc`'s visible layers, rendered in bands.
+fn stamp_layer(doc: &Document, name: String) -> Result<Layer> {
+ let fmt = with_alpha(doc);
+ let mut layer = Layer::raster(name, fmt);
+ *crate::pixels_mut(&mut layer)? = photocraft_compose::flatten_to_surface(doc, fmt, None);
+ Ok(layer)
+}
+
+/// Make `id` the only selected layer and the active one.
+fn select_only(s: &mut Session, id: LayerId) {
+ if let Some(st) = s.active_mut() {
+ st.selected_layers = vec![id];
+ st.active_layer = Some(id);
+ st.layer_anchor = Some(id);
+ crate::fix_selection(st);
+ }
+}
+
+fn stamp_visible(s: &mut Session, p: &Value) -> Result<Value> {
+ object(p, "layer.stampVisible")?;
+ let id = s.edit("Stamp Visible", |doc, active| {
+ if !doc.walk().iter().any(|(path, _, l)| !l.is_group() && (1..=path.len()).all(|n| doc.layer_at(&path[..n]).is_some_and(|a| a.visible))) {
+ return Err(EngineError::Other("there are no visible layers to stamp".into()));
+ }
+ let layer = stamp_layer(doc, doc.next_layer_name("Layer"))?;
+ let id = doc.insert_above(*active, layer);
+ *active = Some(id);
+ Ok(id)
+ })?;
+ select_only(s, id);
+ Ok(json!({ "layer": id.0 }))
+}
+
+fn stamp_down(s: &mut Session, p: &Value) -> Result<Value> {
+ object(p, "layer.stampDown")?;
+ let sel = crate::layer_multi_cmds::selected(s);
+ if sel.len() >= 2 {
+ return stamp_selected(s, &sel);
+ }
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let id = st.active_layer.ok_or_else(|| EngineError::Other("no active layer".into()))?;
+ s.edit("Stamp Down", |doc, _| {
+ let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?;
+ let Some((&idx, parent)) = path.split_last() else { return Err(EngineError::NoLayer(id)) };
+ let below_idx = idx.checked_sub(1).ok_or_else(|| EngineError::Other("there is no layer below to stamp into".into()))?;
+ let mut below = parent.to_vec();
+ below.push(below_idx);
+ let lower = doc.layer_at(&below).ok_or(EngineError::NoLayer(id))?.clone();
+ let upper = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone();
+ if !matches!(lower.content, LayerContent::Raster(_)) {
+ return Err(EngineError::Other("the layer below is not a pixel layer".into()));
+ }
+ if lower.locks.all || lower.locks.pixels {
+ return Err(EngineError::Other("the layer below is locked".into()));
+ }
+ if !upper.visible {
+ return Err(EngineError::Other("the layer is hidden".into()));
+ }
+ // The two layers on their own, composited in bands; the lower one keeps its id, name and
+ // blend mode, as Merge Down does.
+ let mut tmp = doc.clone();
+ let mut base = lower.clone();
+ base.visible = true;
+ tmp.layers = vec![base, upper];
+ let fmt = doc.pixel_format();
+ let fmt = if lower.locks.transparency { fmt } else { PixelFormat::new(fmt.mode, fmt.sample, true) };
+ let surf = photocraft_compose::flatten_to_surface(&tmp, fmt, None);
+ let mut merged = Layer::new(lower.name.clone(), LayerContent::Raster(surf));
+ merged.id = lower.id;
+ merged.blend = lower.blend;
+ merged.visible = lower.visible;
+ merged.locks = lower.locks;
+ merged.opacity = 1.0;
+ *doc.layer_at_mut(&below).ok_or(EngineError::NoLayer(lower.id))? = merged;
+ Ok(())
+ })?;
+ Ok(json!({ "layer": id.0 }))
+}
+
+/// Several layers selected: a copy of them merged into a new layer above the top one.
+fn stamp_selected(s: &mut Session, sel: &[LayerId]) -> Result<Value> {
+ let id = s.edit("Stamp Layers", |doc, active| {
+ let ids = crate::layer_multi_cmds::top_level(doc, sel);
+ let top = *ids.last().ok_or_else(|| EngineError::Other("no layers selected".into()))?;
+ let mut solo = doc.clone();
+ solo.layers = ids.iter().filter_map(|id| doc.layer(*id)).filter(|l| l.visible).cloned().collect();
+ if solo.layers.is_empty() {
+ return Err(EngineError::Other("the selected layers are all hidden".into()));
+ }
+ let name = format!("{} (merged)", doc.layer(top).map_or("Layer", |l| l.name.as_str()));
+ let layer = stamp_layer(&solo, name)?;
+ let id = doc.insert_above(Some(top), layer);
+ *active = Some(id);
+ Ok(id)
+ })?;
+ select_only(s, id);
+ Ok(json!({ "layer": id.0 }))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ CommandSpec {
+ id: "layer.stampVisible",
+ label: "Stamp Visible",
+ menu: &[],
+ shortcut: Some("Cmd+Alt+Shift+E"),
+ params: r##"{} → {layer} (every visible layer merged into a new layer above the active one; the originals stay)"##,
+ enabled: has_doc,
+ journal: true,
+ run: stamp_visible,
+ },
+ CommandSpec {
+ id: "layer.stampDown",
+ label: "Stamp Down",
+ menu: &[],
+ shortcut: Some("Cmd+Alt+E"),
+ params: r##"{} → {layer} (a copy of the active layer merged into the pixel layer below; several selected: into a new layer above them)"##,
+ enabled: has_layer,
+ journal: true,
+ run: stamp_down,
+ },
+ ]
+}
+
+/// The ⌥ variant of a Layer menu merge command (⌥ + Merge Down / Merge Visible / Merge Layers).
+pub fn alt_variant(id: &str) -> Option<&'static str> {
+ match id {
+ "layer.mergeVisible" => Some("layer.stampVisible"),
+ "layer.mergeDown" | "layer.mergeLayers" => Some("layer.stampDown"),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// 64 × 64 at `depth`: a red Background, a blue square (16..48) on "Blue", and "Hidden" (green
+ /// all over, hidden). The Blue layer is active.
+ fn session(depth: u32) -> (Session, LayerId, LayerId, LayerId) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth, "background": "#ff0000"})).unwrap();
+ let bg = s.active().unwrap().doc.layers[0].id;
+ s.execute("layer.new.layer", json!({"name": "Hidden"})).unwrap();
+ s.execute("edit.fill", json!({"color": "#00ff00"})).unwrap();
+ let hidden = s.active().unwrap().active_layer.unwrap();
+ s.execute("layer.setProps", json!({"layer": hidden.0, "visible": false})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "Blue"})).unwrap();
+ s.execute("select.rect", json!({"x": 16, "y": 16, "width": 32, "height": 32})).unwrap();
+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ let blue = s.active().unwrap().active_layer.unwrap();
+ (s, bg, hidden, blue)
+ }
+
+ fn rgba(s: &Session, id: LayerId, x: i32, y: i32) -> [f32; 4] {
+ s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().rgba(x, y)
+ }
+
+ fn ids(s: &Session) -> Vec<LayerId> {
+ s.active().unwrap().doc.walk().iter().map(|(_, _, l)| l.id).collect()
+ }
+
+ fn close(a: [f32; 4], b: [f32; 4]) -> bool {
+ a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3)
+ }
+
+ #[test]
+ fn stamp_visible_adds_the_composite_above_the_active_layer() {
+ for depth in [8, 16, 32] {
+ let (mut s, bg, hidden, blue) = session(depth);
+ let before = ids(&s);
+ let r = s.execute("layer.stampVisible", json!({})).unwrap();
+ let id = LayerId(r["layer"].as_u64().unwrap());
+ // The originals stay; the stamp sits right above the active layer and is selected.
+ assert_eq!(ids(&s), [bg, hidden, blue, id], "{depth}-bit");
+ let st = s.active().unwrap();
+ assert_eq!(st.active_layer, Some(id));
+ assert_eq!(st.selected_layers, vec![id]);
+ let l = st.doc.layer(id).unwrap();
+ assert!(l.visible && matches!(l.content, LayerContent::Raster(_)));
+ assert!(l.name.starts_with("Layer "), "{}", l.name);
+ assert!(l.surface().unwrap().format().alpha);
+ // The visible composite: blue square on red; the hidden green layer is left out.
+ assert!(close(rgba(&s, id, 30, 30), [0.0, 0.0, 1.0, 1.0]), "{depth}: {:?}", rgba(&s, id, 30, 30));
+ assert!(close(rgba(&s, id, 2, 2), [1.0, 0.0, 0.0, 1.0]));
+ assert!(close(rgba(&s, blue, 2, 2), [0.0, 0.0, 0.0, 0.0]), "Blue is untouched");
+ // One undo step.
+ s.undo();
+ assert_eq!(ids(&s), before);
+ }
+ }
+
+ #[test]
+ fn stamp_visible_respects_opacity_blend_and_groups() {
+ let (mut s, bg, _, blue) = session(8);
+ s.execute("layer.setProps", json!({"layer": blue.0, "opacity": 0.5})).unwrap();
+ s.execute("layer.groupLayers", json!({"name": "G"})).unwrap();
+ // The active layer is in a group: the stamp goes into the group, above it.
+ s.execute("layer.select", json!({"layer": blue.0})).unwrap();
+ let id = LayerId(s.execute("layer.stampVisible", json!({})).unwrap()["layer"].as_u64().unwrap());
+ let doc = &s.active().unwrap().doc;
+ let path = doc.path_of(id).unwrap();
+ assert_eq!(path.len(), 2, "inside the group");
+ assert_eq!(doc.path_of(blue).unwrap().last().map(|i| i + 1), path.last().copied());
+ let p = rgba(&s, id, 30, 30);
+ assert!((p[0] - 0.5).abs() < 0.02 && (p[2] - 0.5).abs() < 0.02 && p[3] > 0.99, "50 % blue over red: {p:?}");
+ assert!(doc.layer(bg).is_some());
+ }
+
+ #[test]
+ fn stamp_visible_fails_gracefully() {
+ let mut s = Session::new();
+ assert!(s.execute("layer.stampVisible", json!({})).is_err(), "no document");
+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
+ let bg = s.active().unwrap().doc.layers[0].id;
+ s.execute("layer.setProps", json!({"layer": bg.0, "visible": false})).unwrap();
+ let rev = s.active().unwrap().revision;
+ assert!(s.execute("layer.stampVisible", json!({})).is_err(), "nothing visible");
+ assert_eq!(s.active().unwrap().revision, rev, "no change");
+ s.execute("layer.setProps", json!({"layer": bg.0, "visible": true})).unwrap();
+ for bad in [json!([1, 2]), json!("x"), json!(3)] {
+ assert!(s.execute("layer.stampVisible", bad.clone()).is_err(), "{bad}");
+ assert!(s.execute("layer.stampDown", bad).is_err());
+ }
+ assert!(s.execute("layer.stampVisible", Value::Null).is_ok());
+ }
+
+ #[test]
+ fn stamp_down_merges_a_copy_into_the_layer_below() {
+ let (mut s, bg, hidden, blue) = session(16);
+ // Blue is above Hidden (hidden): stamp into a visible pixel layer instead.
+ s.execute("layer.setProps", json!({"layer": hidden.0, "visible": true})).unwrap();
+ s.execute("layer.stampDown", json!({})).unwrap();
+ assert_eq!(ids(&s), [bg, hidden, blue], "no layer added or removed");
+ assert!(close(rgba(&s, hidden, 30, 30), [0.0, 0.0, 1.0, 1.0]), "the blue square was stamped into Hidden");
+ assert!(close(rgba(&s, hidden, 2, 2), [0.0, 1.0, 0.0, 1.0]));
+ assert!(close(rgba(&s, blue, 30, 30), [0.0, 0.0, 1.0, 1.0]), "Blue stays");
+ assert_eq!(s.active().unwrap().active_layer, Some(blue));
+ s.undo();
+ assert!(close(rgba(&s, hidden, 30, 30), [0.0, 1.0, 0.0, 1.0]));
+ }
+
+ #[test]
+ fn stamp_down_refuses_what_it_cannot_do() {
+ let (mut s, bg, hidden, blue) = session(8);
+ let rev = s.active().unwrap().revision;
+ // The bottom layer has nothing below.
+ s.execute("layer.select", json!({"layer": bg.0})).unwrap();
+ assert!(s.execute("layer.stampDown", json!({})).is_err());
+ // A locked layer below.
+ s.execute("layer.select", json!({"layer": blue.0})).unwrap();
+ s.execute("layer.setProps", json!({"layer": hidden.0, "locks": {"pixels": true}})).unwrap();
+ assert!(s.execute("layer.stampDown", json!({})).is_err());
+ s.execute("layer.setProps", json!({"layer": hidden.0, "locks": {"pixels": false}})).unwrap();
+ // A hidden active layer.
+ s.execute("layer.setProps", json!({"layer": blue.0, "visible": false})).unwrap();
+ assert!(s.execute("layer.stampDown", json!({})).is_err());
+ s.execute("layer.setProps", json!({"layer": blue.0, "visible": true})).unwrap();
+ // A fill layer below is not a pixel layer.
+ s.execute("layer.select", json!({"layer": hidden.0})).unwrap();
+ s.execute("layer.newFillLayer.solidColor", json!({"color": "#ffffff"})).unwrap();
+ s.execute("layer.select", json!({"layer": blue.0})).unwrap();
+ assert!(s.execute("layer.stampDown", json!({})).is_err());
+ assert!(s.active().unwrap().revision > rev);
+ let mut empty = Session::new();
+ assert!(empty.execute("layer.stampDown", json!({})).is_err(), "no document");
+ }
+
+ #[test]
+ fn stamp_with_several_layers_selected_makes_a_new_layer() {
+ let (mut s, bg, hidden, blue) = session(8);
+ s.execute("layer.setProps", json!({"layer": hidden.0, "visible": true})).unwrap();
+ s.execute("layer.select", json!({"layer": hidden.0})).unwrap();
+ s.execute("layer.select", json!({"layer": blue.0, "mode": "add"})).unwrap();
+ let id = LayerId(s.execute("layer.stampDown", json!({})).unwrap()["layer"].as_u64().unwrap());
+ assert_eq!(ids(&s), [bg, hidden, blue, id]);
+ assert!(close(rgba(&s, id, 30, 30), [0.0, 0.0, 1.0, 1.0]));
+ assert!(close(rgba(&s, id, 2, 2), [0.0, 1.0, 0.0, 1.0]), "only the selected layers, not the red Background");
+ assert_eq!(s.active().unwrap().doc.layer(id).unwrap().name, "Blue (merged)");
+ }
+
+ #[test]
+ fn shortcuts_are_photoshops_and_rebindable() {
+ let spec = |id: &str| crate::commands::find(id).unwrap();
+ assert_eq!(spec("layer.stampVisible").shortcut, Some("Cmd+Alt+Shift+E"));
+ assert_eq!(spec("layer.stampDown").shortcut, Some("Cmd+Alt+E"));
+ let mut s = Session::new();
+ s.execute("edit.keyboardShortcuts", json!({"set": {"layer.stampVisible": "F7"}})).unwrap();
+ assert_eq!(s.prefs().shortcut("layer.stampVisible", Some("Cmd+Alt+Shift+E")), Some("F7"));
+ assert_eq!(alt_variant("layer.mergeVisible"), Some("layer.stampVisible"));
+ assert_eq!(alt_variant("layer.mergeDown"), Some("layer.stampDown"));
+ assert_eq!(alt_variant("layer.flattenImage"), None);
+ }
+
+ /// Release timing and peak memory of a 24 MP Stamp Visible:
+ /// `cargo test --release -p photocraft-engine --lib stamp_visible_24mp -- --ignored --nocapture`
+ #[test]
+ #[ignore]
+ fn stamp_visible_24mp() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 6000, "height": 4000})).unwrap();
+ for k in 0..3 {
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 500 * k, "y": 400 * k, "width": 3000, "height": 2000})).unwrap();
+ s.execute("edit.fill", json!({"color": [0.2 * k as f32, 0.5, 0.8, 1.0]})).unwrap();
+ }
+ s.execute("select.deselect", json!({})).unwrap();
+ let t = std::time::Instant::now();
+ s.execute("layer.stampVisible", json!({})).unwrap();
+ println!("stampVisible 6000x4000, 4 layers: {:.0} ms", t.elapsed().as_secs_f64() * 1000.0);
+ }
+}
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 973dce0ed..51b3028ac 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -349,6 +349,8 @@
Merge Layers Sloučit vrstvy
Merge Down Sloučit dolů
Merge Visible Sloučit viditelné
+ Stamp Visible Otisknout viditelné
+ Stamp Down Otisknout dolů
Flatten Image Sloučit do jedné vrstvy
Matting Začištění okrajů
Color Decontaminate… Odstranit barevný lem…
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 3c1a920dd..391b446a9 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -341,6 +341,8 @@
Merge Layers Combinar capas
Merge Down Combinar hacia abajo
Merge Visible Combinar visibles
+ Stamp Visible Estampar visibles
+ Stamp Down Estampar hacia abajo
Flatten Image Acoplar imagen
Matting Matizado
Color Decontaminate… Descontaminar color…
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 641e3255a..4a5959140 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -345,6 +345,8 @@
Merge Layers レイヤーを結合
Merge Down 下のレイヤーと結合
Merge Visible 表示レイヤーを結合
+ Stamp Visible 表示レイヤーをスタンプ
+ Stamp Down 下のレイヤーにスタンプ
Flatten Image 画像を統合
Matting マット処理
Color Decontaminate… カラーの混入を除去…
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index d1dcab58d..45f9f3610 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -1758,6 +1758,8 @@
Merge Layers Объединить слои
Merge Shape Components Объединить компоненты фигуры
Merge Visible Свести видимые
+ Stamp Visible Штамп видимых
+ Stamp Down Штамп вниз
Mesh Сетка
Middle Eastern & South Asian Composer Компоновка для Ближнего Востока и Южной Азии
Modifier Keys Клавиши-модификаторы
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 74e5b341c..ceb5ce342 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -344,6 +344,8 @@
Merge Layers 合并图层
Merge Down 向下合并
Merge Visible 合并可见图层
+ Stamp Visible 盖印可见图层
+ Stamp Down 向下盖印
Flatten Image 拼合图像
Matting 修边
Color Decontaminate… 净化颜色…
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 44f840209..e6d456926 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -349,6 +349,8 @@
Merge Layers 合併圖層
Merge Down 向下合併圖層
Merge Visible 合併可見圖層
+ Stamp Visible 蓋印可見圖層
+ Stamp Down 向下蓋印
Flatten Image 影像平面化
Matting 修邊
Color Decontaminate… 淨化顏色…
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 00871e3f0..000e9a91c 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -1241,6 +1241,9 @@ mod move_auto_select_tests;
#[cfg(test)]
mod marquee_tests;
+#[cfg(test)]
+mod stamp_tests;
+
#[cfg(test)]
mod clipboard_tests {
use super::*;
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index be3fe7983..35fb6fd46 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -757,7 +757,10 @@ pub fn menu_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> f32 {
nav.store(ui.ctx());
if let Some(id) = clicked {
let ctx = ui.ctx().clone();
- let _ = invoke(app, &ctx, &id, json!({}));
+ let id = alt_click(id, ctx.input(|i| i.modifiers.alt));
+ if let Err(e) = invoke(app, &ctx, &id, json!({})) {
+ app.ui.status = e;
+ }
}
right
}
@@ -868,6 +871,15 @@ fn render_level_rows(ui: &mut egui::Ui, items: &[&MenuItem], depth: usize, click
}
}
+/// The command a menu click runs: ⌥ + Merge Down / Merge Layers / Merge Visible keep the
+/// originals, running Stamp Down / Stamp Visible instead (#217).
+pub fn alt_click(id: String, alt: bool) -> String {
+ match photocraft_engine::stamp_cmds::alt_variant(&id) {
+ Some(stamp) if alt => stamp.to_string(),
+ _ => id,
+ }
+}
+
/// Workspace presets (Window → Workspace): which panels are visible.
pub fn apply_workspace(app: &mut PhotocraftApp) {
// Saved workspaces (Window › Workspace › New Workspace…) restore their own layout.
diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs
index 7c5d244e4..8f3ff6a7b 100644
--- a/crates/ui-egui/src/prefs_ui.rs
+++ b/crates/ui-egui/src/prefs_ui.rs
@@ -329,16 +329,23 @@ pub fn shortcut_items(app: &PhotocraftApp) -> Vec<(String, String, Vec<String>,
// temporary tools (#249).
let tools_key = |id: &str| id.starts_with("tools.") || photocraft_engine::fill_key_cmds::IDS.contains(&id);
let mut tools = Vec::new();
+ let mut layer = Vec::new();
for c in photocraft_engine::command_specs() {
if seen.insert(c.id.to_string()) && c.shortcut.is_some() {
let item = (c.id.to_string(), c.label.to_string(), c.menu.iter().map(|s| s.to_string()).collect::<Vec<_>>(), c.shortcut.map(Into::into));
if c.menu.is_empty() && tools_key(c.id) {
tools.push((item.0, item.1, vec!["Tools".to_string()], item.3));
+ } else if c.menu.is_empty() && c.id.starts_with("layer.") {
+ // Stamp Visible / Stamp Down (#217): no menu item in Photoshop; listed at the end
+ // of the Layer section.
+ layer.push((item.0, item.1, vec!["Layer".to_string()], item.3));
} else {
out.push(item);
}
}
}
+ let at = out.iter().rposition(|i| i.2.first().map(String::as_str) == Some("Layer")).map_or(out.len(), |i| i + 1);
+ out.splice(at..at, layer);
out.extend(tools);
for (id, label, def) in prefs::TEMPORARY_TOOLS {
if seen.insert(id.to_string()) {
diff --git a/crates/ui-egui/src/stamp_tests.rs b/crates/ui-egui/src/stamp_tests.rs
new file mode 100644
index 000000000..f45a23e81
--- /dev/null
+++ b/crates/ui-egui/src/stamp_tests.rs
@@ -0,0 +1,121 @@
+//! Stamp Visible / Stamp Down (#217) through the real key handling: the default shortcuts fire,
+//! Edit › Keyboard Shortcuts lists and rebinds them, and ⌥ + the Merge menu items stamp.
+
+use egui::{Event, Key, Modifiers, vec2};
+use egui_kittest::Harness;
+use serde_json::json;
+
+use crate::PhotocraftApp;
+
+fn harness() -> Harness<'static, PhotocraftApp> {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 120, "height": 80})).unwrap();
+ app.run("layer.new.layer", json!({"name": "Paint"})).unwrap();
+ app.run("edit.fill", json!({"color": "#3366cc"})).unwrap();
+ app.sync_views();
+ let mut h = Harness::builder().with_size(vec2(900.0, 600.0)).build_ui_state(
+ |ui, app: &mut PhotocraftApp| {
+ let ctx = ui.ctx().clone();
+ if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
+ return;
+ }
+ crate::shortcuts::handle(app, &ctx);
+ egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));
+ },
+ app,
+ );
+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
+ h.run_steps(4);
+ h
+}
+
+/// ⌘ as the platform reports it (⌘ on the Mac, Ctrl elsewhere).
+fn platform(m: Modifiers) -> Modifiers {
+ let mut out = Modifiers { alt: m.alt, shift: m.shift, ctrl: m.ctrl, ..Default::default() };
+ if m.command {
+ out.command = true;
+ if cfg!(target_os = "macos") {
+ out.mac_cmd = true;
+ } else {
+ out.ctrl = true;
+ }
+ }
+ out
+}
+
+fn tap(h: &mut Harness<'static, PhotocraftApp>, k: Key, m: Modifiers) {
+ let m = platform(m);
+ h.event(Event::ModifiersChanged(m));
+ for pressed in [true, false] {
+ h.event(Event::Key { key: k, physical_key: None, pressed, repeat: false, modifiers: m });
+ h.run_steps(1);
+ }
+ h.event(Event::ModifiersChanged(Modifiers::NONE));
+ h.run_steps(1);
+}
+
+fn layers(h: &Harness<'static, PhotocraftApp>) -> usize {
+ h.state().session.active().unwrap().doc.walk().len()
+}
+
+const STAMP: Modifiers = Modifiers { alt: true, shift: true, command: true, ctrl: false, mac_cmd: false };
+
+#[test]
+fn cmd_alt_shift_e_stamps_visible_and_can_be_rebound() {
+ let mut h = harness();
+ assert_eq!(layers(&h), 2);
+ tap(&mut h, Key::E, STAMP);
+ assert_eq!(layers(&h), 3, "⌘⌥⇧E stamped the visible layers");
+ let top = h.state().session.active().unwrap().doc.layers.last().unwrap().name.clone();
+ assert!(top.starts_with("Layer "), "{top}");
+ // Rebound to F9: the default no longer fires, the new key does.
+ h.state_mut().run("edit.keyboardShortcuts", json!({"set": {"layer.stampVisible": "F9"}})).unwrap();
+ tap(&mut h, Key::E, STAMP);
+ assert_eq!(layers(&h), 3, "the old key is free");
+ tap(&mut h, Key::F9, Modifiers::NONE);
+ assert_eq!(layers(&h), 4);
+}
+
+#[test]
+fn cmd_alt_e_stamps_down() {
+ let mut h = harness();
+ // Stamp Down into the Background: pixels change there, no layer is added.
+ tap(&mut h, Key::E, Modifiers { alt: true, command: true, ..Default::default() });
+ assert_eq!(layers(&h), 2);
+ assert!(h.state().session.journal.iter().any(|(id, _)| id == "layer.stampDown"));
+ let st = h.state().session.active().unwrap();
+ let px = st.doc.layers[0].surface().unwrap().rgba(5, 5);
+ assert!((px[2] - 0.8).abs() < 0.01, "the copy was merged into the Background: {px:?}");
+ // On the Background there is nothing below: a status message, no crash.
+ let bg = h.state().session.active().unwrap().doc.layers[0].id.0;
+ h.state_mut().run("layer.select", json!({"layer": bg})).unwrap();
+ tap(&mut h, Key::E, Modifiers { alt: true, command: true, ..Default::default() });
+ assert!(h.state().ui.status.contains("below"), "{}", h.state().ui.status);
+}
+
+#[test]
+fn keyboard_shortcuts_lists_the_stamps_with_layer() {
+ let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let items = crate::prefs_ui::shortcut_items(&app);
+ let find = |id: &str| items.iter().position(|i| i.0 == id);
+ let (Some(v), Some(d)) = (find("layer.stampVisible"), find("layer.stampDown")) else { panic!("listed") };
+ assert_eq!(items[v].2, ["Layer"]);
+ assert_eq!(items[v].3.as_deref(), Some("Cmd+Alt+Shift+E"));
+ assert_eq!(items[d].3.as_deref(), Some("Cmd+Alt+E"));
+ // Inside one contiguous Layer section.
+ let is_layer = |i: usize| items[i].2.first().map(String::as_str) == Some("Layer");
+ let first = (0..items.len()).find(|i| is_layer(*i)).unwrap();
+ let last = (0..items.len()).rev().find(|i| is_layer(*i)).unwrap();
+ assert!((first..=last).all(is_layer), "one Layer section");
+ assert!(v <= last && d <= last);
+}
+
+#[test]
+fn alt_click_on_merge_items_stamps() {
+ use crate::menus::alt_click;
+ assert_eq!(alt_click("layer.mergeVisible".into(), true), "layer.stampVisible");
+ assert_eq!(alt_click("layer.mergeDown".into(), true), "layer.stampDown");
+ assert_eq!(alt_click("layer.mergeLayers".into(), true), "layer.stampDown");
+ assert_eq!(alt_click("layer.mergeVisible".into(), false), "layer.mergeVisible");
+ assert_eq!(alt_click("file.open".into(), true), "file.open");
+}