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 1bf2183d28..fc42da3c77 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -498,10 +498,8 @@ 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 portal_renamed(&picked, &path) { - let name = confirm_portal_name(app, &picked, &path); - // The panel opens again in the folder of its last answer. - let folder = std::path::Path::new(&picked).parent().map(|p| p.to_string_lossy().into_owned()); + 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) @@ -537,6 +535,17 @@ fn confirm_portal_name(app: &mut VectorcraftApp, picked: &str, path: &str) -> St 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/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]