mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pull request #10448 from qvest-ssels/feat/export-last-folder-10192
Export dialogs start in the last exported folder (#10192)
This commit is contained in:
6 files changed
+180
-17
No files matched your search
@@ -630,6 +630,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 {
|
||||
@@ -642,6 +646,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());
|
||||
}
|
||||
@@ -1050,7 +1050,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.
|
||||
@@ -1112,7 +1112,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)?;
|
||||
@@ -1151,7 +1151,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}))
|
||||
});
|
||||
|
||||
@@ -584,7 +584,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,37 @@ 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, ...): starts in
|
||||
/// the folder [`export_start_dir`] picks (#10192), and once `then` has exported, remembers the
|
||||
/// chosen file's folder in `export.lastFolder`; a failed or cancelled export leaves it 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
|
||||
@@ -169,12 +189,20 @@ impl PhotocraftApp {
|
||||
FileDialogAnswer::SaveTo(path) => {
|
||||
let path = saved_path(app, &path, suggested_ext.as_deref());
|
||||
// The web answers a download name, which has no folder to remember.
|
||||
if let Some(doc) = doc
|
||||
&& let Some(dir) = Path::new(&path).parent().filter(|p| !p.as_os_str().is_empty())
|
||||
{
|
||||
app.save_dirs.insert(doc, dir.to_path_buf());
|
||||
let dir = doc.zip(Path::new(&path).parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf));
|
||||
// An export's folder only once it has exported: a failed one doesn't move where
|
||||
// the next export starts.
|
||||
if !export && let Some((doc, dir)) = dir.clone() {
|
||||
app.save_dirs.insert(doc, dir);
|
||||
}
|
||||
then(app, path)
|
||||
let exported = then(app, path.clone())?;
|
||||
if export {
|
||||
if let Some((doc, dir)) = dir {
|
||||
app.save_dirs.insert(doc, dir);
|
||||
}
|
||||
app.remember_export_folder(&path);
|
||||
}
|
||||
Ok(exported)
|
||||
}
|
||||
_ => Err(UNEXPECTED.into()),
|
||||
})?;
|
||||
@@ -184,6 +212,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 +408,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()?;
|
||||
|
||||
@@ -1517,3 +1517,101 @@ 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), "");
|
||||
// ...and the next export still starts beside the document, not in the failed export's folder.
|
||||
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);
|
||||
// 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, "");
|
||||
}
|
||||
+2
-2
@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
|
||||
| [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) |
|
||||
| [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 |
|
||||
| [Tools](#tools) | 36 | 9 | 0 | |
|
||||
| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 195 (target 0) |
|
||||
| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 196 (target 0) |
|
||||
| [Type](#type) | 5 | 5 | 0 | |
|
||||
| [Automation](#automation) | 5 | 4 | 2 | 662 of 662 menu items live (100.0%) |
|
||||
| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present |
|
||||
@@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu
|
||||
|
||||
## Workspace and UI
|
||||
|
||||
**Settings that do nothing: 10 of 195** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
|
||||
**Settings that do nothing: 10 of 196** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
|
||||
|
||||
Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`.
|
||||
|
||||
|
||||
Reference in new issue
Block a user