PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Load Files into Stack: Photoshop's dialog with a Source Files list and the align option (#4671, #4696) (#4705)
F4LCON321b7da12b96
diff --git a/crates/engine/src/automate_cmds.rs b/crates/engine/src/automate_cmds.rsindex b8f827d12..6a98ee3c4 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<Value> {.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.rsindex 7471f1cfd..b60dc2940 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<String> = (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.rsindex c31d2d8af..9f274d530 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<Vec<String>> {+pub fn list_images(dir: &str) -> Result<Vec<String>> {let rd = std::fs::read_dir(dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))?;let mut out: Vec<String> = rd.filter_map(|e| e.ok())@@ -110,7 +110,7 @@ pub(crate) fn list_images(dir: &str) -> Result<Vec<String>> {Ok(out)}#[cfg(target_arch = "wasm32")]-pub(crate) fn list_images(dir: &str) -> Result<Vec<String>> {+pub fn list_images(dir: &str) -> Result<Vec<String>> {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<Value> {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<Value> {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<CommandSpec> {"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.rsindex 678941484..7633242d8 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<Value, String> {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.rsindex 30b650c9b..486a13dee 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<String> {+pub(crate) fn last_used_dir(recent: &[String]) -> Option<String> {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.tsvindex 4fdabb440..8785f2b8e 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 ImportBrowse… 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ý objektReveal in Finder Zobrazit ve FinderuShow in Explorer Zobrazit v PrůzkumníkoviShow in Folder Zobrazit ve složcediff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex be910dda3..b41bf78ac 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 ImportierenBrowse… 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 erstellenReveal in Finder Im Finder anzeigenShow in Explorer Im Explorer anzeigenShow in Folder Im Ordner anzeigendiff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex d02c1318a..d0e64a7a2 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 Εμφάνιση στο FinderShow in Explorer Εμφάνιση στην Εξερεύνηση αρχείωνShow in Folder Εμφάνιση στον φάκελοdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex cdee7d44b..1b41bd811 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 ImportarBrowse… 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 capasReveal in Finder Mostrar en FinderShow in Explorer Mostrar en el ExploradorShow in Folder Mostrar en la carpetadiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex daf5447d7..eae456798 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 ImporterBrowse… 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 calquesReveal in Finder Afficher dans le FinderShow in Explorer Afficher dans l'ExplorateurShow in Folder Afficher dans le dossierdiff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsvindex ef7905b88..023f69a27 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ánCalculations… 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.tsvindex db948970f..fbe5a2384 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 ImporBrowse… 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 LayerReveal in Finder Tampilkan di FinderShow in Explorer Tampilkan di ExplorerShow in Folder Tampilkan di Folderdiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex cf4c8962c..cd6d991da 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 ImportaBrowse… 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 livelliReveal in Finder Mostra nel FinderShow in Explorer Mostra in Esplora fileShow in Folder Mostra nella cartelladiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 19c36d54a..d28ff1b6b 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.tsvindex 7857b418b..84a67f4d1 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.tsvindex a7f7c2ae1..a84deb41c 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 ImporterenBrowse… 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 lagenReveal in Finder Weergeven in FinderShow in Explorer Weergeven in VerkennerShow in Folder Weergeven in mapdiff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 0c82ac3b9..1012ca21c 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 ImportujBrowse… 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 warstwReveal in Finder Pokaż w FinderzeShow in Explorer Pokaż w EksploratorzeShow in Folder Pokaż w folderzediff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 199fa9734..c21ddd5e4 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 ImportarBrowse… 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 camadasReveal in Finder Mostrar no FinderShow in Explorer Mostrar no ExploradorShow in Folder Mostrar na pastadiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex dd7001bc1..41649e75d 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.tsvindex 43a796bdd..87b908197 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 UvozBrowse… 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 slojevaReveal in Finder Prikaži u FinderuShow in Explorer Prikaži u ExploreruShow in Folder Prikaži u fasciklidiff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsvindex 605ffd26f..897eb2e3e 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 İthalatBrowse… 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şturReveal in Finder Finder'da GösterShow in Explorer Explorer'da GösterShow in Folder Klasörde Gösterdiff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 712766a79..39ab35aed 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.tsvindex 7ef6f16dd..9725a54c9 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óaBatch… 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ớpCheck Spelling… Kiểm tra chính tả…Clear XóaClear Recent Files Xóa tệp gần đâydiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 142718f39..044f8cfc8 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.tsvindex 8e4da035b..7e2cb9b30 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.rsindex 55be083d4..f87a7ec1c 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.rsnew file mode 100644index 000000000..d1d9d01e7--- /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<String, Value>) -> 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<String, Value>) -> bool {+ f.get("use").and_then(Value::as_str) == Some("folder")+}++fn files(f: &Map<String, Value>) -> Vec<String> {+ 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<String, Value>) -> &str {+ f.get("folder").and_then(Value::as_str).unwrap_or("")+}++fn selected(f: &Map<String, Value>) -> Option<usize> {+ 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<String, Value>, paths: impl IntoIterator<Item = String>) {+ 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<String> {+ 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<String, Value>) -> 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<String, Value>, 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<String> = 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<String, Value>) -> Result<Value, String> {+ 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.rsnew file mode 100644index 000000000..1f6c5501e--- /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<String>) {+ 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<Option<FileDialogAnswer>>) -> (Harness<'static, PhotocraftApp>, std::rc::Rc<std::cell::RefCell<Vec<FileDialogRequest>>>) {+ 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<String, Value>)> {+ h.state().ui.dialogs.iter().find(|d| owns(&d.fields)).map(|d| (d.id, d.fields.clone()))+}++fn listed(h: &Harness<'_, PhotocraftApp>) -> Vec<String> {+ 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.rsindex 09d759ed4..eb510eb47 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<Result<Vallet scope = if selected_adjustments { "selected" } else { "all" };dialog(app, json!({"path": format!("{dir}/{stem}.cube"), "size": 33, "title": stem, "scope": scope}), json!({"scope": ["all", "selected"]}))}- "file.scripts.loadFilesIntoStack" => 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,