Skip to content

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

Layers: delete targeted masks and edit Solid Color by thumbnail (#1997)

abc2cb23fbfb9b3c0a
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index aa363a34f..69930266c 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -1098,6 +1098,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::color_to_alpha_cmds::specs());
v.extend(crate::gallery_cmds::specs());
v.extend(crate::gradient_fill_cmds::specs());
+ v.extend(crate::solid_fill_cmds::specs());
v.extend(crate::type_cmds::specs());
v.extend(crate::transform_cmds::specs());
v.extend(crate::float_cmds::specs());
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 0eae7347c..c13571199 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -85,6 +85,7 @@ pub mod slice_cmds;
pub mod smart_cmds;
pub mod smartselect_cmds;
pub mod snap;
+pub mod solid_fill_cmds;
pub mod stamp_cmds;
pub mod swatch_cmds;
pub mod symmetry_cmds;
diff --git a/crates/engine/src/solid_fill_cmds.rs b/crates/engine/src/solid_fill_cmds.rs
new file mode 100644
index 000000000..efa43f611
--- /dev/null
+++ b/crates/engine/src/solid_fill_cmds.rs
@@ -0,0 +1,255 @@
+//! Editing a Solid Color Fill is an undoable content edit, independent of its masks.
+
+use photocraft_color::{Color, ColorMode};
+use photocraft_doc::{Fill, LayerContent};
+use serde_json::{Value, json};
+
+use crate::commands::{CommandSpec, check_pixels_unlocked, layer_param};
+use crate::{EngineError, Result, Session};
+
+pub const SET: &str = "layer.fill.solidColor.set";
+
+fn bad(msg: &str) -> EngineError {
+ EngineError::BadParams { cmd: SET.into(), msg: msg.into() }
+}
+
+/// Parse an RGB picker value or a full colour in its stored model. A three-component RGB
+/// value preserves alpha; opening the picker must not make a translucent fill opaque.
+pub fn color_param(value: &Value, original: Color, mode: ColorMode) -> Result<Color> {
+ let color = match value {
+ Value::String(s) => {
+ let h = s.strip_prefix('#').unwrap_or(s);
+ let channel = |i: usize| h.get(i..i + 2).and_then(|v| u8::from_str_radix(v, 16).ok()).map(|v| f32::from(v) / 255.0);
+ if h.len() != 6 && h.len() != 8 {
+ return Err(bad("color must be #rrggbb or #rrggbbaa"));
+ }
+ let (Some(r), Some(g), Some(b)) = (channel(0), channel(2), channel(4)) else { return Err(bad("invalid hexadecimal color")) };
+ let alpha = if h.len() == 8 { channel(6).ok_or_else(|| bad("invalid alpha"))? } else { original.alpha };
+ Color::rgba(r, g, b, alpha).in_mode(mode)
+ }
+ Value::Array(a) if (3..=4).contains(&a.len()) => {
+ let channel = |i: usize| a.get(i).and_then(Value::as_f64).filter(|v| v.is_finite() && (0.0..=1.0).contains(v)).map(|v| v as f32);
+ let (Some(r), Some(g), Some(b)) = (channel(0), channel(1), channel(2)) else {
+ return Err(bad("RGB components must be finite numbers within 0..1"));
+ };
+ let alpha = if a.len() == 4 { channel(3).ok_or_else(|| bad("alpha must be a finite number within 0..1"))? } else { original.alpha };
+ Color::rgba(r, g, b, alpha).in_mode(mode)
+ }
+ Value::Object(_) => serde_json::from_value::<Color>(value.clone()).map_err(|_| bad("invalid stored Color"))?,
+ _ => return Err(bad("color must be hexadecimal RGB, [r,g,b,a?], or a stored Color")),
+ };
+ if !color.c.iter().all(|v| v.is_finite()) || !color.alpha.is_finite() || !(0.0..=1.0).contains(&color.alpha) {
+ return Err(bad("color must be finite and alpha within 0..1"));
+ }
+ Ok(color)
+}
+
+fn set(s: &mut Session, p: &Value) -> Result<Value> {
+ if !p.is_object() || p.get("layer").is_some_and(|v| v.as_u64().is_none()) {
+ return Err(bad("params must be an object and layer an unsigned id"));
+ }
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ if let Some(document) = p.get("document")
+ && document.as_u64() != Some(st.doc.id.0)
+ {
+ return Err(bad("the target document is no longer active"));
+ }
+ let id = layer_param(s, p)?;
+ let layer = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ let LayerContent::Fill(Fill::Solid(original)) = layer.content else { return Err(bad("the target must be a Solid Color Fill layer")) };
+ let color = color_param(p.get("color").ok_or_else(|| bad("color is required"))?, original, st.doc.mode)?;
+ if color != original {
+ check_pixels_unlocked(&st.doc, id)?;
+ if st.doc.effective_locks(id).transparency && color.alpha != original.alpha {
+ return Err(bad("the layer's transparency is locked"));
+ }
+ s.edit("Solid Color", |doc, _| {
+ let layer = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
+ layer.content = LayerContent::Fill(Fill::Solid(color));
+ Ok(())
+ })?;
+ }
+ Ok(json!({"layer": id.0, "color": color}))
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![CommandSpec {
+ id: SET,
+ label: "Solid Color…",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"layer":id? (default active),"document":id? (reject a stale dialog),"color":"#rrggbb"|"#rrggbbaa"|[r,g,b,a?]|{mode,c:[f32;4],alpha:f32}}; RGB values without alpha preserve it; stored Color preserves its model and precision"##,
+ enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()),
+ run: set,
+ journal: true,
+ }]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn edit_preserves_layer_and_masks_at_all_depths_and_undo_redo() {
+ for depth in [8, 16, 32] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 32, "height": 24, "depth": depth})).unwrap();
+ let id = s.execute("layer.newFillLayer.solidColor", json!({"color": "#12345680"})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ s.execute("layer.vectorMask.revealAll", json!({})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let count = s.active().unwrap().history.entries().len();
+ let color = Color { mode: ColorMode::Lab, c: [0.512345, 0.48, 0.6, 0.0], alpha: 0.345678 };
+ s.execute(SET, json!({"layer": id, "color": color})).unwrap();
+ let mut expected = (*before).clone();
+ expected.layer_mut(photocraft_doc::LayerId(id)).unwrap().content = LayerContent::Fill(Fill::Solid(color));
+ assert_eq!(*s.active().unwrap().doc, expected);
+ assert_eq!(s.active().unwrap().history.entries().len(), count + 1);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(*s.active().unwrap().doc, *before);
+ s.execute("edit.redo", json!({})).unwrap();
+ assert_eq!(s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content, LayerContent::Fill(Fill::Solid(color)));
+ let count = s.active().unwrap().history.entries().len();
+ s.execute(SET, json!({"color": color})).unwrap();
+ assert_eq!(s.active().unwrap().history.entries().len(), count, "unchanged colour is not a history step");
+ s.execute(SET, json!({"color": "#abcdef"})).unwrap();
+ let LayerContent::Fill(Fill::Solid(changed)) = s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content else { panic!() };
+ assert_eq!(changed.alpha, color.alpha);
+ }
+ }
+
+ #[test]
+ fn bad_params_wrong_layer_and_stale_document_leave_history_untouched() {
+ let mut s = Session::new();
+ assert!(s.execute(SET, json!({"color": "#ffffff"})).is_err());
+ s.execute("file.new", json!({"width": 2, "height": 2})).unwrap();
+ let pixels = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("layer.newFillLayer.solidColor", json!({})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let count = s.active().unwrap().history.entries().len();
+ for p in [
+ json!({}),
+ json!(null),
+ json!({"color": true}),
+ json!({"color": [1, "bad", 0]}),
+ json!({"color": [1, 0, 0, 2]}),
+ json!({"color": "#💥💥"}),
+ json!({"layer": "bad", "color": "#ffffff"}),
+ json!({"layer": pixels, "color": "#ffffff"}),
+ json!({"layer": u64::MAX, "color": "#ffffff"}),
+ json!({"document": u64::MAX, "color": "#ffffff"}),
+ ] {
+ assert!(s.execute(SET, p.clone()).is_err(), "{p}");
+ assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc));
+ assert_eq!(s.active().unwrap().history.entries().len(), count);
+ }
+ }
+
+ #[test]
+ fn edits_respect_layer_and_transparency_locks() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 2, "height": 2})).unwrap();
+ s.execute("layer.newFillLayer.solidColor", json!({"color": "#12345680"})).unwrap();
+ for locks in [json!({"all": true}), json!({"all": false, "pixels": true}), json!({"pixels": false, "transparency": true})] {
+ s.execute("layer.setProps", json!({"locks": locks})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ assert!(s.execute(SET, json!({"color": "#abcdef00"})).is_err());
+ assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc));
+ }
+ s.execute(SET, json!({"color": "#abcdef"})).unwrap();
+ }
+
+ #[test]
+ fn rgb_picker_inputs_follow_document_mode_and_preserve_alpha() {
+ for (mode_command, mode) in [(None, ColorMode::Rgb), (Some("image.mode.cmyk"), ColorMode::Cmyk), (Some("image.mode.lab"), ColorMode::Lab)] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 8, "height": 8, "depth": 16})).unwrap();
+ if let Some(cmd) = mode_command {
+ s.execute(cmd, json!({})).unwrap();
+ }
+ let id = s.execute("layer.newFillLayer.solidColor", json!({"color": "#12345680"})).unwrap()["layer"].as_u64().unwrap();
+ let original = match s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content {
+ LayerContent::Fill(Fill::Solid(c)) => c,
+ _ => panic!(),
+ };
+ assert_eq!(s.active().unwrap().doc.mode, mode);
+ let count = s.active().unwrap().history.entries().len();
+ for (value, rgb) in [
+ (json!("#336699"), Color::rgba(51.0 / 255.0, 102.0 / 255.0, 153.0 / 255.0, original.alpha)),
+ (json!([0.25, 0.5, 0.75]), Color::rgba(0.25, 0.5, 0.75, original.alpha)),
+ ] {
+ let expected = rgb.in_mode(mode);
+ let result = s.execute(SET, json!({"layer": id, "color": value})).unwrap();
+ assert_eq!(serde_json::from_value::<Color>(result["color"].clone()).unwrap(), expected);
+ let LayerContent::Fill(Fill::Solid(stored)) = s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content else { panic!() };
+ assert_eq!(stored, expected);
+ assert_eq!(stored.alpha, original.alpha);
+ }
+ assert_eq!(s.active().unwrap().history.entries().len(), count + 2);
+ // Reapplying the same RGB array is a no-op, including after mode conversion.
+ let before_noop = s.active().unwrap().doc.clone();
+ s.execute(SET, json!({"layer": id, "color": [0.25, 0.5, 0.75]})).unwrap();
+ assert!(std::sync::Arc::ptr_eq(&before_noop, &s.active().unwrap().doc));
+ assert_eq!(s.active().unwrap().history.entries().len(), count + 2);
+ let expected = Color::rgba(0.25, 0.5, 0.75, 0.25).in_mode(mode);
+ s.execute(SET, json!({"layer": id, "color": [0.25, 0.5, 0.75, 0.25]})).unwrap();
+ let LayerContent::Fill(Fill::Solid(stored)) = s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content else { panic!() };
+ assert_eq!(stored, expected);
+ s.execute("edit.undo", json!({})).unwrap();
+ let LayerContent::Fill(Fill::Solid(stored)) = s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content else { panic!() };
+ assert_eq!(stored, Color::rgba(0.25, 0.5, 0.75, original.alpha).in_mode(mode));
+ s.execute("edit.redo", json!({})).unwrap();
+ let LayerContent::Fill(Fill::Solid(stored)) = s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().content else { panic!() };
+ assert_eq!(stored, expected);
+ }
+ }
+
+ #[test]
+ fn stored_colour_remains_exact_without_rgb_conversion_or_extra_history() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 4, "height": 4})).unwrap();
+ s.execute("image.mode.cmyk", json!({})).unwrap();
+ s.execute("layer.newFillLayer.solidColor", json!({})).unwrap();
+ let imported = Color { mode: ColorMode::Lab, c: [0.5123457, 0.4987654, 0.5678912, 0.0], alpha: 0.3456789 };
+ s.execute(SET, json!({"color": imported})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let count = s.active().unwrap().history.entries().len();
+ let result = s.execute(SET, json!({"color": imported})).unwrap();
+ assert_eq!(serde_json::from_value::<Color>(result["color"].clone()).unwrap(), imported);
+ assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc));
+ assert_eq!(s.active().unwrap().history.entries().len(), count);
+ }
+
+ #[test]
+ fn invalid_rgb_components_leave_document_and_history_unchanged() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 4, "height": 4})).unwrap();
+ s.execute("layer.newFillLayer.solidColor", json!({})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let count = s.active().unwrap().history.entries().len();
+ for color in [
+ json!([5.0, 0.0, 0.0]),
+ json!([-0.01, 0.0, 0.0]),
+ json!([1.00000000000001_f64, 0.0, 0.0]),
+ json!([0.0, 0.0, 0.0, -0.1]),
+ json!([0.0, 0.0, 0.0, 1.1]),
+ json!([1e300, 0.0, 0.0]),
+ json!(["NaN", 0.0, 0.0]),
+ json!(["Infinity", 0.0, 0.0]),
+ json!([null, 0.0, 0.0]),
+ json!([0.0, 0.0]),
+ json!([0.0, 0.0, 0.0, 0.0, 0.0]),
+ ] {
+ let err = s.execute(SET, json!({"color": color})).unwrap_err();
+ assert!(matches!(err, EngineError::BadParams { .. }), "{err}");
+ assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc));
+ assert_eq!(s.active().unwrap().history.entries().len(), count);
+ }
+ // Stored non-RGB colours are not subject to the RGB picker component limits.
+ let wide = Color { mode: ColorMode::Lab, c: [1.1, -0.1, 0.6, 0.0], alpha: 0.75 };
+ s.execute(SET, json!({"color": wide})).unwrap();
+ let active = s.active().unwrap().active_layer.unwrap();
+ let LayerContent::Fill(Fill::Solid(stored)) = s.active().unwrap().doc.layer(active).unwrap().content else { panic!() };
+ assert_eq!(stored, wide);
+ }
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 331818cc7..44bfef039 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -761,6 +761,9 @@ pub(crate) const GPU_OUTPUT: u32 = u32::MAX;
/// The document to render: the committed one, or a clone with the live adjustment preview applied.
pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>, u64) {
+ if let Some(shown) = crate::solid_fill_ui::display_doc(app, idx) {
+ return shown;
+ }
if let Some(shown) = crate::type_transform::display_doc(app, idx) {
return shown;
}
diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rs
index 74608a8a3..cd5f4a455 100644
--- a/crates/ui-egui/src/color_picker_ui.rs
+++ b/crates/ui-egui/src/color_picker_ui.rs
@@ -641,6 +641,9 @@ pub fn take_add_swatch(app: &mut PhotocraftApp, f: &mut Map<String, Value>) {
/// OK: set the foreground or background colour.
pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ if crate::solid_fill_ui::owns(f) {
+ return crate::solid_fill_ui::confirm(app, f);
+ }
let target = f.get("__colorPicker").and_then(Value::as_str).unwrap_or("foreground");
let color = f.get("color").and_then(Value::as_str).unwrap_or("#000000");
if let Some(cmd) = f.get("__command").and_then(Value::as_str) {
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index e6d0fb041..35c71fb1e 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2303,6 +2303,7 @@ fontWeight Italic Kurzíva
Cycle Orientation Přepnout orientaci
Set the overlay options for the Crop tool Nastavit volby překryvu pro nástroj Oříznutí
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+klik převzalo pracovní prostředí, které pomocí Alt+tažení přesouvá okna. Nastavte jeho klávesu pro přesun oken na Super, nebo zamkněte Alt v nabídce Okno › Modifikační klávesy.
+ Color Picker (Solid Color) Výběr barvy (plná barva)
Straighten the image by drawing a line on it Narovnat obraz nakreslením čáry
Set additional Crop options Nastavit další volby oříznutí
Show Cropped Area Zobrazit oříznutou oblast
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index dd5a3d2de..5e3e8fe3d 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2342,6 +2342,7 @@ fontWeight Italic Kursiv
Cycle Orientation Ausrichtung wechseln
Set the overlay options for the Crop tool Überlagerungsoptionen für das Freistellungswerkzeug festlegen
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Der Alt-Klick ging an die Arbeitsumgebung, die Fenster mit Alt-Ziehen verschiebt. Stelle dort die Taste zum Verschieben von Fenstern auf Super oder raste Alt unter Fenster › Modifikatortasten ein.
+ Color Picker (Solid Color) Farbwähler (Volltonfarbe)
Straighten the image by drawing a line on it Bild durch Ziehen einer Linie gerade ausrichten
Set additional Crop options Zusätzliche Freistellungsoptionen festlegen
Show Cropped Area Freigestellten Bereich anzeigen
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index f9bac804c..40c956f78 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -3413,6 +3413,7 @@ fontWeight Thin Πολύ λεπτά
Cycle Orientation Εναλλαγή προσανατολισμού
Set the overlay options for the Crop tool Ορισμός επιλογών επικάλυψης για το εργαλείο Περικοπή
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Το Alt-κλικ πήγε στο περιβάλλον εργασίας, που μετακινεί παράθυρα με Alt-σύρσιμο. Ορίστε το πλήκτρο μετακίνησης παραθύρων του σε Super ή κλειδώστε το Alt στο Παράθυρο › Πλήκτρα τροποποίησης.
+ Color Picker (Solid Color) Επιλογέας χρώματος (συμπαγές χρώμα)
Straighten the image by drawing a line on it Ευθυγράμμιση της εικόνας σχεδιάζοντας μια γραμμή πάνω της
Set additional Crop options Ορισμός πρόσθετων επιλογών περικοπής
Show Cropped Area Εμφάνιση περιοχής περικοπής
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 909c190b5..3996bfef8 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2371,6 +2371,7 @@ fontWeight Italic Cursiva
Cycle Orientation Alternar orientación
Set the overlay options for the Crop tool Definir las opciones de superposición de la herramienta Recortar
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. El Alt+clic lo recibió el escritorio, que mueve ventanas con Alt+arrastrar. Cambia su tecla para mover ventanas a Super o bloquea Alt en Ventana › Teclas modificadoras.
+ Color Picker (Solid Color) Selector de color (color uniforme)
Straighten the image by drawing a line on it Enderezar la imagen dibujando una línea en ella
Set additional Crop options Definir opciones de recorte adicionales
Show Cropped Area Mostrar área recortada
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 7b05780ed..cfe63dc8c 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2724,6 +2724,7 @@ fontWeight Italic Italique
Cycle Orientation Changer d’orientation
Set the overlay options for the Crop tool Définir les options de superposition de l’outil Recadrage
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. L’Alt-clic a été intercepté par le bureau, qui déplace les fenêtres avec Alt-glisser. Réglez sa touche de déplacement des fenêtres sur Super, ou verrouillez Alt dans Fenêtre › Touches de modification.
+ Color Picker (Solid Color) Sélecteur de couleurs (couleur unie)
Straighten the image by drawing a line on it Redresser l’image en traçant une ligne dessus
Set additional Crop options Définir d’autres options de recadrage
Show Cropped Area Afficher la zone recadrée
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index b1b13921b..d31c58ee5 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2711,6 +2711,7 @@ fontWeight Italic Miring
Cycle Orientation Ganti Orientasi
Set the overlay options for the Crop tool Atur opsi overlay untuk alat Crop
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt-klik diambil oleh desktop, yang memindahkan jendela dengan Alt-seret. Atur tombol pemindah jendelanya ke Super, atau kunci Alt di Jendela › Tombol Pengubah.
+ Color Picker (Solid Color) Pemilih Warna (Warna Solid)
Straighten the image by drawing a line on it Luruskan gambar dengan menggambar garis di atasnya
Set additional Crop options Atur opsi Crop tambahan
Show Cropped Area Tampilkan Area yang Di-crop
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 2897d1173..e2dcf5d00 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2373,6 +2373,7 @@ fontWeight Italic Corsivo
Cycle Orientation Cambia orientamento
Set the overlay options for the Crop tool Imposta le opzioni di sovrapposizione dello strumento Taglierina
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. L’Alt-click è andato al desktop, che sposta le finestre con Alt-trascina. Imposta il suo tasto per spostare le finestre su Super, oppure blocca Alt in Finestra › Tasti modificatori.
+ Color Picker (Solid Color) Selettore colore (tinta unita)
Straighten the image by drawing a line on it Raddrizza l’immagine tracciando una linea
Set additional Crop options Imposta opzioni di ritaglio aggiuntive
Show Cropped Area Mostra area ritagliata
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index a999ef16e..203d0113f 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -3327,6 +3327,7 @@ fontWeight Italic 斜体
Cycle Orientation 方向を切り替え
Set the overlay options for the Crop tool 切り抜きツールのオーバーレイオプションを設定
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+クリックはデスクトップに取られました(Alt+ドラッグでウィンドウを移動する設定です)。デスクトップのウィンドウ移動キーを Super に変更するか、ウィンドウ › 修飾キーで Alt を固定してください。
+ Color Picker (Solid Color) カラーピッカー(べた塗り)
Straighten the image by drawing a line on it 画像上に線を描いて角度を補正
Set additional Crop options 切り抜きの追加オプションを設定
Show Cropped Area 切り抜かれた領域を表示
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index b238c26c8..44c056b1b 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2882,6 +2882,7 @@ fontWeight Italic 기울임
Cycle Orientation 방향 순환
Set the overlay options for the Crop tool 자르기 도구의 오버레이 옵션 설정
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 클릭이 데스크톱으로 전달되었습니다. 데스크톱이 Alt 드래그로 창을 이동합니다. 창 이동 키를 Super로 바꾸거나 창 › 보조 키에서 Alt를 고정하세요.
+ Color Picker (Solid Color) 색상 피커 (단색)
Straighten the image by drawing a line on it 이미지에 선을 그려 수평 맞추기
Set additional Crop options 추가 자르기 옵션 설정
Show Cropped Area 잘린 영역 표시
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 41658b2b9..6b8608d80 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -3488,6 +3488,7 @@ cameraRaw Whites Witten
Cycle Orientation Oriëntatie wisselen
Set the overlay options for the Crop tool Overlay-opties voor het gereedschap Uitsnijden instellen
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. De Alt-klik ging naar het bureaublad, dat vensters verplaatst met Alt-slepen. Stel daar de toets voor het verplaatsen van vensters in op Super, of vergrendel Alt via Venster › Wijzigingstoetsen.
+ Color Picker (Solid Color) Kleurkiezer (effen kleur)
Straighten the image by drawing a line on it Recht de afbeelding uit door er een lijn op te tekenen
Set additional Crop options Aanvullende uitsnijopties instellen
Show Cropped Area Uitgesneden gebied tonen
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 66d83740b..0ce632a37 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -3326,6 +3326,7 @@ cameraRaw Roughness Chropowatość
Cycle Orientation Przełącz orientację
Set the overlay options for the Crop tool Ustaw opcje nakładki narzędzia Kadrowanie
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+kliknięcie przejęło środowisko pulpitu, które przesuwa okna przez Alt+przeciąganie. Ustaw w nim klawisz przesuwania okien na Super lub zablokuj Alt w Okno › Klawisze modyfikujące.
+ Color Picker (Solid Color) Próbnik kolorów (kolor jednolity)
Straighten the image by drawing a line on it Wyprostuj obraz, rysując na nim linię
Set additional Crop options Ustaw dodatkowe opcje kadrowania
Show Cropped Area Pokaż wykadrowany obszar
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index b1d2149fe..9818a70ac 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2732,6 +2732,7 @@ fontWeight Italic Itálico
Cycle Orientation Alternar orientação
Set the overlay options for the Crop tool Definir as opções de sobreposição da ferramenta Corte demarcado
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. O Alt-clique foi para o desktop, que move janelas com Alt-arrastar. Mude a tecla de mover janelas dele para Super ou trave o Alt em Janela › Teclas modificadoras.
+ Color Picker (Solid Color) Seletor de Cores (Cor sólida)
Straighten the image by drawing a line on it Endireitar a imagem desenhando uma linha sobre ela
Set additional Crop options Definir opções adicionais de corte
Show Cropped Area Mostrar área cortada
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 1c3c6c30d..f9ad879e6 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2578,6 +2578,7 @@ fontWeight Italic Курсив
Cycle Orientation Сменить ориентацию
Set the overlay options for the Crop tool Задать параметры перекрытия для инструмента «Рамка»
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt+щелчок перехватило окружение рабочего стола: оно перемещает окна через Alt+перетаскивание. Назначьте для перемещения окон клавишу Super или зафиксируйте Alt в меню Окно › Клавиши-модификаторы.
+ Color Picker (Solid Color) Выбор цвета (сплошной цвет)
Straighten the image by drawing a line on it Выровнять изображение, нарисовав на нем линию
Set additional Crop options Задать дополнительные параметры кадрирования
Show Cropped Area Показать отсекаемую область
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index c9747e7bd..1b807cd08 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -3413,6 +3413,7 @@ cameraRaw Masking Маскування
Cycle Orientation Змінити орієнтацію
Set the overlay options for the Crop tool Задати параметри накладання для інструмента «Рамка»
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt-клік перехопило робоче середовище, яке переміщує вікна через Alt-перетягування. Призначте для переміщення вікон клавішу Super або зафіксуйте Alt у меню Вікно › Клавіші-модифікатори.
+ Color Picker (Solid Color) Вибір кольору (суцільний колір)
Straighten the image by drawing a line on it Вирівняти зображення, намалювавши на ньому лінію
Set additional Crop options Задати додаткові параметри кадрування
Show Cropped Area Показати відсічену область
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 4ca174ff5..24a56ce30 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2311,6 +2311,7 @@ fontWeight Italic 斜体
Cycle Orientation 循环切换取向
Set the overlay options for the Crop tool 设置裁剪工具的叠加选项
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 单击被桌面环境截获了,它用 Alt 拖动来移动窗口。请把桌面的窗口移动键改为 Super,或在 窗口 › 修饰键 中锁定 Alt。
+ Color Picker (Solid Color) 拾色器(纯色)
Straighten the image by drawing a line on it 通过在图像上画一条线来拉直图像
Set additional Crop options 设置其他裁剪选项
Show Cropped Area 显示裁剪区域
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 690f3a54a..261d5a4b8 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2280,6 +2280,7 @@ fontWeight Italic 斜體
Cycle Orientation 循環切換方向
Set the overlay options for the Crop tool 設定裁切工具的覆蓋選項
Alt-click went to the desktop, which moves windows with Alt-drag. Set its window-move key to Super, or latch Alt in Window › Modifier Keys. Alt 按一下被桌面環境攔截了,它用 Alt 拖曳來移動視窗。請把桌面的視窗移動鍵改為 Super,或在 視窗 › 輔助鍵 中鎖定 Alt。
+ Color Picker (Solid Color) 檢色器(純色)
Straighten the image by drawing a line on it 在影像上繪製一條線以拉直影像
Set additional Crop options 設定其他裁切選項
Show Cropped Area 顯示裁切區域
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 8a8d5deaa..41634b0ad 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -132,6 +132,7 @@ mod sizing;
pub mod slice_ui;
pub mod smart_ui;
pub mod snap_ui;
+pub(crate) mod solid_fill_ui;
pub mod state;
pub mod stroke_constraint;
pub mod stroke_trail;
@@ -468,6 +469,7 @@ pub struct PhotocraftApp {
pub(crate) move_mods: move_mods::MoveDrag,
/// Live Layer Style dialog preview: (key over revision + style fields, preview or validation error).
pub(crate) style_preview: Option<(u64, Result<std::sync::Arc<Document>, String>)>,
+ pub(crate) solid_fill_preview: Option<solid_fill_ui::Preview>,
/// Liquify dialog, Puppet Warp and Perspective Warp sessions (distort_ui).
pub(crate) distort: distort_ui::Distort,
/// Gradient tool live-mode drags and previews (gradient_ui).
@@ -610,6 +612,7 @@ impl PhotocraftApp {
transform_preview: None,
move_mods: Default::default(),
style_preview: None,
+ solid_fill_preview: None,
distort: Default::default(),
gradient: Default::default(),
camera_raw: None,
@@ -744,6 +747,12 @@ impl PhotocraftApp {
let params = self.with_mask_target(id, params);
let params = vector_ui::with_active_path(self, id, params);
let path_mask = vector_ui::takes_path_mask(id) && params.get("path").is_some_and(|v| !v.is_null());
+ let creates_active_mask =
+ matches!(id, "layer.layerMask.revealAll" | "layer.layerMask.hideAll" | "layer.layerMask.revealSelection" | "layer.layerMask.hideSelection")
+ && self
+ .session
+ .active()
+ .is_some_and(|st| st.active_layer.is_some_and(|layer| params.get("layer").and_then(Value::as_u64).is_none_or(|target| target == layer.0)));
let r = if id == "actions.play" {
actions::play(self, &params)
} else if photocraft_engine::actions_cmds::shell_view_command(id) {
@@ -760,6 +769,11 @@ impl PhotocraftApp {
// was made from is no longer selected, so the next fill layer isn't masked by it too.
self.ui.selected_path = Some("layer".into());
}
+ if r.is_ok() && creates_active_mask {
+ // Adding a mask selects its thumbnail: the next brush or footer Delete targets it.
+ self.ui.mask_target = true;
+ self.ui.vector_mask_target = false;
+ }
if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") {
self.clip_external = false;
self.export_os_clipboard();
@@ -1358,6 +1372,9 @@ impl PhotocraftApp {
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;
+ }
}
fn prune_thumbs(&mut self) {
diff --git a/crates/ui-egui/src/mask_thumbs_ui/tests.rs b/crates/ui-egui/src/mask_thumbs_ui/tests.rs
index 12f535162..4d3b18cb8 100644
--- a/crates/ui-egui/src/mask_thumbs_ui/tests.rs
+++ b/crates/ui-egui/src/mask_thumbs_ui/tests.rs
@@ -86,6 +86,91 @@ fn deleting_the_vector_mask_prunes_its_thumbnail() {
assert!(!h.state().thumbs.contains_key(&key));
}
+#[test]
+fn footer_trash_deletes_only_the_targeted_mask_linked_or_unlinked() {
+ for linked in [true, false] {
+ for kind in [MaskKind::Pixel, MaskKind::Vector] {
+ let (mut s, masked, shape) = session();
+ s.execute("layer.layerMask.linked", json!({"linked": linked})).unwrap();
+ s.execute("layer.vectorMask.linked", json!({"linked": linked})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let mut h = harness(s, 0, 1.0, 290.0);
+ let r = recorded(&h.ctx, masked).unwrap().0.into_iter().find(|(k, _)| *k == kind).unwrap().1;
+ click_with(&mut h, r.center(), Modifiers::NONE);
+ let label = if kind == MaskKind::Pixel { "Delete Layer Mask" } else { "Delete Vector Mask" };
+ let at = h.get_by_label(label).rect().center();
+ click_with(&mut h, at, Modifiers::NONE);
+ let l = layer(&h, masked);
+ let original = before.layer(photocraft_doc::LayerId(masked)).unwrap();
+ assert_eq!(l.content, original.content);
+ assert_eq!(layer(&h, shape), *before.layer(photocraft_doc::LayerId(shape)).unwrap());
+ if kind == MaskKind::Pixel {
+ assert!(l.mask.is_none());
+ assert_eq!(l.vector_mask, original.vector_mask);
+ assert!(!h.state().ui.mask_target);
+ } else {
+ assert!(l.vector_mask.is_none());
+ assert_eq!(l.mask, original.mask);
+ assert!(!h.state().ui.vector_mask_target);
+ }
+ h.state_mut().run("edit.undo", json!({})).unwrap();
+ assert_eq!(*h.state().session.active().unwrap().doc, *before);
+ h.state_mut().run("edit.redo", json!({})).unwrap();
+ assert_eq!(layer(&h, masked), l);
+ }
+ }
+}
+
+#[test]
+fn footer_trash_still_deletes_the_layer_when_its_content_is_targeted() {
+ let (s, masked, _) = session();
+ let mut h = harness(s, 0, 1.0, 290.0);
+ let row = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == masked).unwrap().row;
+ click_with(&mut h, pos2(row.left() + 46.0, row.center().y), Modifiers::NONE);
+ assert!(!h.state().ui.mask_target && !h.state().ui.vector_mask_target);
+ let at = h.get_by_label("Delete layer").rect().center();
+ click_with(&mut h, at, Modifiers::NONE);
+ assert!(h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(masked)).is_none());
+}
+
+#[test]
+fn a_new_mask_is_targeted_so_the_next_footer_trash_keeps_its_layer() {
+ let (s, _, shape) = session();
+ let mut h = harness(s, 0, 1.0, 290.0);
+ h.state_mut().run("layer.new.layer", json!({"name": "Fresh mask"})).unwrap();
+ let id = h.state().session.active().unwrap().active_layer.unwrap();
+ h.run_steps(3);
+ let at = h.get_by_label("Add a mask (from the selection; Alt inverts)").rect().center();
+ click_with(&mut h, at, Modifiers::NONE);
+ assert!(h.state().ui.mask_target && !h.state().ui.vector_mask_target);
+ assert!(h.state().session.active().unwrap().doc.layer(id).unwrap().mask.is_some());
+ let at = h.get_by_label("Delete Layer Mask").rect().center();
+ click_with(&mut h, at, Modifiers::NONE);
+ assert!(h.state().session.active().unwrap().doc.layer(id).unwrap().mask.is_none());
+ assert!(h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(shape)).is_some());
+}
+
+#[test]
+fn dragging_a_layer_row_to_trash_still_deletes_the_layer_with_a_mask_targeted() {
+ let (s, masked, _) = session();
+ let mut h = harness(s, 0, 1.0, 290.0);
+ let mask = recorded(&h.ctx, masked).unwrap().0.into_iter().find(|(k, _)| *k == MaskKind::Pixel).unwrap().1;
+ click_with(&mut h, mask.center(), Modifiers::NONE);
+ let from = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == masked).unwrap().row.center();
+ let to = h.get_by_label("Delete Layer Mask").rect().center();
+ h.hover_at(from);
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
+ h.run_steps(1);
+ for k in 1..=8 {
+ h.event(egui::Event::PointerMoved(from + (to - from) * (k as f32 / 8.0)));
+ h.run_steps(1);
+ }
+ h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
+ h.run_steps(3);
+ assert!(h.state().session.active().unwrap().doc.layer(photocraft_doc::LayerId(masked)).is_none());
+}
+
#[test]
fn the_chain_toggles_linking_and_it_survives_psd() {
let (s, masked, _) = session();
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 6cd0baf14..d53ddb2d8 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -350,8 +350,11 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
}
Ok(Value::Null)
}
- // Layer Content Options…: the adjustment / fill controls live in Properties.
+ // Solid Color uses the Color Picker; other adjustment / fill controls use Properties.
"layer.layerContentOptions" => {
+ if let Some(dialog) = crate::solid_fill_ui::open(app) {
+ return Ok(json!({"dialog": dialog}));
+ }
let r = app.run(id, params)?;
app.ui.panels.properties = true;
app.ui.dock_tabs.properties = 0;
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 1bdd892bf..8f4eb8d29 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -1801,11 +1801,22 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ctx.data_mut(|d| d.remove::<FxDrag>(fx_drag_key()));
}
widgets::panel_footer(ui, |ui| {
- let trash = icons::button(ui, "trash", 26.0, false, tl!("Delete layer"));
+ let active_layer = active.and_then(|id| doc.layer(id));
+ let (delete, label) = if app.ui.vector_mask_target && active_layer.is_some_and(|l| l.vector_mask.is_some()) {
+ ("layer.vectorMask.delete", "Delete Vector Mask")
+ } else if app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some()) {
+ ("layer.layerMask.delete", "Delete Layer Mask")
+ } else {
+ ("layer.delete", "Delete layer")
+ };
+ let trash = icons::button(ui, "trash", 26.0, false, tl!(label));
if trash.clicked() {
- actions.push(("layer.delete".into(), json!({})));
+ actions.push((delete.into(), json!({})));
}
actions.extend(footer_drop(ui, &trash, footer_drag, "layer.delete"));
+ // A click follows the selected thumbnail; name that action for screen readers even
+ // though dropping a whole layer row onto the same button always deletes the layer.
+ 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!({})));
@@ -1845,6 +1856,7 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
crate::i18n::fmt(tl!("Add a mask (from the selection; {key} inverts)"), &[("key", &crate::shortcuts::pretty("Alt"))])
};
let mask_btn = ui.add_enabled_ui(mask_cmd.is_some(), |ui| icons::button(ui, "layer-mask", 26.0, false, &mask_tip)).inner;
+ mask_btn.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &mask_tip));
if mask_btn.clicked()
&& let Some(cmd) = mask_cmd
{
@@ -2182,7 +2194,8 @@ fn layer_row(
} else if resp.clicked() && !eye_resp.clicked() && !toggled && !fx_toggled && !masks.clicked {
let mode = select_mode(ui.input(|i| i.modifiers));
actions.push(("layer.select".into(), json!({"layer": l.id.0, "mode": mode})));
- // Clicking a thumbnail picks what painting targets; adjustment/fill layers target their mask.
+ // A thumbnail explicitly selects content or a mask. Selecting an adjustment/fill row
+ // defaults to its mask, but clicking its content thumbnail must leave the mask target.
let pos = resp.interact_pointer_pos();
let on_mask = mask_rect.zip(pos).is_some_and(|(r, p)| r.expand(2.0).contains(p));
let on_thumb = pos.is_some_and(|p| thumb.expand(2.0).contains(p));
@@ -2198,7 +2211,7 @@ fn layer_row(
// Paths panel selects the layer's path.
app.ui.selected_path = Some("layer".into());
actions.push(("ui.vectorMaskTarget".into(), json!(true)));
- } else if on_mask || (content_less && l.mask.is_some()) {
+ } else if on_mask || (content_less && l.mask.is_some() && !on_thumb) {
actions.push(("ui.maskTarget".into(), json!(true)));
} else if on_thumb || !row.primary {
actions.push(("ui.maskTarget".into(), json!(false)));
@@ -2270,11 +2283,11 @@ fn draw_layer_thumb(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &egui::Ui,
}
// Gradient fills show the gradient itself (Photoshop); solid ones their colour.
LayerContent::Fill(f) if crate::gradient_ui::paint_thumbnail(ui, l.id, f, rect) => {}
- LayerContent::Fill(f) => {
- let c = match f {
- photocraft_doc::Fill::Solid(c) => c.to_rgba8(),
- _ => [128, 128, 128, 255],
- };
+ LayerContent::Fill(photocraft_doc::Fill::Solid(color)) => {
+ crate::solid_fill_ui::paint_thumbnail(ui, crate::solid_fill_ui::thumbnail_color(app, doc.id, l.id, *color), rect);
+ }
+ LayerContent::Fill(_) => {
+ let c = [128, 128, 128, 255];
p.rect_filled(rect, 6.0, Color32::from_rgba_unmultiplied(c[0], c[1], c[2], c[3]));
}
_ => {
diff --git a/crates/ui-egui/src/solid_fill_ui.rs b/crates/ui-egui/src/solid_fill_ui.rs
new file mode 100644
index 000000000..e9459c10d
--- /dev/null
+++ b/crates/ui-egui/src/solid_fill_ui.rs
@@ -0,0 +1,138 @@
+//! The Solid Color Fill thumbnail opens the shared Color Picker. Preview a shallow document
+//! snapshot; Cancel changes nothing and OK commits exactly one engine command.
+
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+use egui::{Color32, Rect, Stroke, StrokeKind, pos2, vec2};
+use photocraft_color::Color;
+use photocraft_doc::{DocId, Document, Fill, LayerContent, LayerId};
+use photocraft_engine::solid_fill_cmds as cmds;
+use serde_json::{Map, Value, json};
+
+use crate::{PhotocraftApp, color_picker_ui, theme::Tokens};
+
+pub(crate) struct Preview {
+ document: DocId,
+ revision: u64,
+ dialog: u64,
+ layer: LayerId,
+ color: Color,
+ shown: Arc<Document>,
+ key: u64,
+}
+
+pub(crate) fn open(app: &mut PhotocraftApp) -> Option<u64> {
+ let st = app.session.active()?;
+ let layer = st.active_layer?;
+ let LayerContent::Fill(Fill::Solid(color)) = st.doc.layer(layer)?.content else { return None };
+ let params = json!({"layer": layer.0, "document": st.doc.id.0});
+ Some(color_picker_ui::open_for_command(app, "Color Picker (Solid Color)", color.to_rgb(), cmds::SET, params))
+}
+
+pub(crate) fn owns(f: &Map<String, Value>) -> bool {
+ f.get("__command").and_then(Value::as_str) == Some(cmds::SET)
+}
+
+pub(crate) fn thumbnail_color(app: &PhotocraftApp, document: DocId, layer: LayerId, original: Color) -> Color {
+ app.ui
+ .dialogs
+ .iter()
+ .rev()
+ .filter(|d| owns(&d.fields))
+ .find_map(|d| {
+ let params = d.fields.get("__params")?;
+ if params.get("document")?.as_u64()? != document.0 || params.get("layer")?.as_u64()? != layer.0 || d.fields.get("color") == d.fields.get("__orig") {
+ return None;
+ }
+ cmds::color_param(d.fields.get("color")?, original, app.session.documents().iter().find(|st| st.doc.id == document)?.doc.mode).ok()
+ })
+ .unwrap_or(original)
+}
+
+/// No-op OK preserves imported high-precision / non-RGB colour values rather than quantising
+/// them to the picker's display hex. A stale document must never receive the edit.
+pub(crate) fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ let mut params = f.get("__params").cloned().ok_or("missing Solid Color target")?;
+ let st = app.session.active().ok_or("no document open")?;
+ if params.get("document").and_then(Value::as_u64) != Some(st.doc.id.0) {
+ return Err("the target document is no longer active".into());
+ }
+ let layer = LayerId(params.get("layer").and_then(Value::as_u64).ok_or("missing Solid Color layer")?);
+ if !st.doc.layer(layer).is_some_and(|l| matches!(l.content, LayerContent::Fill(Fill::Solid(_)))) {
+ return Err("the target Solid Color Fill layer no longer exists".into());
+ }
+ if f.get("color") == f.get("__orig") {
+ return Ok(json!({"layer": layer.0, "unchanged": true}));
+ }
+ let color = f.get("color").cloned().ok_or("missing color")?;
+ let object = params.as_object_mut().ok_or("invalid Solid Color target")?;
+ object.insert("color".into(), color);
+ app.run(cmds::SET, params)
+}
+
+pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Document>, u64)> {
+ let dialog = app.ui.dialogs.iter().rev().find(|d| owns(&d.fields));
+ let Some(d) = dialog else {
+ app.solid_fill_preview = None;
+ return None;
+ };
+ let st = app.session.documents().get(idx)?;
+ let params = d.fields.get("__params")?;
+ if params.get("document")?.as_u64()? != st.doc.id.0 || d.fields.get("color") == d.fields.get("__orig") {
+ return None;
+ }
+ let layer = LayerId(params.get("layer")?.as_u64()?);
+ let LayerContent::Fill(Fill::Solid(original)) = st.doc.layer(layer)?.content else { return None };
+ let color = cmds::color_param(d.fields.get("color")?, original, st.doc.mode).ok()?;
+ if let Some(p) = &app.solid_fill_preview
+ && p.document == st.doc.id
+ && p.revision == st.revision
+ && p.dialog == d.id
+ && p.layer == layer
+ && p.color == color
+ {
+ return Some((p.shown.clone(), p.key));
+ }
+ let mut doc = (*st.doc).clone();
+ doc.layer_mut(layer)?.content = LayerContent::Fill(Fill::Solid(color));
+ // Include the dialog identity: cancelling and reopening at the same document revision
+ // must not reuse an old preview's pixels in the canvas caches.
+ let mut hash = std::collections::hash_map::DefaultHasher::new();
+ (st.doc.id.0, st.revision, d.id, layer.0).hash(&mut hash);
+ color.mode.hash(&mut hash);
+ for component in color.c.into_iter().chain([color.alpha]) {
+ component.to_bits().hash(&mut hash);
+ }
+ let key = (1 << 36) | (hash.finish() & ((1 << 36) - 1));
+ let shown = Arc::new(photocraft_engine::mode_cmds::display_document(&doc).unwrap_or(doc));
+ app.solid_fill_preview = Some(Preview { document: st.doc.id, revision: st.revision, dialog: d.id, layer, color, shown: shown.clone(), key });
+ Some((shown, key))
+}
+
+/// Clean-room drawing of Photoshop's Solid Color thumbnail: an inset colour sample with the
+/// small fill marker underneath, rather than a raster thumbnail covering the whole tile.
+pub(crate) fn paint_thumbnail(ui: &egui::Ui, color: Color, rect: Rect) {
+ let t = Tokens::get(ui.ctx());
+ let p = ui.painter();
+ p.rect_filled(rect, if t.pro { 0.0 } else { t.radius_sm }, t.field);
+ let size = rect.size() * 0.7;
+ let sample = Rect::from_center_size(rect.center() - vec2(0.0, size.y * 0.08), size);
+ let bar_height = (size.y * 0.17).max(2.0);
+ let swatch = Rect::from_min_max(sample.min, pos2(sample.right(), sample.bottom() - bar_height));
+ let [r, g, b, a] = color.to_rgba8();
+ crate::widgets::checker(p, swatch, 3.0);
+ p.rect_filled(swatch, 0.0, Color32::from_rgba_unmultiplied(r, g, b, a));
+ p.rect_stroke(sample, 0.0, Stroke::new(1.0, t.text), StrokeKind::Outside);
+ let y = swatch.bottom();
+ p.line_segment([pos2(sample.left(), y), pos2(sample.right(), y)], Stroke::new(1.0, t.text));
+ let x = sample.center().x;
+ p.add(egui::Shape::convex_polygon(
+ vec![pos2(x, y + 1.0), pos2(x - bar_height * 0.6, sample.bottom()), pos2(x + bar_height * 0.6, sample.bottom())],
+ t.text,
+ Stroke::NONE,
+ ));
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/ui-egui/src/solid_fill_ui/tests.rs b/crates/ui-egui/src/solid_fill_ui/tests.rs
new file mode 100644
index 000000000..9b919be93
--- /dev/null
+++ b/crates/ui-egui/src/solid_fill_ui/tests.rs
@@ -0,0 +1,195 @@
+use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2};
+use egui_kittest::Harness;
+use photocraft_color::{Color, ColorMode};
+use photocraft_doc::{Fill, LayerContent, LayerId};
+use serde_json::json;
+
+use super::*;
+
+fn harness(ppp: f32) -> (Harness<'static, PhotocraftApp>, LayerId) {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48, "depth": 16})).unwrap();
+ let id = LayerId(s.execute("layer.newFillLayer.solidColor", json!({"color": "#33669980"})).unwrap()["layer"].as_u64().unwrap());
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ s.execute("layer.new.layer", json!({"name": "Other"})).unwrap();
+ let mut h =
+ Harness::builder().with_size(vec2(1440.0, 900.0)).with_pixels_per_point(ppp).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(move |cc| {
+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
+ PhotocraftApp::new(s, crate::Services::default())
+ });
+ let ctx = h.ctx.clone();
+ let (r, _) = crate::control::ControlRequest::new("ui.set", json!({"dock": {"collapsed": ["color", "properties", "history", "navigator"]}}));
+ crate::control::handle(h.state_mut(), &ctx, &r);
+ h.run_steps(8);
+ (h, id)
+}
+
+fn double_click(h: &mut Harness<'_, PhotocraftApp>, at: Pos2) {
+ h.run_steps(40);
+ for _ in 0..2 {
+ h.hover_at(at);
+ h.step();
+ for pressed in [true, false] {
+ h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
+ h.step();
+ }
+ h.run_steps(3);
+ }
+}
+
+fn row(h: &Harness<'_, PhotocraftApp>, id: LayerId) -> crate::layer_row_ui::RowRects {
+ crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == id.0).unwrap()
+}
+
+#[test]
+fn only_the_colour_thumbnail_opens_the_solid_fill_picker() {
+ for ppp in [1.0, 2.0] {
+ let (mut h, id) = harness(ppp);
+ let r = row(&h, id).row;
+ let count = h.state().session.active().unwrap().history.entries().len();
+ double_click(&mut h, pos2(r.left() + 46.0, r.center().y));
+ assert_eq!(h.state().session.active().unwrap().active_layer, Some(id));
+ assert!(!h.state().ui.mask_target && !h.state().ui.vector_mask_target, "the colour thumbnail targets the fill, not its mask");
+ let d = h.state().ui.dialogs.last().expect("Color Picker opened");
+ assert!(owns(&d.fields));
+ assert_eq!(d.fields["__label"], "Color Picker (Solid Color)");
+ assert_eq!(d.fields["color"], "#336699");
+ assert_eq!(d.fields["__params"]["layer"], id.0);
+ assert_eq!(h.state().session.active().unwrap().history.entries().len(), count);
+
+ let (mut h, id) = harness(ppp);
+ let r = row(&h, id).row;
+ double_click(&mut h, pos2(r.right() - 35.0, r.center().y));
+ assert_eq!(h.state().ui.dialogs.last().unwrap().kind, crate::state::DialogKind::LayerStyle, "row body keeps Layer Style");
+
+ let (mut h, id) = harness(ppp);
+ let r = crate::mask_thumbs_ui::recorded(&h.ctx, id.0).unwrap().0[0].1;
+ double_click(&mut h, r.center());
+ assert!(!h.state().ui.dialogs.iter().any(|d| owns(&d.fields)), "mask thumbnail is not the colour thumbnail");
+ }
+}
+
+#[test]
+fn gradient_and_adjustment_thumbnails_keep_their_properties_controls() {
+ for command in ["layer.newFillLayer.gradient", "layer.newAdjustmentLayer.invert"] {
+ let (mut h, _) = harness(1.0);
+ let id = LayerId(h.state_mut().run(command, json!({})).unwrap()["layer"].as_u64().unwrap());
+ h.run_steps(4);
+ let r = row(&h, id).row;
+ double_click(&mut h, pos2(r.left() + 46.0, r.center().y));
+ assert!(h.state().ui.panels.properties);
+ assert!(!h.state().ui.dialogs.iter().any(|d| owns(&d.fields)));
+ }
+}
+
+#[test]
+fn picker_previews_without_editing_cancel_discards_and_ok_is_one_step() {
+ let (mut h, id) = harness(1.0);
+ let app = h.state_mut();
+ app.run("layer.select", json!({"layer": id.0})).unwrap();
+ let before = app.session.active().unwrap().doc.clone();
+ let LayerContent::Fill(Fill::Solid(original)) = before.layer(id).unwrap().content else { panic!() };
+ let steps = app.session.active().unwrap().history.entries().len();
+ let tools = app.session.tools.foreground;
+ let dialog = open(app).unwrap();
+ app.ui.dialog_mut(dialog).unwrap().fields.insert("color".into(), json!("#ff8800"));
+ let (preview, key) = display_doc(app, 0).unwrap();
+ let (again, again_key) = display_doc(app, 0).unwrap();
+ assert_eq!(key, again_key);
+ assert!(Arc::ptr_eq(&preview, &again), "preview is cached");
+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc), "preview does not dirty the real document");
+ assert_eq!(app.session.active().unwrap().history.entries().len(), steps);
+ let LayerContent::Fill(Fill::Solid(color)) = preview.layer(id).unwrap().content else { panic!() };
+ assert_eq!(color.to_rgba8(), [255, 136, 0, 128]);
+ assert_eq!(thumbnail_color(app, before.id, id, original), color);
+ app.ui.close_dialog(dialog);
+ assert!(display_doc(app, 0).is_none());
+ assert!(app.solid_fill_preview.is_none());
+ assert_eq!(thumbnail_color(app, before.id, id, original), original);
+ let dialog = open(app).unwrap();
+ app.ui.dialog_mut(dialog).unwrap().fields.insert("color".into(), json!("#ff8800"));
+ let (_, reopened_key) = display_doc(app, 0).unwrap();
+ assert_ne!(key, reopened_key, "reopening a picker never reuses a cancelled preview key");
+ crate::dialogs::confirm(app, dialog).unwrap();
+ assert_eq!(app.session.active().unwrap().history.entries().len(), steps + 1);
+ assert_eq!(app.session.tools.foreground, tools, "editing a fill doesn't change the tool colour");
+ assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().content, LayerContent::Fill(Fill::Solid(color)));
+ let bytes = photocraft_format::save_to_bytes(&app.session.active().unwrap().doc, &Default::default()).unwrap();
+ let loaded = photocraft_format::load_from_bytes(&bytes).unwrap();
+ assert_eq!(loaded.layer(id).unwrap().content, LayerContent::Fill(Fill::Solid(color)));
+ assert_eq!(loaded.layer(id).unwrap().mask, before.layer(id).unwrap().mask);
+ let bytes = photocraft_io::export(&app.session.active().unwrap().doc, "fill.psd", &Default::default()).unwrap().bytes;
+ let loaded = photocraft_io::import("fill.psd", &bytes).unwrap().document;
+ let fill = loaded.walk().into_iter().find(|(_, _, l)| matches!(l.content, LayerContent::Fill(Fill::Solid(_)))).unwrap().2;
+ let LayerContent::Fill(Fill::Solid(saved)) = fill.content else { panic!() };
+ // PSD's existing SoCo descriptor stores the fill's colour components, not Color.alpha.
+ assert_eq!(&saved.to_rgba8()[..3], &color.to_rgba8()[..3]);
+ assert!(fill.mask.is_some());
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(*app.session.active().unwrap().doc, *before);
+ app.run("edit.redo", json!({})).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().content, LayerContent::Fill(Fill::Solid(color)));
+}
+
+#[test]
+fn unchanged_ok_keeps_imported_model_precision_and_alpha() {
+ let (mut h, id) = harness(1.0);
+ let app = h.state_mut();
+ app.run("layer.select", json!({"layer": id.0})).unwrap();
+ let color = Color { mode: ColorMode::Lab, c: [0.512345, 0.498765, 0.56789, 0.0], alpha: 0.345678 };
+ app.run(cmds::SET, json!({"color": color})).unwrap();
+ let before = app.session.active().unwrap().doc.clone();
+ let dialog = open(app).unwrap();
+ crate::dialogs::confirm(app, dialog).unwrap();
+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));
+}
+
+#[test]
+fn picker_never_applies_to_a_different_document_with_the_same_layer_id() {
+ let (mut h, id) = harness(1.0);
+ let app = h.state_mut();
+ app.run("layer.select", json!({"layer": id.0})).unwrap();
+ let dialog = open(app).unwrap();
+ app.ui.dialog_mut(dialog).unwrap().fields.insert("color".into(), json!("#ff0000"));
+ app.run("file.new", json!({"width": 4, "height": 4})).unwrap();
+ app.run("layer.newFillLayer.solidColor", json!({})).unwrap();
+ let before = app.session.active().unwrap().doc.clone();
+ assert!(display_doc(app, app.session.active_index().unwrap()).is_none());
+ assert!(crate::dialogs::confirm(app, dialog).is_err());
+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));
+}
+
+#[test]
+fn cmyk_lab_preview_thumbnail_cancel_and_ok_are_consistent() {
+ for (command, mode) in [("image.mode.cmyk", ColorMode::Cmyk), ("image.mode.lab", ColorMode::Lab)] {
+ let (mut h, id) = harness(1.0);
+ let app = h.state_mut();
+ app.run(command, json!({})).unwrap();
+ app.run("layer.select", json!({"layer": id.0})).unwrap();
+ let before = app.session.active().unwrap().doc.clone();
+ let LayerContent::Fill(Fill::Solid(original)) = before.layer(id).unwrap().content else { panic!() };
+ assert_eq!(before.mode, mode);
+ let count = app.session.active().unwrap().history.entries().len();
+ let dialog = open(app).unwrap();
+ app.ui.dialog_mut(dialog).unwrap().fields.insert("color".into(), json!("#ff8800"));
+ let (shown, _) = display_doc(app, app.session.active_index().unwrap()).unwrap();
+ let LayerContent::Fill(Fill::Solid(preview)) = shown.layer(id).unwrap().content else { panic!() };
+ assert_eq!(preview, Color::rgba(1.0, 136.0 / 255.0, 0.0, original.alpha).in_mode(mode));
+ assert_eq!(thumbnail_color(app, before.id, id, original), preview);
+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));
+ assert_eq!(app.session.active().unwrap().history.entries().len(), count);
+ app.ui.close_dialog(dialog);
+ assert!(display_doc(app, app.session.active_index().unwrap()).is_none());
+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));
+ assert_eq!(app.session.active().unwrap().history.entries().len(), count);
+ let dialog = open(app).unwrap();
+ app.ui.dialog_mut(dialog).unwrap().fields.insert("color".into(), json!("#ff8800"));
+ crate::dialogs::confirm(app, dialog).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().content, LayerContent::Fill(Fill::Solid(preview)));
+ assert_eq!(app.session.active().unwrap().history.entries().len(), count + 1);
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(*app.session.active().unwrap().doc, *before);
+ app.run("edit.redo", json!({})).unwrap();
+ assert_eq!(app.session.active().unwrap().doc.layer(id).unwrap().content, LayerContent::Fill(Fill::Solid(preview)));
+ }
+}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index a7208f8f1..16660739a 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -83,6 +83,7 @@ store expose and persist the same setting; scripts keep using canonical command
| `layer.select` | `{"layer":id,"mode":"replace\|toggle\|range\|add"}`: ⌘-click = toggle, ⇧-click = range; `document.inspect` reports `selectedLayers` and a per-layer `selected` flag |
| `channel.target` / `channel.setVisible` | Channels panel target and eyes (`"composite"`, colour name, alpha index or name, `"quickMask"`). `document.inspect` (and `channel.list`) report `channels`: composite/colour/alpha rows with visibility, channel options, `quickMask`, `target`. Pixel commands without a `target` param follow the targeted channel |
| `layer.setProps` | `{"layer":id?,"name":…,"visible":…,"opacity":0..1,"blend":"Multiply"}` |
+| `layer.fill.solidColor.set` | `{"layer":id?,"document":id?,"color":"#rrggbb"}`: edit a Solid Color Fill in one undo step; RGB without alpha preserves the fill's alpha. Float RGB arrays and a stored `Color` are also accepted. `document` rejects stale dialog targets. |
| `layer.setExpanded` | `{"layer":id?,"expanded":bool?,"all":bool?}`: open/close a group in the Layers panel (no `expanded`: toggle; `all`: every group). A view change saved with the document (PSD open/closed folder), not an undo step; `document.inspect` reports `expanded` on groups |
| `layer.newAdjustmentLayer.hueSaturation` | `{"hue":30,"saturation":10}` |
| `paint.stroke` | `{"points":[[x,y,pressure],…],"size":20,"color":"#ff0000"}` |