Skip to content

Commit c7a4930

Browse files
UI: open presentations in the background with a progress window (#350)
Opening from the file picker or the Backstage recent list read and parsed the file on the UI thread, so a large PPTX froze the window. The read now runs on a thread (engine: read_presentation_file / add_presentation_file), and a modal shows the file name, elapsed time and Cancel; Escape cancels too. A cancelled read is dropped when it finishes. Scripted opens (control, MCP, CLI) and the web build stay synchronous. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 457406a commit c7a4930

5 files changed

Lines changed: 245 additions & 9 deletions

File tree

‎crates/engine/src/cmd/file.rs‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,13 +94,36 @@ pub fn add_opened(s: &mut Session, name: &str, path: Option<String>, p: Presenta
9494
s.add_document(st)
9595
}
9696

97+
/// A presentation read from disk, not yet added to a session: [`read_presentation_file`] needs no
98+
/// session, so a host can run it on a background thread and add the result with
99+
/// [`add_presentation_file`].
100+
#[derive(Debug)]
101+
pub struct LoadedFile {
102+
pub path: String,
103+
pub doc: Presentation,
104+
/// A native or PPTX file (saving goes back to it); an outline import has no file to save to.
105+
pub native: bool,
106+
}
107+
108+
/// Read and parse the presentation at `path`.
97109
#[cfg(not(target_arch = "wasm32"))]
98-
fn open(s: &mut Session, p: &Value) -> Result<Value> {
99-
let path = str_param(p, "path").ok_or_else(|| bad("file.open", "missing `path`"))?;
110+
pub fn read_presentation_file(path: &str) -> Result<LoadedFile> {
100111
let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
101112
let doc = open_presentation(path, &bytes)?;
102113
let native = deckcraft_format::sniff(&bytes) || deckcraft_pptx::sniff(&bytes);
103-
let i = add_opened(s, path, native.then(|| path.to_string()), doc);
114+
Ok(LoadedFile { path: path.to_string(), doc, native })
115+
}
116+
117+
/// Add a presentation read by [`read_presentation_file`] as the active document.
118+
pub fn add_presentation_file(s: &mut Session, f: LoadedFile) -> usize {
119+
let LoadedFile { path, doc, native } = f;
120+
add_opened(s, &path, native.then(|| path.clone()), doc)
121+
}
122+
123+
#[cfg(not(target_arch = "wasm32"))]
124+
fn open(s: &mut Session, p: &Value) -> Result<Value> {
125+
let path = str_param(p, "path").ok_or_else(|| bad("file.open", "missing `path`"))?;
126+
let i = add_presentation_file(s, read_presentation_file(path)?);
104127
let st = s.doc()?;
105128
Ok(json!({"document": i, "slides": st.doc.slides.len(), "missingFonts": st.missing_fonts}))
106129
}

‎crates/ui-egui/src/backstage.rs‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -568,10 +568,8 @@ fn recent_list(app: &mut SlideApp, ui: &mut Ui, query: &str, limit: usize) {
568568
icons::paint(p, Rect::from_center_size(pos2(rect.left() + 20.0, rect.center().y), vec2(22.0, 22.0)), Icon::Slide, t.text, false);
569569
p.text(pos2(rect.left() + 44.0, rect.center().y - 8.0), Align2::LEFT_CENTER, &name, theme::font(13.0), t.text);
570570
p.text(pos2(rect.left() + 44.0, rect.center().y + 9.0), Align2::LEFT_CENTER, &folder, theme::font(11.0), t.text_dim);
571-
if resp.on_hover_text(&path).clicked()
572-
&& let Err(e) = app.open_path(&path)
573-
{
574-
app.set_status(e);
571+
if resp.on_hover_text(&path).clicked() {
572+
app.open_path_in_background(&path);
575573
}
576574
}
577575
}

‎crates/ui-egui/src/backstage_tests.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,15 @@ fn open_lists_recent_files_and_opens_one() {
217217
h.run_steps(2);
218218
assert!(h.query_by_label("Other.pptx").is_none(), "the search box filters by name");
219219
h.get_by_label("Quarterly review.pptx").click();
220+
h.run_steps(1);
221+
// The file is read in the background (#350); its progress window shows meanwhile.
222+
for _ in 0..300 {
223+
if h.state().opening.is_none() {
224+
break;
225+
}
226+
std::thread::sleep(std::time::Duration::from_millis(10));
227+
h.run_steps(1);
228+
}
220229
h.run_steps(3);
221230
assert_eq!(h.state().session.documents().len(), 2);
222231
assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some(path.as_str()));

‎crates/ui-egui/src/lib.rs‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ pub mod fillui;
1515
pub mod icons;
1616
pub mod media;
1717
pub mod menus;
18+
pub mod opening;
1819
pub mod panes;
1920
pub mod ribbon;
2021
pub mod selpane;
@@ -188,6 +189,8 @@ pub struct SlideApp {
188189
/// Audio/video playback (editor control bar, slide show, `media.*` commands).
189190
pub media: media::MediaHost,
190191
pub status: Option<(String, f64)>,
192+
/// A presentation being read in the background, with its progress window ([`opening`]).
193+
pub opening: Option<opening::Opening>,
191194
/// A brief notice over the bottom of the window (missing fonts on opening a file).
192195
pub toast: Option<toast::Toast>,
193196
/// Documents (by uid) whose missing fonts have been mentioned.
@@ -242,6 +245,7 @@ impl SlideApp {
242245
show: None,
243246
media: media::MediaHost::new(audio_out),
244247
status: None,
248+
opening: None,
245249
toast: None,
246250
fonts_noted: Default::default(),
247251
perf: Perf { frame_ms: 0.0, render_ms: 0.0, fps: 0.0 },
@@ -564,7 +568,7 @@ impl SlideApp {
564568
fn pick_and_open(&mut self) {
565569
if let Some(pick) = self.services.pick_open.as_mut() {
566570
if let Some(path) = pick("open") {
567-
let _ = self.open_path(&path);
571+
self.open_path_in_background(&path);
568572
}
569573
} else if let Some(f) = self.services.open_async.as_mut() {
570574
f("open");
@@ -573,11 +577,16 @@ impl SlideApp {
573577

574578
pub fn open_path(&mut self, path: &str) -> Result<(), String> {
575579
self.session.execute("file.open", &json!({"path": path})).map_err(|e| e.to_string())?;
580+
self.note_recent(path);
581+
Ok(())
582+
}
583+
584+
/// A presentation was opened from `path`: first in the recent list, shown in Normal view.
585+
pub(crate) fn note_recent(&mut self, path: &str) {
576586
self.ui.recent.retain(|p| p != path);
577587
self.ui.recent.insert(0, path.to_string());
578588
self.ui.recent.truncate(12);
579589
self.ui.view = ViewMode::Normal;
580-
Ok(())
581590
}
582591

583592
fn pick_and_insert(&mut self, purpose: &str, cmd: &str) {
@@ -741,6 +750,7 @@ impl SlideApp {
741750
}
742751
self.last_time = now;
743752
self.drain_control(ctx);
753+
self.poll_opening();
744754
if self.fonts_ready {
745755
self.drain_inbox();
746756
}
@@ -935,6 +945,7 @@ impl SlideApp {
935945
let t0 = now_ms();
936946
let t = theme::Tokens::get(&ctx);
937947
self.tick_media(&ctx);
948+
self.opening_ui(&ctx);
938949
if self.show.is_some() {
939950
show::ui(self, ui);
940951
self.perf.frame_ms = now_ms() - t0;

‎crates/ui-egui/src/opening.rs‎

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
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) => {
75+
deckcraft_engine::cmd::file::add_presentation_file(&mut self.session, f);
76+
self.note_recent(&o.path);
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

Comments
 (0)