Skip to content

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

Save: ask before overwriting a file another app changed (#6596) (#6652)

Zuujisfbcb70b31733
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index d4a1611a1..d4e7a0155 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -506,6 +506,11 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
save_file: Some(Arc::new(save_file)),
file_dialog: Some(Box::new(show_file_dialog)),
write: Some(Box::new(|path: &str, bytes: &[u8]| write_atomic(Path::new(path), bytes))),
+ file_stamp: Some(Box::new(|path: &str| {
+ // Follows a symlink, as Save writes through it to the file it points at.
+ let meta = std::fs::metadata(path).ok()?;
+ Some(photocraft_ui_egui::FileStamp { len: meta.len(), modified: meta.modified().ok() })
+ })),
automation_read,
automation_write,
automation_open_pcraft,
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 182b4be8c..43b4f3d3f 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -321,6 +321,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
DialogKind::Command if crate::channel_options_ui::owns_new_spot(&fields) => crate::channel_options_ui::new_spot_body(ui, &mut fields),
DialogKind::Command if crate::shape_dialog::owns(&fields) => crate::shape_dialog::body(app, ui, &mut fields),
DialogKind::Command if crate::delete_layer_prompt::owns(&fields) => crate::delete_layer_prompt::body(ui, &mut fields),
+ DialogKind::Command if crate::disk_change_prompt::owns(&fields) => crate::disk_change_prompt::body(ui, &fields),
DialogKind::Command if crate::actions::owns_insert_stop(&fields) => crate::actions::insert_stop_body(ui, &mut fields),
DialogKind::Command if crate::new_layer_ui::owns(&fields) => crate::new_layer_ui::body(ui, &mut fields),
DialogKind::Command if crate::mask_trash_prompt::owns(&fields) => crate::mask_trash_prompt::body(ui, &fields),
@@ -404,6 +405,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
tl!("Create")
} else if crate::delete_layer_prompt::owns(&d.fields) {
tl!("Delete")
+ } else if crate::disk_change_prompt::owns(&d.fields) {
+ tl!("Replace")
} else if d.fields.contains_key("__export") {
tl!("Export")
} else {
@@ -617,6 +620,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
DialogKind::Command if crate::channel_options_ui::owns_new_spot(&d.fields) => crate::channel_options_ui::confirm_new_spot(app, &d.fields),
DialogKind::Command if crate::shape_dialog::owns(&d.fields) => crate::shape_dialog::confirm(app, &d.fields),
DialogKind::Command if crate::delete_layer_prompt::owns(&d.fields) => crate::delete_layer_prompt::confirm(app, &d.fields),
+ DialogKind::Command if crate::disk_change_prompt::owns(&d.fields) => crate::disk_change_prompt::confirm(app, &d.fields),
DialogKind::Command if crate::actions::owns_insert_stop(&d.fields) => crate::actions::insert_stop_confirm(app, &d.fields),
DialogKind::Command if crate::new_layer_ui::owns(&d.fields) => crate::new_layer_ui::confirm(app, &d.fields),
DialogKind::Command if crate::mask_trash_prompt::owns(&d.fields) => crate::mask_trash_prompt::confirm(app, &d.fields),
diff --git a/crates/ui-egui/src/disk_change_prompt.rs b/crates/ui-egui/src/disk_change_prompt.rs
new file mode 100644
index 000000000..dd9b8215b
--- /dev/null
+++ b/crates/ui-egui/src/disk_change_prompt.rs
@@ -0,0 +1,57 @@
+//! File › Save asks before replacing the document's own file when another app changed it after
+//! the document was opened from it or last saved to it (#6596). Replace writes the document over
+//! it anyway; Cancel leaves the file and the document as they are, and File › Save As keeps both.
+//!
+//! The prompt is an ordinary dialog in the UI state: `ui.dialog.confirm` replaces the file and
+//! `ui.dialog.cancel` keeps it. Recorded actions and automation saves don't ask.
+
+use photocraft_doc::DocId;
+use serde_json::{Map, Value, json};
+
+use crate::PhotocraftApp;
+use crate::state::DialogKind;
+
+const MARK: &str = "__diskChanged";
+
+pub fn owns(fields: &Map<String, Value>) -> bool {
+ fields.contains_key(MARK)
+}
+
+/// Opens the prompt instead of saving `doc` to its own file at `path` when another app changed
+/// that file; `None` saves as usual. `flat` is a flat file confirmed in the Save dialog, which
+/// is saved (and recorded) the way [`PhotocraftApp::save_dialog_flow`] does it.
+pub(crate) fn intercept(app: &mut PhotocraftApp, doc: DocId, path: &str, flat: bool) -> Option<Result<Value, String>> {
+ if !app.changed_on_disk(doc, path) {
+ return None;
+ }
+ if app.ui.dialogs.iter().any(|d| owns(&d.fields)) {
+ return Some(Ok(json!({"confirmationPending": true})));
+ }
+ let name = crate::file_open::display_name(path);
+ let message = crate::i18n::fmt(tl!("{name} was changed by another app after it was opened or saved here."), &[("name", name.as_str())]);
+ let fields = json!({MARK: true, "__label": "Save", "message": message, "document": doc.0, "path": path, "flat": flat});
+ let id = app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap_or_default());
+ Some(Ok(json!({"dialog": id, "confirmationPending": true})))
+}
+
+pub fn body(ui: &mut egui::Ui, fields: &Map<String, Value>) {
+ ui.label(fields.get("message").and_then(Value::as_str).unwrap_or_default());
+ ui.add_space(6.0);
+ ui.label(tl!("Replace it with this document, or cancel and use File › Save As to keep both."));
+}
+
+/// Replace: the save the prompt held back.
+pub fn confirm(app: &mut PhotocraftApp, fields: &Map<String, Value>) -> Result<Value, String> {
+ let doc = fields.get("document").and_then(Value::as_u64).map(DocId).ok_or(tl!("The document is closed"))?;
+ let path = fields.get("path").and_then(Value::as_str).unwrap_or_default().to_string();
+ let flat = fields.get("flat").and_then(Value::as_bool) == Some(true);
+ app.with_document(doc, |app| {
+ if flat {
+ let r = app.save_to(path.clone(), None)?;
+ app.journal_as_plain_save(&path);
+ Ok(r)
+ } else {
+ app.save_in_place(path)
+ }
+ })
+}
diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rs
index 9e4c878f6..6a3ccfcf9 100644
--- a/crates/ui-egui/src/file_dialog/tests.rs
+++ b/crates/ui-egui/src/file_dialog/tests.rs
@@ -1010,3 +1010,90 @@ fn render_video_menu_asks_for_directory_and_writes_frames_only_after_confirmatio
assert!(!app.file_dialog_open());
std::fs::remove_dir_all(&dir).unwrap();
}
+
+/// How many times each path was written, standing in for its size and modification time.
+type Disk = Rc<RefCell<std::collections::HashMap<String, u64>>>;
+
+/// Gives `app` file stamps from a fake disk that its own writes update too.
+fn on_disk(app: &mut PhotocraftApp) -> Disk {
+ let disk = Disk::default();
+ let (read, wrote) = (disk.clone(), disk.clone());
+ app.services.file_stamp = Some(Box::new(move |path| read.borrow().get(path).map(|&n| crate::FileStamp { len: n, modified: None })));
+ let mut write = app.services.write.take().unwrap();
+ app.services.write = Some(Box::new(move |path, bytes| {
+ write(path, bytes)?;
+ *wrote.borrow_mut().entry(path.to_string()).or_default() += 1;
+ Ok(())
+ }));
+ disk
+}
+
+fn changed_by_another_app(disk: &Disk, path: &str) {
+ *disk.borrow_mut().entry(path.to_string()).or_default() += 1;
+}
+
+fn disk_prompt(app: &PhotocraftApp) -> Option<&crate::state::Dialog> {
+ app.ui.dialogs.iter().find(|d| crate::disk_change_prompt::owns(&d.fields))
+}
+
+#[test]
+fn save_asks_before_replacing_a_file_another_app_changed() {
+ let ctx = egui::Context::default();
+ let (mut app, _open, written) = app();
+ let disk = on_disk(&mut app);
+ changed_by_another_app(&disk, "/pics/a.psd");
+ app.opened_from("/pics/a.psd");
+ app.run("layer.new.layer", json!({})).unwrap();
+ // Unchanged on disk: Save writes at once.
+ menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap();
+ assert_eq!(*written.borrow(), ["/pics/a.psd"]);
+ assert!(disk_prompt(&app).is_none());
+
+ // Our own save isn't a change; another app's write after it is.
+ changed_by_another_app(&disk, "/pics/a.psd");
+ app.run("layer.new.layer", json!({})).unwrap();
+ let r = menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap();
+ assert_eq!(r["confirmationPending"], true);
+ assert_eq!(written.borrow().len(), 1, "nothing is written before the answer");
+ let prompt = disk_prompt(&app).expect("Save asks first");
+ assert!(prompt.fields["message"].as_str().unwrap().contains("a.psd"));
+
+ // Cancel leaves the file and the unsaved document alone.
+ let id = prompt.id;
+ app.ui.close_dialog(id);
+ assert_eq!(written.borrow().len(), 1);
+ assert!(app.session.active().unwrap().is_dirty());
+
+ // Replace writes it, and the next Save doesn't ask again.
+ let id = menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap()["dialog"].as_u64().unwrap();
+ crate::dialogs::confirm(&mut app, id).unwrap();
+ assert_eq!(written.borrow().len(), 2);
+ assert!(!app.session.active().unwrap().is_dirty());
+ app.run("layer.new.layer", json!({})).unwrap();
+ menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap();
+ assert_eq!(written.borrow().len(), 3);
+ assert!(disk_prompt(&app).is_none());
+}
+
+#[test]
+fn save_of_a_flat_file_asks_after_the_dialog_when_another_app_changed_it() {
+ let ctx = egui::Context::default();
+ // Lowercase: the Save dialog lowercases a typed extension by default.
+ let path = "/pics/My image.jpg";
+ let (mut app, open, written) = jpeg_app(None, false);
+ let disk = on_disk(&mut app);
+ changed_by_another_app(&disk, path);
+ app.opened_from(path);
+ app.run("image.adjustments.invert", json!({})).unwrap();
+ changed_by_another_app(&disk, path);
+ menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap();
+ app.poll_file_dialog(&ctx, None);
+ answer(&open, Some(FileDialogAnswer::SaveTo(path.into())));
+ app.poll_file_dialog(&ctx, None);
+ assert!(written.borrow().is_empty(), "the changed file is not replaced before the answer");
+ let id = disk_prompt(&app).expect("Save asks first").id;
+ crate::dialogs::confirm(&mut app, id).unwrap();
+ assert_eq!(*written.borrow(), [path]);
+ assert!(!app.session.active().unwrap().is_dirty());
+ assert_eq!(app.session.journal.last().map(|s| s.0.as_str()), Some("file.save"), "still recorded as a plain Save");
+}
diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs
index 13105a321..d752f7ce7 100644
--- a/crates/ui-egui/src/file_open.rs
+++ b/crates/ui-egui/src/file_open.rs
@@ -89,6 +89,8 @@ impl PhotocraftApp {
&& !st.source_read_only
{
st.path = Some(path.to_string());
+ let doc = st.doc.id;
+ self.remember_stamp(doc, path);
}
self.push_recent(path);
}
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index f3fb8c8c4..f50c0249b 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -3816,3 +3816,5 @@ navigator Zoom Zvětšení
This document's layers: {needed} of {budget} for layers Vrstvy tohoto dokumentu: {needed} z {budget} pro vrstvy
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Vrstvy tohoto dokumentu potřebují {needed}, ale mohou zabrat {budget}: překreslení celého dokumentu probíhá na CPU
GPU Memory (MB, 0 = Automatic) Paměť GPU (MB, 0 = Automaticky)
+ {name} was changed by another app after it was opened or saved here. Soubor {name} změnila jiná aplikace poté, co byl zde otevřen nebo uložen.
+ Replace it with this document, or cancel and use File › Save As to keep both. Nahraďte ho tímto dokumentem, nebo zrušte a použijte Soubor › Uložit jako, abyste zachovali obojí.
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 48ebfba67..b1ea8977e 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -3210,3 +3210,5 @@ curves Smooth Glätten
This document's layers: {needed} of {budget} for layers Ebenen dieses Dokuments: {needed} von {budget} für Ebenen
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Die Ebenen dieses Dokuments brauchen {needed}, dürfen aber {budget} belegen: Das ganze Dokument wird auf der CPU neu gezeichnet
GPU Memory (MB, 0 = Automatic) GPU-Speicher (MB, 0 = Automatisch)
+ {name} was changed by another app after it was opened or saved here. {name} wurde von einer anderen App geändert, nachdem es hier geöffnet oder gespeichert wurde.
+ Replace it with this document, or cancel and use File › Save As to keep both. Ersetze die Datei durch dieses Dokument oder brich ab und nutze Datei › Speichern unter, um beide zu behalten.
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index f2c67c2c4..822980630 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -3908,3 +3908,5 @@ curves Smooth Εξομάλυνση
This document's layers: {needed} of {budget} for layers Επίπεδα αυτού του εγγράφου: {needed} από {budget} για επίπεδα
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Τα επίπεδα αυτού του εγγράφου χρειάζονται {needed} αλλά μπορούν να καταλάβουν {budget}: η επανασχεδίαση όλου του εγγράφου γίνεται στη CPU
GPU Memory (MB, 0 = Automatic) Μνήμη GPU (MB, 0 = Αυτόματο)
+ {name} was changed by another app after it was opened or saved here. Το {name} άλλαξε από άλλη εφαρμογή αφού ανοίχτηκε ή αποθηκεύτηκε εδώ.
+ Replace it with this document, or cancel and use File › Save As to keep both. Αντικαταστήστε το με αυτό το έγγραφο ή ακυρώστε και χρησιμοποιήστε Αρχείο › Αποθήκευση ως για να κρατήσετε και τα δύο.
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 45804fa2a..6f3d85002 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -4170,3 +4170,5 @@ navigator Zoom Zoom
This document's layers: {needed} of {budget} for layers Capas de este documento: {needed} de {budget} para capas
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Las capas de este documento necesitan {needed} pero pueden ocupar {budget}: los redibujados de todo el documento usan la CPU
GPU Memory (MB, 0 = Automatic) Memoria de GPU (MB, 0 = Automático)
+ {name} was changed by another app after it was opened or saved here. Otra aplicación cambió {name} después de abrirlo o guardarlo aquí.
+ Replace it with this document, or cancel and use File › Save As to keep both. Reemplázalo con este documento, o cancela y usa Archivo › Guardar como para conservar ambos.
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 3e3451e09..4a819b0e1 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -3213,3 +3213,6 @@ curves Smooth Lisser
This document's layers: {needed} of {budget} for layers Calques de ce document : {needed} sur {budget} pour les calques
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Les calques de ce document ont besoin de {needed} mais peuvent occuper {budget} : le document entier se redessine sur le CPU
GPU Memory (MB, 0 = Automatic) Mémoire GPU (Mo, 0 = Automatique)
+ Replace Remplacer
+ {name} was changed by another app after it was opened or saved here. {name} a été modifié par une autre application après avoir été ouvert ou enregistré ici.
+ Replace it with this document, or cancel and use File › Save As to keep both. Remplacez-le par ce document, ou annulez et utilisez Fichier › Enregistrer sous pour garder les deux.
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index 9dc9a47fb..86a6b30ac 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -4127,3 +4127,5 @@ cameraRaw Yellow Sárga
This document's layers: {needed} of {budget} for layers A dokumentum rétegei: {needed} / {budget} a rétegeknek
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU A dokumentum rétegeinek {needed} kell, de {budget} foglalhatnak: a teljes dokumentum újrarajzolása a CPU-n fut
GPU Memory (MB, 0 = Automatic) GPU-memória (MB, 0 = Automatikus)
+ {name} was changed by another app after it was opened or saved here. A(z) {name} fájlt egy másik alkalmazás módosította, miután itt megnyitották vagy mentették.
+ Replace it with this document, or cancel and use File › Save As to keep both. Cserélje le erre a dokumentumra, vagy válassza a Mégse gombot, és a Fájl › Mentés másként paranccsal tartsa meg mindkettőt.
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 81e850f29..49777913c 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -3200,3 +3200,6 @@ curves Smooth Haluskan
This document's layers: {needed} of {budget} for layers Layer dokumen ini: {needed} dari {budget} untuk layer
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Layer dokumen ini membutuhkan {needed} tetapi boleh memakai {budget}: penggambaran ulang seluruh dokumen memakai CPU
GPU Memory (MB, 0 = Automatic) Memori GPU (MB, 0 = Otomatis)
+ Replace Ganti
+ {name} was changed by another app after it was opened or saved here. {name} diubah oleh aplikasi lain setelah dibuka atau disimpan di sini.
+ Replace it with this document, or cancel and use File › Save As to keep both. Ganti dengan dokumen ini, atau batalkan dan gunakan Berkas › Simpan Sebagai untuk menyimpan keduanya.
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index c097ded29..f1144c0fd 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -4329,3 +4329,5 @@ shape Appearance Aspetto
This document's layers: {needed} of {budget} for layers Livelli di questo documento: {needed} su {budget} per i livelli
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU I livelli di questo documento richiedono {needed} ma possono occupare {budget}: i ridisegni dell'intero documento usano la CPU
GPU Memory (MB, 0 = Automatic) Memoria GPU (MB, 0 = Automatico)
+ {name} was changed by another app after it was opened or saved here. {name} è stato modificato da un'altra app dopo essere stato aperto o salvato qui.
+ Replace it with this document, or cancel and use File › Save As to keep both. Sostituiscilo con questo documento, oppure annulla e usa File › Salva con nome per tenerli entrambi.
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index b46096512..351699ea8 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -3884,3 +3884,6 @@ curves Smooth スムーズ
This document's layers: {needed} of {budget} for layers このドキュメントのレイヤー: レイヤー用 {budget} のうち {needed}
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU このドキュメントのレイヤーには {needed} が必要ですが、使えるのは {budget} です: ドキュメント全体の再描画は CPU で行われます
GPU Memory (MB, 0 = Automatic) GPU メモリ(MB、0 = 自動)
+ Replace 置き換え
+ {name} was changed by another app after it was opened or saved here. {name} は、ここで開くか保存した後に別のアプリで変更されました。
+ Replace it with this document, or cancel and use File › Save As to keep both. この書類で置き換えるか、キャンセルしてファイル › 名前を付けて保存で両方を残してください。
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 361cef2e9..3eaf14397 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -3386,3 +3386,6 @@ curves Smooth 매끄럽게
This document's layers: {needed} of {budget} for layers 이 문서의 레이어: 레이어용 {budget} 중 {needed}
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU 이 문서의 레이어에 {needed}가 필요하지만 {budget}만 사용할 수 있습니다: 문서 전체 다시 그리기는 CPU를 사용합니다
GPU Memory (MB, 0 = Automatic) GPU 메모리(MB, 0 = 자동)
+ Replace 대치
+ {name} was changed by another app after it was opened or saved here. {name}이(가) 여기서 열거나 저장한 뒤 다른 앱에서 변경되었습니다.
+ Replace it with this document, or cancel and use File › Save As to keep both. 이 문서로 대치하거나, 취소하고 파일 › 다른 이름으로 저장을 사용해 둘 다 보관하세요.
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index f1ac67961..09dd56800 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -3968,3 +3968,5 @@ curves Smooth Vloeiend maken
This document's layers: {needed} of {budget} for layers Lagen van dit document: {needed} van {budget} voor lagen
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU De lagen van dit document hebben {needed} nodig maar mogen {budget} gebruiken: het hele document wordt op de CPU opnieuw getekend
GPU Memory (MB, 0 = Automatic) GPU-geheugen (MB, 0 = Automatisch)
+ {name} was changed by another app after it was opened or saved here. {name} is door een andere app gewijzigd nadat het hier is geopend of bewaard.
+ Replace it with this document, or cancel and use File › Save As to keep both. Vervang het door dit document, of annuleer en gebruik Bestand › Opslaan als om beide te houden.
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 04eb15609..c4827aa82 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -3806,3 +3806,6 @@ curves Smooth Wygładź
This document's layers: {needed} of {budget} for layers Warstwy tego dokumentu: {needed} z {budget} na warstwy
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Warstwy tego dokumentu potrzebują {needed}, ale mogą zająć {budget}: odświeżanie całego dokumentu używa CPU
GPU Memory (MB, 0 = Automatic) Pamięć GPU (MB, 0 = Automatycznie)
+ Replace Zastąp
+ {name} was changed by another app after it was opened or saved here. Plik {name} został zmieniony przez inną aplikację po otwarciu lub zapisaniu go tutaj.
+ Replace it with this document, or cancel and use File › Save As to keep both. Zastąp go tym dokumentem albo anuluj i użyj Plik › Zapisz jako, aby zachować oba.
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 8d6b88fb5..f96542d64 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -3998,3 +3998,5 @@ layerLabel No Color Sem cor
This document's layers: {needed} of {budget} for layers Camadas deste documento: {needed} de {budget} para camadas
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU As camadas deste documento precisam de {needed} mas podem ocupar {budget}: o documento inteiro é redesenhado na CPU
GPU Memory (MB, 0 = Automatic) Memória da GPU (MB, 0 = Automático)
+ {name} was changed by another app after it was opened or saved here. {name} foi alterado por outro app depois de ser aberto ou salvo aqui.
+ Replace it with this document, or cancel and use File › Save As to keep both. Substitua-o por este documento, ou cancele e use Arquivo › Salvar como para manter os dois.
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 9d733f11a..f49200b97 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -3178,3 +3178,6 @@ curves Smooth Сгладить
This document's layers: {needed} of {budget} for layers Слои этого документа: {needed} из {budget} для слоёв
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Слоям этого документа нужно {needed}, но занимать они могут {budget}: весь документ перерисовывается на CPU
GPU Memory (MB, 0 = Automatic) Память GPU (МБ, 0 = автоматически)
+ Replace Заменить
+ {name} was changed by another app after it was opened or saved here. Файл {name} был изменён другим приложением после того, как его открыли или сохранили здесь.
+ Replace it with this document, or cancel and use File › Save As to keep both. Замените его этим документом или отмените и используйте Файл › Сохранить как, чтобы сохранить оба.
diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv
index d384c9bad..c207facb7 100644
--- a/crates/ui-egui/src/i18n/sr.tsv
+++ b/crates/ui-egui/src/i18n/sr.tsv
@@ -4281,3 +4281,5 @@ shape Appearance Izgled
This document's layers: {needed} of {budget} for layers Slojevi ovog dokumenta: {needed} od {budget} za slojeve
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Slojevima ovog dokumenta treba {needed}, a smeju da zauzmu {budget}: ceo dokument se ponovo iscrtava na CPU-u
GPU Memory (MB, 0 = Automatic) GPU memorija (MB, 0 = Automatski)
+ {name} was changed by another app after it was opened or saved here. Datoteku {name} je izmenila druga aplikacija nakon što je ovde otvorena ili sačuvana.
+ Replace it with this document, or cancel and use File › Save As to keep both. Zameni je ovim dokumentom ili otkaži i koristi Datoteka › Sačuvaj kao da zadržiš obe.
diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv
index 5c35aba71..a8aa0c3c5 100644
--- a/crates/ui-egui/src/i18n/tr.tsv
+++ b/crates/ui-egui/src/i18n/tr.tsv
@@ -3938,3 +3938,5 @@ cameraData Lens Lens
This document's layers: {needed} of {budget} for layers Bu belgenin katmanları: katmanlar için {budget} içinden {needed}
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Bu belgenin katmanlarının {needed} belleğe ihtiyacı var ama en fazla {budget} kullanabilirler: tüm belgenin yeniden çizimi CPU'yu kullanır
GPU Memory (MB, 0 = Automatic) GPU Belleği (MB, 0 = Otomatik)
+ {name} was changed by another app after it was opened or saved here. {name}, burada açıldıktan veya kaydedildikten sonra başka bir uygulama tarafından değiştirildi.
+ Replace it with this document, or cancel and use File › Save As to keep both. Bu belgeyle değiştirin ya da iptal edip ikisini de korumak için Dosya › Farklı Kaydet'i kullanın.
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index cb6f883eb..48fb60343 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -3907,3 +3907,6 @@ curves Smooth Згладити
This document's layers: {needed} of {budget} for layers Шари цього документа: {needed} з {budget} для шарів
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Шарам цього документа потрібно {needed}, але займати вони можуть {budget}: увесь документ перемальовується на CPU
GPU Memory (MB, 0 = Automatic) Пам'ять GPU (МБ, 0 = автоматично)
+ Replace Замінити
+ {name} was changed by another app after it was opened or saved here. Файл {name} змінила інша програма після того, як його тут відкрили або зберегли.
+ Replace it with this document, or cancel and use File › Save As to keep both. Замініть його цим документом або скасуйте й скористайтеся Файл › Зберегти як, щоб зберегти обидва.
diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv
index e2e55ab1b..f33ef1501 100644
--- a/crates/ui-egui/src/i18n/vi.tsv
+++ b/crates/ui-egui/src/i18n/vi.tsv
@@ -3694,3 +3694,6 @@ curves Smooth Làm mượt
This document's layers: {needed} of {budget} for layers Các lớp của tài liệu này: {needed} trên {budget} dành cho lớp
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Các lớp của tài liệu này cần {needed} nhưng chỉ được dùng {budget}: vẽ lại toàn bộ tài liệu dùng CPU
GPU Memory (MB, 0 = Automatic) Bộ nhớ GPU (MB, 0 = Tự động)
+ Replace Thay thế
+ {name} was changed by another app after it was opened or saved here. {name} đã bị một ứng dụng khác thay đổi sau khi được mở hoặc lưu ở đây.
+ Replace it with this document, or cancel and use File › Save As to keep both. Thay thế bằng tài liệu này, hoặc hủy và dùng Tệp › Lưu thành để giữ cả hai.
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index eebeabaa6..75eacc994 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2824,3 +2824,6 @@ curves Smooth 平滑
This document's layers: {needed} of {budget} for layers 此文档的图层:图层可用 {budget} 中的 {needed}
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU 此文档的图层需要 {needed},但只能占用 {budget}:整个文档的重绘使用 CPU
GPU Memory (MB, 0 = Automatic) GPU 内存(MB,0 = 自动)
+ Replace 替换
+ {name} was changed by another app after it was opened or saved here. {name} 在此处打开或存储后已被其他应用更改。
+ Replace it with this document, or cancel and use File › Save As to keep both. 用此文档替换它,或取消并使用“文件 › 另存为”以保留两者。
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index b35556b6f..95a11dc59 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2809,3 +2809,6 @@ curves Smooth 平滑
This document's layers: {needed} of {budget} for layers 此文件的圖層:圖層可用 {budget} 中的 {needed}
This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU 此文件的圖層需要 {needed},但只能佔用 {budget}:整份文件的重繪使用 CPU
GPU Memory (MB, 0 = Automatic) GPU 記憶體(MB,0 = 自動)
+ Replace 取代
+ {name} was changed by another app after it was opened or saved here. {name} 在此處開啟或儲存後已被其他 App 更改。
+ Replace it with this document, or cancel and use File › Save As to keep both. 以此文件取代它,或取消並使用「檔案 › 另存新檔」以保留兩者。
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 4c8d64832..04c37282e 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -75,6 +75,7 @@ pub mod dialogs;
pub mod direct_select;
pub mod direction;
pub mod discard_ui;
+pub mod disk_change_prompt;
pub mod distort_ui;
pub mod doc_props_ui;
pub mod dock;
@@ -350,6 +351,15 @@ pub(crate) fn plain_raster(doc: &Document) -> Option<&photocraft_doc::Layer> {
/// Encode a document: (file bytes, warnings about anything approximated or dropped).
pub type ExportFn = Box<dyn Fn(&Document, &str, &ExportSettings) -> Result<(Vec<u8>, Vec<String>), String>>;
pub type WriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;
+/// What a file on disk looked like when a document last read or wrote it: File › Save asks
+/// before replacing a file another app changed since (#6596).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct FileStamp {
+ pub len: u64,
+ pub modified: Option<std::time::SystemTime>,
+}
+/// The [`FileStamp`] of the file at a path, `None` when it can't be read.
+pub type FileStampFn = Box<dyn Fn(&str) -> Option<FileStamp>>;
/// Encode a document and write it to a path, reporting the stage to the job; returns the export
/// warnings. Runs on a worker thread (see [`Services::save_file`]). It must call
/// [`jobs_ui::SaveCtl::commit`] right before replacing the file, and write nothing if that fails.
@@ -447,6 +457,9 @@ pub struct Services {
pub file_dialog: Option<FileDialogFn>,
/// Write bytes to a path (native) or trigger a download (web).
pub write: Option<WriteFn>,
+ /// Size and modification time of a file (native); `None` on the web, where Save never
+ /// writes back to a file.
+ pub file_stamp: Option<FileStampFn>,
/// Encode and write in one step on a worker thread, so a large save doesn't freeze the
/// window (#2017). With background jobs on, saves use it instead of `export` and `write`.
pub save_file: Option<SaveFileFn>,
@@ -788,6 +801,9 @@ pub struct PhotocraftApp {
/// Where each document was last saved or exported to through a dialog (#1826): its next Save
/// As or export dialog starts there rather than beside the document. Session-only.
pub(crate) save_dirs: HashMap<photocraft_doc::DocId, std::path::PathBuf>,
+ /// Each document's own file as it was when the document was opened from it or saved to it
+ /// (see [`FileStamp`]).
+ pub(crate) disk_stamps: HashMap<photocraft_doc::DocId, (String, FileStamp)>,
/// A save to an RGB Targa parked behind the Targa Options prompt (see `targa_options_ui`).
pub(crate) targa_options: Option<targa_options_ui::Prompt>,
/// Files read but not opened yet: the first waits on its profile prompt, the rest behind it
@@ -937,6 +953,7 @@ impl PhotocraftApp {
file_dialog: None,
tiff_options: None,
save_dirs: HashMap::new(),
+ disk_stamps: HashMap::new(),
targa_options: None,
held_opens: Default::default(),
allow_close: false,
@@ -1439,6 +1456,13 @@ impl PhotocraftApp {
self.pick_save(&suggested, move |app, path| {
app.with_document(doc, |app| {
let own = app.session.active().and_then(|st| st.path.clone());
+ // Confirming the document's own file: ask first if another app changed it (#6596).
+ if plain_save
+ && own.as_deref() == Some(path.as_str())
+ && let Some(r) = crate::disk_change_prompt::intercept(app, doc, &path, true)
+ {
+ return r;
+ }
let r = app.save_to(path.clone(), tga_bits)?;
if plain_save && own.as_deref() == Some(path.as_str()) {
app.journal_as_plain_save(&path);
@@ -1449,7 +1473,7 @@ impl PhotocraftApp {
}
/// [`Self::save_as_with`] once the path is known.
- fn save_to(&mut self, path: String, tga_bits: Option<photocraft_io::TgaBits>) -> Result<Value, String> {
+ pub(crate) fn save_to(&mut self, path: String, tga_bits: Option<photocraft_io::TgaBits>) -> Result<Value, String> {
// An RGB Targa asks for its bits per pixel, unless the caller chose them; the save
// continues from the prompt (still a copy when it would be one without the prompt),
// which records the step once answered.
@@ -1493,7 +1517,7 @@ impl PhotocraftApp {
}
/// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]).
- fn journal_as_plain_save(&mut self, path: &str) {
+ pub(crate) fn journal_as_plain_save(&mut self, path: &str) {
if let Some(last) = self.session.journal.last_mut()
&& last.0 == "file.saveAs"
&& last.1.get("path").and_then(Value::as_str) == Some(path)
@@ -1634,6 +1658,7 @@ impl PhotocraftApp {
st.saved_to(path.to_string());
// The job locked the document, but record the revision that was written.
st.saved_revision = revision;
+ app.remember_stamp(doc, path);
}
// "Save Document" script events and File › Generate › Image Assets.
if hooks
@@ -1653,6 +1678,9 @@ impl PhotocraftApp {
if hooks {
self.push_recent(path);
}
+ } else if self.disk_stamps.get(&doc).is_some_and(|(own, _)| own == path) {
+ // A copy written over the document's own file is this app's change too.
+ self.remember_stamp(doc, path);
}
self.ui.status_error = false;
let what = crate::i18n::fmt(tl!("Saved {name}"), &[("name", file_open::display_name(path).as_str())]);
@@ -1660,6 +1688,21 @@ impl PhotocraftApp {
self.sync_views();
}
+ /// Note how `doc`'s own file at `path` looks now that the document read or wrote it.
+ pub(crate) fn remember_stamp(&mut self, doc: photocraft_doc::DocId, path: &str) {
+ match self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)) {
+ Some(now) => self.disk_stamps.insert(doc, (path.to_string(), now)),
+ None => self.disk_stamps.remove(&doc),
+ };
+ }
+
+ /// Another app changed `doc`'s own file at `path` since the document was opened from it or
+ /// last saved to it. A file that is gone, or one never stamped, counts as unchanged.
+ pub(crate) fn changed_on_disk(&self, doc: photocraft_doc::DocId, path: &str) -> bool {
+ let Some((own, then)) = self.disk_stamps.get(&doc) else { return false };
+ own == path && self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)).is_some_and(|now| now != *then)
+ }
+
/// TIFF Options or Targa Options is waiting on an answer before a save is written.
pub(crate) fn save_options_open(&self) -> bool {
self.tiff_options.is_some() || self.targa_options.is_some()
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index f2baba7cf..d322e2641 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -231,7 +231,11 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
None => {
let own = app.session.active().and_then(|d| d.path.clone().map(|p| (photocraft_engine::file_cmds::holds_at(&d.doc, &p), p, d)));
match own {
- Some((true, path, _)) => app.save_in_place(path),
+ Some((true, path, d)) => {
+ // Another app changed the file since it was opened or saved: ask first (#6596).
+ let doc = d.doc.id;
+ crate::disk_change_prompt::intercept(app, doc, &path, false).unwrap_or_else(|| app.save_in_place(path))
+ }
Some((false, path, d)) if photocraft_engine::file_cmds::saves_in_place(&path) => {
// Its own file is layered but can't hold what the document has now.
let losses = photocraft_engine::file_cmds::losses_at(&d.doc, &path);