diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 875311e3bc..516fba189e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -253,6 +253,18 @@ impl PdfCraftApp { // PLAN: assumed open_worker::queue(&Host, Wake) -> JobQueue (pdf-shell-w13). opens: open_worker::queue(&host, wake.clone()), #[cfg(not(target_arch = "wasm32"))] + combine_reads: JobQueue::new(host.jobs_shared().clone(), wake.clone(), QueueOptions { + lanes: 1, name: "pdfcraft-combine-read", order: craft::host::queue::QueueOrder::OldestFirst, + }), + #[cfg(not(target_arch = "wasm32"))] + combine_read_paths: Default::default(), + #[cfg(not(target_arch = "wasm32"))] + combine_read_active: None, + #[cfg(not(target_arch = "wasm32"))] + combine_read_batch: Vec::new(), + #[cfg(not(target_arch = "wasm32"))] + combine_read_token: 0, + #[cfg(not(target_arch = "wasm32"))] named_destinations: queue(&host, &wake, "pdfcraft-destinations"), #[cfg(not(target_arch = "wasm32"))] pending_destinations: Vec::new(), @@ -837,6 +849,7 @@ impl PdfCraftApp { #[cfg(not(target_arch = "wasm32"))] { self.poll_pending_opens(ctx); + self.poll_combine_reads(); self.poll_pending_destinations(); } self.check_restored_recent(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3a61684869..9156bd1547 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -494,6 +494,17 @@ pub struct PdfCraftApp { pub(crate) opens: Queue, #[cfg(not(target_arch = "wasm32"))] pending_opens: Vec, + /// Shell Combine reads, sequenced separately from normal document opens. + #[cfg(not(target_arch = "wasm32"))] + combine_reads: Queue)>, + #[cfg(not(target_arch = "wasm32"))] + combine_read_paths: std::collections::VecDeque<(String, bool)>, + #[cfg(not(target_arch = "wasm32"))] + combine_read_active: Option<(u64, bool)>, + #[cfg(not(target_arch = "wasm32"))] + combine_read_batch: Vec, + #[cfg(not(target_arch = "wasm32"))] + combine_read_token: u64, /// The open retrying a closed password prompt's file with its password: replies behind it /// wait for it. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/workflows/combine_ui/session.rs b/crates/ui-egui/src/workflows/combine_ui/session.rs index aee4ba0499..c32b65e878 100644 --- a/crates/ui-egui/src/workflows/combine_ui/session.rs +++ b/crates/ui-egui/src/workflows/combine_ui/session.rs @@ -279,6 +279,12 @@ impl PdfCraftApp { /// Close the Combine files tab and forget its list; the last document shows, if any. pub fn close_combine_tab(&mut self, ctx: &egui::Context) { let showing = self.combine_showing(); + #[cfg(not(target_arch = "wasm32"))] + { + self.combine_read_paths.clear(); + self.combine_read_batch.clear(); + self.combine_read_active = None; + } crate::combine_grid::release_thumbnails(ctx, &self.combine_tab); // (Revisions keep counting: a drag begun before can never match a list made after.) let revision = self.combine_tab.revision.wrapping_add(1); @@ -310,6 +316,10 @@ impl PdfCraftApp { /// Add files to the Combine files list, with what can be known about them up front. pub(crate) fn stage_combine_with(&mut self, files: Vec) { + self.stage_combine_with_focus(files, true); + } + + fn stage_combine_with_focus(&mut self, files: Vec, focus: bool) { let mut added = Vec::new(); for Incoming { name, bytes, modified, note, open_doc } in files { // Images and text files become PDFs as they join the list (#569): from then on they @@ -383,7 +393,9 @@ impl PdfCraftApp { } }); } - self.open_combine_tab(); + if focus { + self.open_combine_tab(); + } } /// Open Unlock…'s password dialog for `rows`. @@ -477,23 +489,44 @@ impl PdfCraftApp { prompt.activate = false; } self.open_combine_tab(); - // A file that can't be read is said and left out; the others still join. - let mut incoming = Vec::new(); - for path in paths.iter().map(std::path::Path::new) { - let name = path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()); - match std::fs::read(path) { - Ok(bytes) => { - let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok(); - incoming.push(Incoming { name, bytes: Arc::new(bytes), modified, note: None, open_doc: None }); - } - Err(e) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e.to_string())]), - } + let last = paths.len().saturating_sub(1); + self.combine_read_paths.extend(paths.iter().enumerate().map(|(i, path)| (path.clone(), i == last))); + self.start_next_combine_read(); + } + + #[cfg(not(target_arch = "wasm32"))] + fn start_next_combine_read(&mut self) { + if self.combine_read_active.is_some() { + return; } - if !incoming.is_empty() { - // Files handed over by the file manager keep the order they arrived in (the combined - // document follows it), not the sort a person last picked in the list. - self.combine_tab.sort = None; - self.stage_combine_with(incoming); + let Some((path, last)) = self.combine_read_paths.pop_front() else { return }; + self.combine_read_token = self.combine_read_token.wrapping_add(1); + let token = self.combine_read_token; + self.combine_read_active = Some((token, last)); + self.combine_reads.submit(token, craft::host::queue::Priority::VISIBLE, move |_| read_combine_path(&path)); + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn poll_combine_reads(&mut self) { + while let Some(done) = self.combine_reads.try_recv() { + // Closing the tab invalidates its outstanding work, including after a reopen. + let Some((token, last)) = self.combine_read_active else { continue }; + if token != done.key { + continue; + } + self.combine_read_active = None; + let (name, result) = done.result; + match result { + Ok(incoming) => self.combine_read_batch.push(incoming), + Err(e) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e)]), + } + if last && !self.combine_read_batch.is_empty() { + self.combine_tab.sort = None; + let batch = std::mem::take(&mut self.combine_read_batch); + // A completion belongs to this tab but must not bring it to the front. + self.stage_combine_with_focus(batch, false); + } + self.start_next_combine_read(); } } @@ -557,3 +590,43 @@ impl PdfCraftApp { } } } + +/// Read one shell-selected regular file on the host queue. The pre-open check avoids opening +/// devices and directories; the handle check also rejects a path replaced during the open. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn read_combine_path(path: &str) -> (String, Result) { + use std::io::Read as _; + let path = std::path::Path::new(path); + let name = path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()); + let read = || -> Result { + let meta = std::fs::metadata(path).map_err(|e| e.to_string())?; + if !meta.is_file() { + return Err("not a regular file".into()); + } + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.custom_flags(if cfg!(target_os = "linux") { 0o4000 } else { 0x4 }); + } + let mut file = options.open(path).map_err(|e| e.to_string())?; + let meta = file.metadata().map_err(|e| e.to_string())?; + if !meta.is_file() { + return Err("not a regular file".into()); + } + let mut bytes = Vec::new(); + let mut chunk = [0; 64 * 1024]; + loop { + let count = file.read(&mut chunk).map_err(|e| e.to_string())?; + if count == 0 { + break; + } + bytes.try_reserve(count).map_err(|e| e.to_string())?; + bytes.extend_from_slice(&chunk[..count]); + } + Ok(Incoming { name: name.clone(), bytes: Arc::new(bytes), modified: meta.modified().ok(), note: None, open_doc: None }) + }; + let result = read(); + (name, result) +} diff --git a/crates/ui-egui/src/workflows/combine_ui/tests.rs b/crates/ui-egui/src/workflows/combine_ui/tests.rs index e8e37e406a..6810685e0e 100644 --- a/crates/ui-egui/src/workflows/combine_ui/tests.rs +++ b/crates/ui-egui/src/workflows/combine_ui/tests.rs @@ -266,8 +266,42 @@ fn files_from_the_file_manager_keep_their_arrival_order_over_a_chosen_sort() { let mut app = PdfCraftApp::for_unit_tests(); app.combine_tab.sort = Some((SortKey::Name, true)); app.combine_paths(&egui::Context::default(), &paths); + let deadline = std::time::Instant::now() + Duration::from_secs(30); + while app.combine_draft.len() < 2 && std::time::Instant::now() < deadline { + app.poll_combine_reads(); + std::thread::sleep(Duration::from_millis(5)); + } let names: Vec<&str> = app.combine_draft.iter().map(|f| f.name.as_str()).collect(); assert_eq!(names, ["b.pdf", "a.pdf"], "arrival order, not name order"); assert_eq!(app.combine_tab.sort, None); std::fs::remove_dir_all(&dir).ok(); } + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn shell_combine_reads_refuse_directories_and_keep_tab_lifecycle() { + let dir = tempfile::tempdir().unwrap(); + let first = dir.path().join("first.pdf"); + let second = dir.path().join("second.pdf"); + std::fs::write(&first, locked()).unwrap(); + std::fs::write(&second, locked()).unwrap(); + assert!(super::session::read_combine_path(&dir.path().to_string_lossy()).1.is_err()); + assert!(super::session::read_combine_path(&dir.path().join("missing.pdf").to_string_lossy()).1.is_err()); + + let ctx = egui::Context::default(); + let mut app = PdfCraftApp::for_unit_tests(); + app.combine_paths(&ctx, &[first.to_string_lossy().into_owned()]); + app.close_combine_tab(&ctx); + app.combine_paths(&ctx, &[dir.path().to_string_lossy().into_owned(), second.to_string_lossy().into_owned()]); + // Switching away while the read runs must not let completion steal focus. + app.combine_tab.focused = false; + let deadline = std::time::Instant::now() + Duration::from_secs(30); + while (app.combine_read_active.is_some() || !app.combine_read_paths.is_empty()) && std::time::Instant::now() < deadline { + app.poll_combine_reads(); + std::thread::sleep(Duration::from_millis(5)); + } + assert!(app.combine_read_active.is_none()); + let names: Vec<&str> = app.combine_draft.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["second.pdf"], "the closed tab's pending file is not restored"); + assert!(!app.combine_showing(), "a background result does not focus Combine"); +} diff --git a/crates/ui-egui/tests/it/ui.rs b/crates/ui-egui/tests/it/ui.rs index d26249c359..4378daec90 100644 --- a/crates/ui-egui/tests/it/ui.rs +++ b/crates/ui-egui/tests/it/ui.rs @@ -1427,7 +1427,7 @@ fn files_to_combine_from_the_operating_system() { assert!(h.state().combine_showing(), "the Combine files tab shows"); assert!(h.state().views.is_empty(), "nothing opens as a document"); sender.open_for(vec![paths[1].clone()], "combine"); - h.run_steps(3); + support::wait_until(&mut h, "both files to combine", |app| app.combine_draft.len() == 2); let _ = std::fs::remove_dir_all(&dir); let names: Vec<_> = h.state().combine_draft.iter().map(|f| f.name.clone()).collect(); assert_eq!(names, ["one.pdf", "two.pdf"], "each launch's file joins the list, in order");