PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Layers: the New Layer dialog (Layer › New › Layer…, ⇧⌘N) (#3104)
Timothy Daly4fe6dc6764e6
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex f9734b57a..70b1385bb 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -525,20 +525,9 @@ fn build() -> Vec<CommandSpec> {"Layer…",["Layer", "New"],Some("Cmd+Shift+N"),- r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway)}"##,+ r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error)}"##,has_doc,- |s, p| {- let clip = p.get("clipToPrevious").and_then(Value::as_bool).unwrap_or(false);- let id = s.edit("New Layer", |doc, active| {- let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| doc.next_layer_name("Layer"));- let id = doc.insert_above(*active, Layer::raster(name, doc.pixel_format()));- crate::clip_group::settle(doc, &[id], &Default::default(), clip);- *active = Some(id);- Ok(id)- })?;- crate::layer_multi_cmds::note_inert_insert(s, id);- Ok(json!({ "layer": id.0 }))- }+ crate::new_layer::run),cmd!("layer.new.group", "Group…", ["Layer", "New"], None, r##"{"name":str?}"##, has_doc, |s, p| {let id = s.edit("New Group", |doc, active| {diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex a7d1e6226..29ea119e1 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -71,6 +71,7 @@ pub mod mask_view_cmds;mod migrate_cmds;pub mod mode_cmds;pub mod multichannel_cmds;+pub mod new_layer;pub mod notes_cmds;pub mod paint_cmds;mod path_edit_cmds;diff --git a/crates/engine/src/new_layer.rs b/crates/engine/src/new_layer.rsnew file mode 100644index 000000000..ca814e6d4--- /dev/null+++ b/crates/engine/src/new_layer.rs@@ -0,0 +1,186 @@+//! Layer › New › Layer: Photoshop's New Layer options (name, Use Previous Layer to Create Clipping+//! Mask, color label, mode, opacity, and Fill with neutral color), applied in one history step.++use photocraft_doc::{BlendMode, LabelColor, Layer};+use serde_json::{Value, json};++use crate::{EngineError, Result, Session};++const CMD: &str = "layer.new.layer";++fn bad(msg: impl Into<String>) -> EngineError {+ EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }+}++/// The color that leaves everything below unchanged in `mode` (Photoshop's "Fill with+/// Multiply-neutral color (white)"), as RGB, and its name. `None` for modes that have none.+pub fn neutral_color(mode: BlendMode) -> Option<([f32; 3], &'static str)> {+ use BlendMode::*;+ match mode {+ Darken | Multiply | ColorBurn | LinearBurn | DarkerColor | Divide => Some(([1.0; 3], "white")),+ Lighten | Screen | ColorDodge | LinearDodge | LighterColor | Difference | Exclusion | Subtract => Some(([0.0; 3], "black")),+ Overlay | SoftLight | HardLight | VividLight | LinearLight | PinLight => Some(([0.5; 3], "50% gray")),+ _ => None,+ }+}++/// `layer.new.layer`: a pixel layer above the active one, joining the clip group it lands in.+pub fn run(s: &mut Session, p: &Value) -> Result<Value> {+ let flag = |k: &str| match p.get(k) {+ None | Some(Value::Null) => Ok(false),+ Some(v) => v.as_bool().ok_or_else(|| bad(format!("`{k}` must be true or false"))),+ };+ let clip = flag("clipToPrevious")?;+ let fill_neutral = flag("fillNeutral")?;+ let mode = match p.get("mode") {+ None | Some(Value::Null) => BlendMode::Normal,+ Some(v) => {+ let name = v.as_str().ok_or_else(|| bad("`mode` must be a blend mode name"))?;+ crate::commands::blend_from_str(name).filter(|m| *m != BlendMode::PassThrough).ok_or_else(|| bad(format!("unknown layer blend mode `{name}`")))?+ }+ };+ let opacity = match p.get("opacity") {+ None | Some(Value::Null) => 1.0,+ Some(v) => v.as_f64().filter(|o| o.is_finite()).ok_or_else(|| bad("`opacity` must be a number from 0 to 1"))?.clamp(0.0, 1.0) as f32,+ };+ let label = match p.get("color") {+ None | Some(Value::Null) => LabelColor::None,+ Some(v) => v.as_str().and_then(LabelColor::from_id).ok_or_else(|| bad(format!("`color` must be a layer color id, not {v}")))?,+ };+ let neutral =+ if fill_neutral { Some(neutral_color(mode).ok_or_else(|| bad(format!("{} has no neutral color to fill with", mode.label())))?.0) } else { None };+ let name = match p.get("name") {+ None | Some(Value::Null) => None,+ Some(v) => Some(v.as_str().ok_or_else(|| bad("`name` must be a string"))?.to_string()),+ };+ let id = s.edit("New Layer", |doc, active| {+ let name = name.clone().unwrap_or_else(|| doc.next_layer_name("Layer"));+ let mut layer = Layer::raster(name, doc.pixel_format());+ layer.blend = mode;+ layer.opacity = opacity;+ layer.label = label;+ if let Some(rgb) = neutral {+ let bounds = doc.bounds();+ let surface = layer.surface_mut().ok_or_else(|| bad("a new pixel layer has no pixels"))?;+ let px = photocraft_raster::from_rgba(&surface.format(), [rgb[0], rgb[1], rgb[2], 1.0]);+ surface.fill_rect(bounds, &px);+ }+ let id = doc.insert_above(*active, layer);+ crate::clip_group::settle(doc, &[id], &Default::default(), clip);+ *active = Some(id);+ Ok(id)+ })?;+ crate::layer_multi_cmds::note_inert_insert(s, id);+ Ok(json!({ "layer": id.0 }))+}++#[cfg(test)]+mod tests {+ use photocraft_doc::{BlendMode, LabelColor};+ use photocraft_geom::Rect;+ use serde_json::json;++ use super::neutral_color;+ use crate::Session;++ /// A document with a busy Background: every pixel a different colour.+ fn busy(mode: &str, depth: u32) -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 32, "height": 32, "mode": mode, "depth": depth})).unwrap();+ s.edit("busy", |doc, active| {+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();+ let fmt = surf.format();+ for y in 0..32 {+ for x in 0..32 {+ let rgba = [x as f32 / 31.0, y as f32 / 31.0, ((x * 7 + y * 3) % 32) as f32 / 31.0, 1.0];+ surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &photocraft_raster::from_rgba(&fmt, rgba));+ }+ }+ Ok(())+ })+ .unwrap();+ s+ }++ fn max_diff(a: &photocraft_compose::Buffer, b: &photocraft_compose::Buffer) -> f32 {+ a.px.iter().zip(&b.px).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs())).fold(0.0, f32::max)+ }++ /// Fill with neutral color leaves the composite unchanged in every mode that offers it, at+ /// every depth; the wrong neutral (gray for Multiply) does change it.+ #[test]+ fn neutral_fills_leave_the_image_unchanged() {+ for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("gray", 8), ("gray", 16)] {+ let s0 = busy(mode, depth);+ let doc0 = s0.active().unwrap().doc.clone();+ let shown = photocraft_compose::render(&doc0, doc0.bounds());+ for m in BlendMode::LAYER_MODES.into_iter().filter(|m| neutral_color(*m).is_some()) {+ let mut s = busy(mode, depth);+ s.execute("layer.new.layer", json!({"mode": m.label(), "fillNeutral": true})).unwrap();+ let doc = &s.active().unwrap().doc;+ let top = doc.layers.last().unwrap();+ assert_eq!(top.blend, m);+ assert!(top.surface().unwrap().tile_count() > 0, "{m:?} filled");+ let d = max_diff(&photocraft_compose::render(doc, doc.bounds()), &shown);+ // 8-bit stores 50% gray as 128 (0.502), which can move a pixel by one level.+ let tolerance = if depth == 8 { 1.0 / 255.0 + 1e-6 } else { 1e-3 };+ assert!(d <= tolerance, "{mode}/{depth}: {m:?} changed the image by {d}");+ }+ let mut s = busy(mode, depth);+ s.execute("layer.new.layer", json!({"mode": "Multiply"})).unwrap();+ s.execute("edit.fill", json!({"contents": "gray"})).unwrap();+ let doc = &s.active().unwrap().doc;+ assert!(max_diff(&photocraft_compose::render(doc, doc.bounds()), &shown) > 0.1, "{mode}/{depth}: the control changes it");+ }+ for m in [BlendMode::Normal, BlendMode::Dissolve, BlendMode::HardMix, BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity] {+ assert!(neutral_color(m).is_none(), "{m:?}");+ }+ }++ #[test]+ fn options_apply_in_one_step() {+ let mut s = busy("rgb", 8);+ let steps = s.active().unwrap().history.past_len();+ let id =+ s.execute("layer.new.layer", json!({"name": "Shade", "mode": "Overlay", "opacity": 0.4, "color": "blue", "fillNeutral": true})).unwrap()["layer"]+ .as_u64()+ .unwrap();+ let st = s.active().unwrap();+ assert_eq!(st.history.past_len(), steps + 1);+ let l = st.doc.layer(photocraft_doc::LayerId(id)).unwrap();+ assert_eq!((l.name.as_str(), l.blend, l.opacity, l.label), ("Shade", BlendMode::Overlay, 0.4, LabelColor::Blue));+ assert_eq!(st.active_layer, Some(l.id));+ // Defaults: what the Layers panel button makes.+ s.execute("layer.new.layer", json!({})).unwrap();+ let st = s.active().unwrap();+ let l = st.doc.layers.last().unwrap();+ assert_eq!((l.blend, l.opacity, l.label, l.clipped), (BlendMode::Normal, 1.0, LabelColor::None, false));+ assert_eq!(l.surface().unwrap().tile_count(), 0);+ }++ /// Bad params are errors, never panics, and change nothing.+ #[test]+ fn bad_params_are_errors() {+ let mut s = busy("rgb", 8);+ let n = s.active().unwrap().doc.layers.len();+ for p in [+ json!({"mode": "Pass Through"}),+ json!({"mode": "Sparkle"}),+ json!({"mode": 3}),+ json!({"opacity": "half"}),+ json!({"color": "plaid"}),+ json!({"color": 1}),+ json!({"fillNeutral": true}),+ json!({"fillNeutral": true, "mode": "Hue"}),+ json!({"fillNeutral": "yes"}),+ json!({"clipToPrevious": 1}),+ json!({"name": 7}),+ ] {+ assert!(s.execute("layer.new.layer", p.clone()).is_err(), "{p}");+ }+ assert_eq!(s.active().unwrap().doc.layers.len(), n);+ // Out-of-range opacity is clamped, as layer.setProps does.+ s.execute("layer.new.layer", json!({"opacity": 7})).unwrap();+ assert_eq!(s.active().unwrap().doc.layers.last().unwrap().opacity, 1.0);+ }+}diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 4a83a8f8b..bac46eed9 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -231,6 +231,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields),DialogKind::Command if crate::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields),DialogKind::Command if crate::delete_layer_prompt::owns(&fields) => crate::delete_layer_prompt::body(ui, &mut fields),+ DialogKind::Command if crate::new_layer_ui::owns(&fields) => crate::new_layer_ui::body(ui, &mut fields),DialogKind::Command if crate::rasterize_prompt::owns(&fields) => crate::rasterize_prompt::body(ui, &fields),DialogKind::Command if crate::tool_reset::owns(&fields) => crate::tool_reset::body(ui),DialogKind::Command if crate::crop_presets::owns(&fields) => crate::crop_presets::body(app, ui, &mut fields),@@ -466,6 +467,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields),DialogKind::Command if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields),DialogKind::Command if crate::delete_layer_prompt::owns(&d.fields) => crate::delete_layer_prompt::confirm(app, &d.fields),+ DialogKind::Command if crate::new_layer_ui::owns(&d.fields) => crate::new_layer_ui::confirm(app, &d.fields),DialogKind::Command if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields),DialogKind::Command if crate::tool_reset::owns(&d.fields) => crate::tool_reset::confirm(app),DialogKind::Command if crate::crop_presets::owns(&d.fields) => crate::crop_presets::confirm(app, &d.fields),diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 260a77080..1634eaa51 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -3637,3 +3637,8 @@ navigator Zoom ZvětšeníEmulsion Down Emulze dolůFunctions FunkcePrint Resolution: Rozlišení tisku:+ Use Previous Layer to Create Clipping Mask Použít předchozí vrstvu k vytvoření ořezové masky+ Fill with {mode}-neutral color (white) Vyplnit neutrální barvou pro režim {mode} (bílá)+ Fill with {mode}-neutral color (black) Vyplnit neutrální barvou pro režim {mode} (černá)+ Fill with {mode}-neutral color (50% gray) Vyplnit neutrální barvou pro režim {mode} (50% šedá)+ (No neutral color exists for {mode} mode.) (Pro režim {mode} neexistuje neutrální barva.)diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 1ca2933fe..012f8959f 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2640,3 +2640,8 @@ cameraData Lens ObjektivEmulsion Down Schichtseite untenFunctions FunktionenPrint Resolution: Druckauflösung:+ Use Previous Layer to Create Clipping Mask Vorherige Ebene zum Erstellen einer Schnittmaske verwenden+ Fill with {mode}-neutral color (white) Mit neutraler Farbe für {mode} füllen (Weiß)+ Fill with {mode}-neutral color (black) Mit neutraler Farbe für {mode} füllen (Schwarz)+ Fill with {mode}-neutral color (50% gray) Mit neutraler Farbe für {mode} füllen (50 % Grau)+ (No neutral color exists for {mode} mode.) (Für den Modus {mode} gibt es keine neutrale Farbe.)diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 83de4aaf1..d18e061a7 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -3700,3 +3700,8 @@ cameraData Lens ΦακόςEmulsion Down Γαλάκτωμα προς τα κάτωFunctions ΛειτουργίεςPrint Resolution: Ανάλυση εκτύπωσης:+ Use Previous Layer to Create Clipping Mask Χρήση του προηγούμενου επιπέδου για δημιουργία μάσκας αποκοπής+ Fill with {mode}-neutral color (white) Γέμισμα με το ουδέτερο χρώμα της λειτουργίας {mode} (λευκό)+ Fill with {mode}-neutral color (black) Γέμισμα με το ουδέτερο χρώμα της λειτουργίας {mode} (μαύρο)+ Fill with {mode}-neutral color (50% gray) Γέμισμα με το ουδέτερο χρώμα της λειτουργίας {mode} (50% γκρι)+ (No neutral color exists for {mode} mode.) (Δεν υπάρχει ουδέτερο χρώμα για τη λειτουργία {mode}.)diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 1e596d51b..cd80c6e48 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2681,3 +2681,8 @@ cameraData Lens ObjetivoEmulsion Down Emulsión hacia abajoFunctions FuncionesPrint Resolution: Resolución de impresión:+ Use Previous Layer to Create Clipping Mask Usar la capa anterior para crear una máscara de recorte+ Fill with {mode}-neutral color (white) Rellenar con el color neutro de {mode} (blanco)+ Fill with {mode}-neutral color (black) Rellenar con el color neutro de {mode} (negro)+ Fill with {mode}-neutral color (50% gray) Rellenar con el color neutro de {mode} (gris al 50%)+ (No neutral color exists for {mode} mode.) (No existe un color neutro para el modo {mode}.)diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 628f9717d..eefe78cc0 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -3018,3 +3018,8 @@ cameraData Lens ObjectifEmulsion Down Émulsion versoFunctions FonctionsPrint Resolution: Résolution d’impression :+ Use Previous Layer to Create Clipping Mask Utiliser le calque précédent pour créer un masque de découpe+ Fill with {mode}-neutral color (white) Remplir avec la couleur neutre de {mode} (blanc)+ Fill with {mode}-neutral color (black) Remplir avec la couleur neutre de {mode} (noir)+ Fill with {mode}-neutral color (50% gray) Remplir avec la couleur neutre de {mode} (gris 50 %)+ (No neutral color exists for {mode} mode.) (Il n’existe aucune couleur neutre pour le mode {mode}.)diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 644330f84..5d468d6a1 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -3005,3 +3005,8 @@ cameraData Lens LensaEmulsion Down Emulsi di BawahFunctions FungsiPrint Resolution: Resolusi Cetak:+ Use Previous Layer to Create Clipping Mask Gunakan Layer Sebelumnya untuk Membuat Clipping Mask+ Fill with {mode}-neutral color (white) Isi dengan warna netral {mode} (putih)+ Fill with {mode}-neutral color (black) Isi dengan warna netral {mode} (hitam)+ Fill with {mode}-neutral color (50% gray) Isi dengan warna netral {mode} (abu-abu 50%)+ (No neutral color exists for {mode} mode.) (Tidak ada warna netral untuk mode {mode}.)diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex ef72361be..793206a06 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2672,3 +2672,8 @@ cameraData Lens ObiettivoEmulsion Down Emulsione sottoFunctions FunzioniPrint Resolution: Risoluzione di stampa:+ Use Previous Layer to Create Clipping Mask Usa il livello precedente per creare una maschera di ritaglio+ Fill with {mode}-neutral color (white) Riempi con il colore neutro di {mode} (bianco)+ Fill with {mode}-neutral color (black) Riempi con il colore neutro di {mode} (nero)+ Fill with {mode}-neutral color (50% gray) Riempi con il colore neutro di {mode} (grigio 50%)+ (No neutral color exists for {mode} mode.) (Non esiste un colore neutro per il metodo {mode}.)diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex dbffc5ae4..e595182d9 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3612,3 +3612,8 @@ cameraData Lens レンズEmulsion Down 乳剤面を下Functions 機能Print Resolution: プリント解像度:+ Use Previous Layer to Create Clipping Mask 下のレイヤーを使用してクリッピングマスクを作成+ Fill with {mode}-neutral color (white) {mode} の中間色で塗りつぶす (白)+ Fill with {mode}-neutral color (black) {mode} の中間色で塗りつぶす (黒)+ Fill with {mode}-neutral color (50% gray) {mode} の中間色で塗りつぶす (50% グレー)+ (No neutral color exists for {mode} mode.) ({mode} モードには中間色がありません。)diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 11a3a9631..438fd2fb7 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -3185,3 +3185,8 @@ cameraData Lens 렌즈Emulsion Down 감광면 아래로Functions 기능Print Resolution: 인쇄 해상도:+ Use Previous Layer to Create Clipping Mask 이전 레이어를 사용하여 클리핑 마스크 만들기+ Fill with {mode}-neutral color (white) {mode} 중립 색상으로 채우기(흰색)+ Fill with {mode}-neutral color (black) {mode} 중립 색상으로 채우기(검정)+ Fill with {mode}-neutral color (50% gray) {mode} 중립 색상으로 채우기(50% 회색)+ (No neutral color exists for {mode} mode.) ({mode} 모드에는 중립 색상이 없습니다.)diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex c13a7eef8..e5018286d 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -3762,3 +3762,8 @@ cameraData Lens LensEmulsion Down Emulsie omlaagFunctions FunctiesPrint Resolution: Afdrukresolutie:+ Use Previous Layer to Create Clipping Mask Vorige laag gebruiken om uitknipmasker te maken+ Fill with {mode}-neutral color (white) Vullen met neutrale kleur voor {mode} (wit)+ Fill with {mode}-neutral color (black) Vullen met neutrale kleur voor {mode} (zwart)+ Fill with {mode}-neutral color (50% gray) Vullen met neutrale kleur voor {mode} (50% grijs)+ (No neutral color exists for {mode} mode.) (Voor de modus {mode} bestaat geen neutrale kleur.)diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 066786463..fa529eea9 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3614,3 +3614,8 @@ cameraData Lens ObiektywEmulsion Down Emulsja w dółFunctions FunkcjePrint Resolution: Rozdzielczość druku:+ Use Previous Layer to Create Clipping Mask Użyj poprzedniej warstwy do utworzenia maski przycinającej+ Fill with {mode}-neutral color (white) Wypełnij kolorem neutralnym dla trybu {mode} (biały)+ Fill with {mode}-neutral color (black) Wypełnij kolorem neutralnym dla trybu {mode} (czarny)+ Fill with {mode}-neutral color (50% gray) Wypełnij kolorem neutralnym dla trybu {mode} (50% szarości)+ (No neutral color exists for {mode} mode.) (Dla trybu {mode} nie istnieje kolor neutralny.)diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex b4bc1de6e..de29b7d99 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -3792,3 +3792,8 @@ layerLabel No Color Sem corEmulsion Down Emulsão para baixoFunctions FunçõesPrint Resolution: Resolução de impressão:+ Use Previous Layer to Create Clipping Mask Usar a camada anterior para criar máscara de corte+ Fill with {mode}-neutral color (white) Preencher com a cor neutra de {mode} (branco)+ Fill with {mode}-neutral color (black) Preencher com a cor neutra de {mode} (preto)+ Fill with {mode}-neutral color (50% gray) Preencher com a cor neutra de {mode} (cinza 50%)+ (No neutral color exists for {mode} mode.) (Não existe cor neutra para o modo {mode}.)diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex f830338f4..3c309da99 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2947,3 +2947,8 @@ cameraData Lens ОбъективEmulsion Down Эмульсией внизFunctions ФункцииPrint Resolution: Разрешение печати:+ Use Previous Layer to Create Clipping Mask Использовать предыдущий слой для создания обтравочной маски+ Fill with {mode}-neutral color (white) Залить нейтральным цветом режима «{mode}» (белый)+ Fill with {mode}-neutral color (black) Залить нейтральным цветом режима «{mode}» (черный)+ Fill with {mode}-neutral color (50% gray) Залить нейтральным цветом режима «{mode}» (50% серого)+ (No neutral color exists for {mode} mode.) (Для режима «{mode}» нет нейтрального цвета.)diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex aba87af15..a383d0a65 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -3700,3 +3700,8 @@ cameraData Lens Об'єктивEmulsion Down Емульсією донизуFunctions ФункціїPrint Resolution: Роздільна здатність друку:+ Use Previous Layer to Create Clipping Mask Використати попередній шар для створення відсічної маски+ Fill with {mode}-neutral color (white) Залити нейтральним кольором режиму «{mode}» (білий)+ Fill with {mode}-neutral color (black) Залити нейтральним кольором режиму «{mode}» (чорний)+ Fill with {mode}-neutral color (50% gray) Залити нейтральним кольором режиму «{mode}» (50% сірого)+ (No neutral color exists for {mode} mode.) (Для режиму «{mode}» немає нейтрального кольору.)diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex b537d011c..ea5621c2d 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2620,3 +2620,8 @@ cameraData Lens 镜头Emulsion Down 药膜朝下Functions 功能Print Resolution: 打印分辨率:+ Use Previous Layer to Create Clipping Mask 使用前一图层创建剪贴蒙版+ Fill with {mode}-neutral color (white) 使用{mode}中性色填充(白色)+ Fill with {mode}-neutral color (black) 使用{mode}中性色填充(黑色)+ Fill with {mode}-neutral color (50% gray) 使用{mode}中性色填充(50% 灰色)+ (No neutral color exists for {mode} mode.) ({mode}模式不存在中性色。)diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 5ade20a63..38326b5e8 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2590,3 +2590,8 @@ cameraData Lens 鏡頭Emulsion Down 感光乳劑面朝下Functions 功能Print Resolution: 列印解析度:+ Use Previous Layer to Create Clipping Mask 使用上一個圖層建立剪裁遮色片+ Fill with {mode}-neutral color (white) 使用{mode}中性色填滿(白色)+ Fill with {mode}-neutral color (black) 使用{mode}中性色填滿(黑色)+ Fill with {mode}-neutral color (50% gray) 使用{mode}中性色填滿(50% 灰色)+ (No neutral color exists for {mode} mode.) ({mode}模式沒有中性色。)diff --git a/crates/ui-egui/src/layer_menu_ui.rs b/crates/ui-egui/src/layer_menu_ui.rsindex da0e1608d..10629f254 100644--- a/crates/ui-egui/src/layer_menu_ui.rs+++ b/crates/ui-egui/src/layer_menu_ui.rs@@ -197,7 +197,7 @@ fn items(app: &crate::PhotocraftApp, ui: &mut egui::Ui, l: &Layer, on_set: bool,}}-fn color_name(color: LabelColor) -> &'static str {+pub(crate) fn color_name(color: LabelColor) -> &'static str {crate::i18n::tr_ctx(crate::i18n::current(), "layerLabel", color.label())}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex c5ca87c20..39037dd1c 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -116,6 +116,7 @@ pub mod move_mods;pub mod move_ui;pub mod native_menu;pub mod new_doc_ui;+pub mod new_layer_ui;pub mod notices;mod numeric_expression;mod opacity_keys;@@ -2219,6 +2220,9 @@ mod move_auto_select_tests;#[cfg(test)]mod new_group_button_tests;+#[cfg(test)]+mod new_layer_button_tests;+#[cfg(test)]mod move_outline_tests;diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 509284dd8..c5d63cd5a 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -560,6 +560,8 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:"edit.transform.warpGrid" if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()) && params.get("warp").is_none() => {crate::transform_tool::edit_session_warp(app, id, ¶ms).map(|_| json!({"transform": app.ui.transform}))}+ // Layer › New › Layer… (⇧⌘N) asks first, as in Photoshop; with params it runs as is.+ crate::new_layer_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::new_layer_ui::open(app)?})),sz if crate::sizing::is_sizing(sz) && params.as_object().is_none_or(|o| o.is_empty()) => {Ok(json!({"dialog": crate::sizing::open(app, sz).ok_or("no document")?}))}diff --git a/crates/ui-egui/src/new_layer_button_tests.rs b/crates/ui-egui/src/new_layer_button_tests.rsnew file mode 100644index 000000000..350ab7eba--- /dev/null+++ b/crates/ui-egui/src/new_layer_button_tests.rs@@ -0,0 +1,43 @@+//! The Layers panel New Layer button: a click makes a layer at once, ⌥-click opens the New Layer+//! dialog first, as in Photoshop.++use egui::Modifiers;+use egui_kittest::kittest::Queryable;+use serde_json::json;++use crate::PhotocraftApp;++fn panel() -> egui_kittest::Harness<'static, PhotocraftApp> {+ let mut s = photocraft_engine::Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_max_steps(64).build_eframe(|cc| {+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());+ PhotocraftApp::new(s, crate::Services::default())+ });+ h.run_steps(4);+ h+}++fn layers(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> usize {+ h.state().session.active().unwrap().doc.layers.len()+}++#[test]+fn click_makes_a_layer_without_asking() {+ let mut h = panel();+ h.get_by_label("Create a new layer").click();+ h.run_steps(4);+ assert_eq!(layers(&h), 2);+ assert!(!h.state().ui.dialogs.iter().any(|d| crate::new_layer_ui::owns(&d.fields)));+}++#[test]+fn alt_click_opens_the_new_layer_dialog() {+ let mut h = panel();+ h.get_by_label("Create a new layer").click_modifiers(Modifiers::ALT);+ h.run_steps(4);+ assert_eq!(layers(&h), 1, "nothing made until OK");+ let id = h.state().ui.dialogs.iter().find(|d| crate::new_layer_ui::owns(&d.fields)).map(|d| d.id).expect("the New Layer dialog");+ crate::dialogs::confirm(h.state_mut(), id).unwrap();+ assert_eq!(layers(&h), 2);+}diff --git a/crates/ui-egui/src/new_layer_ui.rs b/crates/ui-egui/src/new_layer_ui.rsnew file mode 100644index 000000000..af051adbb--- /dev/null+++ b/crates/ui-egui/src/new_layer_ui.rs@@ -0,0 +1,215 @@+//! Layer › New › Layer… (⇧⌘N): Photoshop's New Layer dialog. Name, Use Previous Layer to Create+//! Clipping Mask, Color, Mode, Opacity and Fill with neutral color; OK runs `layer.new.layer` with+//! them. The Layers panel's New Layer button makes a layer without asking, and ⌥-click opens the+//! dialog, as in Photoshop.++use photocraft_doc::{BlendMode, LabelColor};+use photocraft_engine::new_layer::neutral_color;+use serde_json::{Map, Value, json};++use crate::PhotocraftApp;+use crate::state::DialogKind;++const MARK: &str = "__newLayer";+pub const COMMAND: &str = "layer.new.layer";++pub fn owns(fields: &Map<String, Value>) -> bool {+ fields.contains_key(MARK)+}++/// Open the dialog for the active document, with the name the layer would get.+pub fn open(app: &mut PhotocraftApp) -> Result<u64, String> {+ let name = app.session.active().ok_or("no document open")?.doc.next_layer_name("Layer");+ let fields = json!({+ MARK: true, "__command": COMMAND, "__label": "New Layer",+ "name": name, "clipToPrevious": false, "color": "none", "mode": "Normal", "opacity": 100.0, "fillNeutral": false,+ });+ Ok(app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap_or_default()))+}++fn mode(f: &Map<String, Value>) -> BlendMode {+ f.get("mode")+ .and_then(Value::as_str)+ .and_then(photocraft_engine::commands::blend_from_str)+ .filter(|m| *m != BlendMode::PassThrough)+ .unwrap_or(BlendMode::Normal)+}++fn flag(f: &Map<String, Value>, k: &str) -> bool {+ f.get(k).and_then(Value::as_bool).unwrap_or(false)+}++/// The `layer.new.layer` params the dialog stands for (opacity is a percentage in the dialog).+pub fn params(f: &Map<String, Value>) -> Value {+ let mode = mode(f);+ let opacity = f.get("opacity").and_then(Value::as_f64).filter(|o| o.is_finite()).unwrap_or(100.0).clamp(0.0, 100.0) / 100.0;+ let mut p = json!({+ "clipToPrevious": flag(f, "clipToPrevious"),+ "color": f.get("color").and_then(Value::as_str).and_then(LabelColor::from_id).unwrap_or_default().id(),+ "mode": mode.label(),+ "opacity": opacity,+ // Only modes with a neutral color can fill with one (the checkbox is off for the others).+ "fillNeutral": flag(f, "fillNeutral") && neutral_color(mode).is_some(),+ });+ // An empty name gets the next "Layer N", as the Layers panel button does.+ if let Some(name) = f.get("name").and_then(Value::as_str).filter(|n| !n.trim().is_empty()) {+ p["name"] = json!(name);+ }+ p+}++/// The neutral-fill checkbox's label for `mode`, or the note that it has none.+pub fn neutral_label(mode: BlendMode) -> String {+ let name = tl!(mode.label());+ match neutral_color(mode) {+ Some((_, "white")) => crate::i18n::fmt(tl!("Fill with {mode}-neutral color (white)"), &[("mode", name)]),+ Some((_, "black")) => crate::i18n::fmt(tl!("Fill with {mode}-neutral color (black)"), &[("mode", name)]),+ Some(_) => crate::i18n::fmt(tl!("Fill with {mode}-neutral color (50% gray)"), &[("mode", name)]),+ None => crate::i18n::fmt(tl!("(No neutral color exists for {mode} mode.)"), &[("mode", name)]),+ }+}++pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {+ let label_width = 64.0;+ let row_label = |ui: &mut egui::Ui, text: &str| {+ ui.allocate_ui_with_layout(egui::vec2(label_width, 22.0), egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(text));+ };+ ui.horizontal(|ui| {+ row_label(ui, tl!("Name:"));+ let mut name = f.get("name").and_then(Value::as_str).unwrap_or("").to_string();+ let field = ui.add(egui::TextEdit::singleline(&mut name).desired_width(260.0));+ if field.changed() {+ f.insert("name".into(), json!(name));+ }+ // Photoshop opens on the name, selected, so typing replaces it.+ if !ui.is_sizing_pass() && !flag(f, "__nameFocused") {+ field.request_focus();+ crate::field_tab::select_all(ui.ctx(), field.id, &name);+ f.insert("__nameFocused".into(), json!(true));+ }+ });+ ui.horizontal(|ui| {+ ui.add_space(label_width + ui.spacing().item_spacing.x);+ let mut clip = flag(f, "clipToPrevious");+ if crate::widgets::checkbox(ui, &mut clip, tl!("Use Previous Layer to Create Clipping Mask")).changed() {+ f.insert("clipToPrevious".into(), json!(clip));+ }+ });+ ui.horizontal(|ui| {+ row_label(ui, tl!("Color:"));+ let mut color = f.get("color").and_then(Value::as_str).and_then(LabelColor::from_id).unwrap_or_default();+ let options: Vec<(LabelColor, &str)> = LabelColor::ALL.into_iter().map(|c| (c, crate::layer_menu_ui::color_name(c))).collect();+ if crate::widgets::dropdown(ui, "new-layer-color", &mut color, &options, 140.0) {+ f.insert("color".into(), json!(color.id()));+ }+ });+ let mut m = mode(f);+ ui.horizontal(|ui| {+ row_label(ui, tl!("Mode:"));+ let options: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.into_iter().map(|m| (m, m.label())).collect();+ if crate::widgets::dropdown(ui, "new-layer-mode", &mut m, &options, 140.0) {+ f.insert("mode".into(), json!(m.label()));+ }+ ui.add_space(8.0);+ ui.label(tl!("Opacity:"));+ let mut o = f.get("opacity").and_then(Value::as_f64).unwrap_or(100.0) as f32;+ if crate::widgets::value_field(ui, &mut o, 0.0..=100.0, "%", 64.0).changed() {+ f.insert("opacity".into(), json!(o.clamp(0.0, 100.0)));+ }+ });+ ui.horizontal(|ui| {+ ui.add_space(label_width + ui.spacing().item_spacing.x);+ let available = neutral_color(m).is_some();+ let mut fill = available && flag(f, "fillNeutral");+ let changed = ui.add_enabled_ui(available, |ui| crate::widgets::checkbox(ui, &mut fill, &neutral_label(m)).changed()).inner;+ if changed {+ f.insert("fillNeutral".into(), json!(fill));+ }+ });+}++pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {+ app.run(COMMAND, params(f))+}++#[cfg(test)]+mod tests {+ use super::*;+ use egui_kittest::kittest::{NodeT, Queryable};++ fn app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 16, "height": 16})).unwrap();+ app+ }++ fn top(app: &PhotocraftApp) -> &photocraft_doc::Layer {+ app.session.active().unwrap().doc.layers.last().unwrap()+ }++ /// The menu (and its shortcut) opens the dialog; OK makes the layer it describes in one step.+ #[test]+ fn menu_opens_the_dialog_and_ok_makes_the_layer() {+ let mut app = app();+ let ctx = egui::Context::default();+ let layers = app.session.active().unwrap().doc.layers.len();+ let r = crate::menus::invoke(&mut app, &ctx, COMMAND, json!({})).unwrap();+ let id = r["dialog"].as_u64().unwrap();+ assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "nothing made until OK");+ let d = app.ui.dialogs.iter_mut().find(|d| d.id == id).unwrap();+ assert_eq!(d.fields["name"], "Layer 1");+ for (k, v) in+ [("name", json!("Dodge & Burn")), ("mode", json!("Overlay")), ("opacity", json!(60.0)), ("color", json!("violet")), ("fillNeutral", json!(true))]+ {+ d.fields.insert(k.into(), v);+ }+ let steps = app.session.active().unwrap().history.past_len();+ crate::dialogs::confirm(&mut app, id).unwrap();+ let l = top(&app);+ assert_eq!((l.name.as_str(), l.blend, l.label), ("Dodge & Burn", BlendMode::Overlay, LabelColor::Violet));+ assert!((l.opacity - 0.6).abs() < 1e-6);+ assert!(l.surface().unwrap().tile_count() > 0, "filled with 50% gray");+ assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1);+ // Params given (automation, Actions): no dialog.+ crate::menus::invoke(&mut app, &ctx, COMMAND, json!({"name": "Direct"})).unwrap();+ assert_eq!(top(&app).name, "Direct");+ }++ #[test]+ fn params_follow_photoshop_rules() {+ let f = json!({MARK: true, "name": " ", "mode": "Hue", "opacity": 250.0, "fillNeutral": true, "color": "plaid", "clipToPrevious": true});+ let p = params(f.as_object().unwrap());+ assert_eq!(p, json!({"clipToPrevious": true, "color": "none", "mode": "Hue", "opacity": 1.0, "fillNeutral": false}));+ assert_eq!(neutral_label(BlendMode::Multiply), "Fill with Multiply-neutral color (white)");+ assert_eq!(neutral_label(BlendMode::Screen), "Fill with Screen-neutral color (black)");+ assert_eq!(neutral_label(BlendMode::SoftLight), "Fill with Soft Light-neutral color (50% gray)");+ assert_eq!(neutral_label(BlendMode::Normal), "(No neutral color exists for Normal mode.)");+ }++ /// The dialog shows Photoshop's controls; the neutral fill is greyed for a mode without one.+ #[test]+ fn the_dialog_shows_its_controls() {+ let mut app = app();+ open(&mut app).unwrap();+ let mut h = egui_kittest::Harness::builder().with_size(egui::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()))) {+ crate::dialogs::show(app, &ctx);+ }+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);+ h.run_steps(4);+ assert!(h.query_by_label("New Layer").is_some());+ assert!(h.query_by_label("Use Previous Layer to Create Clipping Mask").is_some());+ let fill = h.get_by_label("(No neutral color exists for Normal mode.)");+ assert!(fill.accesskit_node().is_disabled());+ assert!(h.query_by_label("OK").is_some() && h.query_by_label("Cancel").is_some());+ // It opens on the name, selected: typing replaces it.+ h.event(egui::Event::Text("Shade".into()));+ h.run_steps(2);+ assert_eq!(h.state().ui.dialogs[0].fields["name"], "Shade");+ }+}diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 47d5019ce..8a4d029fe 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -2294,7 +2294,9 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {trash.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!(label)));let new_layer = icons::button(ui, "square-plus", 26.0, false, &crate::shortcuts::tip_label(app, "Create a new layer", "layer.new.layer"));if new_layer.clicked() {- actions.push(("layer.new.layer".into(), json!({})));+ // A click makes the layer; ⌥-click asks first (the New Layer dialog), as in Photoshop.+ let alt = ui.input(|i| i.modifiers.alt);+ actions.push(("layer.new.layer".into(), if alt { Value::Null } else { json!({}) }));}actions.extend(footer_drop(ui, &new_layer, footer_drag, "layer.duplicate"));let group = icons::button(ui, "folder", 26.0, false, tl!("Create a new group"));