mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-21 09:26:43 +00:00
feat(ui-egui): export dialogs start in the last exported folder (#10192)
Export As, Quick Export and Save for Web now start in the folder of the last successful export (new preference export.lastFolder, kept across restarts), falling back to the document's folder when none is remembered or the folder is gone. Save As and non-export save dialogs are unchanged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
952c328b3d
commit
13f84218e3
5 files changed
+166
-11
No files matched your search
@@ -543,6 +543,10 @@ pub struct Export {
|
||||
pub webp_quality: u32,
|
||||
pub metadata: ExportMetadata,
|
||||
pub convert_to_srgb: bool,
|
||||
/// The folder the last successful export through a save dialog went to (Export As, Quick
|
||||
/// Export, Save for Web, ...). The next export dialog starts there; empty until the first
|
||||
/// export, and ignored while the folder no longer exists (#10192).
|
||||
pub last_folder: String,
|
||||
}
|
||||
|
||||
impl Default for Export {
|
||||
@@ -555,6 +559,7 @@ impl Default for Export {
|
||||
webp_quality: 85,
|
||||
metadata: ExportMetadata::Copyright,
|
||||
convert_to_srgb: true,
|
||||
last_folder: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,7 +209,7 @@ pub fn quick_export_selected_layers_png(app: &mut PhotocraftApp) -> Result<Value
|
||||
let docs: Vec<_> =
|
||||
layers.into_iter().map(|id| photocraft_engine::layer_menu_cmds::layer_document(&st.doc, id).map_err(|e| e.to_string())).collect::<Result<_, _>>()?;
|
||||
let suggested = format!("{}.png", export_name(&st.doc.name));
|
||||
app.pick_save(&suggested, move |app, path| {
|
||||
app.pick_export(&suggested, move |app, path| {
|
||||
if !path.to_ascii_lowercase().ends_with(".png") {
|
||||
return Err("Quick Export as PNG writes .png files".into());
|
||||
}
|
||||
@@ -1046,7 +1046,7 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
|
||||
let ext = s_fmt(f);
|
||||
let suggested = format!("{stem}.{ext}");
|
||||
let f = f.clone();
|
||||
app.pick_save(&suggested, move |app, path| {
|
||||
app.pick_export(&suggested, move |app, path| {
|
||||
let r = write_export(app, &doc, &f, &path, &source_profile)?;
|
||||
// An action being recorded keeps a whole-document export with its destination and
|
||||
// settings (#7207). A layer's export isn't recorded: its layer is this document's.
|
||||
@@ -1107,7 +1107,7 @@ fn confirm_layers(app: &mut PhotocraftApp, f: &Map<String, Value>, ids: &[photoc
|
||||
let stem = st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a);
|
||||
let suggested = format!("{}.{}", export_name(stem), s_fmt(f));
|
||||
let (f, settings) = (f.clone(), settings(f));
|
||||
app.pick_save(&suggested, move |app, path| {
|
||||
app.pick_export(&suggested, move |app, path| {
|
||||
let mut exported = Vec::new();
|
||||
for (doc, path) in docs.iter().zip(batch_paths(&path, &docs)) {
|
||||
let out = export_document(doc, &f, None, &source_profile)?;
|
||||
@@ -1145,7 +1145,7 @@ pub fn quick_export_png(app: &mut PhotocraftApp) -> Result<Value, String> {
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
let stem = st.doc.name.rsplit_once('.').map_or(st.doc.name.as_str(), |(a, _)| a);
|
||||
let (suggested, doc) = (format!("{stem}.{fmt}"), st.doc.id);
|
||||
return app.pick_save(&suggested, move |app, path| {
|
||||
return app.pick_export(&suggested, move |app, path| {
|
||||
app.refocus(doc)?;
|
||||
quick_export(app, json!({"path": path}))
|
||||
});
|
||||
|
||||
@@ -535,7 +535,7 @@ pub(super) fn web_confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Re
|
||||
let st = WebSettings::from_params(&p, "file.export.saveForWebLegacy").map_err(|e| e.to_string())?;
|
||||
let base = photocraft_doc::slices::base_name(&doc);
|
||||
let suggested = if has_slices && html { format!("{base}.html") } else { format!("{base}.{}", st.format.ext()) };
|
||||
app.pick_save(&suggested, move |app, path| {
|
||||
app.pick_export(&suggested, move |app, path| {
|
||||
app.refocus(doc.id)?;
|
||||
if has_slices {
|
||||
let dir = path.rfind(['/', '\\']).map(|i| path[..i].to_string()).unwrap_or_else(|| ".".into());
|
||||
|
||||
@@ -148,17 +148,39 @@ impl PhotocraftApp {
|
||||
/// (#1826, #1866). A caller's explicit directory is kept. The chosen folder is remembered for
|
||||
/// the document the dialog was asked for.
|
||||
pub(crate) fn pick_save(&mut self, suggested: &str, then: impl FnOnce(&mut Self, String) -> Result<Value, String> + 'static) -> Result<Value, String> {
|
||||
self.pick_save_in(suggested, false, then)
|
||||
}
|
||||
|
||||
/// [`Self::pick_save`] for the export flows (Export As, Quick Export, Save for Web, ...): a
|
||||
/// bare file name starts in the folder of the last successful export (a preference, kept
|
||||
/// across restarts), as in Photoshop, and beside the document where that folder is unset or
|
||||
/// gone (#10192, [`export_start_dir`]). Once `then` has exported, the chosen file's folder is
|
||||
/// remembered; a failed or cancelled export leaves the remembered folder alone.
|
||||
pub(crate) fn pick_export(&mut self, suggested: &str, then: impl FnOnce(&mut Self, String) -> Result<Value, String> + 'static) -> Result<Value, String> {
|
||||
self.pick_save_in(suggested, true, then)
|
||||
}
|
||||
|
||||
fn pick_save_in(
|
||||
&mut self,
|
||||
suggested: &str,
|
||||
export: bool,
|
||||
then: impl FnOnce(&mut Self, String) -> Result<Value, String> + 'static,
|
||||
) -> Result<Value, String> {
|
||||
let mut suggested = std::path::PathBuf::from(suggested);
|
||||
let doc = self.session.active().map(|d| d.doc.id);
|
||||
// Closed documents' folders are no longer needed.
|
||||
let open: Vec<_> = self.session.documents().iter().map(|d| d.doc.id).collect();
|
||||
self.save_dirs.retain(|id, _| open.contains(id));
|
||||
if suggested.parent().is_some_and(|p| p.as_os_str().is_empty())
|
||||
&& let Some(dir) = doc
|
||||
if suggested.parent().is_some_and(|p| p.as_os_str().is_empty()) {
|
||||
let document_dir = doc
|
||||
.and_then(|d| self.save_dirs.get(&d).cloned())
|
||||
.or_else(|| self.session.active().and_then(|d| d.path.as_deref()).and_then(|p| std::path::Path::new(p).parent()).map(Path::to_path_buf))
|
||||
{
|
||||
suggested = dir.join(suggested);
|
||||
// An export doesn't start in a folder that is gone.
|
||||
.filter(|dir| !export || folder_exists(dir))
|
||||
.or_else(|| self.session.active().and_then(|d| d.path.as_deref()).and_then(|p| std::path::Path::new(p).parent()).map(Path::to_path_buf));
|
||||
let remembered = export.then(|| self.session.prefs().export.last_folder.clone());
|
||||
if let Some(dir) = export_start_dir(remembered.as_deref(), document_dir, folder_exists) {
|
||||
suggested = dir.join(suggested);
|
||||
}
|
||||
}
|
||||
// The format comes from the extension, so a name typed without one (common where file
|
||||
// extensions are hidden, #5039) gets the suggested file's extension, as Photoshop's
|
||||
@@ -174,7 +196,11 @@ impl PhotocraftApp {
|
||||
{
|
||||
app.save_dirs.insert(doc, dir.to_path_buf());
|
||||
}
|
||||
then(app, path)
|
||||
let exported = then(app, path.clone())?;
|
||||
if export {
|
||||
app.remember_export_folder(&path);
|
||||
}
|
||||
Ok(exported)
|
||||
}
|
||||
_ => Err(UNEXPECTED.into()),
|
||||
})?;
|
||||
@@ -184,6 +210,16 @@ impl PhotocraftApp {
|
||||
Ok(asked)
|
||||
}
|
||||
|
||||
/// Remember the folder of an export that succeeded as where the next export dialog starts.
|
||||
/// The web answers a download name, which has no folder, and leaves it alone.
|
||||
fn remember_export_folder(&mut self, path: &str) {
|
||||
let Some(dir) = Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()) else { return };
|
||||
let dir = dir.to_string_lossy().into_owned();
|
||||
if self.session.prefs().export.last_folder != dir {
|
||||
self.session.prefs.edit(|p| p.export.last_folder = dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a save to `path` replaces a file the save dialog didn't ask about: the dialog
|
||||
/// answered `answered`, and [`saved_path`] changed it. A file at `path` that
|
||||
/// [`Services::same_file`](crate::Services::same_file) finds is the same entry as `answered` (the
|
||||
@@ -370,6 +406,28 @@ fn saved_path(app: &PhotocraftApp, answered: &str, suggested_ext: Option<&str>)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `dir` is a folder on disk. The web has no file system, so nothing is remembered there.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn folder_exists(dir: &Path) -> bool {
|
||||
dir.is_dir()
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn folder_exists(_dir: &Path) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The folder an export dialog starts in (#10192): the `remembered` folder of the last export
|
||||
/// while `exists` finds it, else the document's own folder (`document_dir`, whatever it is),
|
||||
/// else none, which leaves the choice to the system dialog.
|
||||
pub(crate) fn export_start_dir(
|
||||
remembered: Option<&str>,
|
||||
document_dir: Option<std::path::PathBuf>,
|
||||
exists: impl Fn(&Path) -> bool,
|
||||
) -> Option<std::path::PathBuf> {
|
||||
remembered.filter(|d| !d.is_empty()).map(std::path::PathBuf::from).filter(|d| exists(d)).or(document_dir)
|
||||
}
|
||||
|
||||
/// The folder an open dialog starts in: the directory of the most recent file (UI-217-3).
|
||||
pub(crate) fn last_used_dir(recent: &[String]) -> Option<String> {
|
||||
let dir = std::path::Path::new(recent.first()?).parent()?;
|
||||
|
||||
@@ -1484,3 +1484,95 @@ fn import_variable_data_sets_menu_asks_for_a_csv_and_imports_it() {
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(app.session.active().map(|d| d.doc.variables.data_sets.len()), Some(2));
|
||||
}
|
||||
|
||||
/// #10192: the folder an export dialog starts in, as a pure decision.
|
||||
#[test]
|
||||
fn export_start_dir_prefers_an_existing_remembered_folder() {
|
||||
use std::path::PathBuf;
|
||||
let doc = Some(PathBuf::from("/proj"));
|
||||
let all_exist = |_: &Path| true;
|
||||
let none_exist = |_: &Path| false;
|
||||
// Remembered and present: used.
|
||||
assert_eq!(export_start_dir(Some("/renders"), doc.clone(), all_exist), Some(PathBuf::from("/renders")));
|
||||
// Remembered but gone: the document's folder.
|
||||
assert_eq!(export_start_dir(Some("/renders"), doc.clone(), none_exist), doc);
|
||||
// Nothing remembered (unset or empty): the document's folder, or nothing for an untitled one.
|
||||
assert_eq!(export_start_dir(None, doc.clone(), all_exist), doc);
|
||||
assert_eq!(export_start_dir(Some(""), doc.clone(), all_exist), doc);
|
||||
assert_eq!(export_start_dir(None, None, all_exist), None);
|
||||
assert_eq!(export_start_dir(Some("/renders"), None, none_exist), None);
|
||||
}
|
||||
|
||||
/// #10192: exports start in the last successfully exported folder, across documents; a failed or
|
||||
/// cancelled export, a folder that is gone and other save dialogs change nothing.
|
||||
#[test]
|
||||
fn exports_start_in_the_last_exported_folder() {
|
||||
let (mut app, open, _) = app();
|
||||
let ctx = egui::Context::default();
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let renders = root.path().join("renders");
|
||||
std::fs::create_dir(&renders).unwrap();
|
||||
let renders_text = renders.to_string_lossy().into_owned();
|
||||
app.session.active_mut().unwrap().path = Some("/proj/original.psd".into());
|
||||
let suggested = |open: &Open| match &open.borrow()[0].0 {
|
||||
FileDialogRequest::Save { suggested } => suggested.clone(),
|
||||
other => panic!("save dialog expected, got {other:?}"),
|
||||
};
|
||||
let remembered = |app: &PhotocraftApp| app.session.prefs().export.last_folder.clone();
|
||||
// No export yet: beside the document. Cancelled, nothing is remembered.
|
||||
app.pick_export("a.png", |_, _| Ok(Value::Null)).unwrap();
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(suggested(&open), joined("/proj", "a.png"));
|
||||
answer(&open, None);
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(remembered(&app), "");
|
||||
// The user picks another folder, but the export fails: nothing is remembered.
|
||||
app.pick_export("a.png", |_, _| Err("disk full".into())).unwrap();
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
answer(&open, Some(FileDialogAnswer::SaveTo(joined(&renders_text, "a.png"))));
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(remembered(&app), "");
|
||||
// A successful export is remembered...
|
||||
app.pick_export("a.png", |_, _| Ok(Value::Null)).unwrap();
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
answer(&open, Some(FileDialogAnswer::SaveTo(joined(&renders_text, "a.png"))));
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(remembered(&app), renders_text);
|
||||
// ...and starts the next export, of any document, even an untitled one.
|
||||
app.run("file.new", json!({"width": 4, "height": 4})).unwrap();
|
||||
app.pick_export("b.png", |_, _| Ok(Value::Null)).unwrap();
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(suggested(&open), joined(&renders_text, "b.png"));
|
||||
// A cancelled dialog changes nothing.
|
||||
answer(&open, None);
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(remembered(&app), renders_text);
|
||||
// Other save dialogs keep their own start.
|
||||
app.pick_save("c.psd", |_, _| Ok(Value::Null)).unwrap();
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(suggested(&open), "c.psd");
|
||||
answer(&open, None);
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
// The folder disappears: back to the document's folder.
|
||||
std::fs::remove_dir(&renders).unwrap();
|
||||
app.session.set_active(0);
|
||||
app.pick_export("d.png", |_, _| Ok(Value::Null)).unwrap();
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(suggested(&open), joined("/proj", "d.png"));
|
||||
answer(&open, None);
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_export_folder_is_a_preference_that_old_files_lack() {
|
||||
let prefs = photocraft_engine::prefs::Preferences::default();
|
||||
assert_eq!(prefs.export.last_folder, "");
|
||||
let mut json = serde_json::to_value(&prefs).unwrap();
|
||||
json["export"]["lastFolder"] = "/renders".into();
|
||||
let loaded: photocraft_engine::prefs::Preferences = serde_json::from_value(json.clone()).unwrap();
|
||||
assert_eq!(loaded.export.last_folder, "/renders");
|
||||
// Settings saved before the field existed still load.
|
||||
json["export"].as_object_mut().unwrap().remove("lastFolder");
|
||||
let old: photocraft_engine::prefs::Preferences = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(old.export.last_folder, "");
|
||||
}
|
||||
Reference in new issue
Block a user