|
| 1 | +//! Opening a presentation in the background (#350): reading and parsing a large PPTX no longer |
| 2 | +//! freezes the window. A modal shows the file being opened and the time so far, and Cancel (or |
| 3 | +//! Escape) gives the window back at once; the abandoned read finishes on its thread and is dropped. |
| 4 | +
|
| 5 | +use crate::SlideApp; |
| 6 | +use deckcraft_engine::cmd::file::LoadedFile; |
| 7 | +use std::sync::mpsc::{Receiver, TryRecvError}; |
| 8 | + |
| 9 | +/// A presentation being read on a background thread. |
| 10 | +pub struct Opening { |
| 11 | + pub path: String, |
| 12 | + pub started_ms: f64, |
| 13 | + rx: Receiver<Result<LoadedFile, String>>, |
| 14 | +} |
| 15 | + |
| 16 | +impl Opening { |
| 17 | + /// The file name shown in the window. |
| 18 | + pub fn name(&self) -> String { |
| 19 | + std::path::Path::new(&self.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| self.path.clone()) |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +impl SlideApp { |
| 24 | + /// Open `path` without blocking the UI: the file is read on a thread and the progress window |
| 25 | + /// shows until it arrives. Without threads (the web build) it opens at once. |
| 26 | + pub fn open_path_in_background(&mut self, path: &str) { |
| 27 | + if let Some(o) = &self.opening { |
| 28 | + let name = o.name(); |
| 29 | + self.set_status(format!("Still opening {name}")); |
| 30 | + return; |
| 31 | + } |
| 32 | + #[cfg(target_arch = "wasm32")] |
| 33 | + { |
| 34 | + if let Err(e) = self.open_path(path) { |
| 35 | + self.set_status(e); |
| 36 | + } |
| 37 | + } |
| 38 | + #[cfg(not(target_arch = "wasm32"))] |
| 39 | + { |
| 40 | + let (tx, rx) = std::sync::mpsc::channel(); |
| 41 | + let p = path.to_string(); |
| 42 | + let spawned = std::thread::Builder::new().name("deckcraft-open".into()).spawn(move || { |
| 43 | + let r = deckcraft_engine::cmd::file::read_presentation_file(&p).map_err(|e| e.to_string()); |
| 44 | + let _ = tx.send(r); |
| 45 | + }); |
| 46 | + match spawned { |
| 47 | + Ok(_) => self.opening = Some(Opening { path: path.to_string(), started_ms: crate::now_ms(), rx }), |
| 48 | + Err(_) => { |
| 49 | + if let Err(e) = self.open_path(path) { |
| 50 | + self.set_status(e); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /// Stop waiting for the file being opened; the presentation stays as it is. |
| 58 | + pub fn cancel_opening(&mut self) { |
| 59 | + if let Some(o) = self.opening.take() { |
| 60 | + self.set_status(format!("Stopped opening {}", o.name())); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + /// Take the background read's result when it has arrived. |
| 65 | + pub(crate) fn poll_opening(&mut self) { |
| 66 | + let Some(o) = &self.opening else { return }; |
| 67 | + let r = match o.rx.try_recv() { |
| 68 | + Ok(r) => r, |
| 69 | + Err(TryRecvError::Empty) => return, |
| 70 | + Err(TryRecvError::Disconnected) => Err(format!("{}: reading the file stopped unexpectedly", o.path)), |
| 71 | + }; |
| 72 | + let Some(o) = self.opening.take() else { return }; |
| 73 | + match r { |
| 74 | + Ok(f) => match deckcraft_engine::cmd::file::add_presentation_file(&mut self.session, f) { |
| 75 | + Ok(_) => self.note_recent(&o.path), |
| 76 | + Err(e) => self.set_status(e.to_string()), |
| 77 | + }, |
| 78 | + Err(e) => self.set_status(e), |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + /// The progress window over everything while a file opens. |
| 83 | + pub(crate) fn opening_ui(&mut self, ctx: &egui::Context) { |
| 84 | + let Some(o) = &self.opening else { return }; |
| 85 | + let name = o.name(); |
| 86 | + let secs = ((crate::now_ms() - o.started_ms) / 1000.0).max(0.0); |
| 87 | + let mut cancel = false; |
| 88 | + egui::Modal::new(egui::Id::new("deckcraft-opening")).show(ctx, |ui| { |
| 89 | + ui.set_width(320.0); |
| 90 | + ui.horizontal(|ui| { |
| 91 | + ui.add(egui::Spinner::new().size(18.0)); |
| 92 | + ui.label(format!("Opening {name}…")); |
| 93 | + }); |
| 94 | + ui.add_space(6.0); |
| 95 | + ui.weak(format!("Reading the file: {secs:.0} s")); |
| 96 | + ui.add_space(6.0); |
| 97 | + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { |
| 98 | + cancel = ui.button("Cancel").clicked(); |
| 99 | + }); |
| 100 | + }); |
| 101 | + if cancel || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { |
| 102 | + self.cancel_opening(); |
| 103 | + } |
| 104 | + ctx.request_repaint_after(std::time::Duration::from_millis(100)); |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +#[cfg(test)] |
| 109 | +mod tests { |
| 110 | + #![allow(clippy::unwrap_used, clippy::expect_used)] |
| 111 | + |
| 112 | + use super::*; |
| 113 | + use deckcraft_engine::Session; |
| 114 | + |
| 115 | + fn saved_deck(name: &str, slides: usize) -> String { |
| 116 | + let mut s = Session::with_new(); |
| 117 | + for _ in 1..slides { |
| 118 | + s.execute("slide.new", &serde_json::json!({})).unwrap(); |
| 119 | + } |
| 120 | + let path = std::env::temp_dir().join(format!("deckcraft-opening-{}-{name}.deckcraft", std::process::id())); |
| 121 | + let path = path.to_string_lossy().to_string(); |
| 122 | + s.execute("file.saveAs", &serde_json::json!({"path": path})).unwrap(); |
| 123 | + path |
| 124 | + } |
| 125 | + |
| 126 | + fn wait(app: &mut SlideApp) { |
| 127 | + for _ in 0..500 { |
| 128 | + app.poll_opening(); |
| 129 | + if app.opening.is_none() { |
| 130 | + return; |
| 131 | + } |
| 132 | + std::thread::sleep(std::time::Duration::from_millis(10)); |
| 133 | + } |
| 134 | + panic!("opening did not finish"); |
| 135 | + } |
| 136 | + |
| 137 | + #[test] |
| 138 | + fn opens_in_the_background_and_adds_the_document() { |
| 139 | + let path = saved_deck("ok", 3); |
| 140 | + let mut app = SlideApp::new(Session::new(), crate::Services::default()); |
| 141 | + app.open_path_in_background(&path); |
| 142 | + assert!(app.opening.is_some(), "the read runs on a thread"); |
| 143 | + wait(&mut app); |
| 144 | + assert_eq!(app.session.documents().len(), 1); |
| 145 | + assert_eq!(app.session.active().unwrap().doc.slides.len(), 3); |
| 146 | + assert_eq!(app.ui.recent.first(), Some(&path)); |
| 147 | + std::fs::remove_file(&path).ok(); |
| 148 | + } |
| 149 | + |
| 150 | + #[test] |
| 151 | + fn cancel_drops_the_result() { |
| 152 | + let path = saved_deck("cancel", 2); |
| 153 | + let mut app = SlideApp::new(Session::with_new(), crate::Services::default()); |
| 154 | + app.open_path_in_background(&path); |
| 155 | + app.cancel_opening(); |
| 156 | + assert!(app.opening.is_none()); |
| 157 | + std::thread::sleep(std::time::Duration::from_millis(200)); |
| 158 | + app.poll_opening(); |
| 159 | + assert_eq!(app.session.documents().len(), 1, "nothing is added after Cancel"); |
| 160 | + std::fs::remove_file(&path).ok(); |
| 161 | + } |
| 162 | + |
| 163 | + #[test] |
| 164 | + fn errors_show_in_the_status_bar_and_a_second_open_waits() { |
| 165 | + let mut app = SlideApp::new(Session::new(), crate::Services::default()); |
| 166 | + app.open_path_in_background("/nonexistent/deckcraft/missing.pptx"); |
| 167 | + app.open_path_in_background("/nonexistent/deckcraft/other.pptx"); |
| 168 | + assert!(app.status.as_ref().is_some_and(|(m, _)| m.starts_with("Still opening missing.pptx"))); |
| 169 | + wait(&mut app); |
| 170 | + assert!(app.session.documents().is_empty()); |
| 171 | + assert!(app.status.as_ref().is_some_and(|(m, _)| m.contains("missing.pptx")), "{:?}", app.status); |
| 172 | + } |
| 173 | + |
| 174 | + #[test] |
| 175 | + fn the_progress_window_shows_and_cancel_closes_it() { |
| 176 | + use egui_kittest::kittest::Queryable; |
| 177 | + let mut app = SlideApp::new(Session::with_new(), crate::Services::default()); |
| 178 | + // A read that never answers: the window stays until Cancel. |
| 179 | + let (_tx, rx) = std::sync::mpsc::channel(); |
| 180 | + app.opening = Some(Opening { path: "/decks/Big deck.pptx".into(), started_ms: crate::now_ms(), rx }); |
| 181 | + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state( |
| 182 | + |ui, app: &mut SlideApp| { |
| 183 | + app.logic(ui.ctx()); |
| 184 | + app.ui(ui); |
| 185 | + }, |
| 186 | + app, |
| 187 | + ); |
| 188 | + harness.run_steps(3); |
| 189 | + harness.get_by_label("Opening Big deck.pptx…"); |
| 190 | + harness.get_by_label("Cancel").click(); |
| 191 | + harness.run_steps(2); |
| 192 | + assert!(harness.state().opening.is_none()); |
| 193 | + assert_eq!(harness.state().session.documents().len(), 1); |
| 194 | + } |
| 195 | +} |
0 commit comments