From f285bc5bc97ca51aa44d80bfca3c97e269e4bada Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 27 Nov 2026 14:51:28 +0000 Subject: [PATCH] shell-w6: net change of 3 commits - shell-w6: written from its sheet - shell-w6: repair 1 - shell-w6: review fixes (review-1) --- crates/engine/src/cmd/file.rs | 32 +- crates/ui-egui/src/app/files.rs | 1007 +++++++++++++------------ crates/ui-egui/src/host_save_tests.rs | 156 ++-- crates/ui-egui/src/inbox_tests.rs | 119 ++- 4 files changed, 705 insertions(+), 609 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index f403ca893..f52b053b3 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -500,17 +500,9 @@ pub fn format_for_path(path: &str) -> &'static str { /// becomes its file. `file.save` calls it after writing; the web host bridge calls it once the /// page has the bytes. pub fn mark_saved(s: &mut Session, path: Option) -> Result<()> { - let st = s.doc_mut()?; - st.saved_doc = st.doc.clone(); - if path.is_some() { - st.path = path; - } - st.revision += 1; - let uid = st.uid; - if let Some(dir) = &s.recovery_dir { - crate::recovery::discard(dir, uid); - } - Ok(()) + let st = s.doc()?; + let (uid, snapshot) = (st.uid, st.doc.clone()); + mark_saved_snapshot(s, uid, snapshot, path) } fn write_file(path: &str, bytes: &[u8]) -> Result<()> { @@ -864,13 +856,23 @@ where M: FnOnce(&str) -> std::result::Result<(bool, u64), String>, R: FnOnce(&str) -> std::result::Result, String>, { - let _ = (path, metadata, read); - todo!("sh.A27") + let bytes = crate::io::read_file_with(path, metadata, read).map_err(EngineError::Other)?; + loaded_file(path, &bytes) } /// Records the serialized snapshot as the saved state of its originating document. /// Leaves later edits dirty and never switches or redirects a closed document. pub fn mark_saved_snapshot(s: &mut Session, uid: u64, snapshot: std::sync::Arc, path: Option) -> Result<()> { - let _ = (s, uid, snapshot, path); - todo!("sh.A23") + let st = s.docs.iter_mut().find(|d| d.uid == uid).ok_or_else(|| EngineError::Other("the presentation is closed".into()))?; + st.saved_doc = snapshot; + if path.is_some() { + st.path = path; + } + st.revision += 1; + if !st.is_dirty() + && let Some(dir) = &s.recovery_dir + { + crate::recovery::discard(dir, uid); + } + Ok(()) } diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 0481c3e7b..ed6470974 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1,85 +1,98 @@ -use super::{ - // P3(shell-w6): sh.A8 - FilePlace, - FilePurpose, - FileTarget, - InboxEvent, - LocatedPlace, - PendingFileBase, - RECENT_MAX, - SlideApp, - Target, - UiRequest, - Value, - ViewMode, - dialogs, - json, - media, -}; +use std::cell::RefCell; +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::sync::Arc; -#[derive(Default)] -pub(crate) struct PrintPreviews(Vec); +use craft::host::{PickId, PickRequest, Picked, WriteIntent}; +use deckcraft_engine::cmd::file::{format_for_path, mark_saved_snapshot, save_bytes}; +use deckcraft_model::Presentation; -impl PrintPreviews { - fn create(&mut self, title: &str) -> std::io::Result { - self.create_in(&std::env::temp_dir(), title) - } +use super::{FilePlace, FilePurpose, FileTarget, LocatedPlace, RECENT_MAX, SlideApp, Target, UiRequest, Value, ViewMode, json, media}; +use crate::PendingFile; - fn create_in(&mut self, base: &std::path::Path, title: &str) -> std::io::Result { - let dir = create_private_print_dir(base)?; - self.0.push(dir.clone()); - let safe: String = title.chars().map(|c| if c.is_alphanumeric() || c == ' ' || c == '-' { c } else { '_' }).collect(); - Ok(dir.join(format!("{safe} (print).pdf"))) - } - - fn discard(&mut self, path: &std::path::Path) { - if let Some(dir) = path.parent() { - let _ = std::fs::remove_dir_all(dir); - self.0.retain(|owned| owned != dir); - } - } - - pub(crate) fn cleanup(&mut self) { - for dir in self.0.drain(..) { - let _ = std::fs::remove_dir_all(dir); - } - } +/// The operation retained until its picker answers. +#[derive(Clone)] +pub(crate) enum FileOperation { + /// Open or infer an operation from the supplied file. + Apply(FilePurpose), + /// Execute the captured command on the captured place. + Command { + /// The picker purpose, including the picture-bytes parameter policy. + purpose: String, + /// The registered command id. + command: String, + /// Parameters captured before the picker opens. + params: Value, + }, + /// Offer slides from the supplied bytes without reading them again. + Reuse { + /// Whether inserted slides retain their source formatting. + keep: bool, + }, + /// Finish a document save or an exported copy. + Save(SaveTransfer), } -impl Drop for PrintPreviews { - fn drop(&mut self) { - self.cleanup(); - } +/// Serialized files and the completion shared by every copy in an export. +#[derive(Clone)] +pub(crate) struct SaveTransfer { + snapshot: Option>, + files: Vec<(String, Vec)>, + write_on_answer: bool, + save_as: bool, + batch: Rc>, } -fn create_private_print_dir(base: &std::path::Path) -> std::io::Result { - use std::sync::atomic::{AtomicU64, Ordering}; - static NEXT_DIR: AtomicU64 = AtomicU64::new(0); - - for _ in 0..128 { - let id = NEXT_DIR.fetch_add(1, Ordering::Relaxed); - let path = base.join(format!("deckcraft-print-{}-{id}", std::process::id())); - #[cfg(unix)] - let mut builder = std::fs::DirBuilder::new(); - #[cfg(not(unix))] - let builder = std::fs::DirBuilder::new(); - #[cfg(unix)] - { - use std::os::unix::fs::DirBuilderExt; - builder.mode(0o700); - } - match builder.create(&path) { - Ok(()) => return Ok(path), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(e), - } - } - Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "could not allocate a unique print preview directory")) +struct SaveBatch { + uid: u64, + remaining: usize, + outcome: SaveOutcome, + instance: Option>, + deferred: bool, } +/// The closing prompt's save result, including an outstanding file ticket. +#[derive(Clone, Debug)] +pub(crate) enum SaveOutcome { + /// The service keeps a file of the serialized snapshot. + Saved, + /// The browser handed over a copy without recording a document file. + Downloaded, + /// The service could not complete the operation. + Failed(String), + /// The user dismissed the picker. + Cancelled, + /// The ticket has not answered yet. + Pending, +} + +fn succeeded(outcome: &SaveOutcome) -> bool { + matches!(outcome, SaveOutcome::Saved | SaveOutcome::Downloaded) +} + +fn captures_shapes(command: &str) -> bool { + matches!(command, "shape.fill" | "picture.change") +} + +fn open_request(purpose: &str) -> PickRequest { + let request = PickRequest::open(purpose); + match purpose { + "picture" => request.filter("Pictures", &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff"]), + "audio" => request + .filter("Audio", &["wav", "mp3", "m4a", "m4b", "aac", "flac", "ogg", "oga", "opus", "aif", "aiff", "aifc", "caf", "wma", "weba", "mka"]), + "video" => request.filter("Video", &["mp4", "m4v", "mov", "webm", "mkv", "wmv"]), + "theme" => request.filter("Themes and presentations", &["thmx", "pptx", "potx", "ppsx"]).filter("Office Theme", &["thmx"]), + _ => request + .filter("Presentations", &["deckcraft", "pptx", "potx", "ppsx", "ppt", "pot", "pps"]) + .filter("DeckCraft", &["deckcraft"]) + .filter("PowerPoint", &["pptx", "potx", "ppsx"]) + .filter("PowerPoint 97-2003", &["ppt", "pot", "pps"]) + .filter("Outline", &["txt", "md", "rtf"]), + } +} fn purpose_of(purpose: &str) -> FilePurpose { match purpose { - "open" => FilePurpose::Open, + "document" | "open" => FilePurpose::Open, "picture" => FilePurpose::Picture, "audio" => FilePurpose::Audio, "video" => FilePurpose::Video, @@ -165,7 +178,7 @@ impl SlideApp { if path.starts_with("\\\\") || path.contains("://") { return true; } - let ok = std::path::Path::new(path).is_file(); + let ok = self.host.files().exists(Path::new(path)); if self.recent_checked.len() > 64 { let live: std::collections::HashSet<&String> = self.ui.recent.iter().collect(); self.recent_checked.retain(|p, _| live.contains(p)); @@ -186,7 +199,7 @@ impl SlideApp { pub fn close_presentation(&mut self) { match self.session.active() { None => {} - Some(d) if d.is_dirty() => self.dialog = Some(dialogs::Dialog::new("close")), + Some(d) if d.is_dirty() => self.start_closing(craft::quit::CloseScope::Close, vec![d.uid]), Some(_) => { let _ = self.run("file.close", json!({})); } @@ -200,11 +213,16 @@ impl SlideApp { } /// Exports the active presentation as `fmt` (`pdf`, `png`, `pngAll`, `jpeg`, `jpegAll`, `pptx`, - /// `deckcraft`, `outline`) through `file.export`: the save picker on the desktop, a download - /// on the web. `extra` adds `file.export` params (the PDF's layout, slides…). The - /// presentation keeps its own file. Returns whether a file was written or handed over. + /// `deckcraft`, `outline`) through the installed file service. `extra` supplies export options. + /// The presentation keeps its own file; a pending ticket returns false until it settles. pub fn export_as(&mut self, fmt: &str, extra: Value) -> bool { - let Some(slide) = self.session.active().map(|d| d.selection.slide) else { return false }; + succeeded(&self.export_copies(fmt, extra, None)) + } + + fn export_copies(&mut self, fmt: &str, extra: Value, instance: Option>) -> SaveOutcome { + let Some((uid, doc, slide, title)) = self.session.active().map(|d| (d.uid, d.doc.clone(), d.selection.slide, d.title())) else { + return SaveOutcome::Failed("no presentation is open".into()); + }; let (ext, format, all) = match fmt { "pdf" => ("pdf", "pdf", false), "png" => ("png", "png", false), @@ -216,77 +234,45 @@ impl SlideApp { "rtf" => ("rtf", "rtf", false), "deckcraft" => ("deckcraft", "deckcraft", false), "gif" => ("gif", "gif", false), - other => { - self.set_status(format!("DeckCraft can't export “{other}”")); - return false; - } + other => return self.file_failure(format!("DeckCraft can't export “{other}”")), }; let suggested = self.suggested_name(ext); - if let Some(pick) = self.services.pick_save.as_mut() { - let Some(path) = pick(&suggested) else { return false }; - let mut params = json!({"path": path, "format": format, "all": all}); - if let (Some(o), Some(x)) = (params.as_object_mut(), extra.as_object()) { - o.extend(x.clone()); - } - return match self.run("file.export", params) { - Ok(_) => { - self.set_status(format!("Exported {path}")); - true - } - Err(_) => false, - }; - } - let Some(doc) = self.session.active().map(|d| d.doc.clone()) else { return false }; - let bytes = match format { + let files = match format { "png" | "jpeg" => { - // Every slide for "all slides", one download each, named like the desktop export (#64). - let name = self.session.active().map(|d| d.title()).unwrap_or_else(|| "Presentation".into()); - let mut any = false; let transparent = extra.get("transparentBackground").and_then(Value::as_bool).unwrap_or(false); - for (file, bytes) in web_image_files(&doc, slide, all, &name, ext, transparent) { - any = self.download(&file, Ok(bytes)) || any; + if transparent && format != "png" { + return self.file_failure("A transparent background is for PNG export".into()); + } + web_image_files(&doc, slide, all, &title, ext, transparent) + } + _ => { + let bytes = match format { + "pdf" => deckcraft_engine::cmd::file::pdf_bytes(&doc, &extra), + "gif" => deckcraft_engine::cmd::file::gif_bytes(&doc, &extra), + other => save_bytes(&doc, other), + }; + match bytes { + Ok(bytes) => vec![(suggested.clone(), bytes)], + Err(e) => return self.file_failure(e.to_string()), } - return any; } - "pdf" => deckcraft_engine::cmd::file::pdf_bytes(&doc, &extra), - "gif" => deckcraft_engine::cmd::file::gif_bytes(&doc, &extra), - other => deckcraft_engine::cmd::file::save_bytes(&doc, other), }; - self.download(&suggested, bytes) - } - - /// Hands `bytes` to the browser as a download (web); false (with the reason in the status - /// bar) when there are no bytes or no way to download. - fn download(&mut self, name: &str, bytes: deckcraft_engine::Result>) -> bool { - match (bytes, self.services.download.as_mut()) { - (Ok(b), Some(dl)) => { - dl(name, &b); - true - } - (Err(e), _) => { - self.set_status(e.to_string()); - false - } - (Ok(_), None) => { - self.set_status("Saving a copy needs a file picker, which this window doesn't have."); - false - } - } + self.submit_save(uid, None, files, &suggested, false, instance) } /// File › Print: DeckCraft prints through a PDF. On the desktop the PDF (with the Print page's /// layout, slides and options) is written to the temporary folder and opened in the system's /// PDF viewer, which has the printers; on the web it downloads. pub fn print_pdf(&mut self, params: Value) -> bool { - let Some((title, doc)) = self.session.active().map(|d| (d.title(), d.doc.clone())) else { return false }; + let Some(title) = self.session.active().map(|d| d.title()) else { + return false; + }; let mut params = if params.is_object() { params } else { json!({}) }; - if self.services.pick_save.is_none() { - // Web: the browser hands the PDF to the user. - let bytes = deckcraft_engine::cmd::file::pdf_bytes(&doc, ¶ms); - return self.download(&format!("{title}.pdf"), bytes); + if self.host.files().browser_saves() { + return self.export_as("pdf", params); } - // P3(shell-w6): sh.A8 - let preview_path = match self.print_previews_base.create(&title) { + let title: String = title.chars().map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '-') { c } else { '_' }).collect(); + let preview_path = match self.print_previews.create("deckcraft-print", &format!("{title} (print).pdf")) { Ok(path) => path, Err(e) => { self.set_status(format!("Couldn't create a private print preview: {e}")); @@ -305,28 +291,27 @@ impl SlideApp { true } Err(_) => { - // P3(shell-w6): sh.A8 - self.print_previews_base.discard(&preview_path); + self.print_previews.discard(&preview_path); false } } } + /// Pick a document or outline without borrowing a platform picker closure. pub(crate) fn pick_and_open(&mut self) { - if let Some(pick) = self.services.pick_open.as_mut() { - if let Some(path) = pick("open") { - self.open_path_in_background(&path); - } - } else if self.services.open_async.is_some() { - let id = self.begin_external_file("open"); - if let Some(f) = self.services.open_async.as_mut() { - f("open", id); - } - } + self.queue_file_pick("document", FileOperation::Apply(purpose_of("document"))); } pub fn open_path(&mut self, path: &str) -> Result<(), String> { - self.session.execute("file.open", &json!({"path": path})).map_err(|e| e.to_string())?; + let files = self.host.files(); + let loaded = deckcraft_engine::cmd::file::read_presentation_file_with( + path, + |path| files.read_metadata(Path::new(path)).map_err(|e| e.to_string()), + |path| files.read(Path::new(path)).map_err(|e| e.to_string()), + ) + .map_err(|e| e.to_string())?; + let token = self.session.stage_loaded(loaded); + self.session.execute("file.adopt", &json!({"path": path, "token": token})).map_err(|e| e.to_string())?; self.note_recent(path); Ok(()) } @@ -366,51 +351,39 @@ impl SlideApp { /// Transitions › Sound › Other Sound…: pick an audio file for the selected slides. pub(crate) fn pick_transition_sound(&mut self) { - if self.services.pick_open.is_some() { - self.pick_and_insert("audio", "transition.sound"); + self.pick_and_insert("audio", "transition.sound"); + } + + /// Ask for the presentation whose slides will be offered for reuse. + pub(super) fn pick_and_reuse(&mut self, keep: bool) { + self.queue_file_pick("document", FileOperation::Reuse { keep }); + } + + /// Read a named source once before offering its slides for reuse. + pub(crate) fn begin_reuse(&mut self, path: String, keep: bool) { + let target = self.capture_file_target(); + match self.host.files().read(Path::new(&path)) { + Ok(bytes) => self.begin_reuse_bytes(&path, &bytes, keep, target), + Err(e) => self.set_status(e.to_string()), } } - /// Home › New Slide › Reuse Slides…: pick a presentation and insert all its slides after the - /// current one (desktop only: the browser picker opens what it picks as a document). - pub(super) fn pick_and_reuse(&mut self, keep: bool) { - let Some(pick) = self.services.pick_open.as_mut() else { - self.set_status("Reuse Slides needs the desktop app".to_string()); - return; - }; - let Some(path) = pick("open") else { return }; - // Read the file once: the list shown and the slides inserted come from the same bytes, even - // if the file changes while the dialog is open. Without a reader the path is used as is. - let mut source = json!({}); - match self.services.read.as_ref().map(|r| r(&path)) { - Some(Ok(bytes)) => { - let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); - source["name"] = json!(name); - source["data"] = json!(deckcraft_engine::cmd::base64_encode(&bytes)); - } - Some(Err(e)) => { - self.set_status(e.to_string()); - return; - } - None => source["path"] = json!(path), - } - // Offer the file's slides to choose from; all of them are ticked to begin with. + fn begin_reuse_bytes(&mut self, path: &str, bytes: &[u8], keep: bool, target: FileTarget) { + // Browser Contents have no native path to reopen, so reuse consumes the supplied bytes. + let name = Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let source = json!({"name": name, "data": deckcraft_engine::cmd::base64_encode(bytes)}); match self.session.execute("slide.reuseList", &source) { Ok(list) => { - let mut d = dialogs::Dialog::new("reuseSlides"); - d.params = json!({"path": path, "source": source, "keep": keep, "slides": list["slides"]}); - self.reuse_target = Some(self.capture_file_target()); - self.dialog = Some(d); + self.reuse_target = Some(target); + self.open_dialog("reuseSlides", json!({"path": path, "source": source, "keep": keep, "slides": list["slides"]})); } Err(e) => self.set_status(e.to_string()), } } - /// Insert the slides `picked` (indices) of `source` (the `name` + `data`, or `path`, that - /// `slide.reuseList` listed) after the slide that was current when the picker opened, in that - /// presentation, even if another one is active now; if it is closed or the slide is gone, - /// nothing is inserted. Returns whether they were inserted. - pub fn reuse_slides(&mut self, source: &Value, keep: bool, picked: &[usize]) -> bool { + /// Insert the chosen source slides at the stable place captured by the picker. + /// An error retains the chosen slides so the form can show the reason and retry. + pub fn reuse_slides(&mut self, source: &Value, keep: bool, picked: &[usize]) -> Result<(), String> { let mut args = if source.is_object() { source.clone() } else { json!({}) }; args["keepFormatting"] = json!(keep); args["slides"] = json!(picked); @@ -422,138 +395,7 @@ impl SlideApp { Ok(()) => { self.reuse_target = None; self.set_status(format!("Inserted {} slides", picked.len())); - true - } - Err(e) => { - self.set_status(e); - false - } - } - } - - pub(crate) fn pick_and_insert(&mut self, purpose: &str, cmd: &str) { - // P3(shell-w6): sh.A23 - self.pick_and_run(purpose, cmd, json!({})); - } - - /// Pick a file and run `cmd` with it (`name` + `data`, or `path`) added to `extra`. - pub(crate) fn pick_and_run(&mut self, purpose: &str, command: &str, params: Value) { - // P3(shell-w6): sh.A23 - let (cmd, extra) = (command, ¶ms); - if let Some(pick) = self.services.pick_open.as_mut() { - if let Some(path) = pick(purpose) { - let mut args = if extra.is_object() { extra.clone() } else { json!({}) }; - let r = match self.services.read.as_ref().map(|r| r(&path)) { - Some(Ok(bytes)) => { - let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); - args["name"] = json!(name); - args["data"] = json!(deckcraft_engine::cmd::base64_encode(&bytes)); - self.session.execute(cmd, &args) - } - _ => { - args["path"] = json!(path); - self.session.execute(cmd, &args) - } - }; - if let Err(e) = r { - self.set_status(e.to_string()); - } - } - } else if self.services.open_async.is_some() { - let id = self.begin_external_file(purpose); - // Change Picture: the picture that arrives replaces the selected one (#115). - if cmd == "picture.change" - // P3(shell-w6): sh.A8 - && let Some(r) = self.pending_files_base.iter_mut().find(|r| r.id == id) - { - r.purpose = FilePurpose::ChangePicture; - } - if let Some(f) = self.services.open_async.as_mut() { - f(purpose, id); - } - } - } - - pub fn save_as_dialog(&mut self, format: &str) { - let name = self.session.active().map(|d| d.title()).unwrap_or_else(|| "Presentation".into()); - let ext = if format == "pptx" { "pptx" } else { "deckcraft" }; - let suggested = format!("{name}.{ext}"); - if let Some(pick) = self.services.pick_save.as_mut() { - if let Some(path) = pick(&suggested) { - match self.session.execute("file.saveAs", &json!({"path": path})) { - Ok(_) => { - self.set_status(format!("Saved {path}")); - self.ui.recent.retain(|p| *p != path); - self.ui.recent.insert(0, path); - } - Err(e) => self.set_status(e.to_string()), - } - } - } else if self.services.host_save.is_some() { - let _ = self.save_to_host(Some(ext)); - } else if let Some(dl) = self.services.download.as_mut() - && let Some(d) = self.session.active() - { - match deckcraft_engine::cmd::file::save_bytes(&d.doc, ext) { - Ok(bytes) => dl(&suggested, &bytes), - Err(e) => self.set_status(e.to_string()), - } - } - } - - /// Save every presentation with unsaved changes (asking for a location where needed). - /// Returns false if one wasn't saved (cancelled or failed). - pub fn save_all(&mut self) -> bool { - let dirty: Vec = self.session.documents().iter().enumerate().filter(|(_, d)| d.is_dirty()).map(|(i, _)| i).collect(); - for i in dirty { - self.session.set_active(i); - self.save(); - if self.session.documents().get(i).is_some_and(|d| d.is_dirty()) { - return false; - } - } - true - } - - pub fn save(&mut self) { - if self.services.host_save.is_some() { - let _ = self.save_to_host(None); - return; - } - if self.session.active().and_then(|d| d.path.clone()).is_some() { - match self.session.execute("file.save", &json!({})) { - Ok(_) => self.set_status("Saved"), - Err(e) => self.set_status(e.to_string()), - } - } else { - self.save_as_dialog("deckcraft"); - } - } - - /// Saves to the page that keeps the files ([`Services::host_save`](crate::Services::host_save)). - /// Save (`ext` `None`) writes the presentation's own file (the one the page sent, or the - /// last one saved there) in that file's format, as the desktop app does; a presentation with - /// no file of its own is a new `.deckcraft` file, the name Save suggests on the desktop. Save - /// As (`pptx`, `deckcraft`) is a new file named after the presentation. Once the page has the - /// bytes, the presentation is saved and that name is its file. Returns the name, or why it - /// wasn't saved (also shown in the status bar). - pub(super) fn save_to_host(&mut self, ext: Option<&str>) -> Result { - use deckcraft_engine::cmd::file::{format_for_path, mark_saved, save_bytes}; - let Some(d) = self.session.active() else { return Err("no presentation is open".into()) }; - let own = d.path.as_deref().and_then(|p| std::path::Path::new(p).file_name()).map(|n| n.to_string_lossy().to_string()); - let (name, save_as) = match (ext, own) { - (None, Some(own)) => (own, false), - (ext, _) => (format!("{}.{}", d.title(), ext.unwrap_or("deckcraft")), true), - }; - let saved = save_bytes(&d.doc, format_for_path(&name)).map_err(|e| e.to_string()).and_then(|bytes| { - let host = self.services.host_save.as_mut().ok_or("no page to save to")?; - host(&name, &bytes, save_as).map_err(|e| format!("Couldn't save {name}: {e}"))?; - mark_saved(&mut self.session, Some(name.clone())).map_err(|e| e.to_string()) - }); - match saved { - Ok(()) => { - self.set_status(format!("Saved {name}")); - Ok(name) + Ok(()) } Err(e) => { self.set_status(e.clone()); @@ -562,6 +404,66 @@ impl SlideApp { } } + /// Pick a file for an insertion command at the current place. + pub(crate) fn pick_and_insert(&mut self, purpose: &str, cmd: &str) { + self.pick_and_run(purpose, cmd, json!({})); + } + + /// Pick a file for a registered command, retaining its parameters and shape targets. + pub(crate) fn pick_and_run(&mut self, purpose: &str, command: &str, params: Value) { + let mut params = if params.is_object() { params } else { json!({}) }; + if captures_shapes(command) && params.get("ids").is_none() && params.get("id").is_none() { + params["ids"] = json!(self.session.active().map(|d| d.selection.shapes.clone()).unwrap_or_default()); + } + self.queue_file_pick(purpose, FileOperation::Command { purpose: purpose.into(), command: command.into(), params }); + } + + fn queue_file_pick(&mut self, purpose: &str, operation: FileOperation) { + let target = self.capture_file_target(); + let ticket = self.host.files().pick(open_request(purpose)); + self.pending_files.push(PendingFile { ticket, operation, target }); + } + + /// Ask for a new file of the active document in the requested format. + pub fn save_as_dialog(&mut self, format: &str) { + let _ = self.save_as_outcome(format, None); + } + + fn save_as_outcome(&mut self, format: &str, instance: Option>) -> SaveOutcome { + let Some((uid, snapshot)) = self.session.active().map(|d| (d.uid, d.doc.clone())) else { + return SaveOutcome::Failed("no presentation is open".into()); + }; + if self.document_save_pending(uid) { + return self.file_failure("A save of this presentation is still waiting".into()); + } + let ext = if format == "pptx" { "pptx" } else { "deckcraft" }; + let name = self.suggested_name(ext); + let bytes = match save_bytes(&snapshot, ext) { + Ok(bytes) => bytes, + Err(e) => return self.file_failure(e.to_string()), + }; + self.submit_save(uid, Some(snapshot), vec![(name.clone(), bytes)], &name, true, instance) + } + + /// Save every dirty document; outstanding tickets are retained without resubmission. + pub fn save_all(&mut self) -> bool { + let dirty: Vec = self.session.documents().iter().filter(|d| d.is_dirty()).map(|d| d.uid).collect(); + let mut complete = !self.pending_files.iter().any(|p| matches!(&p.operation, FileOperation::Save(s) if s.snapshot.is_some())); + for uid in dirty { + if !succeeded(&self.save_document(uid)) { + complete = false; + } + } + complete + } + + /// Save the active document through its installed file service. + pub fn save(&mut self) { + if let Some(uid) = self.session.active().map(|d| d.uid) { + let _ = self.save_document(uid); + } + } + /// A file the page that keeps the files sent (`?host=parent`), with the name it sent, if any. /// It opens as File › Open opens it on the desktop: a presentation as itself, an outline /// (.txt, .md, .rtf) as a new untitled presentation. The name is the presentation's file only @@ -613,11 +515,7 @@ impl SlideApp { pub(super) fn drain_requests(&mut self) { for r in std::mem::take(&mut self.session.ui_requests) { match r { - UiRequest::Dialog { id, params } => { - let mut d = dialogs::Dialog::new(&id); - d.params = params; - self.dialog = Some(d); - } + UiRequest::Dialog { id, params } => self.open_dialog(&id, params), UiRequest::Pane { id } => self.ui.pane = Some(id), UiRequest::StartShow { from } => self.start_show(from, false), UiRequest::Message { text } => self.set_status(text), @@ -637,45 +535,16 @@ impl SlideApp { } } - pub(crate) fn drain_inbox(&mut self) { - let Some(inbox) = self.services.inbox.clone() else { return }; - let events = match inbox.lock() { - Ok(mut v) => std::mem::take(&mut *v), - Err(poisoned) => std::mem::take(&mut *poisoned.into_inner()), - }; - for event in events { - match event { - // P3(shell-w6): sh.A8 - InboxEvent::Cancelled { id } => self.pending_files_base.retain(|r| r.id != id), - InboxEvent::File(file) => self.apply_external_file(file.id, &file.name, &file.bytes), - } - } - } - - /// Remember the open presentation, the slide (or master/layout) and the operation for a - /// file the host will read asynchronously. Returns the cancellation identity the host must - /// echo on the [`InboxEvent`]. Call this when the pick or the drop starts, not when the - /// bytes arrive. - pub fn begin_external_file(&mut self, purpose: &str) -> u64 { - let id = self.next_file_id; - self.next_file_id = self.next_file_id.wrapping_add(1).max(1); - // P3(shell-w6): sh.A8 - // P3(shell-w6): sh.A8 - self.pending_files_base.push(PendingFileBase { id, purpose: purpose_of(purpose), target: self.capture_file_target() }); - id - } - - /// A dropped or picked file read synchronously: presentations open, media is inserted on - /// the slide that is current now. + /// Apply a drop at the place captured by the pass that receives its bytes. pub(crate) fn open_or_insert_bytes(&mut self, name: &str, bytes: Vec) { - // P3(shell-w6): sh.A23 - let bytes = bytes.as_slice(); - let id = self.begin_external_file("drop"); - self.apply_external_file(id, name, bytes); + let target = self.capture_file_target(); + self.apply_external_file(FileOperation::Apply(purpose_of("drop")), target, name, &bytes); } fn capture_file_target(&self) -> FileTarget { - let Some(d) = self.session.active() else { return FileTarget::Absent }; + let Some(d) = self.session.active() else { + return FileTarget::Absent; + }; let place = match d.selection.target { Target::Slides => match d.current_slide() { Some(s) => FilePlace::Slide(s.id), @@ -699,8 +568,12 @@ impl SlideApp { /// True when the user is still looking at the place this request captured. fn viewing_target(&self, target: &FileTarget) -> bool { - let FileTarget::Document { doc, place } = target else { return false }; - let Some(d) = self.session.active() else { return false }; + let FileTarget::Document { doc, place } = target else { + return false; + }; + let Some(d) = self.session.active() else { + return false; + }; if d.uid != *doc { return false; } @@ -718,27 +591,45 @@ impl SlideApp { } } - fn apply_external_file(&mut self, id: u64, name: &str, bytes: &[u8]) { - // P3(shell-w6): sh.A8 - let Some(pos) = self.pending_files_base.iter().position(|r| r.id == id) else { return }; - // P3(shell-w6): sh.A8 - let req = self.pending_files_base.remove(pos); - let cmd = match command_for(req.purpose, name, bytes) { - Ok(cmd) => cmd, - Err(e) => { - self.set_status(e); + fn apply_external_file(&mut self, operation: FileOperation, target: FileTarget, name: &str, bytes: &[u8]) { + let (cmd, mut params, picture) = match operation { + FileOperation::Apply(purpose) => { + let cmd = match command_for(purpose, name, bytes) { + Ok(cmd) => cmd, + Err(e) => { + self.set_status(e); + return; + } + }; + let params = if cmd == "slide.fromOutline" { + json!({"text": deckcraft_engine::cmd::file::outline_text(bytes), "markdown": name.to_ascii_lowercase().ends_with(".md")}) + } else { + json!({}) + }; + (cmd.to_string(), params, false) + } + FileOperation::Command { purpose, command, params } => (command, params, purpose == "picture"), + FileOperation::Reuse { keep } => { + self.begin_reuse_bytes(name, bytes, keep, target); return; } + FileOperation::Save(_) => return, }; - let params = if cmd == "slide.fromOutline" { - json!({"text": deckcraft_engine::cmd::file::outline_text(bytes), "markdown": name.to_ascii_lowercase().ends_with(".md")}) + if cmd == "picture.change" + && let Err(e) = command_for(FilePurpose::ChangePicture, name, bytes) + { + self.set_status(e); + return; + } + params["name"] = json!(name); + params["data"] = json!(deckcraft_engine::cmd::base64_encode(bytes)); + if picture { + params["picture"] = params["data"].clone(); + } + let result = if cmd == "file.openBytes" || (self.viewing_target(&target) && !captures_shapes(&cmd)) { + self.session.execute(&cmd, ¶ms).map(|_| ()).map_err(|e| e.to_string()) } else { - json!({"name": name, "data": deckcraft_engine::cmd::base64_encode(bytes)}) - }; - let result = if cmd == "file.openBytes" || self.viewing_target(&req.target) { - self.session.execute(cmd, ¶ms).map(|_| ()).map_err(|e| e.to_string()) - } else { - self.execute_on_target(&req.target, name, cmd, ¶ms) + self.execute_on_target(&target, name, &cmd, ¶ms) }; match result { Err(e) if cmd == "file.openBytes" => self.notify(e), @@ -778,17 +669,30 @@ impl SlideApp { st.selection.text = None; st.selection.cells = None; } - let result = self.session.execute(cmd, params).map(|_| ()).map_err(|e| e.to_string()); - if view == Some(idx) { - if let (Some(sel), Some(st)) = (saved, self.session.active_mut()) { - st.selection = sel; - } - } else { - self.restore_file_view(view); + let result = self.validate_file_shapes(cmd, params).and_then(|()| self.session.execute(cmd, params).map(|_| ()).map_err(|e| e.to_string())); + if let (Some(sel), Some(st)) = (saved, self.session.active_mut()) { + st.selection = sel; } + self.restore_file_view(view); result } + fn validate_file_shapes(&self, command: &str, params: &Value) -> Result<(), String> { + if captures_shapes(command) { + let d = self.session.doc().map_err(|e| e.to_string())?; + let ids = params.get("ids").and_then(Value::as_array).map(Vec::as_slice); + let single = params.get("id").map(std::slice::from_ref); + for id in ids.or(single).unwrap_or_default() { + if let Some(id) = id.as_u64().and_then(|id| u32::try_from(id).ok()) + && d.shape(deckcraft_model::ShapeId(id)).is_none() + { + return Err("the shape it was chosen for was deleted".into()); + } + } + } + Ok(()) + } + fn restore_file_view(&mut self, view: Option) { if let Some(i) = view && i < self.session.documents().len() @@ -848,114 +752,271 @@ pub(crate) fn web_image_files( let opts = deckcraft_render::RenderOpts { scale, transparent_background: transparent && ext == "png", ..Default::default() }; let img = deckcraft_render::render_slide(doc, i, &opts); let bytes = if ext == "png" { img.to_png_at(dpi) } else { img.to_jpeg_at(92, Some(dpi)) }; - let file = if single { format!("{name}.{ext}") } else { format!("{name}{}.{ext}", k + 1) }; + let file = image_file_name(name, ext, k, single); (file, bytes) }) .collect() } -#[cfg(test)] -mod print_preview_tests { - use super::PrintPreviews; - use std::time::{SystemTime, UNIX_EPOCH}; - - #[test] - fn same_title_gets_distinct_private_paths_and_drop_cleans_them() { - let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default(); - let base = std::env::temp_dir().join(format!("deckcraft-print-test-{}-{stamp}", std::process::id())); - std::fs::create_dir(&base).unwrap(); - let (first, second) = { - let mut previews = PrintPreviews::default(); - let first = previews.create_in(&base, "Same title").unwrap(); - let second = previews.create_in(&base, "Same title").unwrap(); - assert_ne!(first, second); - assert_eq!(first.file_name(), second.file_name()); - assert!(first.parent().is_some_and(|dir| dir.is_dir())); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mode = std::fs::metadata(first.parent().unwrap()).unwrap().permissions().mode(); - assert_eq!(mode & 0o777, 0o700); - } - (first, second) - }; - assert!(!first.parent().is_some_and(|dir| dir.exists())); - assert!(!second.parent().is_some_and(|dir| dir.exists())); - std::fs::remove_dir(base).unwrap(); - } - - #[test] - fn explicit_cleanup_removes_previews() { - let stamp = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default(); - let base = std::env::temp_dir().join(format!("deckcraft-print-cleanup-test-{}-{stamp}", std::process::id())); - std::fs::create_dir(&base).unwrap(); - let mut previews = PrintPreviews::default(); - let path = previews.create_in(&base, "Explicit cleanup").unwrap(); - let dir = path.parent().unwrap().to_path_buf(); - - previews.cleanup(); - - assert!(!dir.exists()); - std::fs::remove_dir(base).unwrap(); - } -} - -impl crate::SlideApp { - /// Consumes file answers from the installed host. - #[allow(dead_code)] // P3(shell-w6): sh.A23 +impl SlideApp { + /// Takes only answered tickets; a second pass cannot replay an answer consumed by the first. pub(crate) fn take_file_answers(&mut self) { - todo!("sh.A23") + let tickets: Vec = self.pending_files.iter().map(|p| p.ticket).collect(); + for ticket in tickets { + self.take_file_answer(ticket); + } } -} -/// The closing prompt save result, including a pending file pick. -#[allow(dead_code)] // P3(shell-w6): dl.A8 -pub(crate) enum SaveOutcome { - Saved, - Downloaded, - Failed(String), - Cancelled, - Pending, -} + fn take_file_answer(&mut self, ticket: PickId) { + let Some(answer) = self.host.files().take_answer(ticket) else { + return; + }; + let Some(at) = self.pending_files.iter().position(|p| p.ticket == ticket) else { + return; + }; + let pending = self.pending_files.remove(at); + if let FileOperation::Save(transfer) = pending.operation { + self.finish_save(transfer, answer); + return; + } + match answer { + Picked::Paths(paths) => { + for path in paths { + let name = path.to_string_lossy().to_string(); + if matches!(pending.operation, FileOperation::Apply(FilePurpose::Open)) && open_command(&name) == Some("file.openBytes") { + self.open_path_in_background(&name); + } else { + match self.host.files().read(&path) { + Ok(bytes) => self.apply_external_file(pending.operation.clone(), pending.target, &name, &bytes), + Err(e) => self.set_status(e.to_string()), + } + } + } + } + Picked::Contents(files) => { + for (name, bytes) in files { + self.apply_external_file(pending.operation.clone(), pending.target, &name, &bytes); + } + } + Picked::Failed(e) | Picked::Unavailable(e) => self.set_status(e), + Picked::Cancelled => {} + _ => self.set_status("The file picker did not return an open file"), + } + } -impl crate::SlideApp { - /// Saves a document for the closing prompt. - #[allow(dead_code)] // P3(shell-w6): dl.A8 + /// Saves the named document without changing which document the user is viewing. pub(crate) fn save_document(&mut self, uid: u64) -> SaveOutcome { - let _ = uid; - todo!("dl.A8") + if self.document_save_pending(uid) { + return SaveOutcome::Pending; + } + let Some(d) = self.session.documents().iter().find(|d| d.uid == uid) else { + let outcome = SaveOutcome::Failed("the presentation is closed".into()); + self.save_settled(uid, outcome.clone()); + return outcome; + }; + let snapshot = d.doc.clone(); + let own = d.path.clone(); + let name = own + .as_deref() + .and_then(|p| Path::new(p).file_name()) + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_else(|| format!("{}.deckcraft", d.title())); + let bytes = match save_bytes(&snapshot, format_for_path(&name)) { + Ok(bytes) => bytes, + Err(e) => { + let outcome = self.file_failure(e.to_string()); + self.save_settled(uid, outcome.clone()); + return outcome; + } + }; + if !self.host.files().browser_saves() + && let Some(path) = own.as_ref() + { + let batch = Rc::new(RefCell::new(SaveBatch { uid, remaining: 1, outcome: SaveOutcome::Saved, instance: None, deferred: false })); + let transfer = + SaveTransfer { snapshot: Some(snapshot), files: vec![(name, bytes)], write_on_answer: true, save_as: false, batch: batch.clone() }; + self.finish_save(transfer, Picked::Saved { path: PathBuf::from(path), file_type: None }); + return batch.borrow().outcome.clone(); + } + self.submit_save(uid, Some(snapshot), vec![(name.clone(), bytes)], &name, own.is_none(), None) } -} -impl crate::SlideApp { - /// Settles a closing save when its file pick answers. - #[allow(dead_code)] // P3(shell-w6): dl.A8 + /// Delivers terminal outcomes to the closing pump, which owns all guard transitions. pub(crate) fn save_settled(&mut self, uid: u64, outcome: SaveOutcome) { - let _ = (uid, outcome); - todo!("dl.A8") + if !matches!(outcome, SaveOutcome::Pending) + && let Some(closing) = self.dialogs.closing.as_mut() + { + closing.settle(uid, outcome); + } + } + + /// Save As with completion intent for this particular File view. + pub(crate) fn backstage_save_as(&mut self, format: &str, instance: Arc<()>) -> SaveOutcome { + self.save_as_outcome(format, Some(instance)) + } + + /// Export with completion intent shared by every copy of this particular File view. + pub(crate) fn backstage_export_as(&mut self, format: &str, extra: Value, instance: Arc<()>) -> SaveOutcome { + self.export_copies(format, extra, Some(instance)) + } + + fn document_save_pending(&self, uid: u64) -> bool { + self.pending_files.iter().any(|p| matches!(&p.operation, FileOperation::Save(s) if s.snapshot.is_some() && s.batch.borrow().uid == uid)) + } + + fn file_failure(&mut self, reason: String) -> SaveOutcome { + self.set_status(reason.clone()); + SaveOutcome::Failed(reason) + } + + fn submit_save( + &mut self, + uid: u64, + snapshot: Option>, + files: Vec<(String, Vec)>, + suggested: &str, + save_as: bool, + instance: Option>, + ) -> SaveOutcome { + if files.is_empty() { + return self.file_failure("There are no slides to export".into()); + } + let browser = self.host.files().browser_saves(); + let batch = Rc::new(RefCell::new(SaveBatch { + uid, + remaining: if browser { files.len() } else { 1 }, + outcome: SaveOutcome::Saved, + instance, + deferred: false, + })); + let target = FileTarget::Document { doc: uid, place: FilePlace::Unspecified }; + let request = |name: &str| { + let ext = Path::new(name).extension().and_then(|s| s.to_str()).unwrap_or("deckcraft"); + PickRequest::save("document").file_name(name).suggested_extension(ext).filter(ext, &[ext]).save_as(save_as) + }; + let mut tickets = Vec::new(); + if browser { + for (name, bytes) in files { + let ticket = self.host.files().save(request(&name), bytes); + self.pending_files.push(PendingFile { + ticket, + target, + operation: FileOperation::Save(SaveTransfer { + snapshot: snapshot.clone(), + files: vec![(name, Vec::new())], + write_on_answer: false, + save_as, + batch: batch.clone(), + }), + }); + tickets.push(ticket); + } + } else { + let ticket = self.host.files().pick(request(suggested)); + self.pending_files.push(PendingFile { + ticket, + target, + operation: FileOperation::Save(SaveTransfer { snapshot, files, write_on_answer: true, save_as, batch: batch.clone() }), + }); + tickets.push(ticket); + } + // Ownership is registered before taking even an immediately available answer. + for ticket in tickets { + self.take_file_answer(ticket); + } + let mut batch = batch.borrow_mut(); + if batch.remaining == 0 { + batch.outcome.clone() + } else { + batch.deferred = true; + SaveOutcome::Pending + } + } + + fn finish_save(&mut self, transfer: SaveTransfer, picked: Picked) { + let uid = transfer.batch.borrow().uid; + let name = transfer.files.first().map(|(name, _)| name.as_str()).unwrap_or("Presentation"); + let records = picked.records_file(); + let outcome = match picked { + Picked::Saved { path, .. } => { + let result = self.write_saved_files(&transfer, &path).and_then(|()| { + if records && let Some(snapshot) = transfer.snapshot.as_ref() { + mark_saved_snapshot(&mut self.session, uid, snapshot.clone(), Some(path.to_string_lossy().to_string())) + .map_err(|e| e.to_string())?; + let path = path.to_string_lossy().to_string(); + self.ui.recent.retain(|p| p != &path); + self.ui.recent.insert(0, path); + self.ui.recent.truncate(RECENT_MAX); + } + Ok(()) + }); + match result { + Ok(()) => { + self.set_status(format!("Saved {}", path.display())); + SaveOutcome::Saved + } + Err(e) => self.file_failure(format!("Couldn't save {name}: {e}")), + } + } + Picked::Downloaded(name) => { + self.set_status(format!("Downloaded {name}")); + SaveOutcome::Downloaded + } + Picked::Failed(e) | Picked::Unavailable(e) => self.file_failure(format!("Couldn't save {name}: {e}")), + Picked::Cancelled => SaveOutcome::Cancelled, + _ => self.file_failure(format!("Couldn't save {name}: the picker did not return a save result")), + }; + if transfer.snapshot.is_some() { + self.save_settled(uid, outcome.clone()); + } + let mut batch = transfer.batch.borrow_mut(); + batch.remaining -= 1; + batch.outcome = match (&batch.outcome, &outcome) { + (SaveOutcome::Failed(_), _) | (SaveOutcome::Cancelled, SaveOutcome::Saved | SaveOutcome::Downloaded) => batch.outcome.clone(), + (_, SaveOutcome::Failed(_) | SaveOutcome::Cancelled) => outcome, + (SaveOutcome::Downloaded, _) => SaveOutcome::Downloaded, + _ => outcome, + }; + if batch.remaining == 0 + && batch.deferred + && succeeded(&batch.outcome) + && let Some(instance) = &batch.instance + && self.backstage.as_ref().is_some_and(|b| b.docs.1 == Some(uid) && Arc::ptr_eq(&b.instance, instance)) + { + self.close_backstage(); + } + } + + fn write_saved_files(&self, transfer: &SaveTransfer, path: &Path) -> Result<(), String> { + if !transfer.write_on_answer { + return Ok(()); + } + let intent = if transfer.save_as { WriteIntent::SaveAs } else { WriteIntent::Save }; + let multiple = transfer.files.len() > 1; + for (index, (name, bytes)) in transfer.files.iter().enumerate() { + let out = if multiple { + let stem = path.file_stem().unwrap_or_default().to_string_lossy(); + let ext = path.extension().or_else(|| Path::new(name).extension()).unwrap_or_default().to_string_lossy(); + path.with_file_name(image_file_name(&stem, &ext, index, false)) + } else { + path.to_path_buf() + }; + let encoded; + let bytes = if let Some(snapshot) = &transfer.snapshot + && format_for_path(name) != format_for_path(&out.to_string_lossy()) + { + // The picker may choose a different writable extension; the captured snapshot stays fixed. + encoded = save_bytes(snapshot, format_for_path(&out.to_string_lossy())).map_err(|e| e.to_string())?; + &encoded + } else { + bytes + }; + self.host.files().write(&out, bytes, intent).map_err(|e| e.to_string())?; + } + Ok(()) } } -/// The operation and captured intent completed by a file pick. -#[allow(dead_code)] // P3(shell-w6): sh.A23 -pub(crate) struct FileOperation; - -impl SlideApp { - /// Saves or exports with close intent for the originating Backstage instance. - /// Deferred success closes only that still-open instance for the captured document. - #[allow(dead_code)] // P3(shell-w6): sh.A23 - pub(crate) fn backstage_save_as(&mut self, format: &str, instance: std::sync::Arc<()>) -> SaveOutcome { - let _ = (format, instance); - todo!("sh.A23") - } -} - -impl SlideApp { - /// Saves or exports with close intent for the originating Backstage instance. - /// Deferred success closes only that still-open instance for the captured document. - #[allow(dead_code)] // P3(shell-w6): sh.A23 - pub(crate) fn backstage_export_as(&mut self, format: &str, extra: Value, instance: std::sync::Arc<()>) -> SaveOutcome { - let _ = (format, extra, instance); - todo!("sh.A23") - } +fn image_file_name(stem: &str, ext: &str, index: usize, single: bool) -> String { + if single { format!("{stem}.{ext}") } else { format!("{stem}{}.{ext}", index + 1) } } diff --git a/crates/ui-egui/src/host_save_tests.rs b/crates/ui-egui/src/host_save_tests.rs index 9fcca4121..791745040 100644 --- a/crates/ui-egui/src/host_save_tests.rs +++ b/crates/ui-egui/src/host_save_tests.rs @@ -2,38 +2,36 @@ //! the exports and Print hand that page, under which name, and whether it is a new file. #![allow(clippy::unwrap_used, clippy::expect_used)] -use std::cell::RefCell; -use std::rc::Rc; +use std::path::Path; +use std::sync::Arc; + +use craft::host::{Picked, ScriptedFiles}; use serde_json::json; use super::{Services, SlideApp}; use crate::Session; -/// What the page was handed: (name, Save As, bytes). -type Got = Rc)>>>; +type Got = Arc; -/// The web app inside such a page, with `host_save` and `download` pointed at it as the bridge -/// does; `fail` makes every save miss the page. -fn host_app(fail: bool) -> (SlideApp, Got) { - let got: Got = Rc::default(); - let (saves, downloads) = (got.clone(), got.clone()); - let services = Services { - host_save: Some(Box::new(move |name: &str, bytes: &[u8], save_as: bool| { - if fail { - return Err("the page is gone".into()); - } - saves.borrow_mut().push((name.to_string(), save_as, bytes.to_vec())); - Ok(()) - })), - download: Some(Box::new(move |name: &str, bytes: &[u8]| downloads.borrow_mut().push((name.to_string(), false, bytes.to_vec())))), - ..Default::default() +/// Installs the hosted file service through the app's framework harness. +fn host_app(fail: bool) -> (egui_kittest::Harness<'static, SlideApp>, Got) { + let files = if fail { + ScriptedFiles::answering([Picked::Failed("the page is gone".into())]).in_browser().hosted() + } else { + ScriptedFiles::new().in_browser().hosted().saving_suggested() }; - // Host mode starts as the web shell starts it: an empty presentation for the page's file. - // P3(shell-w6): sh.A2 - let mut app = SlideApp::new_base(Session::new(), services); - app.start_for_host().unwrap(); - (app, got) + host_app_with(files) +} + +fn host_app_with(files: ScriptedFiles) -> (egui_kittest::Harness<'static, SlideApp>, Got) { + let files = Arc::new(files); + let installed = files.clone(); + let mut h = crate::test_harness::harness_with(Session::new(), Services::default(), egui_kittest::Harness::builder(), move |platform| { + platform.host = platform.host.with_files(installed) + }); + h.state_mut().start_for_host().unwrap(); + (h, files) } /// A .pptx with `slides` slides, as the page would send it. @@ -51,7 +49,7 @@ fn edit(app: &mut SlideApp) { } fn calls(got: &Got) -> Vec<(String, bool)> { - got.borrow().iter().map(|(n, s, _)| (n.clone(), *s)).collect() + got.requests().into_iter().map(|r| (r.file_name.unwrap_or_default(), r.save_as)).collect() } fn path(app: &SlideApp) -> Option { @@ -59,25 +57,26 @@ fn path(app: &SlideApp) -> Option { } /// The bug this prevents: Save of a .pptx the page sent came back as `.deckcraft`. Save -/// now hands the page the opened file under its own name and format, not as a new file; Save As +/// hands the page the opened file under its own name and format; Save As /// says it is a new file and becomes the file the next Save writes. #[test] fn host_saves_go_back_to_the_opened_file() { - let (mut app, got) = host_app(false); + let (mut h, got) = host_app(false); + let app = h.state_mut(); app.open_from_host(Some("Lecture 3.pptx"), &pptx(2)); assert_eq!(app.session.documents().len(), 1, "the untouched blank presentation gave way"); - edit(&mut app); + edit(app); app.save(); assert!(!app.session.active().unwrap().is_dirty()); - edit(&mut app); + edit(app); app.save_as_dialog("deckcraft"); assert!(!app.session.active().unwrap().is_dirty()); - edit(&mut app); + edit(app); app.save(); let names = [("Lecture 3.pptx", false), ("Lecture 3.deckcraft", true), ("Lecture 3.deckcraft", false)]; assert_eq!(calls(&got), names.map(|(n, s)| (n.to_string(), s))); // The first save is a .pptx that reopens with the edit in it. - let first = got.borrow()[0].2.clone(); + let first = got.file(Path::new(names[0].0)).unwrap(); assert!(first.windows(20).any(|w| w == b"ppt/presentation.xml"), "Save writes PowerPoint, not .deckcraft"); let reopened = deckcraft_engine::cmd::file::loaded_file("Lecture 3.pptx", &first).unwrap(); assert_eq!(reopened.doc.slides.len(), 3); @@ -87,11 +86,12 @@ fn host_saves_go_back_to_the_opened_file() { /// file of the same name. The next Save goes back to it. #[test] fn host_save_of_an_untitled_presentation_is_save_as() { - let (mut app, got) = host_app(false); + let (mut h, got) = host_app(false); + let app = h.state_mut(); let name = format!("{}.deckcraft", app.session.active().unwrap().title()); - edit(&mut app); + edit(app); app.save(); - edit(&mut app); + edit(app); app.save(); assert_eq!(calls(&got), [(name.clone(), true), (name, false)]); } @@ -100,8 +100,8 @@ fn host_save_of_an_untitled_presentation_is_save_as() { /// its name isn't one the page holds: Save makes a new file. #[test] fn a_file_the_page_never_sent_saves_as_a_new_file() { - let (mut app, got) = host_app(false); - // P3(shell-w6): sh.A23 + let (mut h, got) = host_app(false); + let app = h.state_mut(); app.open_or_insert_bytes("dropped.pptx", pptx(1)); app.save(); assert_eq!(calls(&got), [("dropped.deckcraft".to_string(), true)]); @@ -111,22 +111,24 @@ fn a_file_the_page_never_sent_saves_as_a_new_file() { /// presentation keeps its own file and its unsaved changes. #[test] fn host_exports_and_print_are_copies() { - let (mut app, got) = host_app(false); + let (mut h, got) = host_app(false); + let app = h.state_mut(); app.open_from_host(Some("deck.pptx"), &pptx(1)); - edit(&mut app); + edit(app); assert!(app.export_as("pdf", json!({}))); assert!(app.print_pdf(json!({}))); assert_eq!(calls(&got), [("deck.pdf".to_string(), false), ("deck.pdf".to_string(), false)]); assert!(app.session.active().unwrap().is_dirty()); - assert_eq!(path(&app).as_deref(), Some("deck.pptx")); + assert_eq!(path(app).as_deref(), Some("deck.pptx")); } /// The page not getting the file is a failed save: the presentation keeps its changes. #[test] fn a_host_save_that_fails_leaves_the_presentation_unsaved() { - let (mut app, _) = host_app(true); + let (mut h, _) = host_app(true); + let app = h.state_mut(); app.open_from_host(Some("deck.pptx"), &pptx(1)); - edit(&mut app); + edit(app); app.save(); assert!(app.session.active().unwrap().is_dirty()); assert!(app.status.as_ref().is_some_and(|(m, _)| m.contains("Couldn't save deck.pptx"))); @@ -135,11 +137,12 @@ fn a_host_save_that_fails_leaves_the_presentation_unsaved() { /// Only an untouched start presentation gives way: one with changes stays open beside the file. #[test] fn an_edited_start_presentation_stays_open() { - let (mut app, _) = host_app(false); - edit(&mut app); + let (mut h, _) = host_app(false); + let app = h.state_mut(); + edit(app); app.open_from_host(Some("deck.pptx"), &pptx(1)); assert_eq!(app.session.documents().len(), 2); - assert_eq!(path(&app).as_deref(), Some("deck.pptx")); + assert_eq!(path(app).as_deref(), Some("deck.pptx")); } /// Only the first file from the page takes the start presentation's place. The bug this @@ -147,21 +150,23 @@ fn an_edited_start_presentation_stays_open() { /// is, so the page's next file closed it. #[test] fn only_the_first_file_from_the_page_replaces_the_start_presentation() { - let (mut app, _) = host_app(false); + let (mut h, _) = host_app(false); + let app = h.state_mut(); app.open_from_host(None, &pptx(2)); app.open_from_host(Some("deck.pptx"), &pptx(3)); let slides: Vec = app.session.documents().iter().map(|d| d.doc.slides.len()).collect(); assert_eq!(slides, [2, 3], "the file sent without a name stays open beside the next one"); - assert_eq!(path(&app).as_deref(), Some("deck.pptx")); + assert_eq!(path(app).as_deref(), Some("deck.pptx")); } /// The command palette runs `file.save` by id. With a file of its own the engine would write to /// that path, which a browser can't; in host mode it goes to the page like Ctrl+S. #[test] fn palette_save_goes_to_the_page() { - let (mut app, got) = host_app(false); + let (mut h, got) = host_app(false); + let app = h.state_mut(); app.open_from_host(Some("deck.pptx"), &pptx(1)); - edit(&mut app); + edit(app); let r = app.run("file.save", json!({})).unwrap(); assert_eq!(r["path"], "deck.pptx"); assert_eq!(calls(&got), [("deck.pptx".to_string(), false)]); @@ -173,11 +178,12 @@ fn palette_save_goes_to_the_page() { #[test] fn a_file_sent_without_a_presentation_name_saves_as_a_new_file() { for (name, saved) in [(None, "Presentation.deckcraft"), (Some("Talk"), "Talk.deckcraft")] { - let (mut app, got) = host_app(false); + let (mut h, got) = host_app(false); + let app = h.state_mut(); app.open_from_host(name, &pptx(2)); assert_eq!(app.session.documents().len(), 1, "{name:?}"); assert_eq!(app.session.active().unwrap().doc.slides.len(), 2, "{name:?}"); - assert_eq!(path(&app), None, "{name:?}"); + assert_eq!(path(app), None, "{name:?}"); app.save(); assert_eq!(calls(&got), [(saved.to_string(), true)], "{name:?}"); } @@ -187,11 +193,12 @@ fn a_file_sent_without_a_presentation_name_saves_as_a_new_file() { /// desktop: the blank start presentation gives way, and Save is a new file. #[test] fn an_outline_from_the_page_opens_as_a_new_presentation() { - let (mut app, got) = host_app(false); + let (mut h, got) = host_app(false); + let app = h.state_mut(); app.open_from_host(Some("notes.md"), b"# One\n\n# Two\n\n# Three\n"); assert_eq!(app.session.documents().len(), 1); assert_eq!(app.session.active().unwrap().doc.slides.len(), 3); - assert_eq!(path(&app), None); + assert_eq!(path(app), None); app.save(); assert_eq!(calls(&got), [("notes.deckcraft".to_string(), true)]); } @@ -206,10 +213,51 @@ fn a_damaged_file_from_the_page_saves_as_a_new_repaired_file() { // Pictures are stored as they are, so flipping a byte breaks the entry's CRC. let at = bad.windows(13).position(|w| w == b"PICTURE-BYTES").unwrap(); bad[at] ^= 0xff; - let (mut app, got) = host_app(false); + let (mut h, got) = host_app(false); + let app = h.state_mut(); app.open_from_host(Some("talk.deckcraft"), &bad); - assert_eq!(path(&app), None); + assert_eq!(path(app), None); assert!(app.session.active().unwrap().title().ends_with("(Repaired)")); app.save(); assert_eq!(calls(&got), [("talk (Repaired).deckcraft".to_string(), true)]); } + +/// A late acknowledgement records the bytes sent, preserving edits made while it was pending. +#[test] +fn a_delayed_save_records_its_snapshot_and_keeps_later_edits_dirty() { + let (mut h, files) = host_app_with(ScriptedFiles::held().in_browser().hosted()); + let app = h.state_mut(); + let name = "deck.pptx"; + app.open_from_host(Some(name), &pptx(1)); + app.session.execute("slide.new", &json!({})).unwrap(); + let uid = app.session.active().unwrap().uid; + let serialized = app.session.active().unwrap().doc.clone(); + app.save(); + let ticket = app.pending_files.last().unwrap().ticket; + app.session.execute("slide.new", &json!({})).unwrap(); + let edited = app.session.active().unwrap().doc.clone(); + app.session.execute("file.new", &json!({})).unwrap(); + let viewing = app.session.active().unwrap().uid; + files.answer_to(ticket, Picked::Saved { path: name.into(), file_type: None }); + app.take_file_answers(); + app.take_file_answers(); + assert_eq!(app.session.active().unwrap().uid, viewing); + let original = app.session.documents().iter().find(|d| d.uid == uid).unwrap(); + assert!(original.is_dirty()); + assert!(Arc::ptr_eq(&original.doc, &edited)); + assert!(Arc::ptr_eq(&original.saved_doc, &serialized)); + let written = files.file(Path::new(name)).unwrap(); + let reopened = deckcraft_engine::cmd::file::loaded_file(name, &written).unwrap(); + assert_eq!(reopened.doc.slides.len(), serialized.slides.len()); + assert!(reopened.doc.slides.len() < original.doc.slides.len()); + let index = app.session.documents().iter().position(|d| d.uid == uid).unwrap(); + app.session.set_active(index); + app.save(); + let ticket = app.pending_files.last().unwrap().ticket; + files.answer_to(ticket, Picked::Saved { path: name.into(), file_type: None }); + app.take_file_answers(); + assert!(!app.session.active().unwrap().is_dirty()); + let written = files.file(Path::new(name)).unwrap(); + let reopened = deckcraft_engine::cmd::file::loaded_file(name, &written).unwrap(); + assert_eq!(reopened.doc.slides.len(), edited.slides.len()); +} diff --git a/crates/ui-egui/src/inbox_tests.rs b/crates/ui-egui/src/inbox_tests.rs index 1e90b0714..0deac7597 100644 --- a/crates/ui-egui/src/inbox_tests.rs +++ b/crates/ui-egui/src/inbox_tests.rs @@ -1,12 +1,14 @@ //! #414: a browser file pick finishes on the document, slide and operation that started it. #![allow(clippy::unwrap_used, clippy::expect_used)] -use std::sync::{Arc, Mutex}; +use std::sync::Arc; + +use craft::host::{PickId, Picked, ScriptedFiles}; use deckcraft_model::ShapeKind; use serde_json::json; -use super::{Inbox, InboxEvent, InboxFile, Services, SlideApp}; +use super::{Services, SlideApp}; use crate::Session; fn png() -> Vec { @@ -34,23 +36,17 @@ fn wav() -> Vec { b } -fn setup() -> (SlideApp, Inbox, Arc>>) { - let inbox: Inbox = Inbox::default(); - let started = Arc::new(Mutex::new(Vec::new())); - let record = started.clone(); - let services = Services { - inbox: Some(inbox.clone()), - open_async: Some(Box::new(move |purpose, id| { - record.lock().expect("request log").push((purpose.to_string(), id)); - })), - ..Default::default() - }; - // P3(shell-w6): sh.A2 - (SlideApp::new_base(Session::with_new(), services), inbox, started) +fn setup() -> (egui_kittest::Harness<'static, SlideApp>, Arc) { + let files = Arc::new(ScriptedFiles::held()); + let installed = files.clone(); + let h = crate::test_harness::harness_with(Session::with_new(), Services::default(), egui_kittest::Harness::builder(), move |platform| { + platform.host = platform.host.with_files(installed) + }); + (h, files) } -fn deliver(inbox: &Inbox, id: u64, name: &str, bytes: Vec) { - inbox.lock().expect("inbox").push(InboxEvent::File(InboxFile { id, name: name.into(), bytes })); +fn deliver(files: &ScriptedFiles, ticket: PickId, name: &str, bytes: Vec) { + files.answer_to(ticket, Picked::Contents(vec![(name.into(), bytes)])); } fn pictures(app: &SlideApp, doc: u64, slide: deckcraft_model::SlideId) -> usize { @@ -69,7 +65,8 @@ fn audios(app: &SlideApp, doc: u64, slide: deckcraft_model::SlideId) -> usize { /// Each file uses the operation that was requested and lands on the slide that asked. #[test] fn late_picker_files_keep_their_document_slide_and_operation() { - let (mut app, inbox, started) = setup(); + let (mut h, files) = setup(); + let app = h.state_mut(); let uid_a = app.session.active().unwrap().uid; let slide0 = app.session.active().unwrap().current_slide().unwrap().id; app.session.execute("slide.new", &json!({})).unwrap(); @@ -89,35 +86,37 @@ fn late_picker_files_keep_their_document_slide_and_operation() { // A video was requested on B. Delivering a PNG must not insert a picture anywhere. app.pick_and_insert("video", "insert.video"); - let log = started.lock().expect("request log").clone(); - assert_eq!(log.iter().map(|(p, _)| p.as_str()).collect::>(), vec!["audio", "picture", "open", "video"]); - let audio_id = log[0].1; - let picture_id = log[1].1; - let outline_id = log[2].1; - let video_id = log[3].1; + let purposes: Vec = files.requests().into_iter().map(|r| r.purpose).collect(); + assert_eq!(purposes, ["audio", "picture", "document", "video"]); + let audio_id = app.pending_files[0].ticket; + let picture_id = app.pending_files[1].ticket; + let outline_id = app.pending_files[2].ticket; + let video_id = app.pending_files[3].ticket; // The video request completes first, while B is still current. A PNG must not become a picture. - deliver(&inbox, video_id, "clip.mp4", png()); - app.drain_inbox(); + deliver(&files, video_id, "clip.mp4", png()); + app.take_file_answers(); let status = app.status.as_ref().map(|(t, _)| t.clone()).unwrap_or_default(); assert!(status.contains("not a supported video") || status.contains("no video"), "{status}"); assert_eq!(app.session.active().unwrap().doc.slides[0].shapes.len(), shapes_b); // The earlier picks then finish in reverse order. - deliver(&inbox, outline_id, "talk.md", b"Brought Later\n".to_vec()); - deliver(&inbox, picture_id, "shot.png", png()); - deliver(&inbox, audio_id, "tone.wav", wav()); - app.drain_inbox(); + deliver(&files, outline_id, "talk.md", b"Brought Later\n".to_vec()); + app.take_file_answers(); + deliver(&files, picture_id, "shot.png", png()); + app.take_file_answers(); + deliver(&files, audio_id, "tone.wav", wav()); + app.take_file_answers(); assert_eq!(app.session.active().unwrap().uid, uid_b, "the view stays on the document the user switched to"); assert_eq!(app.session.active().unwrap().doc.slides[0].shapes.len(), shapes_b, "the video request must not insert the PNG here"); - assert_eq!(pictures(&app, uid_b, app.session.documents().iter().find(|d| d.uid == uid_b).unwrap().doc.slides[0].id), 0); + assert_eq!(pictures(app, uid_b, app.session.documents().iter().find(|d| d.uid == uid_b).unwrap().doc.slides[0].id), 0); let status = app.status.as_ref().map(|(t, _)| t.clone()).unwrap_or_default(); - assert_eq!(pictures(&app, uid_a, slide0), 1, "{status}"); - assert_eq!(pictures(&app, uid_a, slide1), 0); - assert_eq!(audios(&app, uid_a, slide1), 1); - assert_eq!(audios(&app, uid_a, slide0), 0); + assert_eq!(pictures(app, uid_a, slide0), 1, "{status}"); + assert_eq!(pictures(app, uid_a, slide1), 0); + assert_eq!(audios(app, uid_a, slide1), 1); + assert_eq!(audios(app, uid_a, slide0), 0); let a = app.session.documents().iter().find(|d| d.uid == uid_a).unwrap(); assert!(a.doc.slides.iter().any(|s| s.title() == "Brought Later"), "the outline stays on the document that opened it"); assert_eq!(a.doc.slides.len(), 3); @@ -129,25 +128,29 @@ fn late_picker_files_keep_their_document_slide_and_operation() { /// it into whatever is open now. #[test] fn a_closed_or_cancelled_request_does_not_insert_into_the_active_document() { - let (mut app, inbox, started) = setup(); + let (mut h, files) = setup(); + let app = h.state_mut(); let slide = app.session.active().unwrap().current_slide().unwrap().id; app.pick_and_insert("picture", "insert.picture"); app.session.execute("slide.new", &json!({})).unwrap(); let kept = app.session.active().unwrap().current_slide().unwrap().id; app.session.execute("slide.delete", &json!({"ids": [slide.0]})).unwrap(); app.pick_and_insert("picture", "insert.picture"); - let log = started.lock().expect("request log").clone(); - let deleted_slide = log[0].1; - let dismiss = log[1].1; + let deleted_slide = app.pending_files[0].ticket; + let dismiss = app.pending_files[1].ticket; + files.answer_to(dismiss, Picked::Cancelled); + app.take_file_answers(); + deliver(&files, dismiss, "late.png", png()); + app.take_file_answers(); + assert_eq!(pictures(app, app.session.active().unwrap().uid, kept), 0, "a file arriving after cancellation is not inserted"); - inbox.lock().expect("inbox").push(InboxEvent::Cancelled { id: dismiss }); - deliver(&inbox, dismiss, "late.png", png()); - deliver(&inbox, deleted_slide, "gone.png", png()); - // An id that was never started must not insert either. - deliver(&inbox, 999, "stray.png", png()); - app.drain_inbox(); + deliver(&files, deleted_slide, "gone.png", png()); + // An unknown ticket has no operation or captured document to apply. + deliver(&files, PickId(999), "stray.png", png()); + app.take_file_answers(); + app.take_file_answers(); - assert_eq!(pictures(&app, app.session.active().unwrap().uid, kept), 0); + assert_eq!(pictures(app, app.session.active().unwrap().uid, kept), 0); let status = app.status.as_ref().map(|(t, _)| t.as_str()).unwrap_or(""); assert!(status.contains("deleted"), "{status}"); @@ -156,34 +159,16 @@ fn a_closed_or_cancelled_request_does_not_insert_into_the_active_document() { // The deleted-slide request was already consumed. Start another and close before it arrives. let closed = app.session.active().unwrap().uid; app.pick_and_insert("audio", "insert.audio"); - let audio_id = started.lock().expect("request log").last().unwrap().1; + let audio_id = app.pending_files.last().unwrap().ticket; app.session.execute("file.close", &json!({})).unwrap(); app.session.execute("file.new", &json!({})).unwrap(); let other = app.session.active().unwrap().uid; assert_ne!(closed, other); - deliver(&inbox, audio_id, "tone.wav", wav()); - app.drain_inbox(); + deliver(&files, audio_id, "tone.wav", wav()); + app.take_file_answers(); let st = app.session.documents().iter().find(|d| d.uid == other).unwrap(); let n = st.doc.slides.iter().flat_map(|s| s.shapes.iter()).filter(|s| matches!(s.kind, ShapeKind::Media(_))).count(); assert_eq!(n, 0, "a file for a closed presentation is not inserted into the one now open"); let status = app.status.as_ref().map(|(t, _)| t.as_str()).unwrap_or(""); assert!(status.contains("closed"), "{status}"); } - -/// A drop is bound to the slide under the pointer at drop time, not the slide current when -/// the bytes have been read. -#[test] -fn a_dropped_file_stays_on_the_slide_it_was_dropped_on() { - let (mut app, inbox, _) = setup(); - let uid = app.session.active().unwrap().uid; - let slide0 = app.session.active().unwrap().current_slide().unwrap().id; - let id = app.begin_external_file("drop"); - app.session.execute("slide.new", &json!({})).unwrap(); - let slide1 = app.session.active().unwrap().current_slide().unwrap().id; - deliver(&inbox, id, "shot.png", png()); - app.drain_inbox(); - assert_eq!(app.session.active().unwrap().current_slide().unwrap().id, slide1, "the view stays on the slide the user moved to"); - let status = app.status.as_ref().map(|(t, _)| t.clone()).unwrap_or_default(); - assert_eq!(pictures(&app, uid, slide0), 1, "{status}"); - assert_eq!(pictures(&app, uid, slide1), 0); -}