diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 3851aeefac..92171a0b71 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -3061,6 +3061,22 @@ fn unembed_bytes(blob: &vectorcraft_doc::ImageBlob, ext: &str) -> std::result::R if same { Ok(blob.bytes.to_vec()) } else { convert_image(&blob.bytes, ext) } } +/// `path` with `.ext` added when it has no extension: the file Unembed writes for a `path` given. +fn with_unembed_extension(path: &str, ext: &str) -> String { + if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() } +} + +/// The file `links.unembed {id, path}` writes embedded image `id` of the active document to: `path` +/// with the extension of the format the image is stored in added when `path` has none. `None` when +/// `id` is not an embedded image there. +pub fn unembed_path(s: &Session, id: u64, path: &str) -> Option { + let st = s.doc().ok()?; + let doc = with_brush_art(&st.doc); + let im = image_of(&doc, NodeId(id)).filter(|im| im.link.is_none())?; + let blob = st.doc.images.get(&im.key)?; + Some(with_unembed_extension(path, stored_extension(blob))) +} + fn unembed(s: &mut Session, p: &Value) -> Result { const C: &str = "links.unembed"; let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); @@ -3097,7 +3113,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { let stem = Path::new(&name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned()); return Ok(json!({ "name": format!("{stem}.{ext}"), "dataBase64": vectorcraft_format::base64_encode(&bytes) })); }; - let path = absolute_path(&if fileio::extension(path).is_empty() { format!("{path}.{ext}") } else { path.to_string() }); + let path = absolute_path(&with_unembed_extension(path, &ext)); // Read before writing: pixels that can't be read leave no file behind. let img = linked_image(&bytes, Some(&path))?; write_file(&path, &bytes)?; diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index 24fb32b996..493c5a1b34 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -556,10 +556,24 @@ fn list_templates(app: &mut VectorcraftApp) -> (Vec<(String, String)>, Option Result<(), String> { let picked = picked.to_string_lossy().into_owned(); let path = if picked.to_ascii_lowercase().ends_with(&format!(".{XMP_EXT}")) { picked.clone() } else { format!("{picked}.{XMP_EXT}") }; + if let Some((name, folder)) = crate::io::save::portal_ask_again(app, &picked, &path) { + let mut request = template_request(name); + if let Some(folder) = folder { + request = request.directory(folder); + } + file_asks::ask(app, request, file_asks::Owner::Free, move |app, picked| { + if let Some(path) = picked.first_path() { + save_template(app, path, fields)?; + } + Ok(Value::Null) + }); + return Ok(()); + } // The save pick does not ask about the completed name. app.session.execute("file.info.templates", &json!({ "create": true })).map_err(|e| e.to_string())?; let save = { @@ -573,6 +587,11 @@ fn save_template(app: &mut VectorcraftApp, picked: PathBuf, fields: Info) -> Res save(app).map(|_| ()) } +/// A save pick for a metadata template, suggesting `name`. +fn template_request(name: String) -> PickRequest { + PickRequest::save(PURPOSE).file_name(name).suggested_extension(XMP_EXT).filter(tl!("XMP metadata templates"), &[XMP_EXT]) +} + /// Save the draft through the browser's file service. Serializing it changes neither drawing nor draft. fn download_template(app: &mut VectorcraftApp, fields: Info) -> Result<(), String> { let title = text_of(&fields, "title"); @@ -580,8 +599,7 @@ fn download_template(app: &mut VectorcraftApp, fields: Info) -> Result<(), Strin let name = format!("{stem}.{XMP_EXT}"); let result = app.run("file.info.saveTemplate", json!({"fields": fields}))?; let data = result["data"].as_str().ok_or("the metadata template contains no data")?.as_bytes().to_vec(); - let request = PickRequest::save(PURPOSE).file_name(name).suggested_extension(XMP_EXT).filter(tl!("XMP metadata templates"), &[XMP_EXT]); - file_asks::save(app, request, data, file_asks::Owner::Free, |app, picked| { + file_asks::save(app, template_request(name), data, file_asks::Owner::Free, |app, picked| { match picked { Picked::Downloaded(name) => app.status(format!("Saved {name}")), Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())), @@ -884,6 +902,32 @@ mod tests { assert!(app.session.active().unwrap().history.undo.is_empty()); } + /// In the document portal, which takes only the name the save pick answered, Save Metadata + /// Template… writes nothing under the completed name (`Card` for `Card.xmp`): the save pick opens + /// again in the answer's folder suggesting `Card.xmp`, and its answer is written. + #[test] + fn a_template_save_asks_again_for_a_name_the_document_portal_did_not_grant() { + let dir = vectorcraft_testkit::TempDir::new("ui-file-info-portal"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let picker = crate::tests::picks::scripted(&mut app); + app.session.attach_metadata_templates_dir(dir.join("Metadata Templates")); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let portal = "/run/user/1000/doc/a1b2c3d4"; + let fields = json!({"author": "Ada"}).as_object().cloned().unwrap_or_default(); + super::save_template(&mut app, format!("{portal}/Card").into(), fields).unwrap(); + let requests = picker.requests(); + let [again] = requests.as_slice() else { panic!("the save pick opens again: {requests:?}") }; + assert_eq!(again.file_name.as_deref(), Some("Card.xmp")); + assert_eq!(again.directory.as_deref(), Some(std::path::Path::new(portal))); + assert!(app.ui.status.contains("Card.xmp"), "{}", app.ui.status); + let granted = dir.join("Card.xmp"); + picker.answer_saved(&granted.to_string_lossy(), None); + let ctx = app.ui_ctx.clone().unwrap_or_default(); + crate::tests::picks::poll(&mut app, &ctx); + assert!(std::fs::read_to_string(&granted).is_ok_and(|xmp| xmp.contains("Ada")), "the granted name is written"); + assert_eq!(picker.requests().len(), 1, "a granted name is written without asking again"); + } + #[test] fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() { let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template"); diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 1990d57e06..fc42da3c77 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -235,9 +235,43 @@ fn write_step(app: &mut VectorcraftApp, uid: u64, path: &str, target: SaveTarget let path = with_picked_type(&answered, &suggested, picked_ext.as_deref(), first.format, mode); // The flow ends here: the questions and options dialogs that follow run on the path alone. app.saves.release(uid); + if portal_renamed(&answered, &path) { + let name = confirm_portal_name(app, &answered, &path); + let folder = Path::new(&answered).parent().map(Path::to_path_buf); + return ask_again(app, mode, ¶ms, ask, target, retrying, (name, folder)); + } replaces_unasked(app, &answered, &path, move |app, path| finish_picked(app, mode, ¶ms, ask, &path, retrying)) } +#[cfg(not(target_arch = "wasm32"))] +/// The save panel again for the active document's save (`mode`, `params`), in the folder the last +/// answer was in and suggesting `name` in the format its extension names, as a new flow with the +/// same options question (`ask_options`) and `target`. A read-only retry (`retrying`) that changes +/// format drops the options it carries and asks for the new format's, as [`finish_picked`] does. +fn ask_again( + app: &mut VectorcraftApp, + mode: SaveMode, + params: &Value, + mut ask_options: bool, + target: SaveTarget, + retrying: bool, + (name, directory): (String, Option), +) -> Result { + let original = plan(app, mode, &acknowledged(params))?.format.id; + let mut q = if params.is_object() { params.clone() } else { json!({}) }; + if let Some(f) = fileio::format_for_name(&name) { + if retrying && f.id != original { + if let Some(o) = q.as_object_mut() { + o.remove("options"); + } + ask_options = true; + } + q["format"] = json!(f.id); + } + let first = plan(app, mode, &acknowledged(&q))?; + start_flow(app, &first, Start { mode, params: &q, ask_options, target, retry: None, name, directory, retrying }) +} + #[cfg(not(target_arch = "wasm32"))] /// What [`start_flow`] needs besides the plan. struct Start<'a> { @@ -456,7 +490,7 @@ fn ask_path( return then(app, with_written_extension(&name, &ext, &keeps)); } let mut request = PickRequest::save("export").file_name(name); - request.filters = filters; + request.filters = filters.clone(); if let Some(folder) = folder { request = request.directory(folder); } @@ -464,10 +498,54 @@ fn ask_path( let Picked::Saved { path: picked, .. } = picked else { return Err("cancelled".into()) }; let picked = picked.to_string_lossy().into_owned(); let path = with_written_extension(&picked, &ext, &keeps); + if let Some((name, folder)) = portal_ask_again(app, &picked, &path) { + let folder = folder.map(|p| p.to_string_lossy().into_owned()); + return ask_path(app, None, name, folder, filters, ext, keeps, then); + } replaces_unasked(app, &picked, &path, then) })) } +/// Whether `path` is a file in a folder of the document portal (`/run/user//doc//` or +/// `/run/flatpak/doc//`), where the save panel's answers point in a Flatpak sandbox. The portal +/// puts only the name the panel answered into the folder picked in it: a file written there under +/// another name is written without an error, and the folder gets no file. +fn in_document_portal(path: &str) -> bool { + let rest = path.strip_prefix("/run/flatpak/doc/").or_else(|| { + let (uid, rest) = path.strip_prefix("/run/user/")?.split_once('/')?; + if uid.is_empty() || !uid.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + rest.strip_prefix("doc/") + }); + rest.and_then(|r| r.split_once('/')).is_some_and(|(id, name)| !id.is_empty() && !name.is_empty() && !name.contains('/')) +} + +/// Whether the save panel's answer `picked` was made into another name, `path`, in a folder of the +/// document portal ([`in_document_portal`]). +fn portal_renamed(picked: &str, path: &str) -> bool { + path != picked && in_document_portal(picked) +} + +/// The file name of `path`, for the save panel to ask with again in place of the answer `picked`; +/// the status bar says why the panel opens again. +fn confirm_portal_name(app: &mut VectorcraftApp, picked: &str, path: &str) -> String { + let name = fileio::file_name(path); + app.status(format!("The file chooser can only save “{}”: confirm “{name}” to save it", fileio::file_name(picked))); + name +} + +/// When `path`, the file the save panel's answer `picked` was made into, is another name in a +/// folder of the document portal ([`portal_renamed`]): the name for the save panel to ask with +/// again and the folder of the answer, for it to open in. The status bar says why. +pub(crate) fn portal_ask_again(app: &mut VectorcraftApp, picked: &str, path: &str) -> Option<(String, Option)> { + if !portal_renamed(picked, path) { + return None; + } + let name = confirm_portal_name(app, picked, path); + Some((name, std::path::Path::new(picked).parent().map(std::path::Path::to_path_buf))) +} + /// `path` as typed in a save panel for a file with extension `ext`: kept when its extension is /// `ext` in any letter case, or names the format `ext` names (`photo.jpeg` for a `.jpg` file) or /// a format `keeps` takes. An extension that names another format (`card.svg` for a `.png` file) diff --git a/crates/ui-egui/src/io/tests_read_only_save.rs b/crates/ui-egui/src/io/tests_read_only_save.rs index 19725e4b4d..ae42d1c4d6 100644 --- a/crates/ui-egui/src/io/tests_read_only_save.rs +++ b/crates/ui-egui/src/io/tests_read_only_save.rs @@ -310,6 +310,31 @@ fn readonly_changed_format_asks_for_its_options_before_writing() { assert_eq!(files.lock().unwrap().attempts, ["/locked/Poster.svg"]); } +/// The retry's save panel in the document portal, with PDF picked and `Poster.svg` kept: the panel +/// opens again for `Poster.pdf`, and its answer asks for the PDF options before writing. +#[test] +fn readonly_changed_format_in_the_document_portal_asks_for_its_options_before_writing() { + let portal = "/run/user/1000/doc/a1b2c3d4"; + let (mut app, files) = app("svg", ErrorKind::PermissionDenied); + let before = state(&app); + let picker = scripted(&mut app); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "fileDialog"); + let pdf = picker.requests()[0].filters.iter().position(|f| f.extensions.iter().any(|e| e == "pdf")); + assert!(pdf.is_some(), "the retry's save panel offers PDF"); + picker.answer_saved(&format!("{portal}/Poster.svg"), pdf); + poll(&mut app); + assert!(fields_of(&app, "pdf-export").is_none(), "no options before the name is granted"); + assert_eq!(picker.requests().len(), 2, "the save panel opens again"); + assert_eq!(picker.requests()[1].file_name.as_deref(), Some("Poster.pdf")); + picker.answer_saved(&format!("{portal}/Poster.pdf"), None); + poll(&mut app); + assert!(fields_of(&app, "pdf-export").is_some(), "the picked format's Save dialog"); + let job = app.save_pdf.as_ref().and_then(|open| open.job.as_ref()); + assert_eq!(job.and_then(|job| job.path.clone()), Some(format!("{portal}/Poster.pdf"))); + assert_eq!(state(&app), before); + assert_eq!(files.lock().unwrap().attempts, ["/locked/Poster.svg"]); +} + /// Typed saves keep the sidecar preflight both before the refused write and at the retry's /// destination. Confirming the ordinary Save still permits its one read-only fallback. #[test] diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index e2c4441815..f976842163 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -428,7 +428,22 @@ pub(crate) fn unembed(app: &mut VectorcraftApp, id: u64, name: &str) { } return; } - ask(app, PickRequest::save("links").file_name(name), move |app, path| { + ask_unembed(app, id, PickRequest::save("links").file_name(name)); +} + +/// Asks `request`'s save panel where to write embedded image `id`, and unembeds it there. In the +/// document portal, which takes only the name answered, a name without an extension opens the panel +/// again with the stored format's extension added, in the answer's folder. +fn ask_unembed(app: &mut VectorcraftApp, id: u64, request: PickRequest) { + ask(app, request, move |app, path| { + let written = vectorcraft_engine::cmd::links::unembed_path(&app.session, id, &path); + if let Some((name, folder)) = written.and_then(|written| crate::io::save::portal_ask_again(app, &path, &written)) { + let mut request = PickRequest::save("links").file_name(name); + if let Some(folder) = folder { + request = request.directory(folder); + } + return ask_unembed(app, id, request); + } let r = app.run("links.unembed", json!({ "id": id, "path": path })); report(app, r, |v| format!("Unembedded to {}", v["path"].as_str().unwrap_or_default())); }); diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 71c9033b8d..48ceb17ea6 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -1037,6 +1037,33 @@ fn unembed_writes_several_images_to_one_picked_folder() { assert_eq!(app.ui.status, format!("Unembedded 2 images to {picked}")); } +/// In the document portal, which takes only the name its save panel answered, Unembed… writes +/// nothing under a name it had to complete (`photo` for a PNG): the panel opens again in the answer's +/// folder suggesting `photo.png`, and its answer is written and linked. +#[test] +fn unembed_asks_again_for_a_name_the_document_portal_did_not_grant() { + use crate::tests::picks::{poll, scripted}; + let dir = Folder::new("unembed-portal"); + let (mut app, _, embedded) = app(&dir); + let picker = scripted(&mut app); + let ctx = crate::testing::ui_context(); + let portal = "/run/user/1000/doc/a1b2c3d4"; + super::links::unembed(&mut app, embedded, "embedded.png"); + picker.answer_saved(&format!("{portal}/photo"), None); + poll(&mut app, &ctx); + assert_eq!(app.run("links.info", json!({"id": embedded})).unwrap()["status"], "embedded", "nothing is written or linked"); + let requests = picker.requests(); + let [_, again] = requests.as_slice() else { panic!("the save panel opens again: {requests:?}") }; + assert_eq!(again.file_name.as_deref(), Some("photo.png")); + assert_eq!(again.directory.as_deref(), Some(std::path::Path::new(portal))); + assert!(app.ui.status.contains("photo.png"), "{}", app.ui.status); + let granted = dir.0.join("photo.png").to_string_lossy().into_owned(); + picker.answer_saved(&granted, None); + poll(&mut app, &ctx); + assert_eq!(app.run("links.info", json!({"id": embedded})).unwrap()["path"], granted.as_str()); + assert_eq!(picker.requests().len(), 2, "a granted name is written without asking again"); +} + #[test] fn switching_documents_dismisses_a_links_row_menu() { let dir = Folder::new("context-switched-document"); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index d32575ef9c..c93eef486f 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1703,24 +1703,7 @@ fn export_text(app: &mut VectorcraftApp, p: &Value) -> Result { } let shown = format.unwrap_or(TextFormat::Text); if !crate::io::is_web(app) { - let offered: Vec = format.map_or_else(|| TextFormat::ALL.to_vec(), |f| vec![f]); - let request = offered.iter().fold(PickRequest::save(SHORTCUT_SETS).file_name(shown.file_name()), |r, f| f.filter(r)); - let (km, set) = (keymap.clone(), name.clone()); - let asked = file_asks::ask(app, request, Owner::Free, move |app, picked| { - let Picked::Saved { path, file_type } = picked else { return Err("cancelled".into()) }; - let answer = path.to_string_lossy().into_owned(); - let typed = file_type.and_then(|i| offered.get(i)).copied(); - let picked = format.unwrap_or_else(|| TextFormat::picked(&answer, typed.map(TextFormat::extension))); - // The format that `format` names, or that the dialog reports as the type picked, gives - // the name its extension. A file already at a path changed that way, which the dialog - // did not check, is replaced only after asking. - let path = if format.is_some() || typed.is_some() { TextFormat::with_extension(&answer, picked) } else { answer.clone() }; - if path != answer && std::path::Path::new(&path).exists() { - let to = path.clone(); - return Ok(file_asks::ask_replace(app, &path, &answer, move |app| write_text_file(app, &km, &set, picked, page, Some(to)))); - } - write_text_file(app, &km, &set, picked, page, Some(path)) - }); + let asked = ask_text_file(app, format, (shown.file_name(), None), keymap.clone(), name.clone(), page); if !asked.is_null() { return Ok(asked); } @@ -1728,6 +1711,43 @@ fn export_text(app: &mut VectorcraftApp, p: &Value) -> Result { write_text_file(app, &keymap, &name, shown, page, None) } +/// Export Text's save panel, suggesting `file` in `folder` (the last folder used when `None`) and +/// offering the file type `format` names, or every one. The answer is written as [`export_text`] +/// says; an answer in the document portal that would be written under another name opens the panel +/// again with that name in the answer's folder, for the picked format. +fn ask_text_file( + app: &mut VectorcraftApp, + format: Option, + (file, folder): (String, Option), + km: Keymap, + set: String, + page: PageSize, +) -> Value { + let offered: Vec = format.map_or_else(|| TextFormat::ALL.to_vec(), |f| vec![f]); + let mut request = offered.iter().fold(PickRequest::save(SHORTCUT_SETS).file_name(file), |r, f| f.filter(r)); + if let Some(folder) = folder { + request = request.directory(folder); + } + file_asks::ask(app, request, Owner::Free, move |app, picked| { + let Picked::Saved { path, file_type } = picked else { return Err("cancelled".into()) }; + let answer = path.to_string_lossy().into_owned(); + let typed = file_type.and_then(|i| offered.get(i)).copied(); + let picked = format.unwrap_or_else(|| TextFormat::picked(&answer, typed.map(TextFormat::extension))); + // The format that `format` names, or that the dialog reports as the type picked, gives + // the name its extension. A file already at a path changed that way, which the dialog + // did not check, is replaced only after asking. + let path = if format.is_some() || typed.is_some() { TextFormat::with_extension(&answer, picked) } else { answer.clone() }; + if let Some(again) = crate::io::save::portal_ask_again(app, &answer, &path) { + return Ok(ask_text_file(app, Some(picked), again, km, set, page)); + } + if path != answer && std::path::Path::new(&path).exists() { + let to = path.clone(); + return Ok(file_asks::ask_replace(app, &path, &answer, move |app| write_text_file(app, &km, &set, picked, page, Some(to)))); + } + write_text_file(app, &km, &set, picked, page, Some(path)) + }) +} + /// Writes Export Text's file to `path`; with none, downloads it, or returns it. fn write_text_file( app: &mut VectorcraftApp, diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 50f14a1ee8..1fe7e2fb57 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -597,6 +597,37 @@ fn keyboard_shortcuts_export_text_writes_the_format_picked_in_its_save_dialog() } } +/// In the document portal, which takes only the name its save panel answered, Export Text writes +/// nothing under a name it had to change (`list` with the sheet picked): the panel opens again in the +/// answer's folder, suggesting `list.pdf` and offering only the sheet, and its answer is written. +#[test] +fn keyboard_shortcuts_export_text_asks_again_for_a_name_the_document_portal_did_not_grant() { + let portal = "/run/user/1000/doc/a1b2c3d4"; + let mut app = app(); + let picker = scripted(&mut app); + let files: Rc>> = Default::default(); + let f = files.clone(); + app.services.write = Some(Box::new(move |path: &str, _: &[u8]| { + f.borrow_mut().push(path.to_string()); + Ok(()) + })); + app_frame(&app.ui_ctx.clone().unwrap(), &mut app, false); + let _ = app.run("shortcuts.exportText", json!({})); + picker.answer_saved(&format!("{portal}/list"), Some(1)); + settle(&mut app); + assert!(files.borrow().is_empty(), "nothing is written under a name the portal did not grant: {:?}", files.borrow()); + let requests = picker.requests(); + let [_, again] = requests.as_slice() else { panic!("the save panel opens again: {requests:?}") }; + assert_eq!(again.file_name.as_deref(), Some("list.pdf")); + assert_eq!(again.directory.as_deref(), Some(std::path::Path::new(portal))); + assert_eq!(again.filters.iter().map(|f| f.extensions.join(",")).collect::>(), ["pdf"]); + assert!(app.ui.status.contains("list.pdf"), "{}", app.ui.status); + picker.answer_saved(&format!("{portal}/list.pdf"), Some(0)); + settle(&mut app); + assert_eq!(files.borrow().as_slice(), [format!("{portal}/list.pdf")]); + assert_eq!(picker.requests().len(), 2, "a granted name is written without asking again"); +} + /// Keyboard Shortcuts' Import opens a shortcut set another app saved as text (`.kys`) in a review /// over the dialog when its file dialog answers; Cancel shows Keyboard Shortcuts again. #[test] diff --git a/crates/ui-egui/src/tests/saveext.rs b/crates/ui-egui/src/tests/saveext.rs index b8b456abd9..807cbdfe48 100644 --- a/crates/ui-egui/src/tests/saveext.rs +++ b/crates/ui-egui/src/tests/saveext.rs @@ -552,3 +552,62 @@ fn an_export_keeps_a_typed_extension_of_the_format_it_writes() { answer_top(&mut app, &[], true); assert_eq!(last(&w), "/tmp/sel.pdf", "Export Selection takes its format from the typed name"); } + +/// The file name the last save panel suggested. +fn suggested_name(picker: &Picker) -> Option { + picker.requests().last()?.file_name.clone() +} + +/// The folder the last save panel opened in. +fn panel_folder(picker: &Picker) -> Option { + picker.requests().last()?.directory.clone() +} + +/// In a Flatpak sandbox the save panel answers with a path in the document portal, which puts only +/// that name into the folder picked. A name the export has to change (`poster` for a PDF) is not +/// written: the save panel opens again suggesting `poster.pdf`, and its answer is written. A +/// look-alike path outside the portal gets the extension at once. +#[test] +fn an_export_asks_again_for_a_name_the_document_portal_did_not_grant() { + for portal in ["/run/user/1000/doc/a1b2c3d4", "/run/flatpak/doc/a1b2c3d4"] { + let (mut app, picker, w) = saving_app(); + save_via(&mut app, &picker, |a| io::export_pdf(a, json!({})), (&format!("{portal}/poster"), None)); + assert!(w.borrow().is_empty(), "nothing is written under a name the portal did not grant: {:?}", w.borrow()); + assert_eq!(picker.requests().len(), 2, "the save panel opens again"); + assert_eq!(suggested_name(&picker).as_deref(), Some("poster.pdf")); + assert_eq!(panel_folder(&picker).as_deref(), Some(Path::new(portal)), "the folder of the last answer"); + assert!(app.ui.status.contains("poster.pdf"), "{}", app.ui.status); + picker.answer_saved(&format!("{portal}/poster.pdf"), None); + poll(&mut app); + assert_eq!(w.borrow().as_slice(), [format!("{portal}/poster.pdf")]); + assert_eq!(picker.requests().len(), 2, "a granted name is written without asking again"); + } + let (mut app, picker, w) = saving_app(); + save_via(&mut app, &picker, |a| io::export_pdf(a, json!({})), ("/home/me/run/user/1000/doc/a1b2/poster", None)); + assert_eq!(w.borrow().as_slice(), ["/home/me/run/user/1000/doc/a1b2/poster.pdf"]); + assert_eq!(picker.requests().len(), 1); +} + +/// Save As in the document portal with PDF picked and the suggested `Untitled-1.vectorcraft` kept: +/// the save panel opens again suggesting `Untitled-1.pdf` with PDF as the file type, and the PDF +/// options and the write follow its answer. +#[test] +fn save_as_asks_again_for_a_name_the_document_portal_did_not_grant() { + let portal = "/run/user/1000/doc/a1b2c3d4"; + let (mut app, picker, w) = saving_app(); + let _ = app.run("file.saveAs", json!({})); + let pdf = type_index(&picker, "pdf").expect("Save As offers PDF"); + picker.answer_saved(&format!("{portal}/Untitled-1.vectorcraft"), Some(pdf)); + poll(&mut app); + assert!(w.borrow().is_empty(), "{:?}", w.borrow()); + assert!(dialog_path(&app).is_none(), "no PDF options before the name is granted"); + assert_eq!(picker.requests().len(), 2, "the save panel opens again"); + assert_eq!(suggested_name(&picker).as_deref(), Some("Untitled-1.pdf")); + assert_eq!(panel_folder(&picker).as_deref(), Some(Path::new(portal)), "the folder of the last answer"); + assert_eq!(type_index(&picker, "pdf"), Some(0), "PDF is the first file type offered"); + picker.answer_saved(&format!("{portal}/Untitled-1.pdf"), Some(0)); + poll(&mut app); + assert_eq!(dialog_path(&app), Some(format!("{portal}/Untitled-1.pdf"))); + answer_top(&mut app, &[], true); + assert_eq!(last(&w), format!("{portal}/Untitled-1.pdf")); +}