PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Save As: the document takes the saved file's name (#2018)
optimalbyteecc0441f9ae0a
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rsindex b0612661e..c6bfa1bea 100644--- a/crates/automation/src/headless.rs+++ b/crates/automation/src/headless.rs@@ -157,8 +157,7 @@ impl Headless {let previously_active = self.session.active_index();self.session.set_active(i);if let Some(st) = self.session.active_mut() {- st.saved_revision = st.revision;- st.path = Some(target.to_string_lossy().into_owned());+ st.saved_to(target.to_string_lossy().into_owned());}if let Some(active) = previously_active {self.session.set_active(active);diff --git a/crates/automation/tests/inactive_save.rs b/crates/automation/tests/inactive_save.rsindex 7f7aaefc8..7e4267051 100644--- a/crates/automation/tests/inactive_save.rs+++ b/crates/automation/tests/inactive_save.rs@@ -25,12 +25,33 @@ fn indexed_native_save_preserves_active_document_and_future_command_target() {assert_eq!(headless.session.active_index(), Some(1), "save must not select document 0");let first = &headless.session.documents()[0];assert_eq!(first.path.as_deref(), path.to_str());+ assert_eq!(first.doc.name, "first.pcraft");assert_eq!(first.revision, first.saved_revision, "saved document is clean");headless.handle("engine.execute", json!({"command": "image.adjustments.invert", "params": {}})).unwrap();assert_eq!(headless.session.active_index(), Some(1));assert_eq!(headless.session.documents()[0].revision, first_revision);assert!(headless.session.documents()[1].revision > second_revision);+ for name in ["保存 first.psd", "renamed.psb"] {+ let path = dir.join(name);+ headless.handle("doc.save", json!({"index": 0, "path": path.to_str().unwrap()})).unwrap();+ assert_eq!(headless.session.active_index(), Some(1));+ assert_eq!(headless.session.documents()[0].doc.name, name);+ assert_eq!(headless.session.documents()[1].doc.name, "second");+ assert!(!headless.session.documents()[0].is_dirty());+ }+ let before = headless.session.documents()[0].clone();+ let blocked = dir.join("not-a-directory");+ std::fs::write(&blocked, b"blocks the parent directory").unwrap();+ let failed = blocked.join("fail.psd");+ assert!(headless.handle("doc.save", json!({"index": 0, "path": failed.to_str().unwrap()})).is_err());+ assert_eq!(headless.session.active_index(), Some(1));+ assert_eq!(headless.session.documents()[0].doc.name, before.doc.name);+ assert_eq!(headless.session.documents()[0].path, before.path);+ let copy = dir.join("copy.png");+ headless.handle("doc.save", json!({"index": 0, "path": copy.to_str().unwrap()})).unwrap();+ assert_eq!(headless.session.documents()[0].doc.name, before.doc.name);+ assert_eq!(headless.session.documents()[0].path, before.path);drop(headless);std::fs::remove_dir_all(dir).unwrap();}diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rsindex 49aa5b32a..657eb02e4 100644--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@ -131,6 +131,19 @@ pub(crate) fn file_name(path: &str) -> String {path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()}+impl crate::DocState {+ /// Complete a successful document save. File identity is not a history step; callers must+ /// finish the write first and must not call this for a copy or export.+ pub fn saved_to(&mut self, path: String) {+ let name = file_name(&path);+ if self.doc.name != name {+ Arc::make_mut(&mut self.doc).name = name;+ }+ self.path = Some(path);+ self.saved_revision = self.revision;+ }+}+/// The lower-case extension of the file name in `path` (none for `.hidden` or `name`).pub fn extension(path: &str) -> Option<String> {file_name(path).rsplit_once('.').filter(|(base, ext)| !base.is_empty() && !ext.is_empty()).map(|(_, ext)| ext.to_ascii_lowercase())diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 89b1af5a3..e14d3d136 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -562,7 +562,11 @@ impl Session {let Some(st) = self.active_mut() else { return false };st.coalesce = None;match st.history.undo(st.doc.clone()) {- Some((d, layers)) => {+ Some((mut d, layers)) => {+ // Save As changes file identity outside history, just like the saved path.+ if d.name != st.doc.name {+ Arc::make_mut(&mut d).name.clone_from(&st.doc.name);+ }// Pixels this step can have touched, so the canvas recomposites only that// (it recomposited everything before).let damage = layer_multi_cmds::step_damage(&d, &st.doc);@@ -583,7 +587,10 @@ impl Session {let Some(st) = self.active_mut() else { return false };st.coalesce = None;match st.history.redo(st.doc.clone()) {- Some((d, layers)) => {+ Some((mut d, layers)) => {+ if d.name != st.doc.name {+ Arc::make_mut(&mut d).name.clone_from(&st.doc.name);+ }let damage = layer_multi_cmds::step_damage(&st.doc, &d);st.doc = d;restore_target(st, layers);diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 084f112b2..5c71341c1 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -7,6 +7,36 @@ fn session_with_doc() -> Session {s}+#[test]+fn successful_save_identity_is_not_undone_or_redone() {+ for depth in [8, 16, 32] {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 4, "height": 4, "depth": depth, "name": "Untitled-1"})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ let original = s.active().unwrap().doc.clone();+ let revision = s.active().unwrap().revision;+ s.active_mut().unwrap().saved_to("C:\\作品\\My picture.PSD".into());+ let saved = s.active().unwrap();+ assert_eq!(saved.doc.name, "My picture.PSD");+ assert_eq!(saved.doc.id, original.id);+ assert_eq!(saved.revision, revision);+ assert!(!saved.is_dirty());+ assert_eq!(original.name, "Untitled-1", "the exported snapshot remains immutable");+ let snapshot = saved.doc.clone();+ s.active_mut().unwrap().saved_to("C:\\作品\\My picture.PSD".into());+ assert!(Arc::ptr_eq(&s.active().unwrap().doc, &snapshot), "saving the same name does not invalidate snapshots or jobs");+ assert!(s.undo());+ assert_eq!(s.active().unwrap().doc.name, "My picture.PSD");+ s.active_mut().unwrap().saved_to("renamed.psb".into());+ assert!(s.redo());+ assert_eq!(s.active().unwrap().doc.name, "renamed.psb");+ assert_eq!(s.active().unwrap().path.as_deref(), Some("renamed.psb"));+ assert!(s.active().unwrap().is_dirty());+ assert!(s.undo());+ assert_eq!(s.active().unwrap().doc.name, "renamed.psb");+ }+}+fn px(s: &mut Session, x: i32, y: i32) -> Vec<f32> {serde_json::from_value(s.execute("document.pixel", json!({"x": x, "y": y})).unwrap()).unwrap()}diff --git a/crates/ui-egui/src/canvas/tabs_tests.rs b/crates/ui-egui/src/canvas/tabs_tests.rsindex 6b13fe7f5..6d8a7adfa 100644--- a/crates/ui-egui/src/canvas/tabs_tests.rs+++ b/crates/ui-egui/src/canvas/tabs_tests.rs@@ -86,3 +86,29 @@ fn studio_tabs_overflow_into_the_same_menu() {let name = h.state().session.documents()[active].doc.name.clone();assert!(h.query_by_label(&name).is_some(), "the active tab is on the strip: {name}");}++#[test]+fn saved_document_tabs_track_file_identity() {+ for theme in ThemeKind::ALL {+ let mut h = harness(2, theme);+ h.state_mut().services.export = Some(Box::new(|_, _, _| Ok((vec![1], Vec::new()))));+ h.state_mut().services.write = Some(Box::new(|_, _| Ok(())));+ h.state_mut().save_as(Some("folder/My saved image.psd".into())).unwrap();+ h.run_steps(2);+ let pro = crate::theme::Tokens::get(&h.ctx).pro;+ let app = h.state();+ let label = if pro { pro_tab_title(app, 1) } else { "My saved image.psd".into() };+ assert!(h.query_by_label(&label).is_some(), "saved tab in {theme:?}: {label}");+ assert_eq!(app.session.active().unwrap().doc.name, "My saved image.psd");+ h.state_mut().session.set_active(0);+ h.run_steps(2);+ assert_eq!(h.state().session.active().unwrap().doc.name, "ch1-p01.png");+ h.state_mut().session.set_active(1);+ h.state_mut().run("layer.new.layer", json!({})).unwrap();+ h.run_steps(2);+ let label = if pro { pro_tab_title(h.state(), 1) } else { "My saved image.psd".into() };+ assert!(h.query_by_label(&label).is_some());+ assert_eq!(h.state().session.active().unwrap().doc.name, "My saved image.psd");+ assert!(h.state().session.active().unwrap().is_dirty());+ }+}diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rsindex 9404d07e1..99e44f4bf 100644--- a/crates/ui-egui/src/file_dialog.rs+++ b/crates/ui-egui/src/file_dialog.rs@@ -194,6 +194,18 @@ impl PhotocraftApp {Ok(())}+ /// Complete a deferred operation on its requesting document without stealing the selected+ /// tab. Restore by ID as script events can close or reorder documents during a save.+ pub(crate) fn with_document<T>(&mut self, id: DocId, run: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {+ let active = self.session.active().map(|d| d.doc.id);+ self.refocus(id)?;+ let result = run(self);+ if let Some(active) = active {+ let _ = self.refocus(active);+ }+ result+ }+/// The active document's id, for [`Self::refocus`].pub(crate) fn active_doc_id(&self) -> Result<DocId, String> {Ok(self.session.active().ok_or("no document")?.doc.id)diff --git a/crates/ui-egui/src/file_dialog/tests.rs b/crates/ui-egui/src/file_dialog/tests.rsindex 6313fef5a..3363b3a5a 100644--- a/crates/ui-egui/src/file_dialog/tests.rs+++ b/crates/ui-egui/src/file_dialog/tests.rs@@ -96,6 +96,7 @@ fn the_app_keeps_running_while_a_dialog_is_open() {assert_eq!(*written.borrow(), ["/pics/a.psd"]);let st = app.session.active().unwrap();assert_eq!(st.path.as_deref(), Some("/pics/a.psd"));+ assert_eq!(st.doc.name, "a.psd", "a successful Save As adopts the file name");assert!(!st.is_dirty());assert!(!app.file_dialog_open());}@@ -178,8 +179,11 @@ fn the_answer_goes_to_the_document_it_was_asked_for() {app.poll_file_dialog(&ctx, None);let paths: Vec<_> = app.session.documents().iter().map(|d| d.path.clone()).collect();assert_eq!(paths, [Some("/pics/first.psd".to_string()), None]);- assert_eq!(app.session.active_index(), Some(0));+ assert_eq!(app.session.active_index(), Some(1), "a completed save preserves the selected tab");+ assert_eq!(app.session.documents()[0].doc.name, "first.psd");+ assert_ne!(app.session.documents()[1].doc.name, "first.psd");// Once that document is closed, the answer has nothing to save.+ app.session.set_active(0);menus::invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();app.poll_file_dialog(&ctx, None);app.run("file.close", json!({"document": 0})).unwrap();@@ -193,6 +197,8 @@ fn the_answer_goes_to_the_document_it_was_asked_for() {fn cancel_and_a_dialog_that_could_not_show_end_quietly() {let (mut app, open, written) = app();let ctx = egui::Context::default();+ app.run("layer.new.layer", json!({})).unwrap();+ let before = app.session.active().unwrap().clone();menus::invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();app.poll_file_dialog(&ctx, None);answer(&open, None);@@ -205,12 +211,55 @@ fn cancel_and_a_dialog_that_could_not_show_end_quietly() {app.poll_file_dialog(&ctx, None);assert!(!app.file_dialog_open() && !app.ui.status_error);assert!(written.borrow().is_empty());+ let after = app.session.active().unwrap();+ assert_eq!(after.doc.name, before.doc.name);+ assert_eq!(after.path, before.path);+ assert_eq!((after.revision, after.saved_revision), (before.revision, before.saved_revision));// Without a dialog service, asking is a Cancel straight away.app.services.file_dialog = None;assert_eq!(app.open_dialog_file().unwrap_err(), CANCELLED);assert!(!app.file_dialog_open());}+#[test]+fn opening_another_document_before_the_save_answer_keeps_its_identity() {+ let (mut app, open, written) = app();+ let ctx = egui::Context::default();+ let first_id = app.active_doc_id().unwrap();+ app.save_as(None).unwrap();+ app.poll_file_dialog(&ctx, None);+ app.run("file.new", json!({"width": 4, "height": 4, "name": "Untitled-2"})).unwrap();+ let second_id = app.active_doc_id().unwrap();+ app.run("document.move", json!({"document": 0, "to": 1})).unwrap();+ answer(&open, Some(FileDialogAnswer::SaveTo("/pics/保存 first.psd".into())));+ app.poll_file_dialog(&ctx, None);+ assert_eq!(*written.borrow(), ["/pics/保存 first.psd"]);+ let first = app.session.documents().iter().find(|s| s.doc.id == first_id).unwrap();+ assert_eq!(first.doc.name, "保存 first.psd");+ assert_eq!(first.path.as_deref(), Some("/pics/保存 first.psd"));+ assert_eq!(app.active_doc_id().unwrap(), second_id);+ assert_eq!(app.session.active().unwrap().doc.name, "Untitled-2");+}++#[test]+fn failed_deferred_save_preserves_both_identities_and_the_selected_tab() {+ let (mut app, open, written) = app();+ let ctx = egui::Context::default();+ app.run("layer.new.layer", json!({})).unwrap();+ app.save_as(None).unwrap();+ app.poll_file_dialog(&ctx, None);+ app.run("file.new", json!({"width": 4, "height": 4, "name": "second"})).unwrap();+ let before: Vec<_> = app.session.documents().iter().map(|d| (d.doc.name.clone(), d.path.clone(), d.revision, d.saved_revision)).collect();+ app.services.write = Some(Box::new(|_, _| Err("disk full".into())));+ answer(&open, Some(FileDialogAnswer::SaveTo("failed.psd".into())));+ app.poll_file_dialog(&ctx, None);+ let after: Vec<_> = app.session.documents().iter().map(|d| (d.doc.name.clone(), d.path.clone(), d.revision, d.saved_revision)).collect();+ assert_eq!(after, before);+ assert_eq!(app.session.active_index(), Some(1));+ assert!(app.ui.status_error && app.ui.status == "disk full");+ assert!(written.borrow().is_empty());+}+#[test]fn an_answer_of_the_wrong_kind_is_an_error_not_a_crash() {let (mut app, open, written) = app();diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 97d500d0c..f2bbcbd56 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -938,10 +938,7 @@ impl PhotocraftApp {p => std::path::Path::new(p.as_deref().unwrap_or(&st.doc.name)).with_extension("psd").to_string_lossy().into_owned(),};let doc = st.doc.id;- self.pick_save(&suggested, move |app, path| {- app.refocus(doc)?;- app.save_to(path)- })+ self.pick_save(&suggested, move |app, path| app.with_document(doc, |app| app.save_to(path)))}/// [`Self::save_as`] once the path is known.@@ -966,8 +963,7 @@ impl PhotocraftApp {let write = self.services.write.as_mut().ok_or("no writer configured")?;write(&path, &bytes)?;if !copy && let Some(st) = self.session.active_mut() {- st.path = Some(path.clone());- st.saved_revision = st.revision;+ st.saved_to(path.clone());}self.ui.status = format!("Saved {path}");// "Save Document" script events and File › Generate › Image Assets.@@ -997,8 +993,7 @@ impl PhotocraftApp {let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?;write(&target, &bytes)?;if let Some(state) = self.session.active_mut() {- state.path = Some(target.clone());- state.saved_revision = state.revision;+ state.saved_to(target.clone());}self.ui.status = format!("Saved {target}");self.ui.status_error = false;@@ -1698,6 +1693,9 @@ mod pencil_tests;#[cfg(test)]mod transform_undo_tests;+#[cfg(test)]+mod save_identity_tests;+#[cfg(test)]mod move_auto_select_tests;diff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rsnew file mode 100644index 000000000..79b0237c5--- /dev/null+++ b/crates/ui-egui/src/save_identity_tests.rs@@ -0,0 +1,116 @@+//! Save identity belongs to the editable document, after a successful write only.++use crate::{ExportSettings, PhotocraftApp, Services, menus};+use photocraft_engine::Session;+use serde_json::json;+use std::{cell::RefCell, rc::Rc};++fn app() -> PhotocraftApp {+ let mut app = PhotocraftApp::new(+ Session::new(),+ Services {+ import: Some(Box::new(|name, bytes| photocraft_io::import(name, bytes).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()))),+ export: Some(Box::new(|doc, path, _| {+ photocraft_io::export(doc, path, &Default::default()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string())+ })),+ write: Some(Box::new(|_, _| Ok(()))),+ automation_write: Some(Box::new(|_, _| Ok(()))),+ ..Default::default()+ },+ );+ app.run("file.new", json!({"width": 4, "height": 4, "name": "Untitled-1"})).unwrap();+ app.run("layer.new.layer", json!({})).unwrap();+ app+}++fn identity(app: &PhotocraftApp) -> (String, Option<String>, u64, u64) {+ let st = app.session.active().unwrap();+ (st.doc.name.clone(), st.path.clone(), st.revision, st.saved_revision)+}++#[test]+fn new_document_psd_and_subsequent_save_as_adopt_the_written_file_name() {+ for depth in [8, 16, 32] {+ let mut app = app();+ app.run("file.new", json!({"width": 4, "height": 4, "depth": depth, "name": "Untitled-1"})).unwrap();+ app.run("layer.new.layer", json!({})).unwrap();+ let bytes = Rc::new(RefCell::new(Vec::new()));+ let written = bytes.clone();+ app.services.write = Some(Box::new(move |_, data| {+ *written.borrow_mut() = data.to_vec();+ Ok(())+ }));+ let id = app.session.active().unwrap().doc.id;+ let revision = app.session.active().unwrap().revision;+ let ctx = egui::Context::default();+ menus::invoke(&mut app, &ctx, "file.saveAs", json!({"path": "作品/My image.PSD"})).unwrap();+ assert_eq!(identity(&app), ("My image.PSD".into(), Some("作品/My image.PSD".into()), revision, revision));+ assert_eq!(app.session.active().unwrap().doc.id, id);+ let reopened = photocraft_io::import("My image.PSD", &bytes.borrow()).unwrap();+ assert_eq!(reopened.document.size, app.session.active().unwrap().doc.size);+ assert_eq!(reopened.document.depth.bits(), depth);+ menus::invoke(&mut app, &ctx, "file.saveAs", json!({"path": "作品/次の画像.psd"})).unwrap();+ assert_eq!(app.session.active().unwrap().doc.name, "次の画像.psd");+ menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap();+ assert_eq!(app.session.active().unwrap().path.as_deref(), Some("作品/次の画像.psd"));+ app.open_bytes("existing.psd", &bytes.borrow()).unwrap();+ let id = app.active_doc_id().unwrap();+ assert_eq!(app.session.active().unwrap().doc.name, "existing.psd");+ app.save_as(Some("renamed existing.psd".into())).unwrap();+ assert_eq!(app.active_doc_id().unwrap(), id);+ assert_eq!(app.session.active().unwrap().doc.name, "renamed existing.psd");+ }+}++#[test]+fn failed_encode_or_write_keeps_the_previous_name_path_and_dirty_state() {+ for saved_before in [false, true] {+ let mut app = app();+ if saved_before {+ app.save_as(Some("before.psd".into())).unwrap();+ app.run("layer.new.layer", json!({})).unwrap();+ }+ let before = identity(&app);+ app.services.write = Some(Box::new(|_, _| Err("disk full".into())));+ assert!(app.save_as(Some("after.psd".into())).is_err());+ assert_eq!(identity(&app), before);+ assert!(app.save_automation(Some("after.psd".into())).is_ok());+ app.run("layer.new.layer", json!({})).unwrap();+ let before = identity(&app);+ app.services.automation_write = Some(Box::new(|_, _| Err("denied".into())));+ assert!(app.save_automation(Some("another.psd".into())).is_err());+ assert_eq!(identity(&app), before);+ app.services.export = Some(Box::new(|_, _, _| Err("cannot encode".into())));+ assert!(app.save_as(Some("after.psd".into())).is_err());+ assert_eq!(identity(&app), before);+ }+}++#[test]+fn save_copy_and_export_keep_the_editable_document_identity() {+ let mut app = app();+ app.save_as(Some("original.psd".into())).unwrap();+ app.run("layer.new.layer", json!({})).unwrap();+ let before = identity(&app);+ app.write_document("copy.psd".into(), &ExportSettings::default(), true).unwrap();+ assert_eq!(identity(&app), before);+ let (dialog, _) = crate::file_dialog::fake(vec![Some(crate::file_dialog::FileDialogAnswer::SaveTo("export.png".into()))]);+ app.services.file_dialog = Some(dialog);+ let ctx = egui::Context::default();+ crate::export_dialog::confirm(&mut app, json!({"format": "png", "scale": 100}).as_object().unwrap()).unwrap();+ app.poll_file_dialog(&ctx, None);+ assert_eq!(identity(&app), before);+ assert!(app.ui.status.starts_with("Exported export.png"), "{}", app.ui.status);+}++#[test]+fn web_download_and_automation_saves_use_the_same_identity_completion() {+ let mut app = app();+ let (dialog, _) = crate::file_dialog::fake(vec![Some(crate::file_dialog::FileDialogAnswer::SaveTo("Untitled-1.psd".into()))]);+ app.services.file_dialog = Some(dialog);+ app.save_as(None).unwrap();+ app.poll_file_dialog(&egui::Context::default(), None);+ assert_eq!(app.session.active().unwrap().doc.name, "Untitled-1.psd");+ app.save_automation(Some("保存/agent save.psd".into())).unwrap();+ assert_eq!(app.session.active().unwrap().doc.name, "agent save.psd");+}diff --git a/crates/ui-egui/src/tiff_options_ui.rs b/crates/ui-egui/src/tiff_options_ui.rsindex 0d868db1d..8614ffcaa 100644--- a/crates/ui-egui/src/tiff_options_ui.rs+++ b/crates/ui-egui/src/tiff_options_ui.rs@@ -71,7 +71,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {app.session.edit_prefs(|prefs| prefs.file_handling.ask_before_saving_layered_tiff = false);}let settings = ExportSettings { tiff_layers: !p.discard_layers, ..Default::default() };- if let Err(e) = app.refocus(p.doc).and_then(|()| app.write_document(p.path, &settings, p.discard_layers)) {+ if let Err(e) = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.discard_layers)) {app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);app.ui.status_error = true;} else if !p.discard_layers {