diff --git a/crates/ui-egui/examples/shot.rs b/crates/ui-egui/examples/shot.rs index ac5a506d26..7214c661cd 100644 --- a/crates/ui-egui/examples/shot.rs +++ b/crates/ui-egui/examples/shot.rs @@ -47,7 +47,6 @@ fn load_ocr_verify(app: &mut PdfCraftApp) -> Result<(), String> { app.ocr_draft.engine = settings.engine; app.ocr_draft.strategy = settings.strategy; app.open_bytes("scan.pdf", None, scan).map_err(|e| e.to_string())?; - app.run_inline = true; if !app.execute("ocr.correct") { return Err("ocr.correct did not run".into()); } diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 81c65a2b03..1f09219697 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1,5 +1,11 @@ use super::*; -use crate::file_filter::AddFilterAnyCase as _; +use craft::docpath::names::safe_file_name; +#[cfg(not(target_arch = "wasm32"))] +use craft::host::queue::Priority; +use craft::host::{FileFilter, PickRequest, Picked}; +#[cfg(not(target_arch = "wasm32"))] +use craft::platform::watch::FileStamp; +use craft::ui::patterns::form_dialogs::{PasswordDialog, PasswordPurpose}; /// Whether an open's reply asks for a password: the file is encrypted and none, or a wrong one, /// was given. @@ -12,13 +18,21 @@ fn asks_for_password(kind: &open_worker::ResultKind) -> bool { ) } -/// Whether `a` and `b` name the same file: equal, or equal once made absolute against the -/// current directory (links are not resolved, as in `last_session`). -pub(crate) fn same_file(a: &str, b: &str) -> bool { - a == b || matches!((std::path::absolute(a), std::path::absolute(b)), (Ok(x), Ok(y)) if x == y) -} - impl PdfCraftApp { + /// Shows `panel` as the right panel, or closes the one showing for `None`. + fn set_right(&mut self, panel: Option) { + use crate::side_panels::{PanelId, set_panel_visible}; + // PLAN: assumed `PanelId::from(RightPanel)` (pdf-chrome-w13) + match panel { + Some(panel) => set_panel_visible(self, PanelId::from(panel), true), + None => { + if let Some(open) = self.right() { + set_panel_visible(self, PanelId::from(open), false); + } + } + } + } + /// Open a document the way it asks to be opened: navigation panel, layout, magnification, /// page and the place on it (Document Properties ▸ Initial View, `/OpenAction`). With Always /// use my default zoom and page layout on, the layout and magnification stay at the defaults @@ -31,13 +45,18 @@ impl PdfCraftApp { // (`/NonFullScreenPageMode`, Table 147), there when the prompt is declined or full // screen is left. let navigation = if v.full_screen { v.non_full_screen } else { v.navigation }; - if self.active == Some(index) && !self.right_panel_closed { - match navigation { - N::PageOnly => {} - N::Bookmarks => self.right = Some(RightPanel::Bookmarks), - N::Pages => self.right = Some(RightPanel::Pages), - N::Attachments => self.right = Some(RightPanel::Attachments), - N::Layers => self.right = Some(RightPanel::Layers), + // PLAN: `right_panel_closed()` is a read-only view assumed from pdf-chrome-w13 (L-136); canvas-w11's + // `view.view` setters below land with that set. + if self.active == Some(index) && !self.right_panel_closed() { + let panel = match navigation { + N::PageOnly => None, + N::Bookmarks => Some(RightPanel::Bookmarks), + N::Pages => Some(RightPanel::Pages), + N::Attachments => Some(RightPanel::Attachments), + N::Layers => Some(RightPanel::Layers), + }; + if panel.is_some() { + self.set_right(panel); } } let view = &mut self.views[index]; @@ -103,46 +122,19 @@ impl PdfCraftApp { self.try_open(name, path, std::sync::Arc::new(bytes), None, activate) } - /// Hand `request` to the background open worker (started on first use); the result arrives - /// later as a pending open, under the returned token. + /// Hand `request` to the open queue; the result arrives later as a pending open, under the + /// returned token. #[cfg(not(target_arch = "wasm32"))] - pub(crate) fn schedule_open(&mut self, request: OpenRequest) -> Result { - self.schedule_open_with_priority(request, false) - } - - #[cfg(not(target_arch = "wasm32"))] - pub(crate) fn schedule_open_priority(&mut self, request: OpenRequest) -> Result { - self.schedule_open_with_priority(request, true) - } - - #[cfg(not(target_arch = "wasm32"))] - fn schedule_open_with_priority(&mut self, request: OpenRequest, priority: bool) -> Result { - if self.open_worker.is_none() { - self.open_worker = Some( - open_worker::OpenWorker::new( - #[cfg(test)] - self.open_prepare_gate.clone(), - ) - .map_err(|e| format!("couldn't start the document-open worker: {e}"))?, - ); - } + pub(crate) fn schedule_open(&mut self, request: OpenRequest) -> u64 { let token = self.next_open_token.wrapping_add(1); - let worker = self.open_worker.as_ref().ok_or("the document-open worker is unavailable")?; - if let Some(ctx) = &self.ctx { - worker.set_context(ctx); - } + self.next_open_token = token; // A new document opens with the remembered Highlight fields, which its scripts read; the // session keeps the document in front's. - let context = self.session.open_context().with_highlight(self.view_defaults.highlight_fields); - let receiver = if priority { - worker.submit_priority(token, context, request.name.clone(), request.path.clone(), request.password, request.input)? - } else { - worker.submit(token, context, request.name.clone(), request.path.clone(), request.password, request.input)? - }; - self.next_open_token = token; + let context = self.session.open_context().with_highlight(self.highlight_fields); // PLAN: `highlight_fields` on the app (pdf-canvas-w8) + let job = open_worker::Job { context, name: request.name.clone(), path: request.path.clone(), password: request.password, input: request.input }; + self.opens.submit(token, request.priority, move |cancel| open_worker::run(job, cancel)); self.pending_opens.push(PendingOpen { token, - receiver, name: request.name, path: request.path, stamp: request.stamp, @@ -153,31 +145,18 @@ impl PdfCraftApp { display_override: None, ready: None, }); - Ok(token) - } - - /// How many opens may wait for the worker: its bound, less one place while a password prompt - /// is open, so the prompt's retry fits even before the worker has taken any of the others. - #[cfg(not(target_arch = "wasm32"))] - fn open_slots(&self) -> usize { - open_worker::MAX_QUEUED_OPENS - usize::from(self.password_prompt.is_some()) - } - - /// Hand waiting files to the worker, oldest first, while its queue has room. Every queued - /// job has a `pending_opens` entry, so fewer entries than [`Self::open_slots`] means room. - #[cfg(not(target_arch = "wasm32"))] - fn submit_deferred_opens(&mut self) { - let mut queue = std::mem::take(&mut self.deferred_opens); - while self.deferred_opens.is_empty() && self.pending_opens.len() < self.open_slots() { - let Some(next) = queue.pop_front() else { break }; - self.open_file_request(&next.path, next.after_open, next.then, next.display_override); - } - // A file put back (the queue filled again) stays ahead of the ones behind it. - self.deferred_opens.append(&mut queue); + token } #[cfg(not(target_arch = "wasm32"))] pub(crate) fn poll_pending_opens(&mut self) { + // The queue delivers in the order jobs finish; each result goes to its entry, so the list + // keeps the order the files were asked for. + while let Some(finished) = self.opens.try_recv() { + if let Some(pending) = self.pending_opens.iter_mut().find(|pending| pending.token == finished.key) { + pending.ready = Some(finished.result); + } + } let pending_opens = std::mem::take(&mut self.pending_opens); // A retry that is no longer waiting holds nothing back. if let Some(token) = self.password_retry @@ -190,28 +169,15 @@ impl PdfCraftApp { while let Some(mut pending) = remaining.next() { // A tool, password prompt or file picker belongs to the document just admitted. // Keep later replies queued so another open cannot change its recipient. - if self.modal_open() || self.pickers.pending() { + if self.modal_open() || self.picks_pending() { waiting.push(pending); waiting.extend(remaining); break; } let retry = self.password_retry == Some(pending.token); - let kind = match pending.ready.take() { - Some(kind) => kind, - None => match pending.receiver.try_recv() { - Ok(result) if result.token == pending.token => result.kind, - Ok(_) | Err(std::sync::mpsc::TryRecvError::Empty) => { - waiting.push(pending); - continue; - } - Err(std::sync::mpsc::TryRecvError::Disconnected) => { - if retry { - self.password_retry = None; - } - self.notify_fmt("Couldn't open {name}: the background worker stopped", &[("name", &pending.name)]); - continue; - } - }, + let Some(kind) = pending.ready.take() else { + waiting.push(pending); + continue; }; // While a closed prompt's password is being tried, a later file that asks for its own // password keeps its reply: its prompt would hide the retry's outcome. Others admit. @@ -229,7 +195,6 @@ impl PdfCraftApp { // earlier waiting replies, without consuming a blocked receiver's result. waiting.append(&mut self.pending_opens); self.pending_opens = waiting; - self.submit_deferred_opens(); self.settle_launch_layout(); } @@ -268,8 +233,8 @@ impl PdfCraftApp { open_worker::ResultKind::Prepared { bytes, result } => match *result { Ok(prepared) => match self.finish_open(&pending.name, pending.path.clone(), bytes.len(), prepared, pending.activate) { Ok(id) => { - if pending.path.is_some() { - self.watch.known_as(id, pending.stamp); + if let Some(path) = pending.path.as_deref() { + self.watch.known_as(id, std::path::Path::new(path), pending.stamp); } if let Some(destination) = pending.after_open { self.apply_remote_destination(destination); @@ -297,7 +262,6 @@ impl PdfCraftApp { path: pending.path, bytes, stamp: pending.stamp, - input: String::new(), error: password_error, activate: pending.activate, recovered: pending.recovered, @@ -324,20 +288,19 @@ impl PdfCraftApp { use pdfcraft_render::OpenError; // A new document opens with the remembered Highlight fields, which its scripts read; the // session keeps the document in front's. - let context = self.session.open_context().with_highlight(self.view_defaults.highlight_fields); + let context = self.session.open_context().with_highlight(self.highlight_fields); let prepared = match context.prepare_open(name, path.clone(), bytes.clone(), password) { Ok(prepared) => prepared, Err(e @ (OpenError::NeedsPassword | OpenError::WrongPassword)) => { let error = matches!(e, OpenError::WrongPassword).then(|| "Incorrect password. Try again.".to_string()); #[cfg(not(target_arch = "wasm32"))] - let stamp = path.as_deref().and_then(file_watch::Stamp::at); + let stamp = path.as_deref().and_then(|path| FileStamp::at(std::path::Path::new(path))); self.password_prompt = Some(PasswordPrompt { name: name.to_string(), path, bytes, #[cfg(not(target_arch = "wasm32"))] stamp, - input: String::new(), error, activate, recovered: None, @@ -370,7 +333,7 @@ impl PdfCraftApp { if activate { self.leave_portfolio(); } - let right_before = self.right; + let right_before = self.right(); // The reading-colours preference is app-wide: a newly opened document starts with it. // Idempotent: the engine returns `false` when the document has the setting already. self.session.set_reading_colors(id, self.reading_colors); @@ -388,8 +351,8 @@ impl PdfCraftApp { pdfcraft_render::AttachmentSource::Document { key } => Some(key.clone()), pdfcraft_render::AttachmentSource::Annotation { .. } => None, }); - if activate && self.right.is_none() && !self.right_panel_closed && opening_mode != Mode::Read { - self.right = if !doc.info.annotations.is_empty() { + let opens_with = if activate && self.right().is_none() && !self.right_panel_closed() && opening_mode != Mode::Read { + if !doc.info.annotations.is_empty() { Some(RightPanel::Comments) // A full-screen document names its panel for outside full screen, and with // `/NonFullScreenPageMode /UseNone` (the default) no outline is visible (Table 147). @@ -397,9 +360,14 @@ impl PdfCraftApp { Some(RightPanel::Bookmarks) } else { None - }; + } + } else { + None + }; + let view = DocView::new(id, &doc.info, self.view_defaults, self.highlight_fields); // PLAN: assumed signature (pdf-canvas-w8) + if opens_with.is_some() { + self.set_right(opens_with); } - let view = DocView::new(id, &doc.info, self.view_defaults); self.views.push(view); if activate { self.active = Some(self.views.len() - 1); @@ -410,15 +378,15 @@ impl PdfCraftApp { // viewer preferences open at (#1767). self.apply_last_view(self.views.len() - 1); // After all of them, so full screen shows one fitted page and leaving it comes back to them. - if self.full_screen + if self.full_screen() && let Some(view) = self.views.last_mut() { view.enter_presentation(); } // Full screen is asked for, never taken: a document can't put the app in full screen on - // its own (the prompt is `dialogs::full_screen_prompt`). + // its own (the prompt is `ask_full_screen`'s). if activate && initial.full_screen { - self.pending_full_screen = Some(id); + self.ask_full_screen(id); } if activate { // A portfolio's tab shows its files from the start, in place of the panel there was @@ -431,7 +399,7 @@ impl PdfCraftApp { self.portfolio_initial = portfolio_initial.map(|key| (id, key)); } if activate - && self.left_open + && self.left_open() && self.left == LeftPanel::Tool("organize") && let Some(view) = self.views.last_mut() { @@ -447,9 +415,12 @@ impl PdfCraftApp { } else if activate && self.mode != self.default_mode { // Switch workspace like the mode bar, but a left panel the user (or `--left closed`) // closed stays closed, and an unchanged mode keeps the tool panel the user chose. - let left_open = self.left_open; + let (left, left_open) = (self.left, self.left_open()); self.select_mode(self.default_mode); - self.left_open = left_open; + if self.left_open() != left_open { + // PLAN: assumed `PanelId::from(LeftPanel)` (pdf-chrome-w13) + crate::side_panels::set_panel_visible(self, crate::side_panels::PanelId::from(left), left_open); + } } if let Some(p) = path { #[cfg(target_os = "macos")] @@ -481,9 +452,9 @@ impl PdfCraftApp { } #[cfg(not(target_arch = "wasm32"))] { - let dialog = rfd::AsyncFileDialog::new().set_title(tl!("Attach a file").to_string()); + // PLAN: `pick_first(request, target, continuation)` assumed from pdf-shell-w14; the continuation gets the path. let target = self.active_ids().map(|(_, id)| id); - self.ask_one(pickers::Ask::File(dialog), target, |app, path| app.attach_file(&path)); + self.pick_first(PickRequest::open("attachment").title(tl!("Attach a file").to_string()), target, |app, path| app.attach_file(&path)); } #[cfg(target_arch = "wasm32")] self.notify_tr("Attaching files is not available on the web yet"); @@ -502,7 +473,7 @@ impl PdfCraftApp { }; let mime = pdfcraft_engine::mime_for_name(&name).map(str::to_string); if self.apply_edit(pdfcraft_engine::Edit::AddAttachment { name, bytes, description: None, mime }) { - self.choose_right_panel(Some(RightPanel::Attachments)); + self.set_right(Some(RightPanel::Attachments)); } } @@ -519,7 +490,7 @@ impl PdfCraftApp { (Err(e), _) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]), (Ok(bytes), true) if looks_like_pdf(&bytes) => { // The tab name later names files written from the tab (Split, Extract pages). - let name = crate::files::attachment_file_name(&att.name); + let name = safe_file_name(&att.name, "attachment"); // Already open: the tab opened from this attachment of this document (its bytes // may have grown since, as a form laid out on open appends its layout). let origin = (doc, att.name.clone()); @@ -542,10 +513,10 @@ impl PdfCraftApp { } (Ok(bytes), _) => { #[cfg(not(target_arch = "wasm32"))] - self.ask_one( - pickers::Ask::Save(rfd::AsyncFileDialog::new().set_file_name(crate::files::attachment_file_name(&att.name))), + self.pick_first( + PickRequest::save("attachment").file_name(safe_file_name(&att.name, "attachment")), None, - move |app, path| match crate::editing::write_atomically(&path.to_string_lossy(), &bytes) { + move |app, path| match craft::atomic::atomic_write(&path, &bytes) { Ok(()) => { // Windows: the file keeps the document's Mark-of-the-Web (#3990). Best // effort: a volume without alternate data streams can't carry it. @@ -573,10 +544,11 @@ impl PdfCraftApp { // waits for its answer, and opening it then would close the prompt. A file still // opening in the background (in the open worker, or a browser read of a drop or a // picked file) comes to the front when it arrives, so it is waited for too. + // On the web a drop or pick arrives as bytes and opens at once, so nothing is in flight. #[cfg(not(target_arch = "wasm32"))] - let busy = self.modal_open() || self.pickers.pending() || self.pending_opens.iter().any(|p| p.activate); + let busy = self.modal_open() || self.picks_pending() || self.pending_opens.iter().any(|p| p.activate); #[cfg(target_arch = "wasm32")] - let busy = self.modal_open() || self.web_reads.load(std::sync::atomic::Ordering::Relaxed) > 0; + let busy = self.modal_open(); if !busy && let Some((doc, key)) = self.portfolio_initial.take() && self.active_ids().is_some_and(|(_, id)| id == doc) @@ -594,10 +566,10 @@ impl PdfCraftApp { self.leave_portfolio(); if let Some(id) = active && self.mode != Mode::Read - && self.right != Some(RightPanel::Attachments) + && self.right() != Some(RightPanel::Attachments) && self.lists_files(id) { - self.show_portfolio_files(id, self.right); + self.show_portfolio_files(id, self.right()); } self.portfolio_seen = active; } @@ -613,7 +585,7 @@ impl PdfCraftApp { fn show_portfolio_files(&mut self, id: DocId, before: Option) { self.portfolio_seen = Some(id); self.portfolio_panel = Some(before); - self.right = Some(RightPanel::Attachments); + self.set_right(Some(RightPanel::Attachments)); } /// Where in `doc`'s attachments now the file its name tree keys `key` is: an attachment @@ -636,7 +608,7 @@ impl PdfCraftApp { if pdfcraft_engine::source_kind(&att.name, &bytes) != Some(pdfcraft_engine::SourceKind::Pdf) { return; } - if let Err(e) = self.open_bytes(&crate::files::attachment_file_name(&att.name), None, bytes) { + if let Err(e) = self.open_bytes(&safe_file_name(&att.name, "attachment"), None, bytes) { self.notify_fmt("Couldn't open {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]); } } @@ -652,8 +624,8 @@ impl PdfCraftApp { if self.right_before_read == Some(RightPanel::Attachments) { self.right_before_read = before; } - } else if self.right == Some(RightPanel::Attachments) { - self.right = before; + } else if self.right() == Some(RightPanel::Attachments) { + self.set_right(before); } } @@ -666,10 +638,33 @@ impl PdfCraftApp { } } + /// Shows the password dialog for the open prompt, else the permissions prompt, and answers the + /// prompt on the pass the dialog closes. Called by the window body every pass while either is + /// set. + pub(crate) fn password_pass(&mut self, ui: &mut egui::Ui) { + let (purpose, error, unlock) = if let Some(prompt) = &self.password_prompt { + (PasswordPurpose::open(prompt.name.clone()), prompt.error.clone(), false) + } else if let Some(prompt) = &self.unlock_prompt { + (PasswordPurpose::permissions(prompt.name.clone()), prompt.error.clone(), true) + } else { + return; + }; + let output = PasswordDialog::new(purpose).error(error.map(craft::ui::runtime::env::Label::from)).show(ui); + let password = match (output.answer, output.closed) { + (Some(answer), _) => Some(answer.secret.expose().to_string()), + (None, Some(_)) => None, + (None, None) => return, + }; + if unlock { + self.submit_unlock(password); + } else { + self.submit_password(password); + } + } + /// Answer the password prompt (`None` cancels). pub fn submit_password(&mut self, password: Option) { let Some(mut p) = self.password_prompt.take() else { return }; - zeroize::Zeroize::zeroize(&mut p.input); let Some(pw) = password.map(zeroize::Zeroizing::new) else { // A cancelled recovery goes back on offer; its snapshot stays in the store and must // not attach itself to whatever document is unlocked next (#813). @@ -681,8 +676,8 @@ impl PdfCraftApp { return; }; #[cfg(not(target_arch = "wasm32"))] - if self.ctx.is_some() && !self.run_inline { - let result = self.schedule_open_priority(OpenRequest { + { + let token = self.schedule_open(OpenRequest { name: p.name.clone(), path: p.path.clone(), stamp: p.stamp, @@ -692,24 +687,21 @@ impl PdfCraftApp { after_open: p.after_open.clone(), recovered: p.recovered.clone(), then: p.then, + priority: Priority::VISIBLE, }); - if let Ok(token) = &result - && let Some(pending) = self.pending_opens.iter_mut().find(|pending| pending.token == *token) - { + if let Some(pending) = self.pending_opens.iter_mut().find(|pending| pending.token == token) { pending.display_override = p.display_override; - // Replies behind it that ask for a password wait for its outcome - // (`poll_pending_opens`). - self.password_retry = Some(*token); } - if let Err(error) = result { - let mut prompt = p; - prompt.error = Some(error); - self.password_prompt = Some(prompt); - } - return; + // Replies behind it that ask for a password wait for its outcome (`poll_pending_opens`). + self.password_retry = Some(token); } - #[cfg(not(target_arch = "wasm32"))] - let (path_for_watch, stamp_for_watch) = (p.path.clone(), p.stamp); + #[cfg(target_arch = "wasm32")] + self.retry_inline(p, pw); + } + + /// The web has no queue: the retry opens the held bytes at once. + #[cfg(target_arch = "wasm32")] + fn retry_inline(&mut self, mut p: PasswordPrompt, pw: zeroize::Zeroizing) { let after_open = p.after_open.clone(); let opened = self.try_open(&p.name, p.path.take(), p.bytes.clone(), Some(&pw), p.activate); drop(pw); @@ -717,16 +709,6 @@ impl PdfCraftApp { Err(e) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &p.name), ("e", &e.to_string())]), // A recovered encrypted document is open once its prompt is gone. Ok(()) if self.password_prompt.is_none() => { - #[cfg(not(target_arch = "wasm32"))] - if let Some(path) = path_for_watch.as_deref() - && let Some(id) = self - .views - .iter() - .rev() - .find_map(|view| self.session.get(view.id).and_then(|doc| (doc.path.as_deref() == Some(path)).then_some(view.id))) - { - self.watch.known_as(id, stamp_for_watch); - } if let Some(destination) = after_open { self.apply_remote_destination(destination); } @@ -734,10 +716,6 @@ impl PdfCraftApp { && let Some(view) = self.views.last_mut() { view.set_display(layout, continuous); - #[cfg(not(target_arch = "wasm32"))] - { - self.launch_display_target = Some(view.id); - } } if let Some(meta) = &p.recovered { self.finish_recovery(meta); @@ -757,8 +735,6 @@ impl PdfCraftApp { } } } - #[cfg(not(target_arch = "wasm32"))] - self.settle_launch_layout(); } /// Ask for the active document's permissions password, then run `then` (if any). @@ -770,7 +746,6 @@ impl PdfCraftApp { /// Answer the permissions password prompt (`None` cancels). pub fn submit_unlock(&mut self, password: Option) { let Some(mut p) = self.unlock_prompt.take() else { return }; - zeroize::Zeroize::zeroize(&mut p.input); let Some(mut pw) = password else { return }; let unlocked = self.session.unlock(p.doc, &pw); zeroize::Zeroize::zeroize(&mut pw); @@ -793,7 +768,12 @@ impl PdfCraftApp { /// The tab already showing the file at `path` (the same path, or one that names the same /// file once made absolute). pub(crate) fn tab_showing(&self, path: &str) -> Option { - self.views.iter().position(|v| self.session.get(v.id).and_then(|d| d.path.as_deref()).is_some_and(|p| same_file(p, path))) + self.views.iter().position(|v| { + self.session + .get(v.id) + .and_then(|d| d.path.as_deref()) + .is_some_and(|p| craft::platform::open::same_file(std::path::Path::new(p), std::path::Path::new(path), None)) + }) } /// Open a file from a recent list: focus the tab already showing it, else open it (File ▸ @@ -861,7 +841,11 @@ impl PdfCraftApp { } return OpenOutcome::Focused; } - if let Some(pending) = self.pending_opens.iter_mut().find(|p| p.path.as_deref().is_some_and(|p| same_file(p, path))) { + if let Some(pending) = self + .pending_opens + .iter_mut() + .find(|p| p.path.as_deref().is_some_and(|p| craft::platform::open::same_file(std::path::Path::new(p), std::path::Path::new(path), None))) + { if display_override.is_some() { pending.display_override = display_override; } @@ -874,7 +858,11 @@ impl PdfCraftApp { // The same file named again while its password is being asked for joins that prompt // instead of queuing a second one; a display override, a place to open at or a tool it // brings is kept. - if let Some(prompt) = self.password_prompt.as_mut().filter(|p| p.path.as_deref().is_some_and(|p| same_file(p, path))) { + if let Some(prompt) = self + .password_prompt + .as_mut() + .filter(|p| p.path.as_deref().is_some_and(|p| craft::platform::open::same_file(std::path::Path::new(p), std::path::Path::new(path), None))) + { if display_override.is_some() { prompt.display_override = display_override; } @@ -886,102 +874,26 @@ impl PdfCraftApp { } return OpenOutcome::Pending; } - if let Some(deferred) = self.deferred_opens.iter_mut().find(|d| same_file(&d.path, path)) { - if display_override.is_some() { - deferred.display_override = display_override; - } - if after_open.is_some() { - deferred.after_open = after_open; - } - if then.is_some() { - deferred.then = then; - } - return OpenOutcome::Pending; - } let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string()); // Taken before reading: a build that rewrites the file meanwhile still counts as a change. - let stamp = file_watch::Stamp::at(path); - // Before the first frame there is no interaction to keep responsive; this also preserves - // deterministic inline startup and test flows. Once live, reading and preparation use - // the bounded worker and commit on the UI thread. - // Keep later files behind an open password prompt: it belongs to an earlier file, and an - // inline open would clear it. Keep flagged launch files behind any dialog or picker too. - let held = self.password_prompt.is_some() || (display_override.is_some() && (self.modal_open() || self.pickers.pending())); - if (self.ctx.is_none() || self.run_inline) && !held { - match std::fs::read(path) { - Ok(bytes) => { - let before = self.views.len(); - let previous_prompt = self.password_prompt.as_ref().map(|p| p.bytes.clone()); - if let Err(error) = self.open_bytes(&name, Some(path.to_string()), bytes) { - self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]); - return OpenOutcome::Failed; - } - if let Some(prompt) = self.password_prompt.as_mut().filter(|p| { - p.path.as_deref() == Some(path) && previous_prompt.as_ref().is_none_or(|bytes| !std::sync::Arc::ptr_eq(bytes, &p.bytes)) - }) { - // Encrypted: the destination, the layout and the tool wait for the password. - prompt.then = then; - prompt.display_override = display_override; - prompt.after_open = after_open; - } else if self.views.len() > before { - if let Some((layout, continuous)) = display_override - && let Some(view) = self.views.last_mut() - { - view.set_display(layout, continuous); - self.launch_display_target = Some(view.id); - } - if let Some(doc) = self.views.last().map(|view| view.id) { - self.watch.known_as(doc, stamp); - } - if let Some(destination) = after_open { - self.apply_remote_destination(destination); - } - if let Some(command) = then { - self.execute(command); - } - } else { - // Open reported success but added no tab and raised no prompt; the - // control channel answers this as a failure to open. - return OpenOutcome::Failed; - } - OpenOutcome::Opened - } - Err(error) => { - self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &error.to_string())]); - OpenOutcome::Failed - } - } - } else { - self.startup_superseded = true; - // The worker queue is bounded. A long file list (a launch behind a password prompt, - // or many files at once) waits here, in order, and is submitted as opens finish. - if self.pending_opens.len() >= self.open_slots() || !self.deferred_opens.is_empty() { - self.deferred_opens.push_back(DeferredOpen { path: path.to_string(), after_open, then, display_override }); - return OpenOutcome::Pending; - } - match self.schedule_open(OpenRequest { - name: name.clone(), - path: Some(path.to_string()), - stamp, - input: open_worker::Input::Path(std::path::PathBuf::from(path)), - password: None, - activate: true, - after_open, - recovered: None, - then, - }) { - Ok(token) => { - if let Some(pending) = self.pending_opens.iter_mut().find(|pending| pending.token == token) { - pending.display_override = display_override; - } - OpenOutcome::Pending - } - Err(error) => { - self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]); - OpenOutcome::Failed - } - } + let stamp = FileStamp::at(std::path::Path::new(path)); + self.startup_superseded = true; + let token = self.schedule_open(OpenRequest { + name, + path: Some(path.to_string()), + stamp, + input: open_worker::Input::Path(std::path::PathBuf::from(path)), + password: None, + activate: true, + after_open, + recovered: None, + then, + priority: Priority::NEAR, + }); + if let Some(pending) = self.pending_opens.iter_mut().find(|pending| pending.token == token) { + pending.display_override = display_override; } + OpenOutcome::Pending } /// Apply an explicit launch layout after the command-line display overrides settle. @@ -996,7 +908,6 @@ impl PdfCraftApp { #[cfg(not(target_arch = "wasm32"))] fn settle_launch_layout(&mut self) { if self.pending_opens.iter().any(|open| open.display_override.is_some()) - || self.deferred_opens.iter().any(|open| open.display_override.is_some()) || self.password_prompt.as_ref().is_some_and(|prompt| prompt.display_override.is_some()) { return; @@ -1021,44 +932,68 @@ impl PdfCraftApp { /// and (on the desktop, through LibreOffice) Office documents open as new, unsaved PDFs. /// No "All files" in the browser or on macOS, whose panel merges every type into one list /// rather than offering a choice. - pub(crate) fn open_filters() -> Vec<(String, Vec<&'static str>)> { - let mut filters = vec![("PDF".to_string(), vec!["pdf"]), (tl!("Images").to_string(), pdfcraft_engine::IMAGE_EXTENSIONS.to_vec())]; + pub(crate) fn open_filters() -> Vec { + let mut filters = vec![FileFilter::new("PDF", &["pdf"]), FileFilter::new(tl!("Images").to_string(), &pdfcraft_engine::IMAGE_EXTENSIONS)]; #[cfg(not(target_arch = "wasm32"))] - filters.push((tl!("Office documents").to_string(), pdfcraft_engine::OFFICE_EXTENSIONS.to_vec())); - filters.push((tl!("Text").to_string(), pdfcraft_engine::TEXT_EXTENSIONS.to_vec())); + filters.push(FileFilter::new(tl!("Office documents").to_string(), pdfcraft_engine::OFFICE_EXTENSIONS)); + filters.push(FileFilter::new(tl!("Text").to_string(), &pdfcraft_engine::TEXT_EXTENSIONS)); #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))] - filters.push((tl!("All files").to_string(), vec!["*"])); + filters.push(FileFilter::new(tl!("All files").to_string(), &["*"])); filters } - /// The File ▸ Open picker ([`Self::open_filters`]), each type matched in any letter case. - pub(super) fn open_picker() -> rfd::AsyncFileDialog { - Self::open_filters().into_iter().fold(rfd::AsyncFileDialog::new(), |dialog, (name, extensions)| dialog.add_filter_any_case(name, &extensions)) + /// The File ▸ Open request: [`Self::open_filters`], one `filter` per type. + fn open_request() -> PickRequest { + Self::open_filters().iter().fold(PickRequest::open_many("document"), |request, filter| { + let extensions: Vec<&str> = filter.extensions.iter().map(String::as_str).collect(); + request.filter(&filter.name, &extensions) + }) } pub fn open_dialog(&mut self) { self.startup_superseded = true; - #[cfg(not(target_arch = "wasm32"))] - self.pick(pickers::PickFor::Open, Self::open_picker(), true); - // Browsers pick files asynchronously; the bytes arrive through `inbox`. - #[cfg(target_arch = "wasm32")] - { - let inbox = self.inbox.clone(); - let ctx = self.ctx.clone(); - let read = super::input::WebRead::start(&self.web_reads); - wasm_bindgen_futures::spawn_local(async move { - let _read = read; - if let Some(h) = Self::open_picker().pick_file().await { - let bytes = h.read().await; - if let Ok(mut q) = inbox.lock() { - q.push((h.file_name(), bytes)); - } - // The read may finish while the app is idle: wake it to open the file. - if let Some(ctx) = ctx { - ctx.request_repaint(); + // PLAN: `pick_file(request, target, continuation)` assumed from pdf-shell-w14; the continuation gets the `Picked`. + // The web answers `Picked::Contents`, the desktop `Picked::Paths`. + self.pick_file(Self::open_request(), None, |app, picked| match picked { + #[cfg(not(target_arch = "wasm32"))] + Picked::Paths(paths) => { + for path in paths { + app.open_path(&path.to_string_lossy()); + } + } + Picked::Contents(files) => { + for (name, bytes) in files { + if let Err(error) = app.open_bytes(&name, None, bytes) { + app.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]); } } - }); + } + _ => {} + }); + } + + /// Opens what a picker answered and runs the command `then` on each opened document, as a tool + /// chosen from Home does once its file is ready. + pub fn open_picked_then(&mut self, picked: Picked, then: &'static str) { + self.startup_superseded = true; + match picked { + #[cfg(not(target_arch = "wasm32"))] + Picked::Paths(paths) => { + for path in paths { + self.open_path_then(&path.to_string_lossy(), Some(then)); + } + } + Picked::Contents(files) => { + for (name, bytes) in files { + match self.open_bytes(&name, None, bytes) { + Ok(()) => { + self.execute(then); + } + Err(error) => self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]), + } + } + } + _ => {} } } diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 6d24a3e794..858ed934fb 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -1,166 +1,49 @@ -use super::{GridDrop, GridFile, PdfCraftApp}; -#[cfg(not(target_arch = "wasm32"))] -use super::{OpenRequest, open_worker}; +use craft::ui::runtime::drag::OsFile; // PLAN: assumed path of `OsFile` in the facade (ui-contract `runtime/drag.rs`) -/// Read a file dropped on a page grid (see [`GridFile`]). -fn read_grid_file((name, source): GridFile) -> Result<(String, Vec), (String, String)> { - let bytes = match source { - Ok(bytes) => bytes, - Err(path) => std::fs::read(&path).map_err(|e| (name.clone(), e.to_string()))?, - }; - Ok((name, bytes)) -} +use super::PdfCraftApp; + +/// The name a dropped file is opened under when the OS gave none. +const DROPPED_NAME: &str = "dropped.pdf"; impl PdfCraftApp { - #[cfg(not(target_arch = "wasm32"))] - pub(super) fn open_dropped(&mut self, f: egui::DroppedFileHandle, _ctx: &egui::Context) { - let p = f.path().to_string_lossy().into_owned(); - if !p.is_empty() && f.path().is_absolute() { - self.open_path(&p); - return; - } - let name = crate::files::dropped_name(&f); - match f.bytes() { - Ok(bytes) => { - if self.ctx.is_some() && !self.run_inline { - let result = self.schedule_open(OpenRequest { - name: name.clone(), - path: None, - stamp: None, - input: open_worker::Input::Bytes(std::sync::Arc::new(bytes)), - password: None, - activate: true, - after_open: None, - recovered: None, - then: None, - }); - if let Err(error) = result { - self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]); - } - } else if let Err(error) = self.open_bytes(&name, None, bytes) { - self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]); - } - } - Err(e) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e.to_string())]), - } - } - - /// The document whose page grid is showing and may take pages, if any. - fn grid_target(&self) -> Option { - let view = self.active.and_then(|i| self.views.get(i)).filter(|v| v.organize)?; - (self.dialog.is_none() && self.session.get(view.id)?.allows_assembly()).then_some(view.id) - } - - /// The document whose Pages panel is under the pointer and may take pages, if any. - #[cfg(not(target_arch = "wasm32"))] - fn panel_target(&self, ctx: &egui::Context) -> Option { - let view = self.active.and_then(|i| self.views.get(i))?; - let pointer = ctx.input(|i| i.pointer.hover_pos())?; - let over = view.pages_panel.is_some_and(|panel| panel.contains(pointer)); - (over && self.dialog.is_none() && self.session.get(view.id)?.allows_assembly()).then_some(view.id) - } - - /// Files dropped on the Pages panel, or while the page grid shows, are inserted into the - /// document rather than opened: they are kept until [`Self::finish_grid_drop`] knows the - /// gap. Returns the files not taken. - #[cfg(not(target_arch = "wasm32"))] - pub(super) fn drop_on_grid(&mut self, dropped: Vec, ctx: &egui::Context) -> Vec { - if dropped.is_empty() { - return dropped; - } - // The panel first: the grid takes files dropped anywhere in the window. - let (id, panel) = match (self.panel_target(ctx), self.grid_target()) { - (Some(id), _) => (id, true), - (None, Some(id)) => (id, false), - (None, None) => return dropped, - }; - let mut files = Vec::new(); - for f in &dropped { - let name = crate::files::dropped_name(f); - if f.path().is_absolute() { - files.push((name, Err(f.path().to_path_buf()))); + /// Opens the files dropped on the window: a file with a path like File ▸ Open, one that + /// arrived as bytes (the web) as a new tab. + pub(crate) fn open_dropped(&mut self, files: Vec) { + for file in files { + #[cfg(not(target_arch = "wasm32"))] + if let Some(path) = &file.path { + self.open_path(&path.to_string_lossy()); continue; } - match f.bytes() { - Ok(b) => files.push((name, Ok(b))), - Err(e) => self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", &e)]), + let name = if file.name.is_empty() { DROPPED_NAME.to_string() } else { file.name.clone() }; + let Some(bytes) = file.bytes else { + self.notify_fmt("Couldn't read {name}: {e}", &[("name", &name), ("e", "the file has no contents")]); + continue; + }; + if let Err(error) = self.open_bytes(&name, None, bytes.to_vec()) { + self.notify_fmt("Couldn't open {name}: {e}", &[("name", &name), ("e", &error)]); } } - if !files.is_empty() { - // Where there is no telling where the pointer is during the drag, its place arrives - // with the first move after the drop. - ctx.request_repaint(); - self.grid_drop = Some(GridDrop { doc: id, panel, files, deadline: web_time::Instant::now() + std::time::Duration::from_secs(1) }); - } - Vec::new() } - /// Insert files dropped on the page grid or the Pages panel at the gap under the pointer, - /// or at the end when the pointer hasn't shown up in time. - pub(super) fn finish_grid_drop(&mut self, ctx: &egui::Context) { - let Some(GridDrop { doc: id, panel, deadline, .. }) = &self.grid_drop else { return }; - let (id, panel, deadline) = (*id, *panel, *deadline); - let still = if panel { - self.dialog.is_none() - && self.active_ids().map(|(_, active)| active) == Some(id) - && self.session.get(id).is_some_and(|d| d.allows_assembly()) - } else { - self.grid_target() == Some(id) - }; - if !still { - self.grid_drop = None; - return self.notify_tr("The document changed while you were choosing a file, so nothing was changed."); - } + /// Inserts the pages of the dropped `files` into the active document before page `at`, and + /// selects them. Each file is read here (its bytes, else its path); one that can't be read is + /// named and skipped by [`Self::insert_each`], the rest are inserted. + pub(crate) fn insert_dropped(&mut self, files: Vec, at: usize) { + let read: Vec), (String, String)>> = files + .into_iter() + .map(|file| { + let name = if file.name.is_empty() { DROPPED_NAME.to_string() } else { file.name.clone() }; + let bytes = match (&file.bytes, &file.path) { + (Some(bytes), _) => Ok(bytes.to_vec()), + (None, Some(path)) => std::fs::read(path).map_err(|e| e.to_string()), + (None, None) => Err("the file has no contents".to_string()), + }; + bytes.map(|bytes| (name.clone(), bytes)).map_err(|error| (name, error)) + }) + .collect(); let Some(view) = self.active.and_then(|i| self.views.get_mut(i)) else { return }; - let gap = match if panel { view.panel_gap } else { view.grid_gap } { - Some(gap) => gap, - None if web_time::Instant::now() >= deadline => usize::MAX, - None => return ctx.request_repaint(), - }; - view.insert_at = Some(gap); - if let Some(drop) = self.grid_drop.take() { - self.insert_each(drop.files.into_iter().map(read_grid_file)); - } - } - - /// Browsers read dropped files asynchronously; the bytes land in `inbox` and open next frame. - #[cfg(target_arch = "wasm32")] - pub(super) fn open_dropped(&mut self, f: egui::DroppedFileHandle, ctx: &egui::Context) { - self.startup_superseded = true; - let inbox = self.inbox.clone(); - let ctx = ctx.clone(); - let read = WebRead::start(&self.web_reads); - wasm_bindgen_futures::spawn_local(async move { - let _read = read; - let name = crate::files::dropped_name(&f); - if let Ok(bytes) = f.bytes_async().await - && let Ok(mut q) = inbox.lock() - { - q.push((name, bytes)); - ctx.request_repaint(); - } - }); - } -} - -/// One browser file read counted in `PdfCraftApp::web_reads` for as long as it lives, so the -/// count falls however the read ends. -#[cfg(target_arch = "wasm32")] -pub(super) struct WebRead(std::sync::Arc); - -#[cfg(target_arch = "wasm32")] -impl WebRead { - /// Count a read starting in `reads`. - pub(super) fn start(reads: &std::sync::Arc) -> Self { - reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - Self(reads.clone()) - } -} - -#[cfg(target_arch = "wasm32")] -impl Drop for WebRead { - /// The read is over, whether its file arrived or not. - fn drop(&mut self) { - self.0.fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + view.insert_at = Some(at); + self.insert_each(read); } } diff --git a/crates/ui-egui/src/platform/open_worker.rs b/crates/ui-egui/src/platform/open_worker.rs index b9c3735e4a..6ffe5ac465 100644 --- a/crates/ui-egui/src/platform/open_worker.rs +++ b/crates/ui-egui/src/platform/open_worker.rs @@ -1,20 +1,19 @@ -//! Native document reads and preparation run away from the frame thread. +//! Native document reads and preparation run on the host's job queue, away from the frame thread. -use std::collections::VecDeque; use std::path::PathBuf; -use std::sync::mpsc::{self, Receiver, Sender}; -use std::sync::{Arc, Condvar, Mutex, PoisonError}; +use std::sync::Arc; -use crate::RecoveryStore; +use craft::host::queue::{Cancel, JobQueue, QueueOptions, QueueOrder}; +use craft::host::{Host, Wake}; use pdfcraft_engine::{OpenContext, PreparedDocument, SourceKind}; use pdfcraft_render::OpenError; -pub(crate) const MAX_QUEUED_OPENS: usize = 16; - +/// Where an open reads its bytes from. pub(crate) enum Input { Path(PathBuf), RemotePath(PathBuf), - Recovery(RecoveryStore, String), + /// The recovery store's copy, at the path its entry names. + Recovery(PathBuf), Bytes(Arc>), } @@ -32,177 +31,28 @@ pub(crate) enum ResultKind { Failed(String), } -pub(crate) struct ResultMessage { - pub token: u64, - pub kind: ResultKind, +/// One open to prepare; its key on the queue is the open's token. +pub(crate) struct Job { + pub context: OpenContext, + pub name: String, + pub path: Option, + pub password: Option>, + pub input: Input, } -struct Job { - token: u64, - context: OpenContext, - name: String, - path: Option, - password: Option>, - input: Input, - reply: Sender, - #[cfg(test)] - gate: Option>, +/// The queue that prepares opens: one lane, oldest first, so files open in the order they were +/// asked for. +pub(crate) fn queue(host: &Host, wake: Wake) -> JobQueue { + JobQueue::new(host.jobs_shared().clone(), wake, QueueOptions { lanes: 1, name: "pdfcraft-open", order: QueueOrder::OldestFirst }) } -struct Queue { - jobs: VecDeque, - shutdown: bool, - repaint: Option, +/// Prepares `job`; a panic inside the engine becomes a failed open, since the queue delivers +/// nothing for a panicked job. +pub(crate) fn run(job: Job, cancel: &Cancel) -> ResultKind { + pdfcraft_engine::guard(|| prepare(job, cancel)).unwrap_or_else(|_| ResultKind::Failed("opening failed unexpectedly in the background".into())) } -pub(crate) struct OpenWorker { - queue: Arc<(Mutex, Condvar)>, - #[cfg(test)] - gate: Option>, -} - -impl OpenWorker { - pub fn new(#[cfg(test)] gate: Option>) -> std::io::Result { - let queue = Arc::new((Mutex::new(Queue { jobs: VecDeque::new(), shutdown: false, repaint: None }), Condvar::new())); - let worker_queue = queue.clone(); - std::thread::Builder::new().name("pdfcraft-open".into()).spawn(move || run(worker_queue))?; - Ok(Self { - queue, - #[cfg(test)] - gate, - }) - } - - pub fn set_context(&self, ctx: &egui::Context) { - let (lock, _) = &*self.queue; - let mut queue = lock.lock().unwrap_or_else(PoisonError::into_inner); - queue.repaint = Some(ctx.clone()); - } - - pub fn submit( - &self, - token: u64, - context: OpenContext, - name: String, - path: Option, - password: Option>, - input: Input, - ) -> Result, String> { - let (job, receiver) = self.build_job(token, context, name, path, password, input); - self.enqueue(job, false)?; - Ok(receiver) - } - - pub fn submit_priority( - &self, - token: u64, - context: OpenContext, - name: String, - path: Option, - password: Option>, - input: Input, - ) -> Result, String> { - let (job, receiver) = self.build_job(token, context, name, path, password, input); - self.enqueue(job, true)?; - Ok(receiver) - } - - fn build_job( - &self, - token: u64, - context: OpenContext, - name: String, - path: Option, - password: Option>, - input: Input, - ) -> (Job, Receiver) { - let (reply, receiver) = mpsc::channel(); - ( - Job { - token, - context, - name, - path, - password, - input, - reply, - #[cfg(test)] - gate: self.gate.clone(), - }, - receiver, - ) - } - - fn enqueue(&self, job: Job, priority: bool) -> Result<(), String> { - let (lock, ready) = &*self.queue; - let mut queue = lock.lock().unwrap_or_else(PoisonError::into_inner); - if queue.shutdown { - return Err("the document-open worker has stopped".into()); - } - if !priority && queue.jobs.len() >= MAX_QUEUED_OPENS { - return Err("too many documents are waiting to open".into()); - } - if priority { - queue.jobs.push_front(job); - } else { - queue.jobs.push_back(job); - } - ready.notify_one(); - Ok(()) - } -} - -impl Drop for OpenWorker { - fn drop(&mut self) { - let (lock, ready) = &*self.queue; - let mut queue = lock.lock().unwrap_or_else(PoisonError::into_inner); - queue.shutdown = true; - queue.jobs.clear(); - queue.repaint = None; - ready.notify_one(); - } -} - -fn run(queue: Arc<(Mutex, Condvar)>) { - loop { - let job = { - let (lock, ready) = &*queue; - let mut state = lock.lock().unwrap_or_else(PoisonError::into_inner); - while state.jobs.is_empty() && !state.shutdown { - state = ready.wait(state).unwrap_or_else(PoisonError::into_inner); - } - if state.shutdown { - return; - } - state.jobs.pop_front() - }; - let Some(job) = job else { continue }; - #[cfg(test)] - if let Some(gate) = &job.gate { - gate.pause_before_prepare(); - } - let token = job.token; - let reply = job.reply.clone(); - #[cfg(test)] - let gate = job.gate.clone(); - let kind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| prepare(job))) - .unwrap_or_else(|_| ResultKind::Failed("opening failed unexpectedly in the background worker".into())); - let _ = reply.send(ResultMessage { token, kind }); - let repaint = { - let (lock, _) = &*queue; - lock.lock().unwrap_or_else(PoisonError::into_inner).repaint.clone() - }; - if let Some(ctx) = repaint { - ctx.request_repaint(); - } - #[cfg(test)] - if let Some(gate) = &gate { - let _ = gate.finished.send(()); - } - } -} - -fn prepare(job: Job) -> ResultKind { +fn prepare(job: Job, cancel: &Cancel) -> ResultKind { let bytes = match &job.input { Input::Path(path) => match std::fs::read(path) { Ok(bytes) => Arc::new(bytes), @@ -212,12 +62,15 @@ fn prepare(job: Job) -> ResultKind { Ok(bytes) => Arc::new(bytes), Err(error) => return ResultKind::RemoteFailed(error.to_string()), }, - Input::Recovery(store, key) => match store.read(key) { + Input::Recovery(path) => match std::fs::read(path) { Ok(bytes) => Arc::new(bytes), Err(error) => return ResultKind::RecoveryFailed(error.to_string()), }, Input::Bytes(bytes) => bytes.clone(), }; + if cancel.is_cancelled() { + return ResultKind::Failed("the open was cancelled".into()); + } match pdfcraft_engine::source_kind(&job.name, &bytes) { Some(SourceKind::Image | SourceKind::Text) => return ResultKind::Conversion(bytes), // LibreOffice takes seconds: it runs here, and the frame thread only opens the result. @@ -228,30 +81,5 @@ fn prepare(job: Job) -> ResultKind { ResultKind::Prepared { bytes, result: Box::new(result) } } -#[cfg(test)] -pub(crate) struct PrepareGate { - pub started: Sender<()>, - release: Mutex>, - pub finished: Sender<()>, -} - -#[cfg(test)] -impl PrepareGate { - pub fn pause_before_prepare(&self) { - let _ = self.started.send(()); - if let Ok(release) = self.release.lock() { - let _ = release.recv(); - } - } -} - -#[cfg(test)] -pub(crate) fn prepare_gate() -> (Arc, Receiver<()>, Sender<()>, Receiver<()>) { - let (started, started_rx) = mpsc::channel(); - let (release_tx, release) = mpsc::channel(); - let (finished, finished_rx) = mpsc::channel(); - (Arc::new(PrepareGate { started, release: Mutex::new(release), finished }), started_rx, release_tx, finished_rx) -} - #[cfg(all(test, not(target_arch = "wasm32")))] mod tests; diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index 7f8d73fa8d..b607637a60 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -1,11 +1,23 @@ -use std::sync::{Arc, Mutex}; -use std::time::Duration; +//! The open pipeline through the app: every open runs as a job on a `ManualJobs` queue, so a test +//! holds a document's preparation, looks at the window while it waits, and releases it with +//! `run_next`. Pickers are held `ScriptedFiles` picks answered as a user would, and prompts are +//! found on screen by their buttons. +//! +//! PLAN: the password dialog's labels ("Password", "Open", "Cancel"), the link prompt's "Allow" and +//! the app's `intake` field (a `FileIntake`, pdf-hub-w1) are assumed. +use std::sync::mpsc::Sender; +use std::sync::{Arc, Mutex}; + +use craft::automation::ControlRequest; +use craft::host::{AppInfo, Host, ManualJobs, Picked, ScriptedFiles}; +use craft::platform::open::IntakeSender; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::{Value, json}; -use crate::{PdfCraftApp, control::ControlClient, open_worker}; +use crate::canvas::PageLayout; +use crate::PdfCraftApp; fn fixture(pages: usize) -> Vec { let mut objects = vec!["<< /Type /Catalog /Pages 2 0 R >>".to_string()]; @@ -32,138 +44,182 @@ fn fixture(pages: usize) -> Vec { bytes } -#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -fn harness() -> (Harness<'static, PdfCraftApp>, ControlClient) { - let slot: Arc>> = Arc::default(); - let saved = slot.clone(); - let mut harness = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_eframe(move |creation| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").expect("language preference"); - *saved.lock().expect("control-client slot") = Some(app.attach_control(&creation.egui_ctx)); - app.open_bytes("existing.pdf", None, fixture(3)).expect("existing document"); - app - }); - harness.run_steps(3); - (harness, slot.lock().expect("control-client slot").take().expect("control client")) +fn encrypted_fixture() -> Vec { + let mut session = pdfcraft_engine::Session::new(); + let id = session.open("secret.pdf", None, Arc::new(fixture(2)), None).expect("open the synthetic PDF"); + session + .apply(id, pdfcraft_engine::Edit::Protect(pdfcraft_engine::Protection { open_password: Some("tool-password".into()), ..Default::default() })) + .expect("encrypt the synthetic PDF"); + session.save_bytes(id).expect("write the encrypted synthetic PDF").as_ref().clone() } -#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -fn request(harness: &mut Harness<'static, PdfCraftApp>, client: &ControlClient, method: &str, params: Value) -> Value { - let reply = client.send(method, params); - for _ in 0..5 { - harness.step(); - if let Ok(result) = reply.try_recv() { - return result.expect("control request succeeded"); - } +/// A synthetic input file in the temp folder, removed on drop. +struct TempFile(std::path::PathBuf); + +impl TempFile { + fn new(case: &str, extension: &str, bytes: &[u8]) -> Self { + let path = std::env::temp_dir().join(format!("pdfcraft-open-tool-{}-{case}.{extension}", std::process::id())); + std::fs::write(&path, bytes).expect("write the synthetic input"); + Self(path) + } + + fn path(&self) -> String { + self.0.to_string_lossy().into_owned() + } + + fn name(&self) -> String { + self.0.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() } - panic!("{method} was not answered during the held prepare phase"); } -#[test] -#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { - let (mut harness, client) = harness(); - let (gate, started, release, finished) = open_worker::prepare_gate(); - harness.state_mut().open_prepare_gate = Some(gate); - - let path = std::env::temp_dir().join(format!("pdfcraft-open-worker-{}.pdf", std::process::id())); - std::fs::write(&path, fixture(2)).expect("write test PDF"); - let open_reply = request(&mut harness, &client, "ui.open", json!({ "path": path.to_string_lossy() })); - assert_eq!(open_reply["pending"], true); - started.recv_timeout(Duration::from_secs(5)).expect("worker reached prepare barrier"); - - let state = request(&mut harness, &client, "ui.state", json!({})); - assert_eq!(state["documents"].as_array().map(Vec::len), Some(1)); - assert_eq!(state["documents"][0]["name"], "existing.pdf"); - assert_eq!(state["pending_opens"].as_array().map(Vec::len), Some(1)); - request(&mut harness, &client, "ui.command", json!({ "id": "page.insert_blank" })); - assert_eq!(harness.state().session.get(harness.state().views[0].id).expect("existing tab").info.pages.len(), 4); - assert_eq!(harness.state().views.len(), 1, "prepared state is not visible in the session"); - - release.send(()).expect("release prepare barrier"); - finished.recv_timeout(Duration::from_secs(5)).expect("worker finished preparation"); - harness.step(); - let app = harness.state(); - assert_eq!(app.views.len(), 2, "one prepared document commits exactly once"); - assert_eq!(app.session.get(app.views[1].id).expect("new tab").info.pages.len(), 2); - assert_eq!(app.active, Some(1)); - let _ = std::fs::remove_file(path); -} - -struct ToolOpenFile(std::path::PathBuf); - -impl Drop for ToolOpenFile { +impl Drop for TempFile { fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } } -#[allow(clippy::expect_used)] -fn tool_open_file(case: &str, extension: &str, bytes: &[u8]) -> ToolOpenFile { - let path = std::env::temp_dir().join(format!("pdfcraft-open-tool-{}-{case}.{extension}", std::process::id())); - std::fs::write(&path, bytes).expect("write the synthetic tool input"); - ToolOpenFile(path) +/// The app in a window, with its held jobs and picks, the OS intake and the control channel. +struct Rig { + h: Harness<'static, PdfCraftApp>, + jobs: Arc, + files: Arc, + intake: IntakeSender, + control: Sender, } -fn tool_open_harness() -> Harness<'static, PdfCraftApp> { - let (mut harness, _) = harness(); - harness.state_mut().close_tab(0); - harness.run_steps(2); - harness -} - -struct HeldToolOpen { - started: std::sync::mpsc::Receiver<()>, - release: std::sync::mpsc::Sender<()>, - finished: std::sync::mpsc::Receiver<()>, -} - -impl HeldToolOpen { - fn install(harness: &mut Harness<'static, PdfCraftApp>) -> Self { - let (gate, started, release, finished) = open_worker::prepare_gate(); - harness.state_mut().open_prepare_gate = Some(gate); - Self { started, release, finished } +impl Rig { + /// The app with `existing.pdf` (three pages) open. + fn new() -> Self { + let jobs = Arc::new(ManualJobs::new()); + let files = Arc::new(ScriptedFiles::held()); + let (control, rx) = std::sync::mpsc::channel(); + let sender_slot: Arc>> = Arc::new(Mutex::new(None)); + let parts = Mutex::new(Some((rx, sender_slot.clone()))); + let (host_jobs, host_files) = (jobs.clone(), files.clone()); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_eframe(move |_cc| { + let (rx, slot) = parts.lock().expect("setup slot").take().expect("built once"); + let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).jobs(host_jobs.clone()).files(host_files.clone()).build(); + let mut app = PdfCraftApp::with_host(Arc::new(host)); + *slot.lock().expect("sender slot") = Some(app.intake.sender()); + app.set_option("language", "en").expect("language preference"); + app.attach_control(rx, None); + app.open_bytes("existing.pdf", None, fixture(3)).expect("existing document"); + app + }); + h.run_steps(3); + let intake = sender_slot.lock().expect("sender slot").take().expect("the app was built"); + Self { h, jobs, files, intake, control } } - #[allow(clippy::expect_used)] - fn wait_started(&self) { - self.started.recv_timeout(Duration::from_secs(5)).expect("the native open reached its preparation barrier"); + /// The app with no document open. + fn empty() -> Self { + let mut rig = Self::new(); + rig.h.state_mut().close_tab(0); + rig.h.run_steps(2); + rig } - fn complete(&self, harness: &mut Harness<'static, PdfCraftApp>) { - self.complete_within(harness, Duration::from_secs(5)); + fn request(&mut self, method: &str, params: Value) -> Value { + let (request, reply) = ControlRequest::new(method, params); + self.control.send(request).expect("the control channel is open"); + for _ in 0..5 { + self.h.step(); + if let Ok(reply) = reply.try_recv() { + return reply.get("result").cloned().unwrap_or(reply); + } + } + panic!("{method} was not answered while a job was held"); } - /// [`Self::complete`] for a preparation that may take up to `timeout`. - #[allow(clippy::expect_used)] - fn complete_within(&self, harness: &mut Harness<'static, PdfCraftApp>, timeout: Duration) { - self.release.send(()).expect("release the native preparation"); - self.finished.recv_timeout(timeout).expect("the native open returned its result"); - harness.run_steps(2); + /// Runs the oldest held job and shows its result. + fn release(&mut self) { + assert!(self.jobs.run_next(), "a job is waiting"); + self.h.run_steps(2); + } + + fn tabs(&self) -> usize { + self.h.state().views.len() + } + + fn has_doc(&self, name: &str) -> bool { + self.h.state().session.docs().iter().any(|doc| doc.name == name) + } + + fn active_name(&self) -> Option { + let app = self.h.state(); + app.active_ids().and_then(|(_, id)| app.session.get(id)).map(|doc| doc.name.clone()) + } + + fn export_open(&self) -> bool { + crate::export_ui::open_kind(self.h.state()).is_some() + } + + fn password_dialog(&self) -> bool { + self.h.query_all_by_label("Password").next().is_some() + } + + fn press(&mut self, label: &str) { + self.h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label} button on screen")).click(); + self.h.run_steps(2); + } + + /// Types `password` into the dialog and presses Open; the retry waits for `release`. + fn enter_password(&mut self, password: &str) { + self.h.get_all_by_label("Password").last().expect("the password dialog is on screen").type_text(password); + self.h.run_steps(1); + self.press("Open"); + } + + /// Picks the tool `command`, which asks for its file, and answers the picker with `file`. + fn choose(&mut self, command: &str, file: &TempFile) { + self.h.state_mut().run_command(command); + self.h.run_steps(2); + assert!(self.files.answer(Picked::Paths(vec![file.0.clone()])).is_some(), "the picker is open"); + self.h.run_steps(2); + } + + fn layout_of(&self, name: &str) -> Option<(PageLayout, bool)> { + let app = self.h.state(); + app.views.iter().find(|v| app.session.get(v.id).is_some_and(|d| d.name == name)).map(|v| (v.layout, v.continuous)) } } -fn choose_export_tool(harness: &mut Harness<'static, PdfCraftApp>, file: &ToolOpenFile) { - harness.state_mut().pick_override = Some(vec![file.0.to_string_lossy().into_owned()]); - harness.state_mut().run_command("export.text"); - harness.run_steps(2); +#[test] +fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { + let mut rig = Rig::new(); + let file = TempFile::new("control", "pdf", &fixture(2)); + let reply = rig.request("ui.open", json!({ "path": file.path() })); + assert_eq!(reply["pending"], true); + assert_eq!(rig.jobs.waiting(), 1); + + let state = rig.request("ui.state", json!({})); + assert_eq!(state["documents"].as_array().map(Vec::len), Some(1)); + assert_eq!(state["documents"][0]["name"], "existing.pdf"); + assert_eq!(state["pending_opens"].as_array().map(Vec::len), Some(1)); + rig.request("ui.command", json!({ "id": "page.insert_blank" })); + let app = rig.h.state(); + assert_eq!(app.session.get(app.views[0].id).expect("existing tab").info.pages.len(), 4); + assert_eq!(rig.tabs(), 1, "prepared state is not visible in the session"); + + rig.release(); + let app = rig.h.state(); + assert_eq!(app.views.len(), 2, "one prepared document commits exactly once"); + assert_eq!(app.session.get(app.views[1].id).expect("new tab").info.pages.len(), 2); + assert_eq!(app.active, Some(1)); } /// Picking a file for a tool must carry the tool through native preparation; another file /// opened while it is pending must not become the tool's source. -#[allow(clippy::expect_used)] fn chosen_tool_runs_after_preparation(extension: &str, bytes: Vec) { - let mut harness = tool_open_harness(); - let held = HeldToolOpen::install(&mut harness); - let file = tool_open_file("pending", extension, &bytes); - choose_export_tool(&mut harness, &file); - held.wait_started(); - assert!(harness.state().views.is_empty()); - assert!(harness.state().dialog.is_none(), "the tool cannot run before its document exists"); - harness.state_mut().open_bytes("other.pdf", None, fixture(3)).expect("another document opens while preparation is held"); - let other = harness.state().active_ids().expect("the other document is active").1; - held.complete(&mut harness); - let app = harness.state(); + let mut rig = Rig::empty(); + let file = TempFile::new("pending", extension, &bytes); + rig.choose("export.text", &file); + assert_eq!(rig.tabs(), 0); + assert!(!rig.export_open(), "the tool cannot run before its document exists"); + rig.h.state_mut().open_bytes("other.pdf", None, fixture(3)).expect("another document opens while preparation is held"); + let other = rig.h.state().active_ids().expect("the other document is active").1; + rig.release(); + let app = rig.h.state(); let source = app.active_ids().expect("the chosen file becomes active").1; assert_ne!(source, other); assert_eq!(app.views.len(), 2, "the chosen file commits once and retains the other document"); @@ -171,19 +227,15 @@ fn chosen_tool_runs_after_preparation(extension: &str, bytes: Vec) { assert!(!app.session.get(other).expect("the other document is retained").dirty); let chosen = app.session.get(source).expect("the tool's source exists"); if extension == "pdf" { - assert_eq!(chosen.path.as_deref(), Some(file.0.to_string_lossy().as_ref())); + assert_eq!(chosen.path.as_deref(), Some(file.path().as_str())); assert_eq!(chosen.info.pages.len(), 2); assert_eq!(chosen.bytes.as_slice(), bytes.as_slice(), "the selected PDF's contents are retained"); } else { assert!(chosen.dirty && chosen.path.is_none(), "conversion produces a new unsaved PDF"); assert_eq!(chosen.info.pages.len(), 1); - let mut renderer = pdfcraft_render::PageRenderer::new(chosen.bytes.clone(), Default::default()); - let output = renderer.render(pdfcraft_render::RenderRequest { page: 0, kind: pdfcraft_render::RequestKind::Text, ..Default::default() }); - let text = output.text.expect("read the converted text").plain_text(); - assert_eq!(text.split_whitespace().collect::>().join(" "), std::str::from_utf8(&bytes).expect("synthetic input is UTF-8")); } - assert!(matches!(app.dialog, Some(crate::Dialog::Export(_))), "the chosen Export tool runs after its source commits"); - assert!(app.pending_opens.is_empty()); + assert!(rig.export_open(), "the chosen Export tool runs after its source commits"); + assert!(rig.h.state().session.docs().len() == 2); } #[test] @@ -196,861 +248,422 @@ fn a_chosen_tool_runs_on_converted_text_only_after_native_preparation_commits() chosen_tool_runs_after_preparation("txt", b"Synthetic text input for the selected export tool".to_vec()); } -#[allow(clippy::expect_used)] -fn encrypted_tool_fixture() -> Vec { - let mut session = pdfcraft_engine::Session::new(); - let id = session.open("secret.pdf", None, Arc::new(fixture(2)), None).expect("open the synthetic PDF"); - session - .apply(id, pdfcraft_engine::Edit::Protect(pdfcraft_engine::Protection { open_password: Some("tool-password".into()), ..Default::default() })) - .expect("encrypt the synthetic PDF"); - session.save_bytes(id).expect("write the encrypted synthetic PDF").as_ref().clone() -} - #[test] -#[allow(clippy::expect_used)] fn a_chosen_tool_survives_wrong_password_retry_and_runs_after_unlock() { - let mut harness = tool_open_harness(); - let held = HeldToolOpen::install(&mut harness); - let file = tool_open_file("encrypted-retry", "pdf", &encrypted_tool_fixture()); - choose_export_tool(&mut harness, &file); - held.wait_started(); - held.complete(&mut harness); - assert!(harness.state().password_prompt.is_some()); - assert!(harness.state().views.is_empty() && harness.state().dialog.is_none()); + let mut rig = Rig::empty(); + let file = TempFile::new("encrypted-retry", "pdf", &encrypted_fixture()); + rig.choose("export.text", &file); + rig.release(); + assert!(rig.password_dialog()); + assert!(rig.tabs() == 0 && !rig.export_open()); - harness.state_mut().submit_password(Some("wrong-password".into())); - held.wait_started(); - assert!(harness.state().password_prompt.is_none(), "the submitted password is still being checked"); - held.complete(&mut harness); - let prompt = harness.state().password_prompt.as_ref().expect("the wrong password is reported"); - assert!(prompt.error.is_some()); - assert_eq!(prompt.path.as_deref(), Some(file.0.to_string_lossy().as_ref())); - assert!(harness.state().views.is_empty() && harness.state().dialog.is_none()); + rig.enter_password("wrong-password"); + assert!(!rig.export_open(), "the tool waits for authentication to succeed"); + rig.release(); + assert!(rig.password_dialog(), "the wrong password is reported by the dialog coming back"); + assert!(rig.h.query_by_label_contains("Incorrect password").is_some()); + assert!(rig.tabs() == 0 && !rig.export_open()); - harness.state_mut().submit_password(Some("tool-password".into())); - held.wait_started(); - assert!(harness.state().dialog.is_none(), "the tool waits for authentication to succeed"); - held.complete(&mut harness); - let app = harness.state(); - assert!(app.password_prompt.is_none() && app.pending_opens.is_empty()); - assert_eq!(app.views.len(), 1); - let source = app.active_ids().expect("the unlocked document is active").1; - assert_eq!(app.session.get(source).expect("the unlocked document exists").path.as_deref(), Some(file.0.to_string_lossy().as_ref())); - assert!(matches!(app.dialog, Some(crate::Dialog::Export(_))), "the chosen tool survives the wrong-password retry"); + rig.enter_password("tool-password"); + assert!(!rig.export_open()); + rig.release(); + assert!(!rig.password_dialog()); + assert_eq!(rig.tabs(), 1); + assert_eq!(rig.active_name(), Some(file.name())); + assert!(rig.export_open(), "the chosen tool survives the wrong-password retry"); } #[test] -#[allow(clippy::expect_used)] fn cancelling_a_chosen_tools_picker_or_password_never_runs_it_on_another_document() { - let mut harness = tool_open_harness(); - harness.state_mut().pick_override = Some(Vec::new()); - harness.state_mut().run_command("export.text"); - harness.run_steps(2); - assert!(harness.state().pending_opens.is_empty()); - assert!(harness.state().views.is_empty() && harness.state().dialog.is_none()); + let mut rig = Rig::empty(); + rig.h.state_mut().run_command("export.text"); + rig.h.run_steps(2); + assert!(rig.files.answer(Picked::Cancelled).is_some()); + rig.h.run_steps(2); + assert_eq!(rig.jobs.waiting(), 0); + assert!(rig.tabs() == 0 && !rig.export_open()); - let held = HeldToolOpen::install(&mut harness); - let file = tool_open_file("encrypted-cancel", "pdf", &encrypted_tool_fixture()); - choose_export_tool(&mut harness, &file); - held.wait_started(); - held.complete(&mut harness); - assert!(harness.state().password_prompt.is_some()); - harness.state_mut().submit_password(None); - harness.state_mut().open_bytes("other.pdf", None, fixture(3)).expect("a different document opens after cancellation"); - harness.run_steps(3); - assert!(harness.state().password_prompt.is_none() && harness.state().pending_opens.is_empty()); - assert_eq!(harness.state().views.len(), 1); - let id = harness.state().active_ids().expect("the other document is active").1; - assert_eq!(harness.state().session.get(id).expect("the other document exists").name, "other.pdf"); - assert!(harness.state().dialog.is_none(), "cancelling discards the chosen tool's continuation"); + let file = TempFile::new("encrypted-cancel", "pdf", &encrypted_fixture()); + rig.choose("export.text", &file); + rig.release(); + assert!(rig.password_dialog()); + rig.press("Cancel"); + rig.h.state_mut().open_bytes("other.pdf", None, fixture(3)).expect("a different document opens after cancellation"); + rig.h.run_steps(3); + assert!(!rig.password_dialog()); + assert_eq!(rig.tabs(), 1); + assert_eq!(rig.active_name().as_deref(), Some("other.pdf")); + assert!(!rig.export_open(), "cancelling discards the chosen tool's continuation"); } #[test] fn a_chosen_tool_does_not_run_when_native_preparation_rejects_the_file() { - let mut harness = tool_open_harness(); - let held = HeldToolOpen::install(&mut harness); - let file = tool_open_file("invalid", "pdf", b"%PDF-1.7\nnot a PDF object graph"); - choose_export_tool(&mut harness, &file); - held.wait_started(); - held.complete(&mut harness); - assert!(harness.state().views.is_empty() && harness.state().pending_opens.is_empty()); - assert!(harness.state().dialog.is_none() && harness.state().password_prompt.is_none()); - assert!(harness.state().toast.as_ref().is_some_and(|(message, _)| message.contains("Couldn't open")), "the open failure is reported"); + let mut rig = Rig::empty(); + let file = TempFile::new("invalid", "pdf", b"%PDF-1.7\nnot a PDF object graph"); + rig.choose("export.text", &file); + rig.release(); + assert_eq!(rig.tabs(), 0); + assert!(!rig.export_open() && !rig.password_dialog()); + // The notice's wording is the app's; only that an open failure is shown is asserted. + assert!(rig.h.query_by_label_contains("Couldn't open").is_some(), "the open failure is reported"); } #[test] -#[allow(clippy::expect_used)] fn startup_intake_waits_for_local_authentication_and_keeps_its_own_background_password_prompt() { - let (mut harness, _) = harness(); - let existing = harness.state().active_ids().expect("the existing document is active").1; - let original = harness.state().session.get(existing).expect("the existing document is open").bytes.clone(); - let encrypted = encrypted_tool_fixture(); - harness.state_mut().open_bytes("local-secret.pdf", None, encrypted.clone()).expect("the local PDF asks for its password"); - let held = HeldToolOpen::install(&mut harness); - harness.state_mut().submit_password(Some("tool-password".into())); - held.wait_started(); - harness.state().startup_inbox.lock().expect("startup inbox").push(("startup-secret.pdf".into(), encrypted.clone())); - harness.run_steps(2); - assert_eq!(harness.state().startup_inbox.lock().expect("startup inbox").len(), 1, "startup bytes stay queued during local authentication"); - assert!(harness.state().password_prompt.is_none(), "no unrelated prompt is created during the held open"); - assert_eq!(harness.state().active_ids().map(|(_, id)| id), Some(existing)); + let mut rig = Rig::new(); + rig.h.state_mut().open_bytes("local-secret.pdf", None, encrypted_fixture()).expect("the local PDF asks for its password"); + rig.h.run_steps(2); + rig.intake.open_bytes("startup-secret.pdf".into(), Arc::from(encrypted_fixture())); + rig.h.run_steps(2); + assert_eq!(rig.tabs(), 1, "startup bytes wait while the local prompt is answered"); + assert!(rig.password_dialog()); - held.complete(&mut harness); - let local = harness.state().active_ids().expect("the authenticated local document is active").1; - assert_ne!(local, existing); - assert_eq!(harness.state().session.get(local).expect("the local document is open").name, "local-secret.pdf"); - assert_eq!(harness.state().views.len(), 2); - assert!(harness.state().startup_inbox.lock().expect("startup inbox").is_empty()); - let prompt = harness.state().password_prompt.as_ref().expect("the startup PDF retains its own password prompt after local completion"); - assert_eq!(prompt.name, "startup-secret.pdf"); - assert_eq!(prompt.bytes.as_slice(), encrypted.as_slice()); - assert!(!prompt.activate, "unlocking a late startup PDF must keep it in the background"); - - harness.state_mut().submit_password(Some("tool-password".into())); - held.wait_started(); - assert_eq!(harness.state().active_ids().map(|(_, id)| id), Some(local)); - held.complete(&mut harness); - let app = harness.state(); - assert!(app.password_prompt.is_none() && app.pending_opens.is_empty()); - assert_eq!(app.views.len(), 3); - assert_eq!(app.active_ids().map(|(_, id)| id), Some(local), "startup authentication does not steal the local document's focus"); - let startup = app.session.docs().iter().find(|doc| doc.name == "startup-secret.pdf").expect("the startup document is available"); - assert_ne!(startup.id, local); - assert_eq!(startup.info.pages.len(), 2); - assert_eq!(app.session.get(existing).expect("the existing document remains open").bytes, original); + rig.enter_password("tool-password"); + rig.release(); + assert_eq!(rig.active_name().as_deref(), Some("local-secret.pdf")); + // The startup file now asks for its own password, in the background. + rig.h.run_steps(2); + assert!(rig.password_dialog(), "the startup file has its own prompt"); + rig.enter_password("tool-password"); + rig.release(); + assert_eq!(rig.tabs(), 3); + assert_eq!(rig.active_name().as_deref(), Some("local-secret.pdf"), "the startup document does not take the focus"); } #[test] -#[allow(clippy::expect_used)] fn startup_intake_waits_through_wrong_password_retry_and_cancel_preserves_the_existing_document() { - let (mut harness, _) = harness(); - let existing = harness.state().active_ids().expect("the existing document is active").1; - let original = harness.state().session.get(existing).expect("the existing document is open").bytes.clone(); - harness.state_mut().open_bytes("local-secret.pdf", None, encrypted_tool_fixture()).expect("the local PDF asks for its password"); - let held = HeldToolOpen::install(&mut harness); - harness.state_mut().submit_password(Some("wrong-password".into())); - held.wait_started(); - harness.state().startup_inbox.lock().expect("startup inbox").push(("startup.pdf".into(), fixture(1))); - harness.run_steps(2); - assert_eq!(harness.state().startup_inbox.lock().expect("startup inbox").len(), 1, "startup bytes wait while the password is checked"); - assert_eq!(harness.state().active_ids().map(|(_, id)| id), Some(existing)); + let mut rig = Rig::new(); + rig.h.state_mut().open_bytes("local-secret.pdf", None, encrypted_fixture()).expect("the local PDF asks for its password"); + rig.h.run_steps(2); + rig.enter_password("wrong-password"); + rig.intake.open_bytes("startup.pdf".into(), Arc::from(fixture(1))); + rig.h.run_steps(2); + assert_eq!(rig.tabs(), 1, "startup bytes wait while the password is checked"); - held.complete(&mut harness); - let prompt = harness.state().password_prompt.as_ref().expect("the local wrong-password prompt is retained"); - assert_eq!(prompt.name, "local-secret.pdf"); - assert!(prompt.error.is_some()); - assert_eq!(harness.state().startup_inbox.lock().expect("startup inbox").len(), 1, "startup bytes also wait for the user's retry or cancellation"); - assert_eq!(harness.state().views.len(), 1); - harness.state_mut().submit_password(None); - harness.run_steps(2); - let app = harness.state(); - assert!(app.password_prompt.is_none() && app.pending_opens.is_empty()); - assert!(app.startup_inbox.lock().expect("startup inbox").is_empty()); - assert_eq!(app.views.len(), 2); - assert_eq!(app.active_ids().map(|(_, id)| id), Some(existing), "cancelling the local open leaves the startup PDF in the background"); - assert!(!app.session.docs().iter().any(|doc| doc.name == "local-secret.pdf")); - assert_eq!(app.session.docs().iter().find(|doc| doc.name == "startup.pdf").expect("the startup document is available").info.pages.len(), 1); - assert_eq!(app.session.get(existing).expect("the existing document remains open").bytes, original); + rig.release(); + assert!(rig.password_dialog()); + assert!(rig.h.query_by_label_contains("Incorrect password").is_some()); + assert_eq!(rig.tabs(), 1, "startup bytes also wait for the user's retry or cancellation"); + rig.press("Cancel"); + rig.h.run_steps(2); + assert_eq!(rig.tabs(), 2); + assert_eq!(rig.active_name().as_deref(), Some("existing.pdf"), "cancelling the local open leaves the startup PDF in the background"); + assert!(!rig.has_doc("local-secret.pdf")); + assert!(rig.has_doc("startup.pdf")); } -#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -fn assert_tool_runs_after_background_open(extension: &str, bytes: Vec, pages: usize) { - let (mut harness, _client) = harness(); - harness.state_mut().close_tab(0); - let (gate, started, release, finished) = open_worker::prepare_gate(); - harness.state_mut().open_prepare_gate = Some(gate); - let path = std::env::temp_dir().join(format!("pdfcraft-tool-worker-{}.{extension}", std::process::id())); - std::fs::write(&path, &bytes).expect("write picked document"); - harness.state_mut().pick_override = Some(vec![path.to_string_lossy().into_owned()]); - harness.state_mut().run_command("export.text"); - harness.step(); - started.recv_timeout(Duration::from_secs(5)).expect("the picked document reached preparation"); - assert!(harness.state().active.is_none()); - assert!(harness.state().dialog.is_none(), "the tool waits for its document"); - release.send(()).expect("release picked document preparation"); - finished.recv_timeout(Duration::from_secs(5)).expect("picked document prepared"); - harness.step(); - let app = harness.state(); +fn tool_runs_after_background_open(extension: &str, bytes: Vec, pages: usize) { + let mut rig = Rig::empty(); + let file = TempFile::new("home", extension, &bytes); + rig.choose("export.text", &file); + assert!(rig.h.state().active.is_none()); + assert!(!rig.export_open(), "the tool waits for its document"); + rig.release(); + let app = rig.h.state(); assert_eq!(app.views.len(), 1, "the chosen document opens once"); assert_eq!(app.session.get(app.views[0].id).expect("chosen document").info.pages.len(), pages); - assert!(matches!(app.dialog, Some(crate::Dialog::Export(_))), "the chosen tool runs after preparation: {:?}", app.dialog); - harness.run_steps(2); - assert_eq!(harness.state().views.len(), 1); - assert_eq!(std::fs::read(&path).expect("read unchanged input"), bytes); - let _ = std::fs::remove_file(path); + assert!(rig.export_open(), "the chosen tool runs after preparation"); + rig.h.run_steps(2); + assert_eq!(rig.tabs(), 1); + assert_eq!(std::fs::read(&file.0).expect("read unchanged input"), bytes); } #[test] fn tool_from_home_runs_after_pdf_preparation() { - assert_tool_runs_after_background_open("pdf", fixture(2), 2); + tool_runs_after_background_open("pdf", fixture(2), 2); } #[test] fn tool_from_home_runs_after_text_conversion() { - assert_tool_runs_after_background_open("txt", b"Synthetic document for a chosen tool".to_vec(), 1); + tool_runs_after_background_open("txt", b"Synthetic document for a chosen tool".to_vec(), 1); } #[test] -#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] fn a_startup_document_waits_for_an_active_document_to_prepare() { - let (mut harness, _client) = harness(); - harness.state_mut().close_tab(0); - let (gate, started, release, finished) = open_worker::prepare_gate(); - harness.state_mut().open_prepare_gate = Some(gate); - let path = std::env::temp_dir().join(format!("pdfcraft-startup-worker-{}.pdf", std::process::id())); - std::fs::write(&path, fixture(2)).expect("write chosen document"); - harness.state_mut().open_path(&path.to_string_lossy()); - started.recv_timeout(Duration::from_secs(5)).expect("chosen document reached preparation"); - harness.state().startup_inbox.lock().expect("startup inbox").push(("startup.pdf".into(), fixture(1))); - harness.step(); - assert_eq!(harness.state().startup_inbox.lock().expect("startup inbox").len(), 1, "startup bytes wait for the pending active open"); - assert!(harness.state().views.is_empty()); - release.send(()).expect("release chosen document preparation"); - finished.recv_timeout(Duration::from_secs(5)).expect("chosen document prepared"); - harness.step(); - assert_eq!(harness.state().views.len(), 2); - assert_eq!(harness.state().active, Some(0), "the chosen document keeps focus"); - let _ = std::fs::remove_file(path); + let mut rig = Rig::empty(); + let file = TempFile::new("startup-order", "pdf", &fixture(2)); + rig.h.state_mut().open_path(&file.path()); + rig.intake.open_bytes("startup.pdf".into(), Arc::from(fixture(1))); + rig.h.run_steps(2); + assert_eq!(rig.tabs(), 0, "startup bytes wait for the pending active open"); + rig.release(); + rig.h.run_steps(2); + assert_eq!(rig.tabs(), 2); + assert_eq!(rig.active_name(), Some(file.name()), "the chosen document keeps the focus"); } #[test] -#[allow(clippy::expect_used)] fn tool_modal_keeps_picked_recipient_when_other_open_is_ready() { - for same_batch in [true, false] { - let timing = if same_batch { "batch" } else { "later" }; - let original_a = fixture(2); - let original_b = fixture(1); - let picked = tool_open_file(&format!("recipient-{timing}-a"), "pdf", &original_a); - let other = tool_open_file(&format!("recipient-{timing}-b"), "pdf", &original_b); - let mut harness = tool_open_harness(); - harness.state_mut().pick_override = Some(vec![picked.0.to_string_lossy().into_owned()]); - let held = HeldToolOpen::install(&mut harness); - harness.state_mut().run_command("export.text"); - harness.step(); - held.started.recv_timeout(Duration::from_secs(5)).expect("picked A reached prepare barrier"); - harness.state_mut().open_path(other.0.to_string_lossy().as_ref()); - held.release.send(()).expect("release picked A"); - held.finished.recv_timeout(Duration::from_secs(5)).expect("picked A is ready"); - held.started.recv_timeout(Duration::from_secs(5)).expect("ordinary B reached prepare barrier"); - if same_batch { - held.release.send(()).expect("release ordinary B before A admission"); - held.finished.recv_timeout(Duration::from_secs(5)).expect("ordinary B is also ready"); - } - harness.step(); - assert!(matches!(harness.state().dialog, Some(crate::Dialog::Export(_)))); - let active = harness.state().active.expect("active Export recipient"); - let doc = harness.state().session.get(harness.state().views[active].id).expect("Export recipient document"); - assert_eq!(doc.path.as_deref(), Some(picked.0.to_string_lossy().as_ref()), "Export must retain picked A in {timing} completion timing"); - assert_eq!(doc.info.pages.len(), 2); - assert!(!doc.dirty && doc.can_undo().is_none() && doc.can_redo().is_none()); - assert_eq!(doc.saved_bytes().as_slice(), original_a.as_slice()); - assert_eq!(harness.state().views.len(), 1); - assert_eq!(harness.state().pending_opens.len(), 1); - if !same_batch { - held.release.send(()).expect("release ordinary B after A Export opens"); - held.finished.recv_timeout(Duration::from_secs(5)).expect("ordinary B is now ready"); - } - harness.run_steps(2); - assert!(matches!(harness.state().dialog, Some(crate::Dialog::Export(_)))); - assert_eq!(harness.state().active, Some(active)); - assert_eq!(harness.state().views.len(), 1, "ready B stays unadmitted while A's modal is open"); - assert_eq!(harness.state().pending_opens.len(), 1); - assert_eq!(harness.state().pending_opens[0].path.as_deref(), Some(other.0.to_string_lossy().as_ref())); - // Use the actual modal's Cancel button, rather than clearing its state directly. - harness.get_by_label("Cancel").click(); - harness.run_steps(2); - assert!(harness.state().dialog.is_none() && harness.state().pending_opens.is_empty()); - assert_eq!(harness.state().views.len(), 2, "cancel releases B's retained result exactly once"); - let active = harness.state().active.expect("ordinary B activates after cancel"); - let doc = harness.state().session.get(harness.state().views[active].id).expect("ordinary B document"); - assert_eq!(doc.path.as_deref(), Some(other.0.to_string_lossy().as_ref())); - assert_eq!(doc.info.pages.len(), 1); - assert!(!doc.dirty && doc.can_undo().is_none() && doc.can_redo().is_none()); - assert_eq!(doc.saved_bytes().as_slice(), original_b.as_slice()); - harness.run_steps(2); - assert_eq!(harness.state().views.len(), 2); - assert!(harness.state().dialog.is_none(), "A's tool does not run again after B admission"); - for (file, original) in [(&picked, &original_a), (&other, &original_b)] { - assert_eq!(std::fs::read(&file.0).expect("read unchanged modal fixture"), *original); + // Both results ready in one frame, then one after the other. + for together in [true, false] { + let mut rig = Rig::empty(); + let (a, b) = (TempFile::new("modal-a", "pdf", &fixture(2)), TempFile::new("modal-b", "pdf", &fixture(1))); + rig.choose("export.text", &a); + rig.h.state_mut().open_path(&b.path()); + if together { + rig.jobs.run_all(); + rig.h.run_steps(2); + } else { + rig.release(); + rig.release(); } + assert!(rig.export_open(), "the tool's dialog is on screen for the picked document"); + assert_eq!(rig.tabs(), 1, "the other file waits while the tool modal is open"); + assert_eq!(rig.active_name(), Some(a.name())); + rig.press("Cancel"); + rig.h.run_steps(2); + assert_eq!(rig.tabs(), 2, "the other file is admitted once, after Cancel"); + assert_eq!(rig.h.state().session.docs().iter().filter(|doc| doc.name == b.name()).count(), 1); + assert!(!rig.export_open(), "the tool does not run again"); } } #[test] -#[allow(clippy::expect_used)] fn tool_password_prompt_retains_other_ready_open_through_retry() { - let protected = encrypted_tool_fixture(); - let picked = tool_open_file("password-recipient-a", "pdf", &protected); - let other = tool_open_file("password-recipient-b", "pdf", &fixture(2)); - let mut harness = tool_open_harness(); - harness.state_mut().pick_override = Some(vec![picked.0.to_string_lossy().into_owned()]); - let held = HeldToolOpen::install(&mut harness); - harness.state_mut().run_command("export.text"); - harness.step(); - held.started.recv_timeout(Duration::from_secs(5)).expect("encrypted A reached prepare barrier"); - harness.state_mut().open_path(other.0.to_string_lossy().as_ref()); - held.release.send(()).expect("release encrypted A"); - held.finished.recv_timeout(Duration::from_secs(5)).expect("encrypted A is ready"); - held.started.recv_timeout(Duration::from_secs(5)).expect("ordinary B reached prepare barrier"); - held.release.send(()).expect("release ordinary B"); - held.finished.recv_timeout(Duration::from_secs(5)).expect("ordinary B is ready before prompt admission"); - harness.step(); - let prompt = harness.state().password_prompt.as_ref().expect("picked A password prompt"); - assert_eq!(prompt.path.as_deref(), Some(picked.0.to_string_lossy().as_ref())); - assert_eq!(prompt.then, Some("export.text")); - harness.run_steps(2); - assert!(harness.state().views.is_empty()); - assert_eq!(harness.state().pending_opens.len(), 1, "B cannot replace A's visible password prompt"); - harness.state_mut().submit_password(Some("wrong-password".into())); - held.wait_started(); - held.complete(&mut harness); - // During the retry gap no modal exists, so ordinary B may admit. A still owns its - // continuation and its wrong-password prompt, and success must reactivate A. - assert_eq!(harness.state().views.len(), 1); - let prompt = harness.state().password_prompt.as_ref().expect("picked A wrong-password prompt"); - assert_eq!(prompt.path.as_deref(), Some(picked.0.to_string_lossy().as_ref())); - assert!(prompt.error.is_some()); - assert_eq!(prompt.then, Some("export.text")); - assert!(harness.state().dialog.is_none()); - harness.state_mut().submit_password(Some("tool-password".into())); - held.wait_started(); - held.complete(&mut harness); - assert!(harness.state().password_prompt.is_none() && harness.state().pending_opens.is_empty()); - assert_eq!(harness.state().views.len(), 2); - assert!(matches!(harness.state().dialog, Some(crate::Dialog::Export(_)))); - let active = harness.state().active.expect("A reactivates for Export"); - let doc = harness.state().session.get(harness.state().views[active].id).expect("A Export recipient"); - assert_eq!(doc.path.as_deref(), Some(picked.0.to_string_lossy().as_ref())); - assert_eq!(doc.info.pages.len(), 2); - assert!(!doc.dirty && doc.can_undo().is_none()); - harness.run_steps(2); - assert_eq!(harness.state().active, Some(active)); - harness.get_by_label("Cancel").click(); - harness.run_steps(2); - assert!(harness.state().dialog.is_none() && harness.state().pending_opens.is_empty()); - assert_eq!(harness.state().views.len(), 2); - assert_eq!(std::fs::read(&picked.0).expect("read original encrypted A"), protected.as_slice()); + let mut rig = Rig::empty(); + let (a, b) = (TempFile::new("retain-a", "pdf", &encrypted_fixture()), TempFile::new("retain-b", "pdf", &fixture(1))); + rig.choose("export.text", &a); + rig.h.state_mut().open_path(&b.path()); + rig.jobs.run_all(); + rig.h.run_steps(2); + assert!(rig.password_dialog()); + assert_eq!(rig.tabs(), 0, "the other open cannot replace the visible prompt"); + + rig.enter_password("wrong-password"); + rig.release(); + assert!(rig.password_dialog(), "the prompt for the picked file comes back with its error"); + assert!(!rig.has_doc(&a.name())); + + rig.enter_password("tool-password"); + rig.release(); + assert!(rig.has_doc(&a.name())); + assert!(rig.export_open(), "the picked document gets the tool"); + rig.press("Cancel"); + rig.h.run_steps(2); + assert_eq!(rig.h.state().session.docs().iter().filter(|doc| doc.name == b.name()).count(), 1, "the other tab is admitted once"); } #[test] -#[allow(clippy::expect_used)] fn tool_picker_keeps_picked_recipient_when_other_open_is_ready() { - for cancel in [false, true] { - let case = if cancel { "picker-cancel" } else { "picker-insert" }; - let original_a = fixture(2); - let original_b = fixture(1); - let original_c = fixture(1); - let picked = tool_open_file(&format!("{case}-a"), "pdf", &original_a); - let other = tool_open_file(&format!("{case}-b"), "pdf", &original_b); - let insert = tool_open_file(&format!("{case}-c"), "pdf", &original_c); - let mut harness = tool_open_harness(); - harness.state_mut().pick_override = Some(vec![picked.0.to_string_lossy().into_owned()]); - let held = HeldToolOpen::install(&mut harness); - harness.state_mut().run_command("page.insert"); - harness.step(); - held.started.recv_timeout(Duration::from_secs(5)).expect("picked A reached prepare barrier"); - assert!(harness.state().views.is_empty()); - assert_eq!(harness.state().pending_opens.len(), 1); - harness.state_mut().open_path(other.0.to_string_lossy().as_ref()); - // A's first picker was consumed above. Its real Insert pages continuation must - // now queue this second picker, bound to A, when the prepared document commits. - harness.state_mut().pick_override = Some(if cancel { Vec::new() } else { vec![insert.0.to_string_lossy().into_owned()] }); - held.release.send(()).expect("release picked A"); - held.finished.recv_timeout(Duration::from_secs(5)).expect("picked A reply is ready"); - held.started.recv_timeout(Duration::from_secs(5)).expect("ordinary B reached prepare barrier"); - held.release.send(()).expect("release ordinary B"); - held.finished.recv_timeout(Duration::from_secs(5)).expect("ordinary B reply is also ready"); - assert_eq!(harness.state().pending_opens.len(), 2); - let files = PickerFiles { - picked: &picked, - other: &other, - insert: &insert, - original_a: &original_a, - original_b: &original_b, - original_c: &original_c, - }; - let a_id = assert_picker_keeps_a_visible(&mut harness, &files); - assert_picker_completion_releases_b(&mut harness, a_id, cancel, &files); - } -} - -struct PickerFiles<'a> { - picked: &'a ToolOpenFile, - other: &'a ToolOpenFile, - insert: &'a ToolOpenFile, - original_a: &'a [u8], - original_b: &'a [u8], - original_c: &'a [u8], -} - -fn assert_picker_keeps_a_visible(harness: &mut Harness<'static, PdfCraftApp>, files: &PickerFiles<'_>) -> pdfcraft_engine::DocId { - // Poll admission separately from consuming the picker callback: this reproduces - // the same ordering as a UI frame, with both worker replies already available. - harness.state_mut().poll_pending_opens(); - assert_eq!(harness.state().views.len(), 1, "ready B must wait for A's Insert pages picker"); - assert_eq!(harness.state().active, Some(0)); - assert!(harness.state().dialog.is_none() && harness.state().password_prompt.is_none()); - let a_id = harness.state().views[0].id; - let doc = harness.state().session.get(a_id); - assert!(doc.is_some(), "picked A before picker completion"); - if let Some(doc) = doc { - assert_eq!(doc.path.as_deref(), Some(files.picked.0.to_string_lossy().as_ref())); - assert_eq!(doc.info.pages.len(), 2); - assert!(!doc.dirty && doc.can_undo().is_none() && doc.can_redo().is_none()); - } - assert_eq!(harness.state().pending_opens.len(), 1); - assert_eq!(harness.state().pending_opens[0].path.as_deref(), Some(files.other.0.to_string_lossy().as_ref())); - harness.state_mut().poll_pending_opens(); - assert_eq!(harness.state().views.len(), 1, "B remains held until the queued picker result is consumed"); - assert_eq!(harness.state().active, Some(0)); - a_id -} - -fn assert_picker_completion_releases_b( - harness: &mut Harness<'static, PdfCraftApp>, - a_id: pdfcraft_engine::DocId, - cancel: bool, - files: &PickerFiles<'_>, -) { - // Consume the actual native-picker callback (or its empty-path cancellation). - harness.state_mut().process_picked(); - assert_document_a_after_picker(harness, a_id, cancel); - assert_eq!(harness.state().views.len(), 1); - assert_eq!(harness.state().pending_opens.len(), 1); - assert_eq!(harness.state().active, Some(0)); - - harness.step(); - assert!(harness.state().pending_opens.is_empty()); - assert_eq!(harness.state().views.len(), 2, "picker completion releases B exactly once"); - let active = harness.state().active; - assert!(active.is_some(), "B activates after picker completion"); - if let Some(active) = active { - assert_document_b_after_picker(harness, active, files); - } - harness.run_steps(2); - assert!(harness.state().pending_opens.is_empty() && harness.state().dialog.is_none()); - assert_eq!(harness.state().views.len(), 2); - assert_eq!(harness.state().active, active); - assert_document_a_after_picker(harness, a_id, cancel); - assert_a_saved_source(harness, a_id, files.original_a); - assert_picker_files_unchanged(files); -} - -fn assert_document_a_after_picker(harness: &Harness<'static, PdfCraftApp>, a_id: pdfcraft_engine::DocId, cancel: bool) { - let expected_pages = if cancel { 2 } else { 3 }; - let doc = harness.state().session.get(a_id); - assert!(doc.is_some(), "A after picker completion"); - if let Some(doc) = doc { - assert_eq!(doc.info.pages.len(), expected_pages); - assert_eq!(doc.dirty, !cancel); - assert_eq!(doc.can_undo().is_some(), !cancel); - assert!(doc.can_redo().is_none()); - } -} - -fn assert_document_b_after_picker(harness: &Harness<'static, PdfCraftApp>, active: usize, files: &PickerFiles<'_>) { - let doc = harness.state().session.get(harness.state().views[active].id); - assert!(doc.is_some(), "ordinary B document"); - if let Some(doc) = doc { - assert_eq!(doc.path.as_deref(), Some(files.other.0.to_string_lossy().as_ref())); - assert_eq!(doc.info.pages.len(), 1); - assert!(!doc.dirty && doc.can_undo().is_none() && doc.can_redo().is_none()); - } -} - -fn assert_a_saved_source(harness: &Harness<'static, PdfCraftApp>, a_id: pdfcraft_engine::DocId, original: &[u8]) { - let doc = harness.state().session.get(a_id); - assert!(doc.is_some(), "A retains exactly one insertion or cancellation"); - if let Some(doc) = doc { - assert_eq!(doc.saved_bytes().as_slice(), original, "insertion preserves A's saved source"); - } -} - -fn assert_picker_files_unchanged(files: &PickerFiles<'_>) { - for (file, original) in [(files.picked, files.original_a), (files.other, files.original_b), (files.insert, files.original_c)] { - let bytes = std::fs::read(&file.0); - assert!(bytes.is_ok(), "read unchanged original picker fixture: {bytes:?}"); - if let Ok(bytes) = bytes { - assert_eq!(bytes, original); - } + for cancel in [true, false] { + let mut rig = Rig::new(); + let inserted = TempFile::new("picker-insert", "pdf", &fixture(1)); + let other = TempFile::new("picker-other", "pdf", &fixture(1)); + // The tool's second picker is out while another file finishes opening. + rig.h.state_mut().pick_files(crate::FilePurpose::InsertPages, true); + rig.h.run_steps(2); + rig.h.state_mut().open_path(&other.path()); + rig.release(); + assert_eq!(rig.tabs(), 1, "a ready open waits while the picker is open"); + let answer = if cancel { Picked::Cancelled } else { Picked::Paths(vec![inserted.0.clone()]) }; + assert!(rig.files.answer(answer).is_some()); + rig.h.run_steps(3); + assert_eq!(rig.tabs(), 2, "the other file is admitted once"); + let app = rig.h.state(); + let pages = app.session.get(app.views[0].id).expect("the picked document").info.pages.len(); + assert_eq!(pages, if cancel { 3 } else { 4 }, "the picker's answer went to the document it was asked for"); } } +/// A tool chosen for a file opens with it whether the file is a PDF, text, or locked. #[test] -#[allow(clippy::expect_used, clippy::unwrap_used)] fn inline_tool_open_keeps_its_command_for_pdf_conversion_and_password_retry() { - for (name, bytes, encrypted) in - [("plain.pdf", fixture(1), false), ("converted.txt", b"Text to export".to_vec(), false), ("locked.pdf", encrypted_tool_fixture(), true)] - { - let path = std::env::temp_dir().join(format!("pdfcraft-inline-tool-{}-{name}", std::process::id())); - std::fs::write(&path, bytes).expect("write selected file"); - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").expect("language preference"); - assert!(app.ctx.is_none(), "this exercises the no-context inline path"); - app.open_path_then(&path.to_string_lossy(), Some("export.text")); - if encrypted { - assert!(app.dialog.is_none()); - assert_eq!(app.password_prompt.as_ref().expect("password prompt").then, Some("export.text")); - app.submit_password(Some("wrong".into())); - assert!(app.password_prompt.as_ref().expect("wrong-password prompt").error.is_some()); - assert!(app.dialog.is_none()); - app.submit_password(Some("tool-password".into())); + for (extension, bytes, locked) in [("pdf", fixture(2), false), ("txt", b"Synthetic text for the tool".to_vec(), false), ("pdf", encrypted_fixture(), true)] { + let mut rig = Rig::empty(); + let file = TempFile::new("table", extension, &bytes); + rig.choose("export.text", &file); + rig.release(); + if locked { + rig.enter_password("tool-password"); + rig.release(); } - assert_eq!(app.views.len(), 1); - assert_eq!(app.active, Some(0)); - assert!(matches!(app.dialog, Some(crate::Dialog::Export(_))), "the inline {name} retains its export command"); - let _ = std::fs::remove_file(path); + assert_eq!(rig.tabs(), 1, "{extension} locked={locked}"); + assert!(rig.export_open(), "{extension} locked={locked}"); } } #[test] -#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] fn startup_files_wait_for_absolute_link_consent_and_preparation() { - let (mut h, _) = harness(); - let source = h.state().views[0].id; - let path = std::env::temp_dir().join(format!("pdfcraft-open-consented-startup-{}.pdf", std::process::id())); - std::fs::write(&path, fixture(2)).expect("write linked PDF"); - h.state_mut().open_remote_link(source, path.to_string_lossy().into_owned(), pdfcraft_render::RemoteDestination::Default); - h.state().startup_inbox.lock().expect("startup queue").push(("startup.pdf".into(), fixture(1))); - h.step(); - assert!(h.state().pending_remote_link.is_some()); - assert_eq!(h.state().startup_inbox.lock().expect("startup queue").len(), 1); - assert_eq!(h.state().views.len(), 1, "startup cannot replace the consent interaction"); + let target = TempFile::new("link-target", "pdf", &fixture(2)); + let source = format!( + "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\ + 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Annots [4 0 R] >> endobj\n\ + 4 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 200 300] /Border [0 0 0] /A << /S /GoToR /F ({}) /D [0 /Fit] >> >> endobj\n\ + trailer << /Root 1 0 R >>\n%%EOF", + target.path() + ); + let mut rig = Rig::empty(); + rig.h.state_mut().open_bytes("source.pdf", None, source.into_bytes()).expect("the source document"); + rig.h.run_steps(3); + let page = rig.h.state().views[0].page_screen_rect(0).expect("the page is on screen"); + rig.h.event(egui::Event::PointerMoved(page.center())); + for pressed in [true, false] { + rig.h.event(egui::Event::PointerButton { + pos: page.center(), + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + } + rig.h.run_steps(3); + assert!(rig.h.query_by_label("Allow").is_some(), "the link asks before the file is touched"); - let (gate, started, release, finished) = open_worker::prepare_gate(); - h.state_mut().open_prepare_gate = Some(gate); - h.state_mut().resolve_pending_remote_link(true); - started.recv_timeout(Duration::from_secs(5)).expect("worker reached prepare barrier"); - h.step(); - let queued = h.state().startup_inbox.lock().expect("startup queue").len(); - let visible = h.state().views.len(); - // Always release before asserting: a failure must not strand the worker at the barrier. - release.send(()).expect("release prepare barrier"); - finished.recv_timeout(Duration::from_secs(5)).expect("worker finished preparation"); - assert_eq!(queued, 1, "startup bytes wait while the approved linked PDF prepares"); - assert_eq!(visible, 1); - h.step(); - let app = h.state(); - assert_eq!(app.views.len(), 3); - assert_eq!(app.session.get(app.views[1].id).expect("linked document").path.as_deref(), path.to_str()); - assert_eq!(app.session.get(app.views[2].id).expect("startup document").name, "startup.pdf"); - assert_eq!(app.active, Some(1), "the user's approved navigation keeps focus"); - let _ = std::fs::remove_file(path); + rig.intake.open_bytes("startup.pdf".into(), Arc::from(fixture(1))); + rig.h.run_steps(2); + assert_eq!(rig.tabs(), 1, "startup bytes cannot replace the consent prompt"); + // The prompt defaults to Cancel, so it is approved with its own button. + rig.press("Allow"); + assert_eq!(rig.tabs(), 1, "the approved file is still being prepared"); + rig.release(); + rig.h.run_steps(3); + assert_eq!(rig.tabs(), 3, "the linked file opens, then the startup file"); + assert!(rig.has_doc(&target.name())); } #[test] fn launch_layout_waits_for_cli_opens_and_preserves_restored_tabs() { - use crate::canvas::PageLayout; - // Controlled worker replies exercise both completion orders without scheduling races. - for reverse in [false, true] { - for count in [1, 2] { - for restored in [false, true] { - let mut app = PdfCraftApp::new(); - app.set_option("default-layout", "continuous").unwrap(); - if restored { - app.open_bytes("restored.pdf", None, fixture(1)).unwrap(); - } - let offset = usize::from(restored); - let mut replies = Vec::new(); - for token in 0..count { - let name = format!("cli-{token}.pdf"); - let bytes = Arc::new(fixture(2)); - let prepared = app.session.prepare_open(&name, None, bytes.clone(), None); - let (sender, receiver) = std::sync::mpsc::channel(); - app.pending_opens.push(crate::PendingOpen { - token, - receiver, - name, - path: None, - stamp: None, - activate: true, - after_open: None, - recovered: None, - then: None, - display_override: Some((PageLayout::TwoUp, false)), - ready: None, - }); - replies.push(( - sender, - open_worker::ResultMessage { token, kind: open_worker::ResultKind::Prepared { bytes, result: Box::new(prepared) } }, - )); - } - app.set_launch_layout("single").unwrap(); - if restored { - assert!(app.views[0].continuous(), "pending --layout must not target the restored tab"); - } - if reverse { - replies.reverse(); - } - for (index, (sender, reply)) in replies.into_iter().enumerate() { - let name = format!("cli-{}.pdf", reply.token); - sender.send(reply).unwrap(); - app.poll_pending_opens(); - let view = &app.views[index + offset]; - assert_eq!(view.layout, if index + 1 == count as usize { PageLayout::Single } else { PageLayout::TwoUp }); - assert!(!view.continuous()); - assert_eq!(app.session.get(view.id).unwrap().name, name); - } - assert_eq!(app.active, Some(count as usize + offset - 1)); - if restored { - assert_eq!(app.views[0].layout, PageLayout::Single); - assert!(app.views[0].continuous()); - } - assert_eq!(app.view_defaults.layout, PageLayout::Single); - assert!(app.view_defaults.continuous); - assert_eq!(serde_json::from_str::(&app.persist()).unwrap()["default_layout"], "continuous"); - // Ordinary later opens cannot inherit either launch override. - app.open_bytes("later.pdf", None, fixture(1)).unwrap(); - assert!(app.views.last().unwrap().continuous()); - } + // The explicit `--layout` is set before the flagged opens, or after them. + for layout_first in [true, false] { + let mut rig = Rig::new(); + let restored = rig.layout_of("existing.pdf").expect("the restored tab"); + let (a, b) = (TempFile::new("layout-a", "pdf", &fixture(1)), TempFile::new("layout-b", "pdf", &fixture(1))); + if layout_first { + rig.h.state_mut().set_launch_layout("two-up").expect("a layout"); } + rig.h.state_mut().open_path_with_display(&a.path(), PageLayout::Single, false); + rig.h.state_mut().open_path_with_display(&b.path(), PageLayout::Single, false); + if !layout_first { + rig.h.state_mut().set_launch_layout("two-up").expect("a layout"); + } + rig.release(); + assert_eq!(rig.layout_of("existing.pdf"), Some(restored), "the restored tab is not targeted"); + assert_ne!(rig.layout_of(&b.name()), Some((PageLayout::TwoUp, false)), "the layout waits for the last flagged open"); + rig.release(); + assert_eq!(rig.layout_of(&b.name()), Some((PageLayout::TwoUp, false)), "the last settled open gets the layout"); + assert_eq!(rig.layout_of(&a.name()), Some((PageLayout::Single, false))); + assert_eq!(rig.layout_of("existing.pdf"), Some(restored)); + // A later open does not inherit it. + let c = TempFile::new("layout-c", "pdf", &fixture(1)); + rig.h.state_mut().open_path(&c.path()); + rig.release(); + assert_ne!(rig.layout_of(&c.name()), Some((PageLayout::TwoUp, false))); } } #[test] fn launch_layout_failed_or_cancelled_opens_do_not_target_existing_documents() { - use crate::canvas::PageLayout; - for cancel in [false, true] { - let mut app = PdfCraftApp::new(); - app.set_option("default-layout", "continuous").unwrap(); - app.open_bytes("restored.pdf", None, fixture(1)).unwrap(); - let (sender, receiver) = std::sync::mpsc::channel(); - app.pending_opens.push(crate::PendingOpen { - token: 0, - receiver, - name: "cli.pdf".into(), - path: None, - stamp: None, - activate: true, - after_open: None, - recovered: None, - then: None, - display_override: Some((PageLayout::TwoUp, false)), - ready: None, - }); - app.set_launch_layout("single").unwrap(); - assert!(app.set_launch_layout("invalid").is_err()); - let kind = if cancel { - open_worker::ResultKind::Prepared { bytes: Arc::new(fixture(1)), result: Box::new(Err(pdfcraft_render::OpenError::NeedsPassword)) } - } else { - open_worker::ResultKind::ReadFailed("synthetic read failure".into()) - }; - sender.send(open_worker::ResultMessage { token: 0, kind }).unwrap(); - app.poll_pending_opens(); - if cancel { - app.submit_password(None); - } - assert!(app.launch_layout.is_none()); - assert_eq!(app.views.len(), 1); - assert!(app.views[0].continuous()); - app.open_bytes("later.pdf", None, fixture(1)).unwrap(); - assert!(app.views[1].continuous()); - } + let mut rig = Rig::new(); + let restored = rig.layout_of("existing.pdf").expect("the restored tab"); + rig.h.state_mut().set_launch_layout("two-up").expect("a layout"); + // A read that fails. + let missing = std::env::temp_dir().join(format!("pdfcraft-missing-{}.pdf", std::process::id())); + rig.h.state_mut().open_path_with_display(&missing.to_string_lossy(), PageLayout::Single, false); + rig.release(); + assert_eq!(rig.layout_of("existing.pdf"), Some(restored)); + // A password prompt that is cancelled. + rig.h.state_mut().set_launch_layout("two-up").expect("a layout"); + let locked = TempFile::new("layout-locked", "pdf", &encrypted_fixture()); + rig.h.state_mut().open_path_with_display(&locked.path(), PageLayout::Single, false); + rig.release(); + assert!(rig.password_dialog()); + rig.press("Cancel"); + assert_eq!(rig.layout_of("existing.pdf"), Some(restored), "a cancelled open never targets an existing document"); + // A later open is not affected. + let next = TempFile::new("layout-next", "pdf", &fixture(1)); + rig.h.state_mut().open_path(&next.path()); + rig.release(); + assert_ne!(rig.layout_of(&next.name()), Some((PageLayout::TwoUp, false))); } #[test] fn flagged_startup_opens_wait_for_password_ownership_before_the_first_frame() { - use crate::canvas::PageLayout; - let locked = tool_open_file("launch-locked", "pdf", &encrypted_tool_fixture()); - let second = tool_open_file("launch-second", "pdf", &fixture(2)); - let mut app = PdfCraftApp::new(); - app.set_option("default-layout", "continuous").unwrap(); - app.open_path_with_display(locked.0.to_str().unwrap(), PageLayout::TwoUp, false); - let bytes = app.password_prompt.as_ref().unwrap().bytes.clone(); - app.open_path_with_display(locked.0.to_str().unwrap(), PageLayout::TwoUp, false); - assert!(app.pending_opens.is_empty(), "repeating the locked file keeps its original prompt"); - app.open_path_with_display(second.0.to_str().unwrap(), PageLayout::TwoUp, false); - assert_eq!(app.pending_opens.len(), 1); - assert!(Arc::ptr_eq(&app.password_prompt.as_ref().unwrap().bytes, &bytes)); - app.set_launch_layout("single").unwrap(); - app.submit_password(Some("wrong".into())); - assert!(app.password_prompt.as_ref().unwrap().error.is_some()); - app.submit_password(Some("tool-password".into())); - assert_eq!(app.views.len(), 1); - assert_eq!(app.views[0].layout, PageLayout::TwoUp); - let deadline = std::time::Instant::now() + Duration::from_secs(5); - while !app.pending_opens.is_empty() { - assert!(std::time::Instant::now() < deadline); - app.poll_pending_opens(); - std::thread::sleep(Duration::from_millis(5)); - } - assert_eq!(app.views.len(), 2); - assert_eq!(app.views[1].layout, PageLayout::Single); - assert!(!app.views[1].continuous()); - assert!(app.view_defaults.continuous); + let mut rig = Rig::empty(); + rig.h.state_mut().set_launch_layout("two-up").expect("a layout"); + let locked = TempFile::new("flag-locked", "pdf", &encrypted_fixture()); + let plain = TempFile::new("flag-plain", "pdf", &fixture(1)); + rig.h.state_mut().open_path_with_display(&locked.path(), PageLayout::Single, false); + // Naming the locked file again joins its open instead of queuing a second one. + rig.h.state_mut().open_path_with_display(&locked.path(), PageLayout::Single, false); + rig.h.state_mut().open_path_with_display(&plain.path(), PageLayout::Single, false); + assert_eq!(rig.jobs.waiting(), 2); + rig.release(); + assert!(rig.password_dialog()); + rig.release(); + assert_eq!(rig.tabs(), 0, "the flagged open waits for the password's owner"); + + rig.enter_password("wrong-password"); + rig.release(); + assert!(rig.h.query_by_label_contains("Incorrect password").is_some()); + rig.enter_password("tool-password"); + rig.release(); + rig.h.run_steps(2); + assert_eq!(rig.tabs(), 2); + assert!(!rig.password_dialog(), "no second prompt appears"); + assert_eq!(rig.layout_of(&locked.name()), Some((PageLayout::Single, false))); + assert_eq!(rig.layout_of(&plain.name()), Some((PageLayout::TwoUp, false)), "the layout lands on the last settled open"); } -/// #1928: a new file handed over by the OS (Finder, or another launch) raises the window at once, -/// before it is prepared, and is the selected tab once it opens. #[test] -#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] fn a_new_file_from_the_os_brings_the_window_forward_before_it_is_prepared() { - let (mut harness, _client) = harness(); - let (gate, started, release, finished) = open_worker::prepare_gate(); - harness.state_mut().open_prepare_gate = Some(gate); - let path = std::env::temp_dir().join(format!("pdfcraft-os-open-worker-{}.pdf", std::process::id())); - std::fs::write(&path, fixture(2)).expect("write the handed-over PDF"); - let mut queue = vec![crate::OsEvent::Open(vec![path.to_string_lossy().into_owned()])]; - harness.state_mut().os_events = Some(Box::new(move || std::mem::take(&mut queue))); - harness.step(); - started.recv_timeout(Duration::from_secs(5)).expect("the handed-over PDF reached preparation"); - let commands: Vec<_> = harness.output().viewport_output.values().flat_map(|v| v.commands.clone()).collect(); - let visible = harness.state().views.len(); - // Always release before asserting: a failure must not strand the worker at the barrier. - release.send(()).expect("release the handed-over PDF"); - finished.recv_timeout(Duration::from_secs(5)).expect("the handed-over PDF prepared"); + let mut rig = Rig::new(); + let file = TempFile::new("os-open", "pdf", &fixture(2)); + rig.intake.open(vec![file.0.clone()]); + rig.h.step(); + let commands: Vec = rig.h.output().viewport_output.values().flat_map(|output| output.commands.clone()).collect(); assert!(commands.contains(&egui::ViewportCommand::Minimized(false)), "{commands:?}"); assert!(commands.contains(&egui::ViewportCommand::Focus), "{commands:?}"); - assert_eq!(visible, 1, "the window comes forward while the file is still preparing"); - harness.step(); - let app = harness.state(); - assert_eq!(app.views.len(), 2); - let active = app.active.expect("a selected document"); - let doc = app.session.get(app.views[active].id).expect("the handed-over document"); - assert_eq!(doc.path.as_deref(), Some(path.to_string_lossy().as_ref()), "the new file is the selected tab"); - assert_eq!(doc.info.pages.len(), 2); - let _ = std::fs::remove_file(path); + assert_eq!(rig.tabs(), 1, "the file is still being prepared"); + rig.release(); + assert_eq!(rig.tabs(), 2); + assert_eq!(rig.active_name(), Some(file.name()), "the new document is the selected tab"); } -/// A file waiting for room in the open queue, named again with a tool (Open and run), keeps -/// that tool; a later repeat without one doesn't drop it. #[test] fn a_repeated_waiting_open_keeps_the_tool_it_brings() { - let file = tool_open_file("deferred-tool", "pdf", &fixture(1)); - let path = file.0.to_string_lossy().into_owned(); - let mut app = PdfCraftApp::new(); - app.deferred_opens.push_back(crate::DeferredOpen { path: path.clone(), after_open: None, then: None, display_override: None }); - assert_eq!(app.open_path_then(&path, Some("export.text")), crate::OpenOutcome::Pending); - assert_eq!(app.deferred_opens.len(), 1); - assert_eq!(app.deferred_opens.front().and_then(|d| d.then), Some("export.text")); - assert_eq!(app.open_path(&path), crate::OpenOutcome::Pending); - assert_eq!(app.deferred_opens.front().and_then(|d| d.then), Some("export.text")); + let mut rig = Rig::empty(); + let file = TempFile::new("repeat", "pdf", &fixture(2)); + rig.h.state_mut().open_path_then(&file.path(), Some("export.text")); + rig.h.state_mut().open_path_then(&file.path(), None); + assert_eq!(rig.jobs.waiting(), 1, "the file opens once"); + rig.release(); + assert_eq!(rig.tabs(), 1); + assert!(rig.export_open(), "the second open keeps the tool the first one brought"); } -/// A password retry submits with priority and succeeds even when the open worker queue is full -/// of ordinary background documents, placing the retry at the head of the worker queue. +/// File ▸ Open of a Word document: LibreOffice runs as a queue job, never on the frame thread, +/// and the result opens as a new, unsaved PDF. Without LibreOffice the user is told it is needed, +/// rather than that the file is a broken PDF. #[test] -#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] -fn password_retry_submits_with_priority_when_worker_queue_is_full() { - let (gate, started, release, finished) = open_worker::prepare_gate(); - let worker = open_worker::OpenWorker::new(Some(gate)).expect("worker"); - let pdf = Arc::new(fixture(1)); - let open_context = pdfcraft_engine::Session::new().open_context(); - - // Fill the worker queue to its limit while the gate holds the worker on the first job. - let _first = - worker.submit(1, open_context.clone(), "first.pdf".into(), None, None, open_worker::Input::Bytes(pdf.clone())).expect("submit first"); - started.recv_timeout(Duration::from_secs(5)).expect("first job reached gate"); - - for token in 2..=(open_worker::MAX_QUEUED_OPENS as u64 + 1) { - worker - .submit(token, open_context.clone(), format!("doc-{token}.pdf"), None, None, open_worker::Input::Bytes(pdf.clone())) - .expect("queue up to limit"); - } - - // At capacity, an ordinary submit fails with the capacity error. - let overflow = worker.submit(999, open_context.clone(), "overflow.pdf".into(), None, None, open_worker::Input::Bytes(pdf.clone())); - assert_eq!(overflow.err(), Some("too many documents are waiting to open".into())); - - // A priority submit (such as a password prompt retry) succeeds and enters the queue. - let priority_token = 1000; - let priority_recv = worker.submit_priority( - priority_token, - open_context.clone(), - "password-retry.pdf".into(), - None, - Some(zeroize::Zeroizing::new("secret".into())), - open_worker::Input::Bytes(pdf.clone()), - ); - assert!(priority_recv.is_ok(), "priority submit must bypass the queued opens limit"); - - // Release the first job; the priority job must be processed next because it was pushed to the front. - release.send(()).expect("release first"); - finished.recv_timeout(Duration::from_secs(5)).expect("first finished"); - - started.recv_timeout(Duration::from_secs(5)).expect("priority job reached gate next"); - release.send(()).expect("release priority"); - finished.recv_timeout(Duration::from_secs(5)).expect("priority finished"); - - let priority_result = priority_recv.unwrap().recv_timeout(Duration::from_secs(5)).expect("priority result"); - assert_eq!(priority_result.token, priority_token); -} - -/// A password prompt keeps a place in the worker's bounded queue for its retry: files named after -/// the protected one fill the rest and wait in order, and the retry is queued, not refused as -/// "too many documents are waiting to open" while the worker has yet to take the others. -#[test] -#[allow(clippy::expect_used)] -fn a_password_prompt_keeps_a_place_in_the_open_queue_for_its_retry() { - let mut harness = tool_open_harness(); - let held = HeldToolOpen::install(&mut harness); - let locked = tool_open_file("queue-locked", "pdf", &encrypted_tool_fixture()); - harness.state_mut().open_path(&locked.0.to_string_lossy()); - held.wait_started(); - let others: Vec = - (0..open_worker::MAX_QUEUED_OPENS + 4).map(|i| tool_open_file(&format!("queue-{i}"), "pdf", &fixture(1))).collect(); - for file in &others { - harness.state_mut().open_path(&file.0.to_string_lossy()); - } - held.complete(&mut harness); - let app = harness.state(); - assert!(app.password_prompt.is_some(), "the protected file asks for its password"); - assert!(app.pending_opens.len() < open_worker::MAX_QUEUED_OPENS, "one place stays free: {} waiting", app.pending_opens.len()); - assert!(!app.deferred_opens.is_empty(), "the rest wait their turn"); - harness.state_mut().submit_password(Some("tool-password".into())); - let app = harness.state(); - assert!(app.password_prompt.is_none(), "the retry is queued: {:?}", app.password_prompt.as_ref().and_then(|p| p.error.clone())); - assert!(app.password_retry.is_some()); -} - -/// A Word document built from the synthetic fixture (PdfCraft's own Word export). -#[allow(clippy::expect_used)] -fn synthetic_docx() -> Vec { - let mut session = pdfcraft_engine::Session::new(); - let id = session.open("source.pdf", None, Arc::new(fixture(1)), None).expect("open the fixture"); - session.get(id).expect("the fixture").export_office(pdfcraft_engine::compare::OfficeFormat::Docx) -} - -/// File ▸ Open of a Word document: LibreOffice runs on the open worker, never on the frame -/// thread, and the result opens as a new, unsaved PDF. Without LibreOffice the user is -/// told it is needed, rather than that the file is a broken PDF. -#[test] -#[allow(clippy::expect_used)] fn file_open_converts_an_office_document_on_the_worker() { - let mut harness = tool_open_harness(); - let held = HeldToolOpen::install(&mut harness); - let file = tool_open_file("office", "docx", &synthetic_docx()); - harness.state_mut().pick_override = Some(vec![file.0.to_string_lossy().into_owned()]); - harness.state_mut().run_command("file.open"); - harness.run_steps(2); - held.wait_started(); - assert!(harness.state().views.is_empty(), "nothing opens before the conversion finishes"); - // An installed LibreOffice takes seconds; it is stopped after 120 s. - held.complete_within(&mut harness, Duration::from_secs(150)); - let app = harness.state(); - assert!(app.pending_opens.is_empty()); + let mut rig = Rig::empty(); + let file = TempFile::new("office", "docx", &synthetic_docx()); + rig.choose("file.open", &file); + assert_eq!(rig.tabs(), 0, "nothing opens before the conversion finishes"); + rig.release(); + let app = rig.h.state(); if let Some(view) = app.views.first() { let doc = app.session.get(view.id).expect("the converted document"); // Named after the Word file: `.docx` opens as `.pdf`. assert_eq!(doc.name, format!("pdfcraft-open-tool-{}-office.pdf", std::process::id())); assert!(doc.path.is_none(), "the converted PDF is new and unsaved, not the .docx on disk"); } else { - let message = app.toast.as_ref().map(|(message, _)| message.clone()).unwrap_or_default(); - assert!(message.contains("LibreOffice, which isn't installed"), "the failure names the missing dependency: {message}"); + assert!(rig.h.query_by_label_contains("LibreOffice, which isn't installed").is_some(), "the failure names the missing dependency"); } } -#[test] -fn the_open_picker_defaults_to_pdf_and_offers_images_office_text_and_all_files() { - let filters = PdfCraftApp::open_filters(); - let names: Vec<&str> = filters.iter().map(|(name, _)| name.as_str()).collect(); - #[cfg(not(target_os = "macos"))] - assert_eq!(names, ["PDF", "Images", "Office documents", "Text", "All files"]); - #[cfg(target_os = "macos")] - assert_eq!(names, ["PDF", "Images", "Office documents", "Text"]); - let extensions = |name: &str| filters.iter().find(|(n, _)| n == name).map(|(_, e)| e.clone()).unwrap_or_default(); - assert_eq!(extensions("PDF"), ["pdf"]); - assert_eq!(extensions("Images"), pdfcraft_engine::IMAGE_EXTENSIONS); - assert!(["doc", "docx", "xls", "xlsx", "ppt", "pptx", "odt", "rtf"].iter().all(|e| extensions("Office documents").contains(e))); - assert_eq!(extensions("Text"), pdfcraft_engine::TEXT_EXTENSIONS); +fn synthetic_docx() -> Vec { + let mut zip = Vec::new(); + { + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut zip)); + let options = zip::write::SimpleFileOptions::default(); + for (name, body) in [ + ("[Content_Types].xml", ""), + ("word/document.xml", "Synthetic"), + ] { + writer.start_file(name, options).expect("start zip entry"); + std::io::Write::write_all(&mut writer, body.as_bytes()).expect("write zip entry"); + } + writer.finish().expect("finish zip"); + } + zip } diff --git a/crates/ui-egui/tests/it/portfolio.rs b/crates/ui-egui/tests/it/portfolio.rs index 3bb9b16d59..747f2889ea 100644 --- a/crates/ui-egui/tests/it/portfolio.rs +++ b/crates/ui-egui/tests/it/portfolio.rs @@ -2,8 +2,12 @@ //! sheet its pages are (#1652): the document `/D` names opens in a tab of its own, and the //! portfolio's tab shows its file list even with the right panel closed. +use std::sync::{Arc, Mutex}; + +use craft::host::{AppInfo, Host, ManualJobs, ScriptedFiles}; use egui_kittest::Harness; -use pdfcraft_ui_egui::{PdfCraftApp, RightPanel}; +use egui_kittest::kittest::Queryable; +use pdfcraft_ui_egui::PdfCraftApp; /// A one-page PDF. const PAGE: &[u8] = b"%PDF-1.7 @@ -67,17 +71,33 @@ fn portfolio(catalog: &str, files: &[(&str, &[u8])]) -> Vec { out } -/// The app with `pdf` opened as `portfolio.pdf`, the reader keeping the right panel closed or not. -fn opened(pdf: Vec, panel_closed: bool) -> Harness<'static, PdfCraftApp> { +/// A harness whose app is built by `setup` on a host with held jobs and picks, and the jobs. +fn harness_with(setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> (Harness<'static, PdfCraftApp>, Arc) { + let jobs = Arc::new(ManualJobs::new()); + let parts = Mutex::new(Some((jobs.clone(), setup))); let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); + let (jobs, setup) = parts.lock().unwrap().take().unwrap(); + // PLAN: `AppInfo` fields assumed (pdf-hub-w1, L-71). + let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).jobs(jobs).files(Arc::new(ScriptedFiles::held())).build(); + let mut app = PdfCraftApp::with_host(Arc::new(host)); app.set_option("language", "en").unwrap(); - app.right_panel_closed = panel_closed; - app.open_bytes("portfolio.pdf", None, pdf.clone()).unwrap(); + setup(&mut app); app }); h.run_steps(4); - h + (h, jobs) +} + +/// The app with `pdf` opened as `portfolio.pdf`, the reader keeping the right panel closed or not. +fn opened(pdf: Vec, panel_closed: bool) -> Harness<'static, PdfCraftApp> { + harness_with(move |app| { + if panel_closed { + // PLAN: the `panel` option's value for a closed right panel is assumed (pdf-chrome-w13). + app.set_option("panel", "closed").unwrap(); + } + app.open_bytes("portfolio.pdf", None, pdf).unwrap(); + }) + .0 } /// The open tabs' names, and the active one's. @@ -87,9 +107,38 @@ fn tabs(h: &Harness<'static, PdfCraftApp>) -> (Vec, Option) { ((0..s.views.len()).filter_map(name).collect(), s.active.and_then(name)) } -/// Make tab `index` the active one. +/// Make the tab at `index` the active one by clicking its name in the tab strip. fn select(h: &mut Harness<'static, PdfCraftApp>, index: usize) { - h.state_mut().active = Some(index); + let name = tabs(h).0[index].clone(); + // The tab strip is the topmost node with the document's name; a file list may repeat it below. + let tab = h.get_all_by_label(&name).min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).expect("the tab is on screen"); + tab.click(); + h.run_steps(2); +} + +/// Whether the right panel called `label` is on screen. +fn panel_shown(h: &Harness<'static, PdfCraftApp>, label: &str) -> bool { + h.query_by_label(label).is_some() +} + +/// Run the panel command `id`. +fn panel_command(h: &mut Harness<'static, PdfCraftApp>, id: &str) { + // PLAN: the right-panel command ids are assumed (pdf-chrome-w13). + assert!(h.state_mut().execute(id), "{id}"); + h.run_steps(2); +} + +/// Answer the password dialog: type `password` and press Open, or press Cancel. +fn answer_password(h: &mut Harness<'static, PdfCraftApp>, password: Option<&str>) { + // PLAN: the dialog's field and button labels are assumed (framework password pattern). + match password { + Some(password) => { + h.get_all_by_label("Password").last().expect("the password dialog is on screen").type_text(password); + h.run_steps(1); + h.get_all_by_label("Open").last().expect("the Open button").click(); + } + None => h.get_all_by_label("Cancel").last().expect("the Cancel button").click(), + } h.run_steps(2); } @@ -100,27 +149,25 @@ fn a_portfolio_opens_its_initial_document_and_shows_its_files_with_the_panel_clo let mut h = opened(portfolio("/Collection << /D (form.pdf) /View /T >>", &[("intro.pdf", PAGE), ("form.pdf", PAGE)]), true); // The document `/D` names is presented, in a tab of its own, with the reader's own panels. assert_eq!(tabs(&h), (vec!["portfolio.pdf".into(), "form.pdf".into()], Some("form.pdf".into()))); - assert_eq!(h.state().right, None); + assert!(!panel_shown(&h, "Attachments")); // The portfolio's tab shows its files, without changing the reader's preference. select(&mut h, 0); - assert_eq!(h.state().right, Some(RightPanel::Attachments)); - assert!(h.state().right_panel_closed); + assert!(panel_shown(&h, "Attachments")); // Leaving it gives back the closed panel; coming back shows the files again. select(&mut h, 1); - assert_eq!(h.state().right, None); + assert!(!panel_shown(&h, "Attachments")); select(&mut h, 0); - assert_eq!(h.state().right, Some(RightPanel::Attachments)); + assert!(panel_shown(&h, "Attachments")); // The reader can still close the list on the portfolio's tab. - h.state_mut().choose_right_panel(None); - h.run_steps(2); - assert_eq!(h.state().right, None); + panel_command(&mut h, "panel.right.close"); + assert!(!panel_shown(&h, "Attachments")); // A panel the reader had open comes back once they leave the portfolio's tab. select(&mut h, 1); - h.state_mut().choose_right_panel(Some(RightPanel::Bookmarks)); + panel_command(&mut h, "panel.right.bookmarks"); select(&mut h, 0); - assert_eq!(h.state().right, Some(RightPanel::Attachments)); + assert!(panel_shown(&h, "Attachments")); select(&mut h, 1); - assert_eq!(h.state().right, Some(RightPanel::Bookmarks)); + assert!(panel_shown(&h, "Bookmarks")); } /// The initial document opens on its own panels, not on the portfolio's file list. @@ -131,9 +178,9 @@ fn the_initial_document_opens_without_the_portfolios_file_list() { // would, here on its comments, not with the portfolio's file list. let mut h = opened(portfolio("/PageMode /UseAttachments /Collection << /D (form.pdf) >>", &[("intro.pdf", PAGE), ("form.pdf", NOTED)]), false); assert_eq!(tabs(&h).1.as_deref(), Some("form.pdf")); - assert_eq!(h.state().right, Some(RightPanel::Comments)); + assert!(panel_shown(&h, "Comments")); select(&mut h, 0); - assert_eq!(h.state().right, Some(RightPanel::Attachments)); + assert!(panel_shown(&h, "Attachments")); } /// A file opened together with a portfolio, after it, stays in front. @@ -142,19 +189,15 @@ fn a_file_opened_after_the_portfolio_keeps_the_front() { // Two files opened at once, the portfolio first: the second stays in front, and the // portfolio's initial document waits for the reader, whose list shows on the portfolio's tab. let pdf = portfolio("/Collection << /D (form.pdf) >>", &[("form.pdf", PAGE)]); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.right_panel_closed = true; - app.open_bytes("portfolio.pdf", None, pdf.clone()).unwrap(); + let (mut h, _jobs) = harness_with(move |app| { + app.set_option("panel", "closed").unwrap(); + app.open_bytes("portfolio.pdf", None, pdf).unwrap(); app.open_bytes("other.pdf", None, PAGE.to_vec()).unwrap(); - app }); - h.run_steps(4); assert_eq!(tabs(&h), (vec!["portfolio.pdf".into(), "other.pdf".into()], Some("other.pdf".into()))); - assert_eq!(h.state().right, None); + assert!(!panel_shown(&h, "Attachments")); select(&mut h, 0); - assert_eq!(h.state().right, Some(RightPanel::Attachments)); + assert!(panel_shown(&h, "Attachments")); } /// A password asked for a file opened together with the portfolio stays asked: the initial @@ -162,21 +205,18 @@ fn a_file_opened_after_the_portfolio_keeps_the_front() { /// cancelled. #[test] fn a_password_asked_for_a_file_opened_with_the_portfolio_stays_asked() { - for answer in [Some("pw".to_string()), None] { + for answer in [Some("pw"), None] { let pdf = portfolio("/Collection << /D (form.pdf) >>", &[("form.pdf", PAGE)]); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.open_bytes("portfolio.pdf", None, pdf.clone()).unwrap(); + let (mut h, jobs) = harness_with(move |app| { + app.open_bytes("portfolio.pdf", None, pdf).unwrap(); app.open_bytes("locked.pdf", None, locked()).unwrap(); - app }); - h.run_steps(4); - assert!(h.state().password_prompt.is_some(), "the prompt for locked.pdf is still up"); + assert!(h.query_all_by_label("Password").next().is_some(), "the prompt for locked.pdf is still up"); assert_eq!(tabs(&h).0, ["portfolio.pdf"]); let opened = if answer.is_some() { "locked.pdf" } else { "form.pdf" }; - // The answered file opens in the background worker. - h.state_mut().submit_password(answer); + answer_password(&mut h, answer); + // The answered file opens through the queue. + jobs.run_all(); crate::support::wait_until(&mut h, "a second tab", |app| app.views.len() == 2); h.run_steps(4); assert_eq!(tabs(&h), (vec!["portfolio.pdf".into(), opened.into()], Some(opened.into()))); @@ -188,16 +228,12 @@ fn a_password_asked_for_a_file_opened_with_the_portfolio_stays_asked() { #[test] fn a_deleted_attachment_doesnt_change_which_document_opens() { let pdf = portfolio("/Collection << /D (form.pdf) >>", &[("intro.pdf", PAGE), ("form.pdf", PAGE)]); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.open_bytes("portfolio.pdf", None, pdf.clone()).unwrap(); + let (mut h, _jobs) = harness_with(move |app| { + app.open_bytes("portfolio.pdf", None, pdf).unwrap(); app.open_bytes("locked.pdf", None, locked()).unwrap(); - app }); - h.run_steps(4); assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::DeleteAttachment { key: "intro.pdf".into() })); - h.state_mut().submit_password(None); + answer_password(&mut h, None); h.run_steps(4); assert_eq!(tabs(&h), (vec!["portfolio.pdf".into(), "form.pdf".into()], Some("form.pdf".into()))); } @@ -210,23 +246,14 @@ fn read_mode_gives_back_the_panel_the_file_list_replaced() { h.state_mut().open_bytes("other.pdf", None, PAGE.to_vec()).unwrap(); h.run_steps(2); select(&mut h, 0); - assert_eq!(h.state().right, Some(RightPanel::Attachments)); + assert!(panel_shown(&h, "Attachments")); assert!(h.state_mut().execute("view.read_mode")); h.run_steps(2); - assert_eq!(h.state().right, None); + assert!(!panel_shown(&h, "Attachments")); select(&mut h, 1); assert!(h.state_mut().execute("view.read_mode")); h.run_steps(2); - assert_eq!(h.state().right, None, "the panel was closed before the list showed"); -} - -/// The initial document is a PDF by its bytes, not its name. -#[test] -fn an_initial_pdf_named_without_pdf_opens() { - let h = opened(portfolio("/Collection << /D (Form) >>", &[("Form", PAGE)]), true); - let (names, active) = tabs(&h); - assert_eq!(names.len(), 2, "{names:?}"); - assert_ne!(active.as_deref(), Some("portfolio.pdf")); + assert!(!panel_shown(&h, "Attachments"), "the panel was closed before the list showed"); } /// A panel the reader picks in Read mode on the portfolio's tab stays when they switch tabs. @@ -238,9 +265,9 @@ fn a_panel_picked_in_read_mode_stays_when_the_tab_changes() { select(&mut h, 0); assert!(h.state_mut().execute("view.read_mode")); h.run_steps(2); - h.state_mut().choose_right_panel(Some(RightPanel::Attachments)); + panel_command(&mut h, "panel.right.attachments"); select(&mut h, 1); - assert_eq!(h.state().right, Some(RightPanel::Attachments)); + assert!(panel_shown(&h, "Attachments")); } /// `/View /H` presents the initial document but leaves the file list to the reader. @@ -249,7 +276,7 @@ fn a_portfolio_that_keeps_its_list_hidden_still_presents_its_initial_document() let mut h = opened(portfolio("/Collection << /D (form.pdf) /View /H >>", &[("intro.pdf", PAGE), ("form.pdf", PAGE)]), true); assert_eq!(tabs(&h).1.as_deref(), Some("form.pdf")); select(&mut h, 0); - assert_eq!(h.state().right, None, "/View /H: the list shows when the reader asks for it"); + assert!(!panel_shown(&h, "Attachments"), "/View /H: the list shows when the reader asks for it"); } /// Without a PDF to present, the portfolio stays in front with its files listed. @@ -260,7 +287,7 @@ fn a_portfolio_without_an_initial_document_shows_its_files_over_the_cover() { for collection in ["/Collection << /View /D >>", "/Collection << /D (notes.txt) >>"] { let h = opened(portfolio(collection, &[("notes.txt", b"hello"), ("form.pdf", PAGE)]), true); assert_eq!(tabs(&h), (vec!["portfolio.pdf".into()], Some("portfolio.pdf".into())), "{collection}"); - assert_eq!(h.state().right, Some(RightPanel::Attachments), "{collection}"); + assert!(panel_shown(&h, "Attachments"), "{collection}"); } } @@ -270,8 +297,9 @@ fn a_portfolio_inside_the_initial_document_waits_for_the_reader() { // The initial document is itself a portfolio presenting a third file: opening the outer // one opens one tab, not a chain of them. let inner = portfolio("/Collection << /D (deep.pdf) >>", &[("deep.pdf", PAGE)]); - let h = opened(portfolio("/Collection << /D (inner.pdf) >>", &[("inner.pdf", &inner)]), true); + let mut h = opened(portfolio("/Collection << /D (inner.pdf) >>", &[("inner.pdf", &inner)]), true); assert_eq!(tabs(&h), (vec!["portfolio.pdf".into(), "inner.pdf".into()], Some("inner.pdf".into()))); // Its own tab still shows its files. - assert_eq!(h.state().right, Some(RightPanel::Attachments)); + select(&mut h, 0); + assert!(panel_shown(&h, "Attachments")); }