mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-26 04:58:07 +00:00
pdf-shell-w13: net change of 3 commits
- pdf-shell-w13: written from its sheet - pdf-shell-w13: repair 1 - pdf-shell-w13: review fixes (review-1)
This commit is contained in:
@@ -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());
|
||||
}
|
||||
|
||||
+212
-277
@@ -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<RightPanel>) {
|
||||
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<u64, String> {
|
||||
self.schedule_open_with_priority(request, false)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn schedule_open_priority(&mut self, request: OpenRequest) -> Result<u64, String> {
|
||||
self.schedule_open_with_priority(request, true)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn schedule_open_with_priority(&mut self, request: OpenRequest, priority: bool) -> Result<u64, String> {
|
||||
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<RightPanel>) {
|
||||
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<String>) {
|
||||
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<String>) {
|
||||
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<String>) {
|
||||
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<usize> {
|
||||
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<FileFilter> {
|
||||
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)]),
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+37
-154
@@ -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<u8>), (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<pdfcraft_engine::DocId> {
|
||||
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<pdfcraft_engine::DocId> {
|
||||
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<egui::DroppedFileHandle>, ctx: &egui::Context) -> Vec<egui::DroppedFileHandle> {
|
||||
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<OsFile>) {
|
||||
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<OsFile>, at: usize) {
|
||||
let read: Vec<Result<(String, Vec<u8>), (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<std::sync::atomic::AtomicUsize>);
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
impl WebRead {
|
||||
/// Count a read starting in `reads`.
|
||||
pub(super) fn start(reads: &std::sync::Arc<std::sync::atomic::AtomicUsize>) -> 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Vec<u8>>),
|
||||
}
|
||||
|
||||
@@ -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<String>,
|
||||
pub password: Option<zeroize::Zeroizing<String>>,
|
||||
pub input: Input,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
token: u64,
|
||||
context: OpenContext,
|
||||
name: String,
|
||||
path: Option<String>,
|
||||
password: Option<zeroize::Zeroizing<String>>,
|
||||
input: Input,
|
||||
reply: Sender<ResultMessage>,
|
||||
#[cfg(test)]
|
||||
gate: Option<Arc<PrepareGate>>,
|
||||
/// 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<u64, ResultKind> {
|
||||
JobQueue::new(host.jobs_shared().clone(), wake, QueueOptions { lanes: 1, name: "pdfcraft-open", order: QueueOrder::OldestFirst })
|
||||
}
|
||||
|
||||
struct Queue {
|
||||
jobs: VecDeque<Job>,
|
||||
shutdown: bool,
|
||||
repaint: Option<egui::Context>,
|
||||
/// 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<Queue>, Condvar)>,
|
||||
#[cfg(test)]
|
||||
gate: Option<Arc<PrepareGate>>,
|
||||
}
|
||||
|
||||
impl OpenWorker {
|
||||
pub fn new(#[cfg(test)] gate: Option<Arc<PrepareGate>>) -> std::io::Result<Self> {
|
||||
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<String>,
|
||||
password: Option<zeroize::Zeroizing<String>>,
|
||||
input: Input,
|
||||
) -> Result<Receiver<ResultMessage>, 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<String>,
|
||||
password: Option<zeroize::Zeroizing<String>>,
|
||||
input: Input,
|
||||
) -> Result<Receiver<ResultMessage>, 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<String>,
|
||||
password: Option<zeroize::Zeroizing<String>>,
|
||||
input: Input,
|
||||
) -> (Job, Receiver<ResultMessage>) {
|
||||
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<Queue>, 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<Receiver<()>>,
|
||||
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<PrepareGate>, 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;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The app with `pdf` opened as `portfolio.pdf`, the reader keeping the right panel closed or not.
|
||||
fn opened(pdf: Vec<u8>, 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<ManualJobs>) {
|
||||
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<u8>, 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<String>, Option<String>) {
|
||||
((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"));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user