Load Files into Stack: Photoshop's dialog with a Source Files list and the align option (#4671, #4696) (#4705)

Co-authored-by: Brandon Thomas <[email protected]>
This commit is contained in:
F4LCONandBrandon Thomas authored and GitHub committed 2026-10-12 23:54:15 -04:00
1 parent 25dd3b4794
commit 321b7da12b
29 files changed
+559 -23

No files matched your search

+1 -16
View File
@@ -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}))?;
+42
View File
@@ -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);
}
+25 -4
View File
@@ -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
),
+3 -1
View File
@@ -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),
+1 -1
View File
@@ -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())
}
+7
View File
@@ -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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+8
View File
@@ -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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+7
View File
@@ -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 Εμφάνιση στον φάκελο
1 # Greek (el) PhotoCraft interface catalog.
91
92
93
94
95
96
97
98
99
100
101
102
103
+8
View File
@@ -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
Can't render this file because it contains an unexpected character in line 4 and column 47.
+8
View File
@@ -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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+7
View File
@@ -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ő…
Can't render this file because it contains an unexpected character in line 6 and column 47.
+8
View File
@@ -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
Can't render this file because it contains an unexpected character in line 4 and column 47.
+7
View File
@@ -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
1 # Italian (it) catalog. Columns, separated by a TAB: context <TAB> source <TAB> translation
107
108
109
110
111
112
113
114
115
116
117
118
119
+8
View File
@@ -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 フォルダーで表示
Can't render this file because it contains an unexpected character in line 6 and column 47.
+8
View File
@@ -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 폴더에서 보기
1 # Korean (ko) catalog. UTF-8: context<TAB>English source<TAB>translation.
97
98
99
100
101
102
103
104
105
106
107
108
109
110
+7
View File
@@ -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
Can't render this file because it contains an unexpected character in line 8 and column 34.
+8
View File
@@ -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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+7
View File
@@ -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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+8
View File
@@ -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 Удалить направляющие холста
Can't render this file because it contains an unexpected character in line 6 and column 47.
+7
View File
@@ -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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+7
View File
@@ -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
Can't render this file because it contains an unexpected character in line 8 and column 34.
+8
View File
@@ -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 Очистити напрямні полотна
Can't render this file because it contains an unexpected character in line 1362 and column 18.
+8
View File
@@ -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
Can't render this file because it contains an unexpected character in line 6 and column 47.
+8
View File
@@ -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 在文件夹中显示
1 # Simplified Chinese (zh-hans) catalog. UTF-8, TAB-separated columns:
106
107
108
109
110
111
112
113
114
115
116
117
118
119
+8
View File
@@ -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 在資料夾中顯示
Can't render this file because it contains an unexpected character in line 6 and column 47.
+1
View File
@@ -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;
+205
View File
@@ -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;
+128
View File
@@ -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(_)));
}
+1 -1
View File
@@ -1279,7 +1279,7 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Val
let 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,