Skip to content

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

Layers: Pattern Fill dialog for new and edited pattern fill layers (#2908) (#2979)

David Mann6601bbc3e7f5
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 9fa4caf90..01f669f14 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -1114,6 +1114,7 @@ fn build() -> Vec<CommandSpec> {
v.extend(crate::gallery_cmds::specs());
v.extend(crate::gradient_fill_cmds::specs());
v.extend(crate::solid_fill_cmds::specs());
+ v.extend(crate::pattern_fill_cmds::specs());
v.extend(crate::type_cmds::specs());
v.extend(crate::type_mask_cmds::specs());
v.extend(crate::transform_cmds::specs());
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 5264eee7a..3377eda07 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -73,6 +73,7 @@ pub mod notes_cmds;
pub mod paint_cmds;
mod path_edit_cmds;
pub mod pattern_cmds;
+pub mod pattern_fill_cmds;
pub mod perspective_crop_cmds;
pub mod photo_cmds;
pub mod pick_cmds;
diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/pattern_cmds.rs
index 2cf3cf144..21bee1283 100644
--- a/crates/engine/src/pattern_cmds.rs
+++ b/crates/engine/src/pattern_cmds.rs
@@ -305,18 +305,22 @@ pub(crate) fn placement(p: &Value) -> (f32, f32, bool, (f32, f32)) {
((num("scale", 100.0) / 100.0).clamp(0.01, 10.0), num("angle", 0.0), p.get("link").and_then(Value::as_bool).unwrap_or(true), phase)
}
+/// The edit of `layer.newFillLayer.pattern`: a Pattern Fill layer of `pat` placed as `p` asks,
+/// above `active`. The Pattern Fill dialog previews it on a copy of the document.
+pub(crate) fn insert_fill_layer(doc: &mut Document, active: &mut Option<photocraft_doc::LayerId>, pat: &Pattern, p: &Value) -> Result<photocraft_doc::LayerId> {
+ let (scale, angle, link, phase) = placement(p);
+ ensure_in_doc(doc, pat);
+ let fill = Fill::Pattern { name: pat.name.clone(), scale, id: pat.id.clone(), angle, link, phase };
+ let mut l = Layer::new(doc.next_layer_name("Pattern Fill"), LayerContent::Fill(fill));
+ crate::commands::mask_new_layer(doc, &mut l, p, "layer.newFillLayer.pattern")?;
+ let id = doc.insert_above(*active, l);
+ *active = Some(id);
+ Ok(id)
+}
+
fn new_fill_layer(s: &mut Session, p: &Value) -> Result<Value> {
let pat = resolve_param(s, "layer.newFillLayer.pattern", p)?;
- let (scale, angle, link, phase) = placement(p);
- let id = s.edit("New Pattern Fill Layer", |doc, active| {
- ensure_in_doc(doc, &pat);
- let fill = Fill::Pattern { name: pat.name.clone(), scale, id: pat.id.clone(), angle, link, phase };
- let mut l = Layer::new(doc.next_layer_name("Pattern Fill"), LayerContent::Fill(fill));
- crate::commands::mask_new_layer(doc, &mut l, p, "layer.newFillLayer.pattern")?;
- let id = doc.insert_above(*active, l);
- *active = Some(id);
- Ok(id)
- })?;
+ let id = s.edit("New Pattern Fill Layer", |doc, active| insert_fill_layer(doc, active, &pat, p))?;
Ok(json!({"layer": id.0, "pattern": pat.id}))
}
diff --git a/crates/engine/src/pattern_fill_cmds.rs b/crates/engine/src/pattern_fill_cmds.rs
new file mode 100644
index 000000000..daa7e9660
--- /dev/null
+++ b/crates/engine/src/pattern_fill_cmds.rs
@@ -0,0 +1,261 @@
+//! Editing a Pattern Fill layer: Photoshop's Pattern Fill dialog (pattern, Angle, Scale, Link with
+//! Layer, Snap to Origin) commits one undoable content edit, independent of the layer's masks.
+
+use photocraft_doc::{Document, Fill, LayerContent, Pattern};
+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.pattern.set";
+/// Layer › New Fill Layer › Pattern… (`pattern_cmds`).
+pub const CREATE: &str = "layer.newFillLayer.pattern";
+
+/// Photoshop's Scale range in the Pattern Fill dialog (percent).
+pub const SCALE_RANGE: (f64, f64) = (1.0, 1000.0);
+/// Largest phase (origin offset) accepted, in pixels.
+const MAX_PHASE: f64 = 1.0e7;
+
+fn bad(msg: impl Into<String>) -> EngineError {
+ EngineError::BadParams { cmd: SET.into(), msg: msg.into() }
+}
+
+/// The pattern fill `p` asks for, each param optional and defaulting to `base`. Returns the new
+/// fill and the pattern to copy into the document (when `pattern` was given).
+fn edited(s: &Session, base: &Fill, p: &Value) -> Result<(Fill, Option<Pattern>)> {
+ let Fill::Pattern { name, scale, id, angle, link, phase } = base else { return Err(bad("the target must be a Pattern Fill layer")) };
+ let num = |k: &str, (min, max): (f64, f64)| -> Result<Option<f32>> {
+ match p.get(k) {
+ None | Some(Value::Null) => Ok(None),
+ Some(v) => v
+ .as_f64()
+ .filter(|v| v.is_finite() && (min..=max).contains(v))
+ .map(|v| Some(v as f32))
+ .ok_or_else(|| bad(format!("`{k}` must be a number within {min}..{max}"))),
+ }
+ };
+ let (mut scale, mut angle, mut link, mut phase, mut pat) = (*scale, *angle, *link, *phase, None);
+ if let Some(v) = p.get("pattern").filter(|v| !v.is_null()) {
+ let key = v.as_str().filter(|k| !k.is_empty()).ok_or_else(|| bad("`pattern` is a pattern id or name"))?;
+ pat = Some(crate::pattern_cmds::resolve(s, key).ok_or_else(|| bad(format!("no pattern \"{key}\" (see pattern.list)")))?);
+ }
+ if let Some(v) = num("scale", SCALE_RANGE)? {
+ scale = v / 100.0;
+ }
+ if let Some(v) = num("angle", (-180.0, 180.0))? {
+ angle = v;
+ }
+ match p.get("link") {
+ None | Some(Value::Null) => {}
+ Some(v) => link = v.as_bool().ok_or_else(|| bad("`link` is true or false"))?,
+ }
+ match p.get("phase") {
+ None | Some(Value::Null) => {}
+ Some(v) => {
+ let a = v.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad("`phase` is [x, y]"))?;
+ let c = |i: usize| a.get(i).and_then(Value::as_f64).filter(|v| v.is_finite() && v.abs() <= MAX_PHASE).map(|v| v as f32);
+ let (Some(x), Some(y)) = (c(0), c(1)) else { return Err(bad(format!("`phase` needs finite coordinates within ±{MAX_PHASE}"))) };
+ phase = (x, y);
+ }
+ }
+ let (name, id) = match &pat {
+ Some(pat) => (pat.name.clone(), pat.id.clone()),
+ None => (name.clone(), id.clone()),
+ };
+ Ok((Fill::Pattern { name, scale, id, angle, link, phase }, pat))
+}
+
+/// The target layer and the fill `p` gives it, checked against the active document.
+fn target(s: &Session, p: &Value) -> Result<(photocraft_doc::LayerId, Fill, Fill, Option<Pattern>)> {
+ 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(original @ Fill::Pattern { .. }) = &layer.content else { return Err(bad("the target must be a Pattern Fill layer")) };
+ let (fill, pat) = edited(s, original, p)?;
+ Ok((id, original.clone(), fill, pat))
+}
+
+fn set(s: &mut Session, p: &Value) -> Result<Value> {
+ let (id, original, fill, pat) = target(s, p)?;
+ if fill != original {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ check_pixels_unlocked(&st.doc, id)?;
+ s.edit("Pattern Fill", |doc, _| {
+ if let Some(pat) = &pat {
+ crate::pattern_cmds::ensure_in_doc(doc, pat);
+ }
+ doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.content = LayerContent::Fill(fill.clone());
+ Ok(())
+ })?;
+ }
+ Ok(info(id, &fill))
+}
+
+fn info(layer: photocraft_doc::LayerId, fill: &Fill) -> Value {
+ match fill {
+ Fill::Pattern { scale, id, angle, link, phase, .. } => {
+ json!({"layer": layer.0, "pattern": id, "scale": scale * 100.0, "angle": angle, "link": link, "phase": [phase.0, phase.1]})
+ }
+ _ => json!({"layer": layer.0}),
+ }
+}
+
+/// The active document as [`SET`] or [`CREATE`] with `p` would leave it, without a history
+/// step: the Pattern Fill dialog's live preview, so it shows exactly what OK commits.
+pub fn preview(s: &Session, cmd: &str, p: &Value) -> Result<Document> {
+ let st = s.active().ok_or(EngineError::NoDocument)?;
+ let mut doc = (*st.doc).clone();
+ match cmd {
+ SET => {
+ let (id, _, fill, pat) = target(s, p)?;
+ if let Some(pat) = &pat {
+ crate::pattern_cmds::ensure_in_doc(&mut doc, pat);
+ }
+ doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.content = LayerContent::Fill(fill);
+ }
+ CREATE => {
+ let pat = crate::pattern_cmds::resolve_param(s, CREATE, p)?;
+ let mut active = st.active_layer;
+ crate::pattern_cmds::insert_fill_layer(&mut doc, &mut active, &pat, p)?;
+ }
+ other => return Err(EngineError::BadParams { cmd: other.into(), msg: "no Pattern Fill preview for this command".into() }),
+ }
+ Ok(doc)
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![CommandSpec {
+ id: SET,
+ label: "Pattern Fill…",
+ menu: &[],
+ shortcut: None,
+ params: r##"{"layer":id? (default active; a Pattern Fill layer),"document":id? (reject a stale dialog),"pattern":id|name?,"scale":1..1000?,"angle":-180..180?,"link":bool?,"phase":[x,y]? (Snap to Origin: [0,0])}; omitted values keep the layer's"##,
+ enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()),
+ run: set,
+ journal: true,
+ }]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use photocraft_doc::LayerId;
+ use std::sync::Arc;
+
+ fn session(depth: u64) -> (Session, LayerId) {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap();
+ s.execute("select.rect", json!({"x": 2, "y": 2, "width": 20, "height": 10})).unwrap();
+ let id = s.execute(CREATE, json!({"pattern": "Checkerboard"})).unwrap()["layer"].as_u64().unwrap();
+ (s, LayerId(id))
+ }
+
+ fn fill(s: &Session, id: LayerId) -> Fill {
+ let LayerContent::Fill(f) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("not a fill") };
+ f.clone()
+ }
+
+ #[test]
+ fn edit_keeps_masks_is_one_step_and_undoes_at_every_depth() {
+ for depth in [8, 16, 32] {
+ let (mut s, id) = session(depth);
+ let before = s.active().unwrap().doc.clone();
+ let count = s.active().unwrap().history.entries().len();
+ let r = s.execute(SET, json!({"layer": id.0, "pattern": "Bricks", "scale": 250, "angle": -45, "link": false, "phase": [3, -4]})).unwrap();
+ assert_eq!(r["scale"], json!(250.0));
+ let bricks = crate::pattern_cmds::resolve(&s, "Bricks").unwrap();
+ assert_eq!(
+ fill(&s, id),
+ Fill::Pattern { name: bricks.name.clone(), scale: 2.5, id: bricks.id.clone(), angle: -45.0, link: false, phase: (3.0, -4.0) }
+ );
+ let st = s.active().unwrap();
+ assert_eq!(st.history.entries().len(), count + 1);
+ assert!(st.doc.patterns.iter().any(|p| p.id == bricks.id), "the new pattern is copied into the document");
+ assert_eq!(st.doc.layer(id).unwrap().mask, before.layer(id).unwrap().mask, "the selection mask is kept");
+ // Omitted values keep the layer's; Snap to Origin zeroes the phase.
+ s.execute(SET, json!({"phase": [0, 0]})).unwrap();
+ let Fill::Pattern { scale, angle, phase, link, .. } = fill(&s, id) else { panic!() };
+ assert_eq!((scale, angle, phase, link), (2.5, -45.0, (0.0, 0.0), false));
+ s.undo();
+ s.undo();
+ assert_eq!(*s.active().unwrap().doc, *before);
+ s.redo();
+ assert_eq!(fill(&s, id), Fill::Pattern { name: bricks.name.clone(), scale: 2.5, id: bricks.id, angle: -45.0, link: false, phase: (3.0, -4.0) });
+ let count = s.active().unwrap().history.entries().len();
+ s.execute(SET, json!({"scale": 250, "angle": -45})).unwrap();
+ assert_eq!(s.active().unwrap().history.entries().len(), count, "an unchanged fill is not a history step");
+ }
+ }
+
+ #[test]
+ fn preview_matches_what_the_command_commits() {
+ let (mut s, id) = session(8);
+ let p = json!({"layer": id.0, "pattern": "Dots", "scale": 50, "angle": 30});
+ let (before, count) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.entries().len());
+ let shown = preview(&s, SET, &p).unwrap();
+ assert!(Arc::ptr_eq(&before, &s.active().unwrap().doc));
+ assert_eq!(s.active().unwrap().history.entries().len(), count, "previewing is not an edit");
+ s.execute(SET, p).unwrap();
+ assert_eq!(shown, *s.active().unwrap().doc);
+ let p = json!({"pattern": "Grid", "scale": 300, "angle": 90, "link": false});
+ let shown = preview(&s, CREATE, &p).unwrap();
+ s.execute(CREATE, p).unwrap();
+ // Layer ids are allocated per process, so the preview's new layer has its own id: compare
+ // what the documents look like.
+ let all = photocraft_geom::Rect::new(0, 0, 40, 30);
+ assert_eq!(photocraft_compose::render(&shown, all).px, photocraft_compose::render(&s.active().unwrap().doc, all).px);
+ assert_eq!(shown.layers.len(), s.active().unwrap().doc.layers.len());
+ assert!(preview(&s, "edit.fill", &json!({})).is_err());
+ }
+
+ #[test]
+ fn bad_params_and_targets_are_errors_not_panics() {
+ let (mut s, id) = session(8);
+ let before = s.active().unwrap().doc.clone();
+ for p in [
+ json!(null),
+ json!([1, 2]),
+ json!({"layer": -1}),
+ json!({"layer": "x"}),
+ json!({"layer": 999_999}),
+ json!({"document": 999_999}),
+ json!({"pattern": "nope"}),
+ json!({"pattern": ""}),
+ json!({"pattern": 5}),
+ json!({"scale": 0}),
+ json!({"scale": 1001}),
+ json!({"scale": "big"}),
+ json!({"angle": 181}),
+ json!({"angle": -1e300}),
+ json!({"link": "yes"}),
+ json!({"phase": [1]}),
+ json!({"phase": [1, "x"]}),
+ json!({"phase": [1e30, 0]}),
+ json!({"phase": {"x": 1}}),
+ ] {
+ assert!(s.execute(SET, p.clone()).is_err(), "{p}");
+ assert!(preview(&s, SET, &p).is_err(), "{p}");
+ }
+ s.execute("layer.new.layer", json!({})).unwrap();
+ assert!(s.execute(SET, json!({"scale": 50})).is_err(), "a pixel layer is not a Pattern Fill");
+ s.execute("layer.newFillLayer.solidColor", json!({})).unwrap();
+ assert!(s.execute(SET, json!({"scale": 50})).is_err(), "a Solid Color Fill is not a Pattern Fill");
+ assert_eq!(s.active().unwrap().doc.layer(id), before.layer(id));
+ assert!(Session::new().execute(SET, json!({})).is_err(), "no document");
+ }
+
+ #[test]
+ fn locked_layer_is_refused() {
+ let (mut s, id) = session(8);
+ s.execute("layer.lockLayers", json!({"pixels": true})).unwrap();
+ assert!(s.execute(SET, json!({"layer": id.0, "scale": 50})).is_err());
+ }
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 74a261252..bf57067c0 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -965,6 +965,9 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Ar
if let Some(shown) = crate::solid_fill_ui::display_doc(app, idx) {
return shown;
}
+ if let Some(shown) = crate::pattern_fill_ui::display_doc(app, idx) {
+ return shown;
+ }
if let Some(shown) = crate::shape_fill_ui::display_doc(app, idx) {
return shown;
}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index c3994e591..1823542fe 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -212,6 +212,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
DialogKind::Command if crate::guide_layout_ui::owns(&fields) => outcome = crate::guide_layout_ui::body(app, ui, &mut fields, interactive),
DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields),
+ DialogKind::Command if crate::pattern_fill_ui::owns(&fields) => crate::pattern_fill_ui::body(app, ui, &mut fields),
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),
@@ -440,6 +441,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
}
DialogKind::Command if crate::guide_layout_ui::owns(&d.fields) => crate::guide_layout_ui::confirm(app, &d.fields),
DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields),
+ DialogKind::Command if crate::pattern_fill_ui::owns(&d.fields) => crate::pattern_fill_ui::confirm(app, &d.fields),
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),
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index d0ed52cff..60e6a3474 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2543,5 +2543,7 @@ cameraData Lens Objektiv
Select the crop presets to delete Vyberte předvolby oříznutí k odstranění
Enter a name for the crop preset Zadejte název předvolby oříznutí
There is no crop size or ratio to save Není žádná velikost ani poměr oříznutí k uložení
+ Scale: Měřítko:
+ Snap to Origin Přichytit k počátku
Search settings… Hledat nastavení…
No matching settings Žádná odpovídající nastavení
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index dc2f87dfa..13789303c 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2574,5 +2574,7 @@ cameraData Lens Objektiv
Select the crop presets to delete Wählen Sie die zu löschenden Freistellungsvorgaben
Enter a name for the crop preset Geben Sie einen Namen für die Freistellungsvorgabe ein
There is no crop size or ratio to save Es gibt keine Freistellungsgröße und kein Seitenverhältnis zum Speichern
+ Scale: Skalierung:
+ Snap to Origin An Ursprung ausrichten
Search settings… Einstellungen durchsuchen…
No matching settings Keine passenden Einstellungen
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index 726df4723..14833e03c 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -3637,5 +3637,7 @@ cameraData Lens Φακός
Select the crop presets to delete Επιλέξτε τις προεπιλογές περικοπής για διαγραφή
Enter a name for the crop preset Εισαγάγετε ένα όνομα για την προεπιλογή περικοπής
There is no crop size or ratio to save Δεν υπάρχει μέγεθος ή αναλογία περικοπής για αποθήκευση
+ Scale: Κλίμακα:
+ Snap to Origin Προσκόλληση στην αρχή
Search settings… Αναζήτηση ρυθμίσεων…
No matching settings Δεν βρέθηκαν ρυθμίσεις
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index cb6fa2460..68500026d 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2616,5 +2616,7 @@ cameraData Lens Objetivo
Select the crop presets to delete Seleccione los ajustes preestablecidos de recorte que desea eliminar
Enter a name for the crop preset Introduzca un nombre para el ajuste preestablecido de recorte
There is no crop size or ratio to save No hay ningún tamaño ni proporción de recorte que guardar
+ Scale: Escala:
+ Snap to Origin Ajustar a origen
Search settings… Buscar ajustes…
No matching settings No hay ajustes que coincidan
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index fa1bac0db..f5f7ccb4c 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2952,5 +2952,7 @@ cameraData Lens Objectif
Select the crop presets to delete Sélectionnez les paramètres prédéfinis de recadrage à supprimer
Enter a name for the crop preset Saisissez un nom pour le paramètre prédéfini de recadrage
There is no crop size or ratio to save Aucune taille ni proportion de recadrage à enregistrer
+ Scale: Échelle :
+ Snap to Origin Aligner sur l'origine
Search settings… Rechercher des réglages…
No matching settings Aucun réglage correspondant
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index acf8860d4..c5c05f3cf 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2939,5 +2939,7 @@ cameraData Lens Lensa
Select the crop presets to delete Pilih preset pangkas yang akan dihapus
Enter a name for the crop preset Masukkan nama untuk preset pangkas
There is no crop size or ratio to save Tidak ada ukuran atau rasio pangkas untuk disimpan
+ Scale: Skala:
+ Snap to Origin Jepret ke Titik Asal
Search settings… Cari pengaturan…
No matching settings Tidak ada pengaturan yang cocok
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 57e14771c..c1f75bcc2 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2606,5 +2606,7 @@ cameraData Lens Obiettivo
Select the crop presets to delete Seleziona i predefiniti di ritaglio da eliminare
Enter a name for the crop preset Inserisci un nome per il predefinito di ritaglio
There is no crop size or ratio to save Non c'è nessuna dimensione o proporzione di ritaglio da salvare
+ Scale: Scala:
+ Snap to Origin Aggancia all'origine
Search settings… Cerca impostazioni…
No matching settings Nessuna impostazione corrispondente
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 907a8bd7f..e8d8eebee 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -3551,5 +3551,7 @@ cameraData Lens レンズ
Select the crop presets to delete 削除する切り抜きプリセットを選択してください
Enter a name for the crop preset 切り抜きプリセットの名前を入力してください
There is no crop size or ratio to save 保存する切り抜きのサイズまたは比率がありません
+ Scale: 比率:
+ Snap to Origin 原点にスナップ
Search settings… 設定を検索…
No matching settings 一致する設定はありません
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 74463f57b..7b068773b 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -3120,5 +3120,7 @@ cameraData Lens 렌즈
Select the crop presets to delete 삭제할 자르기 사전 설정을 선택하십시오
Enter a name for the crop preset 자르기 사전 설정의 이름을 입력하십시오
There is no crop size or ratio to save 저장할 자르기 크기나 비율이 없습니다
+ Scale: 비율:
+ Snap to Origin 원점에 스냅
Search settings… 설정 검색…
No matching settings 일치하는 설정 없음
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 6cca65919..2dbcc0277 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -3705,3 +3705,5 @@ cameraData Lens Lens
Create a new rectangular frame Nieuw rechthoekig kader maken
Create a new elliptical frame Nieuw ovaal kader maken
Include in playback Opnemen in afspelen
+ Scale: Schaal:
+ Snap to Origin Uitlijnen op oorsprong
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 9e681356e..44e17ebb5 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -3552,5 +3552,7 @@ cameraData Lens Obiektyw
Select the crop presets to delete Wybierz ustawienia kadrowania do usunięcia
Enter a name for the crop preset Wprowadź nazwę ustawienia kadrowania
There is no crop size or ratio to save Brak rozmiaru lub proporcji kadrowania do zapisania
+ Scale: Skala:
+ Snap to Origin Przyciągnij do początku
Search settings… Szukaj ustawień…
No matching settings Brak pasujących ustawień
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 370a58c78..e38325c37 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2959,5 +2959,7 @@ cameraData Lens Lente
Select the crop presets to delete Selecione as predefinições de corte a excluir
Enter a name for the crop preset Digite um nome para a predefinição de corte
There is no crop size or ratio to save Não há tamanho nem proporção de corte para salvar
+ Scale: Escala:
+ Snap to Origin Ajustar à origem
Search settings… Pesquisar configurações…
No matching settings Nenhuma configuração encontrada
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index c83fe7c80..905c0b417 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2873,6 +2873,9 @@ cameraData Lens Объектив
Curve Fit: Точность кривой:
Drag: draw freehand · Release on the start point: close Перетаскивание: рисовать от руки · отпустить на начальной точке: замкнуть
Click: smooth point · Double-click: corner · Drag a point: move · Click first point: close · {key} finish Клик: гладкая точка · двойной клик: угол · перетаскивание точки: переместить · клик по первой точке: замкнуть · {key} завершить
+ Scale: Масштаб:
+ Snap to Origin Привязать к началу координат
+ Link with Layer Связать со слоем
Rasterize Layer Style Растрировать стиль слоя
Search settings… Поиск настроек…
No matching settings Нет подходящих настроек
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index fa2812560..4cb207ecc 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -3641,3 +3641,5 @@ cameraData Lens Об'єктив
Select the crop presets to delete Виберіть набори параметрів кадрування для видалення
Enter a name for the crop preset Введіть назву набору параметрів кадрування
There is no crop size or ratio to save Немає розміру чи співвідношення сторін кадрування для збереження
+ Scale: Масштаб:
+ Snap to Origin Прив'язати до початку координат
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 5e60d76ae..f4156cbdc 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2544,6 +2544,8 @@ cameraData Lens 镜头
Curve Fit: 曲线拟合:
Drag: draw freehand · Release on the start point: close 拖动:自由绘制 · 在起点松开:闭合
Click: smooth point · Double-click: corner · Drag a point: move · Click first point: close · {key} finish 单击:平滑点 · 双击:角点 · 拖动点:移动 · 单击起点:闭合 · {key} 完成
+ Scale: 缩放:
+ Snap to Origin 贴紧原点
Search settings… 搜索设置…
No matching settings 没有匹配的设置
New Crop Preset… 新建裁剪预设…
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 70d2ac05f..9ce516bf9 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2514,6 +2514,8 @@ cameraData Lens 鏡頭
Curve Fit: 曲線擬合:
Drag: draw freehand · Release on the start point: close 拖曳:手繪 · 在起點放開:閉合
Click: smooth point · Double-click: corner · Drag a point: move · Click first point: close · {key} finish 按一下:平滑點 · 按兩下:轉角 · 拖曳點:移動 · 按一下第一點:閉合 · {key} 完成
+ Scale: 縮放:
+ Snap to Origin 靠齊原點
Search settings… 搜尋設定…
No matching settings 沒有符合的設定
New Crop Preset… 新增裁切預設集…
diff --git a/crates/ui-egui/src/layer_style.rs b/crates/ui-egui/src/layer_style.rs
index f582197bd..b934b3d3e 100644
--- a/crates/ui-egui/src/layer_style.rs
+++ b/crates/ui-egui/src/layer_style.rs
@@ -1288,7 +1288,7 @@ fn blend_if_bar(ui: &mut egui::Ui, id: egui::Id, q: &mut [u8; 4]) -> bool {
}
/// Light direction uses document angles: counter-clockwise from three o'clock.
-fn angle_row(ui: &mut egui::Ui, label: &str, angle: &mut f32) -> egui::Response {
+pub(crate) fn angle_row(ui: &mut egui::Ui, label: &str, angle: &mut f32) -> egui::Response {
let t = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(RichText::new(tl!(label)).color(t.text_dim));
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 0dabb759b..5f4fcff16 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -124,6 +124,7 @@ mod panel_docking;
pub mod panels;
pub mod parity;
pub mod patch_preview;
+pub(crate) mod pattern_fill_ui;
pub mod pattern_preview;
pub mod perspective_crop_ui;
pub mod perspective_ui;
@@ -582,6 +583,8 @@ pub struct PhotocraftApp {
/// 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>,
+ /// Live Pattern Fill dialog preview (pattern_fill_ui).
+ pub(crate) pattern_fill_preview: Option<pattern_fill_ui::Preview>,
/// Shape fill Color Picker preview (shape_fill_ui).
pub(crate) shape_fill_preview: Option<shape_fill_ui::Preview>,
/// Liquify dialog, Puppet Warp and Perspective Warp sessions (distort_ui).
@@ -749,6 +752,7 @@ impl PhotocraftApp {
style_preview: None,
text_style_preview: None,
solid_fill_preview: None,
+ pattern_fill_preview: None,
shape_fill_preview: None,
distort: Default::default(),
gradient: Default::default(),
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 2bc1829e9..5b5b28b67 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -425,12 +425,15 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
}
Ok(Value::Null)
}
- // Solid Color fills and solid-colour shapes use the Color Picker; other adjustment /
- // fill / shape controls use Properties.
+ // Solid Color fills and solid-colour shapes use the Color Picker, Pattern fills the Pattern
+ // Fill dialog; other adjustment / fill / shape controls use Properties.
"layer.layerContentOptions" => {
if let Some(dialog) = crate::solid_fill_ui::open(app).or_else(|| crate::shape_fill_ui::open(app)) {
return Ok(json!({"dialog": dialog}));
}
+ if let Some(dialog) = crate::pattern_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;
@@ -447,6 +450,11 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
// Photoshop's "Select and Mask…" is the engine's select.refineEdge.
// Select › Color Range… from the menu: the dialog (with params: the engine directly).
"select.colorRange" if params.as_object().is_none_or(|o| o.is_empty()) => Ok(json!({"dialog": crate::color_range_ui::open(app)})),
+ // Layer › New Fill Layer › Pattern… from the menu: the Pattern Fill dialog (with params:
+ // the engine directly).
+ photocraft_engine::pattern_fill_cmds::CREATE if params.as_object().is_none_or(|o| o.is_empty()) => {
+ Ok(json!({"dialog": crate::pattern_fill_ui::open_new(app)?}))
+ }
// Edit › Fill… from the menu or its shortcuts: the Fill dialog (with params: the engine).
crate::fill_ui::COMMAND if params.as_object().is_none_or(|o| o.is_empty()) => {
if let Some(Err(why)) = photocraft_engine::commands::find(id).map(|c| (c.enabled)(&app.session)) {
diff --git a/crates/ui-egui/src/pattern_fill_ui.rs b/crates/ui-egui/src/pattern_fill_ui.rs
new file mode 100644
index 000000000..859c0f22a
--- /dev/null
+++ b/crates/ui-egui/src/pattern_fill_ui.rs
@@ -0,0 +1,194 @@
+//! Photoshop's Pattern Fill dialog (#2908): Layer › New Fill Layer › Pattern… and double-clicking a
+//! Pattern Fill layer's thumbnail open it. Pattern (swatch picker), Snap to Origin, Angle, Scale
+//! and Link with Layer, previewed live on the canvas from a document snapshot. OK runs one engine
+//! command (`layer.newFillLayer.pattern` for a new layer, `layer.fill.pattern.set` for an existing
+//! one), so it is one History step; Cancel changes nothing. The fields are the command's params,
+//! so `ui.dialog.set` / `ui.dialog.confirm` drive it like any dialog.
+
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+use photocraft_doc::{DocId, Document, Fill, LayerContent};
+use photocraft_engine::pattern_fill_cmds as cmds;
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+use crate::theme::Tokens;
+
+const MARK: &str = "__patternFill";
+/// The fields that are command params (besides the target in `__params`).
+const KEYS: [&str; 5] = ["pattern", "scale", "angle", "link", "phase"];
+
+pub(crate) struct Preview {
+ document: DocId,
+ revision: u64,
+ dialog: u64,
+ params: Value,
+ shown: Arc<Document>,
+ key: u64,
+}
+
+/// Is this dialog the Pattern Fill dialog?
+pub(crate) fn owns(f: &Map<String, Value>) -> bool {
+ f.contains_key(MARK)
+}
+
+fn fields(command: &str, target: Value, values: Value) -> Map<String, Value> {
+ let mut f = Map::new();
+ f.insert(MARK.into(), json!(true));
+ f.insert("__command".into(), json!(command));
+ f.insert("__label".into(), json!("Pattern Fill"));
+ f.insert("__params".into(), target);
+ for k in KEYS {
+ if let Some(v) = values.get(k) {
+ f.insert(k.into(), v.clone());
+ }
+ }
+ f.insert("__orig".into(), values);
+ f
+}
+
+/// Edit the active Pattern Fill layer (its thumbnail, Layer › Layer Content Options…).
+pub(crate) fn open(app: &mut PhotocraftApp) -> Option<u64> {
+ let st = app.session.active()?;
+ let layer = st.active_layer?;
+ let LayerContent::Fill(Fill::Pattern { scale, id, angle, link, phase, .. }) = &st.doc.layer(layer)?.content else { return None };
+ let values = json!({"pattern": id, "scale": scale * 100.0, "angle": angle, "link": link, "phase": [phase.0, phase.1]});
+ let f = fields(cmds::SET, json!({"layer": layer.0, "document": st.doc.id.0}), values);
+ Some(app.ui.open_dialog(crate::state::DialogKind::Command, f))
+}
+
+/// Layer › New Fill Layer › Pattern…: the dialog in front of creating the layer, starting from
+/// the Patterns panel's pattern at 100 %, 0° and linked, as in Photoshop.
+pub(crate) fn open_new(app: &mut PhotocraftApp) -> Result<u64, String> {
+ if let Some(Err(why)) = photocraft_engine::commands::find(cmds::CREATE).map(|c| (c.enabled)(&app.session)) {
+ return Err(why);
+ }
+ let st = app.session.active().ok_or("no document open")?;
+ let pattern = photocraft_engine::pattern_cmds::resolve(&app.session, "").ok_or("no patterns")?;
+ let values = json!({"pattern": pattern.id, "scale": 100.0, "angle": 0.0, "link": true, "phase": [0.0, 0.0]});
+ let f = fields(cmds::CREATE, json!({"document": st.doc.id.0}), values);
+ Ok(app.ui.open_dialog(crate::state::DialogKind::Command, f))
+}
+
+/// The command and its params: the target plus the dialog's values.
+fn command(app: &PhotocraftApp, f: &Map<String, Value>) -> Option<(&'static str, Value)> {
+ let cmd = match f.get("__command").and_then(Value::as_str)? {
+ cmds::SET => cmds::SET,
+ cmds::CREATE => cmds::CREATE,
+ _ => return None,
+ };
+ let mut params = f.get("__params").filter(|p| p.is_object()).cloned()?;
+ for k in KEYS {
+ if let Some(v) = f.get(k) {
+ params[k] = v.clone();
+ }
+ }
+ // A new fill layer is masked by the path selected in the Paths panel, as when it runs.
+ let params = if cmd == cmds::CREATE {
+ params.as_object_mut()?.remove("document");
+ crate::vector_ui::with_active_path(app, cmd, params)
+ } else {
+ params
+ };
+ Some((cmd, params))
+}
+
+/// An edit dialog whose values are still the layer's.
+fn unchanged(f: &Map<String, Value>) -> bool {
+ f.get("__command").and_then(Value::as_str) == Some(cmds::SET) && KEYS.iter().all(|k| f.get(*k) == f.get("__orig").and_then(|o| o.get(*k)))
+}
+
+/// The document the dialog targets, if it is still the active one.
+fn target_is_active(app: &PhotocraftApp, f: &Map<String, Value>) -> bool {
+ let target = f.get("__params").and_then(|p| p.get("document")).and_then(Value::as_u64);
+ app.session.active().is_some_and(|st| target == Some(st.doc.id.0))
+}
+
+/// OK: one engine command. A stale document never receives the edit.
+pub(crate) fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
+ if !target_is_active(app, f) {
+ return Err("the target document is no longer active".into());
+ }
+ if unchanged(f) {
+ return Ok(json!({"unchanged": true}));
+ }
+ let (cmd, params) = command(app, f).ok_or("invalid Pattern Fill dialog")?;
+ app.run(cmd, params)
+}
+
+/// The canvas preview while the dialog is open: the document as OK would leave it.
+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.pattern_fill_preview = None;
+ return None;
+ };
+ let st = app.session.documents().get(idx)?;
+ if !target_is_active(app, &d.fields) || app.session.active_index() != Some(idx) || unchanged(&d.fields) {
+ return None;
+ }
+ let (cmd, params) = command(app, &d.fields)?;
+ if let Some(p) = &app.pattern_fill_preview
+ && p.document == st.doc.id
+ && p.revision == st.revision
+ && p.dialog == d.id
+ && p.params == params
+ {
+ return Some((p.shown.clone(), p.key));
+ }
+ // Out-of-range values typed by automation show the committed document; OK reports them.
+ let doc = cmds::preview(&app.session, cmd, &params).ok()?;
+ // 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, params.to_string()).hash(&mut hash);
+ let key = (1 << 47) | (hash.finish() & ((1 << 36) - 1));
+ let (document, revision, dialog) = (st.doc.id, st.revision, d.id);
+ let shown = Arc::new(photocraft_engine::mode_cmds::display_document(&doc).unwrap_or(doc));
+ app.pattern_fill_preview = Some(Preview { document, revision, dialog, params, shown: shown.clone(), key });
+ Some((shown, key))
+}
+
+fn num(f: &Map<String, Value>, k: &str, d: f64) -> f32 {
+ f.get(k).and_then(Value::as_f64).unwrap_or(d) as f32
+}
+
+/// The dialog body, in Photoshop's layout: the pattern with Snap to Origin beside it, then
+/// Angle, Scale and Link with Layer.
+pub(crate) fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
+ ui.spacing_mut().item_spacing.y = 6.0;
+ ui.horizontal(|ui| {
+ let pat = f.get("pattern").and_then(Value::as_str).unwrap_or_default().to_string();
+ if app.session.patterns.items.is_empty() {
+ ui.label(egui::RichText::new(tl!("No patterns")).color(Tokens::get(ui.ctx()).text_faint));
+ } else if let Some(id) = crate::preset_panels::pattern_picker(app, ui, &pat) {
+ f.insert("pattern".into(), json!(id));
+ }
+ ui.add_space(8.0);
+ // Photoshop: Snap to Origin puts the pattern's origin back at the layer's (or canvas's).
+ if crate::widgets::secondary_button(ui, tl!("Snap to Origin"), 110.0).clicked() {
+ f.insert("phase".into(), json!([0.0, 0.0]));
+ }
+ });
+ let mut angle = num(f, "angle", 0.0);
+ if crate::layer_style::angle_row(ui, tl!("Angle:"), &mut angle).changed() {
+ f.insert("angle".into(), json!(angle.clamp(-180.0, 180.0)));
+ }
+ let (min, max) = cmds::SCALE_RANGE;
+ let mut scale = num(f, "scale", 100.0);
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new(tl!("Scale:")).color(Tokens::get(ui.ctx()).text_dim));
+ if crate::widgets::value_field(ui, &mut scale, min as f32..=max as f32, "%", 70.0).changed() {
+ f.insert("scale".into(), json!(scale.clamp(min as f32, max as f32)));
+ }
+ });
+ let mut link = f.get("link").and_then(Value::as_bool).unwrap_or(true);
+ if crate::widgets::checkbox(ui, &mut link, tl!("Link with Layer")).changed() {
+ f.insert("link".into(), json!(link));
+ }
+}
+
+#[cfg(test)]
+#[path = "pattern_fill_ui_tests.rs"]
+mod tests;
diff --git a/crates/ui-egui/src/pattern_fill_ui_tests.rs b/crates/ui-egui/src/pattern_fill_ui_tests.rs
new file mode 100644
index 000000000..4fc88522b
--- /dev/null
+++ b/crates/ui-egui/src/pattern_fill_ui_tests.rs
@@ -0,0 +1,172 @@
+use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2};
+use egui_kittest::Harness;
+use egui_kittest::kittest::Queryable;
+use photocraft_doc::{Fill, LayerContent, LayerId};
+use serde_json::json;
+
+use super::*;
+
+fn app() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 40, "height": 30, "depth": 16})).unwrap();
+ app
+}
+
+fn pattern_id(app: &PhotocraftApp, name: &str) -> String {
+ app.session.patterns.items.iter().find(|p| p.name == name).unwrap().id.clone()
+}
+
+fn steps(app: &PhotocraftApp) -> usize {
+ app.session.active().unwrap().history.entries().len()
+}
+
+fn set(app: &mut PhotocraftApp, dialog: u64, values: serde_json::Value) {
+ let d = app.ui.dialog_mut(dialog).unwrap();
+ for (k, v) in values.as_object().unwrap() {
+ d.fields.insert(k.clone(), v.clone());
+ }
+}
+
+#[test]
+fn new_pattern_fill_opens_the_dialog_previews_and_ok_is_one_step() {
+ let mut app = app();
+ let ctx = egui::Context::default();
+ let before = app.session.active().unwrap().doc.clone();
+ let count = steps(&app);
+ let dialog = crate::menus::invoke(&mut app, &ctx, cmds::CREATE, json!({})).unwrap()["dialog"].as_u64().unwrap();
+ let d = app.ui.dialogs.last().unwrap();
+ assert!(owns(&d.fields));
+ assert_eq!(crate::dialogs::title(d), "Pattern Fill");
+ assert_eq!((d.fields["scale"].clone(), d.fields["angle"].clone(), d.fields["link"].clone()), (json!(100.0), json!(0.0), json!(true)));
+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc), "no layer until OK");
+ let bricks = pattern_id(&app, "Bricks");
+ set(&mut app, dialog, json!({"pattern": bricks, "scale": 200.0, "angle": 45.0, "link": false}));
+ let (shown, key) = display_doc(&mut app, 0).unwrap();
+ let (again, again_key) = display_doc(&mut app, 0).unwrap();
+ assert!(Arc::ptr_eq(&shown, &again) && key == again_key, "the preview is cached");
+ assert_eq!(shown.layers.len(), before.layers.len() + 1, "the preview shows the new layer");
+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc), "previewing does not edit");
+ assert_eq!(steps(&app), count);
+ crate::dialogs::confirm(&mut app, dialog).unwrap();
+ assert_eq!(steps(&app), count + 1);
+ let st = app.session.active().unwrap();
+ let LayerContent::Fill(Fill::Pattern { id, scale, angle, link, .. }) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else {
+ panic!("no pattern fill")
+ };
+ assert_eq!((id.as_str(), *scale, *angle, *link), (bricks.as_str(), 2.0, 45.0, false));
+ assert!(display_doc(&mut app, 0).is_none() && app.pattern_fill_preview.is_none());
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(*app.session.active().unwrap().doc, *before);
+}
+
+#[test]
+fn cancelling_a_new_pattern_fill_adds_nothing() {
+ let mut app = app();
+ let ctx = egui::Context::default();
+ let before = app.session.active().unwrap().doc.clone();
+ let count = steps(&app);
+ let dialog = crate::menus::invoke(&mut app, &ctx, cmds::CREATE, json!({})).unwrap()["dialog"].as_u64().unwrap();
+ set(&mut app, dialog, json!({"scale": 300.0}));
+ assert!(display_doc(&mut app, 0).is_some());
+ crate::dialogs::cancel(&mut app, dialog).unwrap();
+ assert!(display_doc(&mut app, 0).is_none());
+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));
+ assert_eq!(steps(&app), count);
+ // Explicit params (Actions, CLI, MCP) still create the layer directly.
+ let r = crate::menus::invoke(&mut app, &ctx, cmds::CREATE, json!({"pattern": "Grid"})).unwrap();
+ assert!(r["layer"].as_u64().is_some());
+ // No document: an error, not a dialog or a panic.
+ let mut empty = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ assert!(crate::menus::invoke(&mut empty, &ctx, cmds::CREATE, json!({})).is_err());
+ assert!(empty.ui.dialogs.is_empty());
+}
+
+#[test]
+fn content_options_edit_the_layer_and_cancel_restores() {
+ let mut app = app();
+ let ctx = egui::Context::default();
+ let id = app.run(cmds::CREATE, json!({"pattern": "Checkerboard", "scale": 150, "angle": 10})).unwrap()["layer"].as_u64().unwrap();
+ let before = app.session.active().unwrap().doc.clone();
+ let count = steps(&app);
+ let dialog = crate::menus::invoke(&mut app, &ctx, "layer.layerContentOptions", serde_json::Value::Null).unwrap()["dialog"].as_u64().unwrap();
+ let checkerboard = pattern_id(&app, "Checkerboard");
+ let f = &app.ui.dialog_mut(dialog).unwrap().fields;
+ assert!(owns(f));
+ assert_eq!((f["pattern"].clone(), f["scale"].clone(), f["angle"].clone()), (json!(checkerboard), json!(150.0), json!(10.0)));
+ assert_eq!(f["__params"]["layer"], id);
+ // Unchanged: no preview and OK is no History step.
+ assert!(display_doc(&mut app, 0).is_none());
+ crate::dialogs::confirm(&mut app, dialog).unwrap();
+ assert_eq!(steps(&app), count);
+ // Changed then cancelled: previewed, but the layer keeps its fill.
+ let dialog = open(&mut app).unwrap();
+ let dots = pattern_id(&app, "Dots");
+ set(&mut app, dialog, json!({"pattern": dots, "phase": [5.0, 5.0]}));
+ let (shown, _) = display_doc(&mut app, 0).unwrap();
+ assert!(matches!(&shown.layer(LayerId(id)).unwrap().content, LayerContent::Fill(Fill::Pattern { phase, .. }) if *phase == (5.0, 5.0)));
+ crate::dialogs::cancel(&mut app, dialog).unwrap();
+ assert!(Arc::ptr_eq(&before, &app.session.active().unwrap().doc));
+ assert!(display_doc(&mut app, 0).is_none());
+ // A stale dialog never edits another document.
+ let dialog = open(&mut app).unwrap();
+ set(&mut app, dialog, json!({"scale": 50.0}));
+ app.run("file.new", json!({"width": 4, "height": 4})).unwrap();
+ assert!(display_doc(&mut app, 1).is_none());
+ assert!(crate::dialogs::confirm(&mut app, dialog).is_err());
+ // Gradient and Solid Color fills keep their own editors.
+ app.run("layer.newFillLayer.gradient", json!({})).unwrap();
+ assert!(open(&mut app).is_none());
+}
+
+fn harness() -> (Harness<'static, PhotocraftApp>, LayerId) {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
+ let id = LayerId(s.execute(cmds::CREATE, json!({"pattern": "Checkerboard"})).unwrap()["layer"].as_u64().unwrap());
+ s.execute("layer.new.layer", json!({"name": "Other"})).unwrap();
+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).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);
+ }
+}
+
+#[test]
+fn double_clicking_the_thumbnail_opens_the_dialog_and_a_picked_pattern_is_applied() {
+ let (mut h, id) = harness();
+ let r = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == id.0).unwrap().row;
+ let count = steps(h.state());
+ double_click(&mut h, pos2(r.left() + 46.0, r.center().y));
+ let d = h.state().ui.dialogs.last().expect("the Pattern Fill dialog opened").clone();
+ assert!(owns(&d.fields));
+ assert_eq!(d.fields["__params"]["layer"], id.0);
+ h.run_steps(3);
+ h.get_by_role_and_label(egui::accesskit::Role::Button, "Patterns").click();
+ h.run_steps(3);
+ h.get_by_label("Bricks").click();
+ h.run_steps(3);
+ let bricks = pattern_id(h.state(), "Bricks");
+ assert_eq!(h.state().ui.dialogs.iter().find(|x| x.id == d.id).unwrap().fields["pattern"], json!(bricks));
+ h.get_by_label("OK").click();
+ h.run_steps(3);
+ assert!(!h.state().ui.dialogs.iter().any(|x| owns(&x.fields)));
+ assert_eq!(steps(h.state()), count + 1);
+ let content = h.state().session.active().unwrap().doc.layer(id).unwrap().content.clone();
+ assert!(matches!(content, LayerContent::Fill(Fill::Pattern { id: ref p, .. }) if *p == bricks));
+}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index cc9443429..a15f85cc9 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -93,6 +93,7 @@ store expose and persist the same setting; scripts keep using canonical command
| `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.fill.pattern.set` | `{"layer":id?,"document":id?,"pattern":id\|name?,"scale":1..1000?,"angle":-180..180?,"link":bool?,"phase":[x,y]?}`: edit a Pattern Fill (the Pattern Fill dialog's OK) in one undo step; omitted values keep the layer's, `phase` `[0,0]` is Snap to Origin. `layer.newFillLayer.pattern` from a menu (no params) and `layer.layerContentOptions` on a Pattern Fill layer open the Pattern Fill dialog. |
| `layer.layerMask.edit` | `{"layer":id?,"document":id?,"density":0..100?,"feather":0..1000?}`: edit pixel-mask Density (%) and Feather (px) without changing mask pixels, including adjustment masks. At least one setting is required; `document` rejects stale targets. A shared `coalesce` key groups slider updates into one undo step. |
| `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}` |