From 321b7da12b965cdfd131887b0ca31bed586626b6 Mon Sep 17 00:00:00 2001 From: F4LCON <107556180+itsF4LCON@users.noreply.github.com> Date: Tue, 13 Oct 2026 05:54:15 +0200 Subject: [PATCH] Load Files into Stack: Photoshop's dialog with a Source Files list and the align option (#4671, #4696) (#4705) Co-authored-by: Brandon Thomas --- crates/engine/src/automate_cmds.rs | 17 +- crates/engine/src/automate_cmds/tests.rs | 42 +++++ crates/engine/src/file_cmds.rs | 29 +++- crates/ui-egui/src/dialogs.rs | 4 +- crates/ui-egui/src/file_dialog.rs | 2 +- crates/ui-egui/src/i18n/cs.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/hu.tsv | 7 + crates/ui-egui/src/i18n/id.tsv | 8 + crates/ui-egui/src/i18n/it.tsv | 7 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-br.tsv | 7 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/sr.tsv | 7 + crates/ui-egui/src/i18n/tr.tsv | 7 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/vi.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/stack_dialog.rs | 205 +++++++++++++++++++++++ crates/ui-egui/src/stack_dialog_tests.rs | 128 ++++++++++++++ crates/ui-egui/src/view_cmds.rs | 2 +- 29 files changed, 559 insertions(+), 23 deletions(-) create mode 100644 crates/ui-egui/src/stack_dialog.rs create mode 100644 crates/ui-egui/src/stack_dialog_tests.rs diff --git a/crates/engine/src/automate_cmds.rs b/crates/engine/src/automate_cmds.rs index b8f827d125..6a98ee3c4f 100644 --- a/crates/engine/src/automate_cmds.rs +++ b/crates/engine/src/automate_cmds.rs @@ -391,23 +391,8 @@ fn statistics(s: &mut Session, p: &Value) -> Result { .ok_or_else(|| bad(cmd, format!("unknown stack mode `{mode}`")))?; let input = p.get("input").or_else(|| p.get("paths")).cloned().ok_or_else(|| bad(cmd, "missing \"input\" (files or a folder)"))?; let align = p.get("align").and_then(Value::as_bool).unwrap_or(false); - let r = s.execute("file.scripts.loadFilesIntoStack", json!({"paths": input, "createSmartObject": !align}))?; + let r = s.execute("file.scripts.loadFilesIntoStack", json!({"paths": input, "align": align, "createSmartObject": true}))?; let n = r["layers"].as_u64().unwrap_or(0); - if align && n > 1 { - s.execute("select.allLayers", json!({}))?; - s.execute("edit.autoAlignLayers", json!({"projection": "auto"}))?; - let name = s.active().map(|d| d.doc.name.clone()).unwrap_or_default(); - s.edit("Convert to Smart Object", |doc, active| { - let layers = std::mem::take(&mut doc.layers); - let smart = crate::smart_cmds::layers_to_smart(doc, &name, layers)?; - *active = Some(smart.id); - doc.layers = vec![smart]; - Ok(()) - })?; - if let Some(st) = s.active_mut() { - st.selected_layers = st.active_layer.into_iter().collect(); - } - } let id = s.active().and_then(|d| d.doc.layers.first().map(|l| l.id)).ok_or(EngineError::NoDocument)?; s.select_layer(id)?; s.execute(&format!("layer.smartObjects.stackMode.{}", sm.id()), json!({"layer": id.0}))?; diff --git a/crates/engine/src/automate_cmds/tests.rs b/crates/engine/src/automate_cmds/tests.rs index 7471f1cfd2..b60dc2940e 100644 --- a/crates/engine/src/automate_cmds/tests.rs +++ b/crates/engine/src/automate_cmds/tests.rs @@ -371,3 +371,45 @@ fn a_failed_step_inside_a_called_action_fails_scripts_and_batch() { s.actions.list.push(Action { name: "Loop".into(), steps: vec![("file.automate.batch".into(), inner)], disabled: Default::default(), ..Default::default() }); batch(&mut s, "Loop"); } + +/// #4671: Load Files into Stack's Attempt to Automatically Align Source Images runs Auto-Align +/// Layers on the loaded layers, then (with Create Smart Object) puts them in one smart object; +/// without the smart object they stay loose layers, selected. +#[test] +fn load_files_into_stack_aligns_before_the_smart_object() { + let dir = tmp("stack-align"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 96, "height": 72, "background": "#606060"})).unwrap(); + s.edit("texture", |doc, active| { + let surf = doc.layer_mut(active.ok_or(EngineError::NoDocument)?).and_then(Layer::surface_mut).ok_or(EngineError::NoDocument)?; + for k in 0..40 { + let (x, y, v) = ((k * 37) % 88, (k * 23) % 66, (k % 7) as f32 / 6.0); + surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 3 + k % 5, y + 2 + k % 4), &[v, 1.0 - v, 0.5, 1.0]); + } + Ok(()) + }) + .unwrap(); + let files: Vec = (0..2) + .map(|i| { + let path = format!("{dir}/img{i}.png"); + crate::file_cmds::save_doc(&s.active().unwrap().doc, &path, None).unwrap(); + path + }) + .collect(); + let mut s = Session::new(); + let r = s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files, "align": true})).unwrap(); + assert_eq!(r["layers"], 2); + let st = s.active().unwrap(); + assert_eq!(st.doc.layers.len(), 2, "loose layers"); + assert!(st.doc.layers.iter().all(|l| matches!(l.content, LayerContent::Raster(_)))); + assert_eq!(st.selected_layers().len(), 2, "Auto-Align ran on them all"); + let mut s = Session::new(); + s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files, "align": true, "createSmartObject": true})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.layers.len(), 1); + let LayerContent::Smart(_) = &d.layers[0].content else { panic!("not a smart object") }; + // A single file has nothing to align with: it just loads. + let mut s = Session::new(); + s.execute("file.scripts.loadFilesIntoStack", json!({"paths": [files[0].clone()], "align": true})).unwrap(); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index c31d2d8afb..9f274d530d 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -98,7 +98,7 @@ pub(crate) fn write_file(path: &str, _bytes: &[u8]) -> Result<()> { /// Files of a folder that look like images we can open, sorted by name. #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn list_images(dir: &str) -> Result> { +pub fn list_images(dir: &str) -> Result> { let rd = std::fs::read_dir(dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))?; let mut out: Vec = rd .filter_map(|e| e.ok()) @@ -110,7 +110,7 @@ pub(crate) fn list_images(dir: &str) -> Result> { Ok(out) } #[cfg(target_arch = "wasm32")] -pub(crate) fn list_images(dir: &str) -> Result> { +pub fn list_images(dir: &str) -> Result> { Err(EngineError::Other(format!("cannot list {dir}: no file system on the web"))) } @@ -1045,7 +1045,11 @@ fn load_files_into_stack(s: &mut Session, p: &Value) -> Result { stack.layers.push(Layer::new(name.clone(), LayerContent::Raster(flattened(d, fmt)))); } let n = stack.layers.len(); - if p.get("createSmartObject").and_then(Value::as_bool).unwrap_or(false) { + let smart = p.get("createSmartObject").and_then(Value::as_bool).unwrap_or(false); + // "Attempt to Automatically Align Source Images": Auto-Align Layers on the loaded layers, before + // they go into the smart object. + let align = p.get("align").and_then(Value::as_bool).unwrap_or(false) && n > 1; + if smart && !align { // "Create Smart Object after Loading Layers": the layers go inside one smart object, ready // for Layer › Smart Objects › Stack Mode. Like Photoshop, they sit at the top level of the // contents, with no wrapper group. @@ -1054,6 +1058,23 @@ fn load_files_into_stack(s: &mut Session, p: &Value) -> Result { stack.layers = vec![smart]; } let i = s.add_document(stack, None); + if align { + s.execute("select.allLayers", json!({}))?; + s.execute("edit.autoAlignLayers", json!({"projection": "auto"}))?; + if smart { + let name = s.active().map(|d| d.doc.name.clone()).unwrap_or_default(); + s.edit("Convert to Smart Object", |doc, active| { + let layers = std::mem::take(&mut doc.layers); + let smart = crate::smart_cmds::layers_to_smart(doc, &name, layers)?; + *active = Some(smart.id); + doc.layers = vec![smart]; + Ok(()) + })?; + if let Some(st) = s.active_mut() { + st.selected_layers = st.active_layer.into_iter().collect(); + } + } + } Ok(json!({"document": i, "layers": n})) } @@ -1504,7 +1525,7 @@ pub fn specs() -> Vec { "Load Files into Stack…", &["File", "Scripts"], None, - r##"{"paths":[str]|folder,"createSmartObject":bool=false} → new document with one layer per file (inside one smart object with createSmartObject)"##, + r##"{"paths":[str]|folder,"align":bool=false (Auto-Align Layers on them first),"createSmartObject":bool=false} → new document with one layer per file (inside one smart object with createSmartObject)"##, native, load_files_into_stack ), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 678941484d..7633242d86 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -266,6 +266,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { DialogKind::Command if crate::mask_trash_prompt::owns(&fields) => crate::mask_trash_prompt::body(ui, &fields), DialogKind::Command if crate::rasterize_prompt::owns(&fields) => crate::rasterize_prompt::body(ui, &fields), DialogKind::Command if crate::duplicate_layer_ui::owns(&fields) => crate::duplicate_layer_ui::body(app, ui, &mut fields), + DialogKind::Command if crate::stack_dialog::owns(&fields) => crate::stack_dialog::body(app, ui, &mut fields, d.id), DialogKind::Command if crate::tool_reset::owns(&fields) => crate::tool_reset::body(ui), DialogKind::Command if crate::crop_presets::owns(&fields) => crate::crop_presets::body(app, ui, &mut fields), DialogKind::Command if crate::variables_ui::owns(&fields) => crate::variables_ui::body(app, ui, &mut fields), @@ -338,7 +339,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::file_ui::ok_label(&d.fields).unwrap_or(tl!("OK")) }; // Dialogs that need an input first (a preset name, a selection) grey OK out. - let can_ok = crate::crop_presets::can_confirm(app, &fields); + let can_ok = crate::crop_presets::can_confirm(app, &fields) && crate::stack_dialog::can_confirm(&fields); let ok = DialogButton::new(ButtonRole::Default, ok_label, 84.0).enabled(can_ok); // Photoshop: holding Alt turns Cancel into Reset (the dialog stays open). // Dialogs opt in via `dialog_alt_reset::supported` (per marker). @@ -545,6 +546,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result { DialogKind::Command if crate::mask_trash_prompt::owns(&d.fields) => crate::mask_trash_prompt::confirm(app, &d.fields), DialogKind::Command if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields), DialogKind::Command if crate::duplicate_layer_ui::owns(&d.fields) => crate::duplicate_layer_ui::confirm(app, &d.fields), + DialogKind::Command if crate::stack_dialog::owns(&d.fields) => crate::stack_dialog::confirm(app, &d.fields), DialogKind::Command if crate::tool_reset::owns(&d.fields) => crate::tool_reset::confirm(app), DialogKind::Command if crate::crop_presets::owns(&d.fields) => crate::crop_presets::confirm(app, &d.fields), DialogKind::Command if crate::variables_ui::owns(&d.fields) => crate::variables_ui::confirm(app, &d.fields), diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index 30b650c9b3..486a13dee0 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -291,7 +291,7 @@ impl PhotocraftApp { } /// The folder an open dialog starts in: the directory of the most recent file (UI-217-3). -fn last_used_dir(recent: &[String]) -> Option { +pub(crate) fn last_used_dir(recent: &[String]) -> Option { let dir = std::path::Path::new(recent.first()?).parent()?; (!dir.as_os_str().is_empty()).then(|| dir.to_string_lossy().into_owned()) } diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4fdabb4406..8785f2b8ea 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -114,6 +114,13 @@ Script Events Manager… Správce událostí skriptů… Import Import Browse… Procházet… + Source Files Zdrojové soubory + Use: Použít: + Files Soubory + Add Open Files Přidat otevřené soubory + Sort By Name Seřadit podle názvu + Attempt to Automatically Align Source Images Pokusit se automaticky zarovnat zdrojové obrazy + Create Smart Object after Loading Layers Po načtení vrstev vytvořit chytrý objekt Reveal in Finder Zobrazit ve Finderu Show in Explorer Zobrazit v Průzkumníkovi Show in Folder Zobrazit ve složce diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index be910dda32..b41bf78acd 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -110,6 +110,14 @@ Script Events Manager… Skriptereignis-Manager… Import Importieren Browse… Durchsuchen… + Source Files Quelldateien + Use: Verwenden: + Files Dateien + Folder Ordner + Add Open Files Geöffnete Dateien hinzufügen + Sort By Name Nach Namen sortieren + Attempt to Automatically Align Source Images Quellbilder nach Möglichkeit automatisch ausrichten + Create Smart Object after Loading Layers Nach dem Laden der Ebenen Smart-Objekt erstellen Reveal in Finder Im Finder anzeigen Show in Explorer Im Explorer anzeigen Show in Folder Im Ordner anzeigen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index d02c1318aa..d0e64a7a2f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -91,6 +91,13 @@ Script Events Manager… Διαχείριση συμβάντων δεσμών ενεργειών… Import Εισαγωγή Browse… Περιήγηση… + Source Files Αρχεία προέλευσης + Use: Χρήση: + Files Αρχεία + Add Open Files Προσθήκη ανοιχτών αρχείων + Sort By Name Ταξινόμηση κατά όνομα + Attempt to Automatically Align Source Images Απόπειρα αυτόματης στοίχισης εικόνων προέλευσης + Create Smart Object after Loading Layers Δημιουργία έξυπνου αντικειμένου μετά τη φόρτωση επιπέδων Reveal in Finder Εμφάνιση στο Finder Show in Explorer Εμφάνιση στην Εξερεύνηση αρχείων Show in Folder Εμφάνιση στον φάκελο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index cdee7d44b9..1b41bd811b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -107,6 +107,14 @@ Script Events Manager… Administrador de eventos de secuencias de comandos… Import Importar Browse… Examinar… + Source Files Archivos de origen + Use: Usar: + Files Archivos + Folder Carpeta + Add Open Files Añadir archivos abiertos + Sort By Name Ordenar por nombre + Attempt to Automatically Align Source Images Intentar alinear automáticamente las imágenes de origen + Create Smart Object after Loading Layers Crear objeto inteligente tras cargar las capas Reveal in Finder Mostrar en Finder Show in Explorer Mostrar en el Explorador Show in Folder Mostrar en la carpeta diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index daf5447d76..eae4567983 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -112,6 +112,14 @@ Script Events Manager… Gestionnaire d'événements de script… Import Importer Browse… Parcourir… + Source Files Fichiers source + Use: Utiliser : + Files Fichiers + Folder Dossier + Add Open Files Ajouter les fichiers ouverts + Sort By Name Trier par nom + Attempt to Automatically Align Source Images Tenter d'aligner automatiquement les images source + Create Smart Object after Loading Layers Créer un objet intelligent après le chargement des calques Reveal in Finder Afficher dans le Finder Show in Explorer Afficher dans l'Explorateur Show in Folder Afficher dans le dossier diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index ef7905b881..023f69a272 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -75,6 +75,13 @@ Black & White… Fekete-fehér… Brightness/Contrast… Fényerő/kontraszt… Browse… Tallózás… + Source Files Forrásfájlok + Use: Használat: + Files Fájlok + Add Open Files Megnyitott fájlok hozzáadása + Sort By Name Rendezés név szerint + Attempt to Automatically Align Source Images Forrásképek automatikus igazításának megkísérlése + Create Smart Object after Loading Layers Intelligens objektum létrehozása a rétegek betöltése után Calculations… Számítások… Canvas Size… Vászonméret… Channel Mixer… Csatornakeverő… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index db948970fe..fbe5a23849 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -105,6 +105,14 @@ Script Events Manager… Pengelola Event Skrip… Import Impor Browse… Telusuri… + Source Files File Sumber + Use: Gunakan: + Files File + Folder Folder + Add Open Files Tambahkan File Terbuka + Sort By Name Urutkan Menurut Nama + Attempt to Automatically Align Source Images Coba Sejajarkan Gambar Sumber Secara Otomatis + Create Smart Object after Loading Layers Buat Smart Object setelah Memuat Layer Reveal in Finder Tampilkan di Finder Show in Explorer Tampilkan di Explorer Show in Folder Tampilkan di Folder diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cf4c8962cf..cd6d991dae 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -107,6 +107,13 @@ Script Events Manager… Gestore eventi script… Import Importa Browse… Sfoglia… + Source Files File di origine + Use: Usa: + Files File + Add Open Files Aggiungi file aperti + Sort By Name Ordina per nome + Attempt to Automatically Align Source Images Prova ad allineare automaticamente le immagini di origine + Create Smart Object after Loading Layers Crea oggetto avanzato dopo il caricamento dei livelli Reveal in Finder Mostra nel Finder Show in Explorer Mostra in Esplora file Show in Folder Mostra nella cartella diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 19c36d54ab..d28ff1b6bb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -108,6 +108,14 @@ Script Events Manager… スクリプトイベント管理… Import 読み込み Browse… 参照… + Source Files ソースファイル + Use: 使用: + Files ファイル + Folder フォルダー + Add Open Files 開いているファイルを追加 + Sort By Name 名前順に並べ替え + Attempt to Automatically Align Source Images ソース画像の自動整列を試す + Create Smart Object after Loading Layers レイヤーの読み込み後にスマートオブジェクトを作成 Reveal in Finder Finder で表示 Show in Explorer エクスプローラーで表示 Show in Folder フォルダーで表示 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 7857b418b7..84a67f4d1b 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -97,6 +97,14 @@ Script Events Manager… 스크립트 이벤트 관리자… Import 가져오기 Browse… 찾아보기… + Source Files 소스 파일 + Use: 사용: + Files 파일 + Folder 폴더 + Add Open Files 열린 파일 추가 + Sort By Name 이름순 정렬 + Attempt to Automatically Align Source Images 소스 이미지 자동 정렬 시도 + Create Smart Object after Loading Layers 레이어를 불러온 후 스마트 오브젝트 만들기 Reveal in Finder Finder에서 보기 Show in Explorer 파일 탐색기에서 보기 Show in Folder 폴더에서 보기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a7f7c2ae13..a84deb41cc 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -100,6 +100,13 @@ Script Events Manager… Beheer scriptgebeurtenissen… Import Importeren Browse… Bladeren… + Source Files Bronbestanden + Use: Gebruiken: + Files Bestanden + Add Open Files Geopende bestanden toevoegen + Sort By Name Sorteren op naam + Attempt to Automatically Align Source Images Proberen bronafbeeldingen automatisch uit te lijnen + Create Smart Object after Loading Layers Slim object maken na laden van lagen Reveal in Finder Weergeven in Finder Show in Explorer Weergeven in Verkenner Show in Folder Weergeven in map diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0c82ac3b9b..1012ca21c7 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -107,6 +107,14 @@ Script Events Manager… Menedżer zdarzeń skryptów… Import Importuj Browse… Przeglądaj… + Source Files Pliki źródłowe + Use: Użyj: + Files Pliki + Folder Folder + Add Open Files Dodaj otwarte pliki + Sort By Name Sortuj według nazwy + Attempt to Automatically Align Source Images Spróbuj automatycznie wyrównać obrazy źródłowe + Create Smart Object after Loading Layers Utwórz obiekt inteligentny po wczytaniu warstw Reveal in Finder Pokaż w Finderze Show in Explorer Pokaż w Eksploratorze Show in Folder Pokaż w folderze diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 199fa97345..c21ddd5e4b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -108,6 +108,13 @@ Script Events Manager… Gerenciador de eventos de scripts… Import Importar Browse… Procurar… + Source Files Arquivos de origem + Use: Usar: + Files Arquivos + Add Open Files Adicionar arquivos abertos + Sort By Name Classificar por nome + Attempt to Automatically Align Source Images Tentar alinhar automaticamente as imagens de origem + Create Smart Object after Loading Layers Criar objeto inteligente após carregar as camadas Reveal in Finder Mostrar no Finder Show in Explorer Mostrar no Explorador Show in Folder Mostrar na pasta diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index dd7001bc1f..41649e75df 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1846,6 +1846,14 @@ Border… Граница… Bottom Edges Нижние края Browse… Обзор… + Source Files Исходные файлы + Use: Использовать: + Files Файлы + Folder Папка + Add Open Files Добавить открытые файлы + Sort By Name Сортировать по имени + Attempt to Automatically Align Source Images Попытаться автоматически выровнять исходные изображения + Create Smart Object after Loading Layers Создать смарт-объект после загрузки слоёв Canvas Guides Направляющие холста Character Styles Panel Панель «Стили символов» Clear Canvas Guides Удалить направляющие холста diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 43a796bdd6..87b9081972 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -115,6 +115,13 @@ Script Events Manager… Upravljač događajima skripti… Import Uvoz Browse… Pregledaj… + Source Files Izvorne datoteke + Use: Koristi: + Files Datoteke + Add Open Files Dodaj otvorene datoteke + Sort By Name Poređaj po imenu + Attempt to Automatically Align Source Images Pokušaj automatski poravnati izvorne slike + Create Smart Object after Loading Layers Napravi pametni objekat posle učitavanja slojeva Reveal in Finder Prikaži u Finderu Show in Explorer Prikaži u Exploreru Show in Folder Prikaži u fascikli diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 605ffd26f9..897eb2e3ea 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -97,6 +97,13 @@ Script Events Manager… Komut Dosyası Olay Yöneticisi… Import İthalat Browse… Göz at… + Source Files Kaynak Dosyalar + Use: Kullan: + Files Dosyalar + Add Open Files Açık Dosyaları Ekle + Sort By Name Ada Göre Sırala + Attempt to Automatically Align Source Images Kaynak Görüntüleri Otomatik Hizalamayı Dene + Create Smart Object after Loading Layers Katmanları Yükledikten Sonra Akıllı Nesne Oluştur Reveal in Finder Finder'da Göster Show in Explorer Explorer'da Göster Show in Folder Klasörde Göster diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 712766a793..39ab35aedd 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1825,6 +1825,14 @@ Border… Межа… Bottom Edges Нижні краї Browse… Огляд… + Source Files Вихідні файли + Use: Використовувати: + Files Файли + Folder Папка + Add Open Files Додати відкриті файли + Sort By Name Сортувати за назвою + Attempt to Automatically Align Source Images Спробувати автоматично вирівняти вихідні зображення + Create Smart Object after Loading Layers Створити смартоб'єкт після завантаження шарів Canvas Guides Напрямні полотна Character Styles Panel Панель стилів символів Clear Canvas Guides Очистити напрямні полотна diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7ef6f16dd6..9725a54c9e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -32,6 +32,14 @@ Automate Tự động hóa Batch… Hàng loạt… Browse… Duyệt… + Source Files Tệp nguồn + Use: Dùng: + Files Tệp + Folder Thư mục + Add Open Files Thêm các tệp đang mở + Sort By Name Sắp xếp theo tên + Attempt to Automatically Align Source Images Thử tự căn các ảnh nguồn + Create Smart Object after Loading Layers Tạo đối tượng thông minh sau khi tải lớp Check Spelling… Kiểm tra chính tả… Clear Xóa Clear Recent Files Xóa tệp gần đây diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 142718f393..044f8cfc8b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -106,6 +106,14 @@ Script Events Manager… 脚本事件管理器… Import 导入 Browse… 浏览… + Source Files 源文件 + Use: 使用: + Files 文件 + Folder 文件夹 + Add Open Files 添加打开的文件 + Sort By Name 按名称排序 + Attempt to Automatically Align Source Images 尝试自动对齐源图像 + Create Smart Object after Loading Layers 载入图层后创建智能对象 Reveal in Finder 在 Finder 中显示 Show in Explorer 在文件资源管理器中显示 Show in Folder 在文件夹中显示 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8e4da035be..7e2cb9b30a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -114,6 +114,14 @@ Script Events Manager… 指令碼事件管理員… Import 匯入 Browse… 瀏覽… + Source Files 來源檔案 + Use: 使用: + Files 檔案 + Folder 資料夾 + Add Open Files 增加開啟的檔案 + Sort By Name 依名稱排序 + Attempt to Automatically Align Source Images 嘗試自動對齊來源影像 + Create Smart Object after Loading Layers 載入圖層後建立智慧型物件 Reveal in Finder 在 Finder 中顯示 Show in Explorer 在檔案總管中顯示 Show in Folder 在資料夾中顯示 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 55be083d42..f87a7ec1c5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -179,6 +179,7 @@ pub mod smart_ui; pub mod snap_ui; pub(crate) mod solid_fill_ui; pub mod spring_tools; +pub mod stack_dialog; pub mod state; pub mod stroke_constraint; pub mod stroke_trail; diff --git a/crates/ui-egui/src/stack_dialog.rs b/crates/ui-egui/src/stack_dialog.rs new file mode 100644 index 0000000000..d1d9d01e75 --- /dev/null +++ b/crates/ui-egui/src/stack_dialog.rs @@ -0,0 +1,205 @@ +//! File › Scripts › Load Files into Stack… (#4671, #4696), laid out as Photoshop's: Source Files +//! with Use (Files or Folder), the list of what will be loaded, Browse…, Remove, Add Open Files and +//! Sort By Name, then Attempt to Automatically Align Source Images and Create Smart Object after +//! Loading Layers. OK runs `file.scripts.loadFilesIntoStack` with the list or the folder. +use egui::{RichText, vec2}; +use serde_json::{Map, Value, json}; + +use crate::file_dialog::{FileDialogAnswer, FileDialogRequest}; +use crate::{PhotocraftApp, state::DialogKind, theme::Tokens, widgets}; + +const MARK: &str = "__loadStack"; +pub const COMMAND: &str = "file.scripts.loadFilesIntoStack"; + +pub fn owns(fields: &Map) -> bool { + fields.contains_key(MARK) +} + +/// Open the dialog with an empty Files list. Returns its id. +pub fn open(app: &mut PhotocraftApp) -> u64 { + let mut f = Map::new(); + f.insert(MARK.into(), json!(true)); + f.insert("__command".into(), json!(COMMAND)); + f.insert("__label".into(), json!("Load Files into Stack…")); + f.insert("use".into(), json!("files")); + f.insert("files".into(), json!([])); + f.insert("folder".into(), json!("")); + f.insert("align".into(), json!(false)); + f.insert("smartObject".into(), json!(false)); + app.ui.open_dialog(DialogKind::Command, f) +} + +fn folder_mode(f: &Map) -> bool { + f.get("use").and_then(Value::as_str) == Some("folder") +} + +fn files(f: &Map) -> Vec { + f.get("files").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default() +} + +fn folder(f: &Map) -> &str { + f.get("folder").and_then(Value::as_str).unwrap_or("") +} + +fn selected(f: &Map) -> Option { + f.get("selected").and_then(Value::as_u64).map(|i| i as usize) +} + +/// Add `paths` to the Files list, skipping those already in it, in their order. +fn add(f: &mut Map, paths: impl IntoIterator) { + let mut list = files(f); + for p in paths { + if !list.contains(&p) { + list.push(p); + } + } + f.insert("files".into(), json!(list)); +} + +fn file_name(p: &str) -> &str { + std::path::Path::new(p).file_name().and_then(|n| n.to_str()).unwrap_or(p) +} + +/// The open documents that have a file, in tab order (what Add Open Files adds). +fn open_files(app: &PhotocraftApp) -> Vec { + app.session.documents().iter().filter_map(|d| d.path.clone()).collect() +} + +/// OK needs files to load: some in the list, or a chosen folder. +pub fn can_confirm(f: &Map) -> bool { + !owns(f) || if folder_mode(f) { !folder(f).is_empty() } else { !files(f).is_empty() } +} + +/// Browse…: files to add (Files) or the folder to load (Folder), into dialog `id` once the file +/// dialog answers. +fn browse(app: &mut PhotocraftApp, id: u64, folder: bool) { + let r = if folder { + app.ask_folder(move |app, path| { + let d = app.ui.dialog_mut(id).ok_or("the dialog was closed")?; + d.fields.insert("folder".into(), json!(path)); + Ok(Value::Null) + }) + } else { + let initial_dir = crate::file_dialog::last_used_dir(&app.ui.recent_files); + app.ask_file(FileDialogRequest::Open { multiple: true, initial_dir, extensions: None }, move |app, answer| { + let FileDialogAnswer::Paths(paths) = answer else { return Err("Load Files into Stack reads files from disk".into()) }; + let d = app.ui.dialog_mut(id).ok_or("the dialog was closed")?; + add(&mut d.fields, paths); + Ok(Value::Null) + }) + }; + if let Err(e) = r.map(|_| ()).or_else(|e| if e == crate::file_dialog::CANCELLED { Ok(()) } else { Err(e) }) { + app.ui.status = e; + } +} + +/// The dialog's body (dialog `id`); OK and Cancel are the standard ones below it. +pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64) { + let t = Tokens::get(ui.ctx()); + ui.label(RichText::new(tl!("Source Files")).font(crate::theme::semibold(13.0))); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.label(tl!("Use:")); + let mut mode = usize::from(folder_mode(f)); + let options = [(0, tl!("Files")), (1, tl!("Folder"))]; + if widgets::dropdown(ui, "load-stack-use", &mut mode, &options, 120.0) { + f.insert("use".into(), json!(if mode == 1 { "folder" } else { "files" })); + f.remove("selected"); + } + }); + ui.add_space(6.0); + let folder_mode = folder_mode(f); + let mut browse_now = false; + ui.horizontal_top(|ui| { + // The list: the chosen files, or the images in the chosen folder. + let shown: Vec = if folder_mode { + if folder(f).is_empty() { Vec::new() } else { photocraft_engine::file_cmds::list_images(folder(f)).unwrap_or_default() } + } else { + files(f) + }; + let sel = selected(f); + egui::Frame::NONE.fill(t.field).stroke(egui::Stroke::new(1.0, t.field_border)).corner_radius(t.radius_sm).inner_margin(4.0).show(ui, |ui| { + ui.set_min_size(vec2(300.0, 160.0)); + ui.set_max_width(300.0); + egui::ScrollArea::vertical().id_salt("load-stack-files").max_height(160.0).auto_shrink([false, false]).show(ui, |ui| { + if folder_mode && !folder(f).is_empty() { + ui.label(RichText::new(folder(f)).color(t.text_dim)); + } + for (i, p) in shown.iter().enumerate() { + let row = ui.add(egui::Button::selectable(!folder_mode && sel == Some(i), file_name(p))).on_hover_text(p.as_str()); + if row.clicked() && !folder_mode { + f.insert("selected".into(), json!(i)); + } + } + }); + }); + ui.add_space(8.0); + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 4.0; + if widgets::secondary_button(ui, tl!("Browse…"), 120.0).clicked() { + browse_now = true; + } + let can_remove = !folder_mode && sel.is_some_and(|i| i < files(f).len()); + if ui.add_enabled_ui(can_remove, |ui| widgets::secondary_button(ui, tl!("Remove"), 120.0)).inner.clicked() + && let Some(i) = sel + { + let mut list = files(f); + list.remove(i); + f.insert("files".into(), json!(list)); + f.remove("selected"); + } + let open = open_files(app); + if ui.add_enabled_ui(!folder_mode && !open.is_empty(), |ui| widgets::secondary_button(ui, tl!("Add Open Files"), 120.0)).inner.clicked() { + add(f, open); + } + if ui.add_enabled_ui(!folder_mode && files(f).len() > 1, |ui| widgets::secondary_button(ui, tl!("Sort By Name"), 120.0)).inner.clicked() { + let mut list = files(f); + list.sort_by_key(|p| file_name(p).to_lowercase()); + f.insert("files".into(), json!(list)); + f.remove("selected"); + } + }); + }); + ui.add_space(8.0); + for (key, label) in [("align", tl!("Attempt to Automatically Align Source Images")), ("smartObject", tl!("Create Smart Object after Loading Layers"))] { + let mut on = f.get(key).and_then(Value::as_bool).unwrap_or(false); + if widgets::checkbox(ui, &mut on, label).changed() { + f.insert(key.into(), json!(on)); + } + } + if browse_now { + // The file dialog's answer lands in the dialog's own fields: save this frame's edits first. + if let Some(d) = app.ui.dialog_mut(id) { + d.fields = f.clone(); + } + browse(app, id, folder_mode); + } +} + +/// OK: load the list (or the folder) into a new document. +pub fn confirm(app: &mut PhotocraftApp, f: &Map) -> Result { + let paths = if folder_mode(f) { + let dir = folder(f); + if dir.is_empty() { + return Err("Choose a folder to load".into()); + } + json!(dir) + } else { + let list = files(f); + if list.is_empty() { + return Err("Add the files to load".into()); + } + json!(list) + }; + let align = f.get("align").and_then(Value::as_bool).unwrap_or(false); + let smart = f.get("smartObject").and_then(Value::as_bool).unwrap_or(false); + let r = app.run(COMMAND, json!({"paths": paths, "align": align, "createSmartObject": smart})); + if r.is_ok() { + app.sync_views(); + } + r +} + +#[cfg(test)] +#[path = "stack_dialog_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/stack_dialog_tests.rs b/crates/ui-egui/src/stack_dialog_tests.rs new file mode 100644 index 0000000000..1f6c5501ed --- /dev/null +++ b/crates/ui-egui/src/stack_dialog_tests.rs @@ -0,0 +1,128 @@ +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +use super::*; +use crate::file_dialog::{FileDialogAnswer, FileDialogRequest}; + +/// `n` small PNGs named `names` in a fresh folder for `tag`: (folder, paths). +fn pngs(tag: &str, names: &[&str]) -> (String, Vec) { + let dir = std::env::temp_dir().join(format!("photocraft-load-stack-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 6, "background": "#406080"})).unwrap(); + let paths = names + .iter() + .map(|n| { + let p = dir.join(n).to_string_lossy().into_owned(); + s.execute("file.saveACopy", json!({"path": p})).unwrap(); + p + }) + .collect(); + (dir.to_string_lossy().into_owned(), paths) +} + +fn harness(answers: Vec>) -> (Harness<'static, PhotocraftApp>, std::rc::Rc>>) { + let (show, asked) = crate::file_dialog::fake(answers); + let h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services { file_dialog: Some(show), ..Default::default() }) + }); + (h, asked) +} + +fn dialog(h: &Harness<'_, PhotocraftApp>) -> Option<(u64, Map)> { + h.state().ui.dialogs.iter().find(|d| owns(&d.fields)).map(|d| (d.id, d.fields.clone())) +} + +fn listed(h: &Harness<'_, PhotocraftApp>) -> Vec { + dialog(h).map(|(_, f)| files(&f).iter().map(|p| file_name(p).to_string()).collect()).unwrap_or_default() +} + +/// #4671 / #4696: the menu opens Photoshop's dialog, Browse… adds files (once each), Remove, +/// Sort By Name and Add Open Files edit the list, and OK loads it. +#[test] +fn source_files_list_is_built_with_browse_remove_sort_and_open_files() { + let (_, paths) = pngs("files", &["b.png", "c.png", "a.png"]); + let (mut h, asked) = harness(vec![ + Some(FileDialogAnswer::Paths(vec![paths[0].clone(), paths[1].clone()])), + Some(FileDialogAnswer::Paths(vec![paths[2].clone(), paths[0].clone()])), + ]); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap(); + h.run_steps(4); + assert!(dialog(&h).is_some(), "the menu opens the dialog"); + for label in [ + "Source Files", + "Browse…", + "Remove", + "Add Open Files", + "Sort By Name", + "Attempt to Automatically Align Source Images", + "Create Smart Object after Loading Layers", + ] { + assert!(h.query_by_label(label).is_some(), "{label}"); + } + assert!(h.get_by_label("OK").accesskit_node().is_disabled(), "nothing to load yet"); + assert!(h.get_by_label("Remove").accesskit_node().is_disabled()); + + h.get_by_label("Browse…").click(); + h.run_steps(4); + assert!(matches!(asked.borrow()[0], FileDialogRequest::Open { multiple: true, .. }), "{:?}", asked.borrow()); + assert_eq!(listed(&h), ["b.png", "c.png"]); + h.get_by_label("Browse…").click(); + h.run_steps(4); + assert_eq!(listed(&h), ["b.png", "c.png", "a.png"], "b.png only once"); + + h.get_by_label("Sort By Name").click(); + h.run_steps(2); + assert_eq!(listed(&h), ["a.png", "b.png", "c.png"]); + h.get_by_label("b.png").click(); + h.run_steps(2); + h.get_by_label("Remove").click(); + h.run_steps(2); + assert_eq!(listed(&h), ["a.png", "c.png"]); + + // Add Open Files: the open documents that have a file (b.png, already saved; not the untitled one). + h.state_mut().run("file.new", json!({"width": 4, "height": 4})).unwrap(); + h.state_mut().session.active_mut().unwrap().path = Some(paths[0].clone()); + h.state_mut().run("file.new", json!({"width": 4, "height": 4})).unwrap(); + h.run_steps(3); + h.get_by_label("Add Open Files").click(); + h.run_steps(2); + assert_eq!(listed(&h), ["a.png", "c.png", "b.png"]); + + let docs = h.state().session.documents().len(); + h.get_by_label("OK").click(); + h.run_steps(4); + assert!(dialog(&h).is_none()); + assert_eq!(h.state().session.documents().len(), docs + 1, "a new document"); + let d = &h.state().session.active().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["a.png", "c.png", "b.png"], "one layer per file, in the list's order"); +} + +/// Use: Folder loads the images of the folder Browse… chose, listed in the dialog; with Create +/// Smart Object they go into one smart object. +#[test] +fn a_folder_loads_its_images() { + let (dir, _) = pngs("folder", &["one.png", "two.png"]); + let (mut h, asked) = harness(vec![Some(FileDialogAnswer::FolderTo(dir.clone()))]); + let id = open(h.state_mut()); + h.run_steps(3); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("use".into(), json!("folder")); + h.run_steps(2); + assert!(h.get_by_label("Remove").accesskit_node().is_disabled() && h.get_by_label("Add Open Files").accesskit_node().is_disabled()); + h.get_by_label("Browse…").click(); + h.run_steps(4); + assert!(matches!(asked.borrow()[0], FileDialogRequest::Folder { .. })); + assert!(h.query_by_label("one.png").is_some() && h.query_by_label("two.png").is_some(), "the folder's images are listed"); + // Create Smart Object after Loading Layers: both images inside one smart object. + h.get_by_label("Create Smart Object after Loading Layers").click(); + h.run_steps(2); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + let d = &h.state().session.active().unwrap().doc; + assert_eq!(d.layers.len(), 1); + assert!(matches!(d.layers[0].content, photocraft_doc::LayerContent::Smart(_))); +} diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs index 09d759ed45..eb510eb473 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/view_cmds.rs @@ -1279,7 +1279,7 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option dialog(app, json!({"paths": dir}), json!({})), + "file.scripts.loadFilesIntoStack" => Some(Ok(json!({"dialog": crate::stack_dialog::open(app)}))), // Photography automation (photo_cmds / lens_cmds): a folder (or the open documents). "file.automate.photomerge" => dialog( app,