Merge cfix2/workflows (doc tabs: both ctx calls)

This commit is contained in:
Dylan M. Taylor
2026-11-18 16:44:51 -05:00
28 changed files with 131 additions and 124 deletions
+7 -1
View File
@@ -159,6 +159,12 @@ impl PdfCraftApp {
/// wake-ups, no autosave folder, the GitHub update source, a fresh intake and an inline watch.
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) fn for_unit_tests() -> Self {
Self::for_unit_tests_on(Arc::new(Host::builder(APP_INFO).build()))
}
/// [`for_unit_tests`](Self::for_unit_tests) over `host`, for a test whose jobs or files are scripted.
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(crate) fn for_unit_tests_on(host: Arc<Host>) -> Self {
let services = AppServices::new(
Wake::none(),
Clipboard::new(craft::platform::clipboard::SystemClipboard::new()),
@@ -167,7 +173,7 @@ impl PdfCraftApp {
FileIntake::new(Wake::none()).0,
craft::platform::watch::FileWatch::new(Wake::none()).inline(),
);
Self::with_host(Arc::new(Host::builder(APP_INFO).build()), services)
Self::with_host(host, services)
}
/// The app over `host` and `services`, with no document open: every queue runs on the host's
+1 -1
View File
@@ -643,7 +643,7 @@ fn replace_all_is_one_undo_step_and_counts_pages_whose_matches_had_no_paragraph(
let doc = h.state().session.get(id).unwrap();
assert_eq!(doc.undo_depth(), depth + 1, "both pages are one undo step");
assert_ne!(doc.bytes, before, "the text changed");
h.state_mut().undo();
h.state_mut().undo(&egui::Context::default());
let doc = h.state().session.get(id).unwrap();
assert_eq!((doc.undo_depth(), &doc.bytes), (depth, &before), "one undo puts both pages back");
}
+1 -1
View File
@@ -68,7 +68,7 @@ pub(crate) fn strip(app: &mut PdfCraftApp, ui: &mut egui::Ui, place: Place) {
app.combine_tab.focused = true;
}
DocumentTabsEvent::CloseRequested(StripTab::View(key)) => app.tab_action(ui.ctx(), Action::Close(key)),
DocumentTabsEvent::CloseRequested(StripTab::Combine) => app.close_combine_tab(),
DocumentTabsEvent::CloseRequested(StripTab::Combine) => app.close_combine_tab(ui.ctx()),
DocumentTabsEvent::Reordered { documents, before, .. } => {
for document in documents {
let StripTab::View(key) = document else { continue };
+2 -2
View File
@@ -579,8 +579,8 @@ impl PdfCraftApp {
fn run_edit_command(&mut self, ctx: &egui::Context, id: &str, active: Option<usize>) -> Option<bool> {
match id {
"edit.attach" => self.attach_file_dialog(),
"edit.undo" => self.undo(),
"edit.redo" => self.redo(),
"edit.undo" => self.undo(ctx),
"edit.redo" => self.redo(ctx),
"edit.find" => {
if let Some(i) = active {
self.views[i].open_find();
+1 -1
View File
@@ -97,7 +97,7 @@ fn results(app: &mut PdfCraftApp, ctx: &egui::Context) {
crate::a11y_ui::pass(app);
crate::actions_ui::pass(app);
crate::export_ui::pass(app);
crate::compare_ui::pass(app);
crate::compare_ui::pass(app, ctx);
// Shell.
app.recovery_pass(ctx);
app.close_guard_pass(ctx);
+4 -4
View File
@@ -315,7 +315,7 @@ impl PdfCraftApp {
}
/// Undo the last change: to the Combine files list while its tab shows, else the document.
pub fn undo(&mut self) {
pub fn undo(&mut self, ctx: &egui::Context) {
// While a polygon, cloud or run of connected lines is being drawn, Undo takes back its
// last point instead of the last finished edit.
if let Some((i, _)) = self.active_ids()
@@ -324,7 +324,7 @@ impl PdfCraftApp {
return;
}
if self.combine_showing() {
self.combine_history_step(true);
self.combine_history_step(ctx, true);
} else if !self.undo_in_page_box() {
self.history_step(true);
}
@@ -345,9 +345,9 @@ impl PdfCraftApp {
false
}
pub fn redo(&mut self) {
pub fn redo(&mut self, ctx: &egui::Context) {
if self.combine_showing() {
self.combine_history_step(false);
self.combine_history_step(ctx, false);
} else if !self.redo_in_page_box() {
self.history_step(false);
}
+1 -1
View File
@@ -92,7 +92,7 @@ fn a_refused_text_box_is_put_back_whole() {
app.open_bytes("a.pdf", None, no_changes_pdf()).unwrap();
let style = crate::content_ui::default_style();
app.views[0].session.content.draft = Some(crate::content_ui::TextDraft::new(0, None, [20.0, 20.0, 120.0, 40.0], "Typed".into(), style));
app.undo();
app.undo(&egui::Context::default());
let content = &app.views[0].session.content;
assert_eq!(content.draft.as_ref().map(|d| d.text.as_str()), Some("Typed"), "the refused box stays open");
assert_eq!(content.select_added, None, "nothing was added to select");
+1 -1
View File
@@ -85,7 +85,7 @@ pub fn panel_body(app: &mut PdfCraftApp, ui: &mut egui::Ui, cx: &mut BodyCx<'_>,
app.a11y_action(&ctx, index, a);
}
if let Some(a) = compare_action {
app.compare_action(index, a);
app.compare_action(ui.ctx(), index, a);
}
match sig_action {
Some(crate::sign_ui::PanelAction::Validate) => app.run_command(&ctx, "sign.validate"),
+1 -1
View File
@@ -565,7 +565,7 @@ mod review13_ui_tests {
assert_ne!(new, old);
let new_before = app.session.save_bytes(new).unwrap();
app.compare_old = Some(old);
app.run_compare();
app.run_compare(&egui::Context::default());
assert!(app.compare.as_ref().unwrap().side_by_side);
app.printer_source = Some(std::sync::Arc::new(Vec::new));
app.start_ui_script(old, &format!("var comparisonKept=42;{request}"), None, None);
+4 -4
View File
@@ -169,7 +169,7 @@ fn options_dialog(fields: &mut DialogFields, pages: usize, current: usize) -> Pa
.companions(shown_rule_keys(fields)),
);
params.push(Param::new("show_dialog", tl!("Show this dialog when the Checker starts"), ParamKind::bool(true)));
ParamDialog::new("a11y.options", tl!("Accessibility Checker Options"), params).ok_label(tl!("Start Checking"))
ParamDialog::new("a11y.options", tl!("Accessibility Checker Options"), params).ok_label(tl!("Start Checking").into())
}
/// Opens the Accessibility Checker Options dialog over the saved options.
@@ -502,7 +502,7 @@ impl PdfCraftApp {
self.a11y.previous = None;
self.a11y.options = Some(options);
self.a11y.report = Some((id, report));
self.right = Some(RightPanel::Accessibility);
self.set_right(Some(RightPanel::Accessibility));
self.notify(if failed == 0 {
tl!("No untagged content was found.").to_string()
} else {
@@ -547,7 +547,7 @@ impl PdfCraftApp {
if self.a11y.options.as_ref() == Some(&options) { self.a11y.report.take().filter(|(prior_id, _)| *prior_id == id) } else { None };
self.a11y.options = Some(options);
self.a11y.report = Some((id, report));
self.right = Some(RightPanel::Accessibility);
self.set_right(Some(RightPanel::Accessibility));
self.notify(if failed == 0 && manual == 0 && skipped == 0 {
tl!("The checker found no problems in this document.").to_string()
} else if failed == 1 {
@@ -612,7 +612,7 @@ impl PdfCraftApp {
return;
}
if self.tags_state.select(id, &tags, object) {
self.right = Some(RightPanel::Tags);
self.set_right(Some(RightPanel::Tags));
if let Some(page) = page {
self.a11y_show_on_page(index, page, bbox);
}
+2 -1
View File
@@ -230,7 +230,8 @@ pub(crate) fn pass(app: &mut PdfCraftApp) {
}
open_list(app, Some(name));
}
Some(DialogResult::Cancel) => open_list(app, None),
// Any answer but OK leaves the editor and returns to the list, as Cancel does.
Some(_) => open_list(app, None),
None => {}
}
}
@@ -86,7 +86,7 @@ impl PdfCraftApp {
}
/// Put `list` back (undo, redo).
fn combine_set_list(&mut self, list: CombineList) {
fn combine_set_list(&mut self, ctx: &egui::Context, list: CombineList) {
let ids: BTreeSet<u64> = list.files.iter().map(|f| f.id).collect();
let lead = list.selected.last().copied();
self.combine_draft = list.files;
@@ -96,9 +96,7 @@ impl PdfCraftApp {
self.combine_tab.revision = self.combine_tab.revision.wrapping_add(1);
// A Pages field with the keyboard would otherwise keep typing into the restored list
// without an undo step.
if let Some(ctx) = &self.ctx {
ctx.memory_mut(|m| m.stop_text_input());
}
ctx.memory_mut(|m| m.stop_text_input());
}
/// Run `change` on the list as one undo step named `label`; a change that leaves the list as it
@@ -133,7 +131,7 @@ impl PdfCraftApp {
}
/// Edit ▸ Undo / Redo (⌘Z, ⇧⌘Z) while the Combine files tab shows.
pub(crate) fn combine_history_step(&mut self, undo: bool) {
pub(crate) fn combine_history_step(&mut self, ctx: &egui::Context, undo: bool) {
// ⌘Z in the password box is not about the list, and a Pages field being edited has its own
// undo; the history never sees that edit's `Begin`, so `is_open` can't say so.
if self.combine_tab.unlock.is_some() || self.combine_tab.range_edit.is_some() {
@@ -142,7 +140,7 @@ impl PdfCraftApp {
let mut now = self.combine_list();
let step = if undo { Step::Undo } else { Step::Redo };
if self.combine_tab.history.step(&mut now, step) {
self.combine_set_list(now);
self.combine_set_list(ctx, now);
}
}
@@ -277,10 +275,9 @@ impl PdfCraftApp {
}
/// Close the Combine files tab and forget its list; the last document shows, if any.
pub fn close_combine_tab(&mut self) {
pub fn close_combine_tab(&mut self, ctx: &egui::Context) {
let showing = self.combine_showing();
// PLAN: assumed `release_thumbnails(&CombineTab)` without a context (pdf-workflows-w7; L-208)
crate::combine_grid::release_thumbnails(&self.combine_tab);
crate::combine_grid::release_thumbnails(ctx, &self.combine_tab);
// (Revisions keep counting: a drag begun before can never match a list made after.)
let revision = self.combine_tab.revision.wrapping_add(1);
self.combine_tab = CombineTab { revision, ..CombineTab::default() };
@@ -518,7 +515,7 @@ impl PdfCraftApp {
/// Combine the listed files into a new, unsaved document; the tab makes way for it.
/// Files that can't be read are left out (the user was asked).
pub fn combine_staged(&mut self) {
pub fn combine_staged(&mut self, ctx: &egui::Context) {
let files: Vec<&CombineFile> = self.combine_draft.iter().filter(|f| !f.unreadable()).collect();
if files.is_empty() {
return;
@@ -531,7 +528,7 @@ impl PdfCraftApp {
let passwords: Vec<Option<&str>> = files.iter().map(|f| f.password()).collect();
match self.session.combine_grouped(&sources, &groups, &passwords) {
Ok(bytes) => {
self.close_combine_tab();
self.close_combine_tab(ctx);
let message = crate::i18n::fmt(tl!("Combined {n} files"), &[("n", &count.to_string())]);
self.open_created("Combined.pdf", bytes, &message)
}
@@ -77,9 +77,10 @@ fn duplicate_warnings_reuse_results_and_track_removal_and_parts() {
let duplicate = app.combine_draft.last().unwrap().id;
app.combine_apply(RowAction::RemoveFile(duplicate));
assert_eq!(&*app.combine_tab.duplicate_warnings(&app.combine_draft), &[false, false]);
app.combine_history_step(true);
let ctx = egui::Context::default();
app.combine_history_step(&ctx, true);
assert_eq!(&*app.combine_tab.duplicate_warnings(&app.combine_draft), &[true, true, true]);
app.close_combine_tab();
app.close_combine_tab(&ctx);
assert!(app.combine_tab.duplicate_warnings(&app.combine_draft).is_empty());
}
@@ -113,7 +114,7 @@ fn every_read_of_a_file_is_new_even_after_undo() {
let added = app.combine_draft[0].auth;
assert!(app.combine_unlock_rows(&[0], "pw"));
let first = app.combine_draft[0].auth;
app.combine_history_step(true);
app.combine_history_step(&egui::Context::default(), true);
assert_eq!(app.combine_draft[0].auth, added, "undo brings back the file as it was read");
assert!(app.combine_unlock_rows(&[0], "owner"));
let second = app.combine_draft[0].auth;
@@ -125,7 +125,7 @@ pub(crate) fn page(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
// The list; files dropped over the window join it.
DropVeil::new(tl!("Drop to add the files")).show(ui, |ui, files| {
if let Some(files) = files {
dropped = Some(files.to_vec());
dropped = Some(files.files.clone());
}
if n == 0 {
Notice::new(Tone::Info, tl!("Add the files to combine"))
@@ -183,7 +183,7 @@ pub(crate) fn page(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
if app.combine_draft.iter().any(CombineFile::unreadable) {
app.combine_tab.confirm_skip = true;
} else {
app.combine_staged();
app.combine_staged(ui.ctx());
}
}
skip_prompt(app, ui);
@@ -258,7 +258,7 @@ fn skip_prompt(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
if out.closed.is_some() {
app.combine_tab.confirm_skip = false;
if out.picked == Some(0) {
app.combine_staged();
app.combine_staged(ui.ctx());
}
}
}
@@ -278,7 +278,7 @@ fn unlock_dialog(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
};
let mut dialog = PasswordDialog::new(purpose).tag(rows.clone()).note(tl!("The password is only used to read the file; it isn't saved."));
if let Some(error) = error {
dialog = dialog.error(error);
dialog = dialog.error(error.into());
}
let out = dialog.show(ui);
if let Some(mut answer) = out.answer {
+10 -10
View File
@@ -100,22 +100,22 @@ pub(crate) fn open_compare_dialog(app: &mut PdfCraftApp, ctx: &egui::Context) {
];
let reason = if chosen.is_none() { tl!("Open the older version first") } else { tl!("Enter valid page numbers") };
ParamDialog::new(DIALOG_KEY, tl!("Compare Files").to_string(), params)
.ok_label(tl!("Compare").to_string())
.ok_label(tl!("Compare").into())
.ok_enabled(chosen.is_some() && pages_ok)
.ok_reason(reason.to_string())
.ok_reason(reason.into())
.footer_note(tl!("Text is compared word by word; the differences are shown on the new file.").to_string())
};
crate::dialogs::host::open(app, HostedParamDialog::new(ctx, DIALOG_KEY, fields, build));
}
/// Once per frame: when the Compare Files dialog answered OK, runs the comparison it asked for.
pub(crate) fn pass(app: &mut PdfCraftApp) {
pub(crate) fn pass(app: &mut PdfCraftApp, ctx: &egui::Context) {
let Some(DialogResult::Ok(result)) = app.dialogs.take_by_id::<HostedParamDialog>(dialog_id(DIALOG_KEY)) else { return };
let chosen = result.fields.text("old").unwrap_or_default();
let Some(old) = app.views.iter().map(|v| v.id).find(|id| option_key(*id) == chosen) else { return };
app.compare_old = Some(old);
app.compare_pages = result.fields.text("pages").unwrap_or_default().to_owned();
app.run_compare();
app.run_compare(ctx);
}
/// The text a change shows in the list.
@@ -221,7 +221,7 @@ impl PdfCraftApp {
}
/// Compare the chosen older document with the active one and show the differences.
pub fn run_compare(&mut self) {
pub fn run_compare(&mut self, ctx: &egui::Context) {
let Some((i, new)) = self.active_ids() else { return };
let Some(old) = self.compare_old else { return };
let count = self.views.get(i).map_or(0, |v| v.page_count());
@@ -237,7 +237,7 @@ impl PdfCraftApp {
}
let n = result.changes.len();
// Side by side when the old version is open in a tab and the window has the room.
let side_by_side = self.views.iter().any(|v| v.id == old) && self.ctx.as_ref().is_none_or(|c| c.content_rect().width() >= 1000.0);
let side_by_side = self.views.iter().any(|v| v.id == old) && ctx.content_rect().width() >= 1000.0;
self.compare = Some(crate::compare_ui::CompareState {
old,
new,
@@ -251,7 +251,7 @@ impl PdfCraftApp {
show_visual: true,
});
self.shade_compare(i);
self.right = Some(RightPanel::Compare);
self.set_right(Some(RightPanel::Compare));
self.notify(if n == 0 {
tl!("The text is the same").to_string()
} else if n == 1 {
@@ -264,7 +264,7 @@ impl PdfCraftApp {
}
}
pub(crate) fn compare_action(&mut self, index: usize, a: PanelAction) {
pub(crate) fn compare_action(&mut self, ctx: &egui::Context, index: usize, a: PanelAction) {
let Some(s) = self.compare.as_mut() else { return };
let (old, new, pages) = (s.old, s.new, s.pages.clone());
match a {
@@ -295,7 +295,7 @@ impl PdfCraftApp {
PanelAction::Mark => match self.session.mark_differences_of(old, new, &pages) {
Ok(n) => {
if let Some(info) = self.session.get(new).map(|d| d.info.clone()) {
self.views[index].document_changed(&info);
self.views[index].document_changed(ctx, &info);
}
self.notify(if n == 1 {
tl!("Added 1 comment").to_string()
@@ -319,7 +319,7 @@ impl PdfCraftApp {
if let Some(oi) = self.views.iter().position(|v| v.id == old) {
self.views[oi].session.compare_marks.clear();
}
self.right = None;
self.set_right(None);
}
}
}
+4 -6
View File
@@ -69,7 +69,7 @@ fn image_import_dialog(ctx: &egui::Context, count: usize) -> HostedParamDialog {
];
ParamDialog::new(IMAGES_DIALOG, tl!("Create PDF from Images"), params)
.values(Bind::bound(fields))
.ok_label(tl!("Create"))
.ok_label(tl!("Create").into())
.footer_note(tl!("DPI sets the printed page size without resampling the image."))
})
}
@@ -415,11 +415,9 @@ mod tests {
/// An app on `files` and `jobs` with `notes.pdf` open, in a harness.
fn reducing(files: Arc<dyn Files>, jobs: Arc<ManualJobs>, source: Vec<u8>) -> Harness<'static, PdfCraftApp> {
let host = Arc::new(Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files).jobs(jobs).build());
// PLAN: assumed `AppServices::new(wake, clipboard, recovery_dir, update_source, intake, watch)` (L-207, pdf-hub-w1)
let services = crate::AppServices::new(craft::host::Wake::none(), None, None, None, None, None);
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| {
let mut app = PdfCraftApp::with_host(host, services);
app.set_option("language", "en").unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |cc| {
let mut app = PdfCraftApp::for_unit_tests_on(host);
app.set_option(&cc.egui_ctx, "language", "en").unwrap();
app.session = std::mem::take(&mut app.session).with_clock(|| 1_700_000_000);
app.open_bytes("notes.pdf", None, source).unwrap();
app
+3 -3
View File
@@ -128,7 +128,7 @@ fn fields_of(d: &ExportDraft) -> DialogFields {
/// Opens the Export dialog for `kind` over the active document.
pub(crate) fn open(app: &mut PdfCraftApp, ctx: &egui::Context, kind: ExportKind) {
let (count, current) = match app.active_ids() {
Some((i, id)) => (app.session.get(id).map_or(0, |d| d.info.pages.len()), app.views[i].current),
Some((i, id)) => (app.session.get(id).map_or(0, |d| d.info.pages.len()), app.views[i].current()),
None => (0, 0),
};
let fields = fields_of(&app.export_draft);
@@ -151,7 +151,7 @@ pub(crate) fn open(app: &mut PdfCraftApp, ctx: &egui::Context, kind: ExportKind)
};
ParamDialog::new(kind.key(), title, params(kind, count, current))
.values(Bind::bound(fields))
.ok_label(tl!("Export"))
.ok_label(tl!("Export").into())
.ok_enabled(usable)
.footer_note(note)
});
@@ -299,7 +299,7 @@ impl PdfCraftApp {
let Some(doc) = self.session.get(id) else { return };
let src = doc.export_source();
let stem = doc.name.trim_end_matches(".pdf").trim_end_matches(".PDF").to_string();
let current = self.views[view].current;
let current = self.views[view].current();
let pages = self.export_draft.range.pages(src.pages, current, &[]);
let dpi = self.export_draft.dpi;
let format = self.export_draft.format;
+4 -13
View File
@@ -870,23 +870,14 @@ mod tests {
use std::path::PathBuf;
use std::sync::Arc;
use craft::host::{AppInfo, Host, ManualJobs, Picked, ScriptedFiles, Wake};
use craft::platform::clipboard::{Clipboard, EventClipboard};
use craft::platform::open::FileIntake;
use craft::platform::watch::FileWatch;
use craft::host::{AppInfo, Host, ManualJobs, Picked, ScriptedFiles};
use crate::{AppServices, PdfCraftApp};
use crate::PdfCraftApp;
fn app_with(files: Arc<ScriptedFiles>, jobs: Arc<ManualJobs>) -> PdfCraftApp {
let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files).jobs(jobs).build();
let wake = Wake::none();
let clipboard = Clipboard::new(EventClipboard::new(|| 0, |_| Ok(0)));
let (intake, _) = FileIntake::new(wake.clone());
let watch = FileWatch::new(wake.clone()).inline();
let services = AppServices::new(wake, clipboard, None, None, intake, watch);
// PLAN: assumed `with_host(Arc<Host>, AppServices)` and `AppServices::new(wake, clipboard, recovery_dir, update_source, intake, watch)` (pdf-hub-w1, L-207)
let mut app = PdfCraftApp::with_host(Arc::new(host), services);
app.set_option("language", "en").unwrap();
let mut app = PdfCraftApp::for_unit_tests_on(Arc::new(host));
app.set_option(&egui::Context::default(), "language", "en").unwrap();
app
}
+7 -7
View File
@@ -388,9 +388,9 @@ fn recognize_dialog(fields: &mut DialogFields, count: usize, current: usize) ->
output_row = output_row.option_description(mode.name(), *about);
}
let flag = |key: &str, label: &str, about: Option<&str>| {
let row = Param::new(key, label, ParamKind::bool(false));
let row = Param::new(key, label.to_string(), ParamKind::bool(false));
match about {
Some(text) => row.tooltip(text),
Some(text) => row.tooltip(text.to_string()),
None => row,
}
};
@@ -498,7 +498,7 @@ impl PdfCraftApp {
return;
}
let count = self.session.get(id).map_or(1, |d| d.info.pages.len().max(1));
let current = self.views[vi].current + 1;
let current = self.views[vi].current() + 1;
let fields = fields_from(&self.ocr_draft, count);
let dialog = HostedParamDialog::new(ctx, "ocr.recognize", fields, move |f| recognize_dialog(f, count, current)).held_ok();
// PLAN: assumed `crate::dialogs::host::open(app: &mut PdfCraftApp, dialog: HostedParamDialog)` from pdf-dialogs-w4.
@@ -553,7 +553,7 @@ impl PdfCraftApp {
let d = &self.ocr_draft;
let pages: Vec<usize> = match d.pages {
OcrPages::All => Vec::new(),
OcrPages::Current => vec![self.views[vi].current],
OcrPages::Current => vec![self.views[vi].current()],
OcrPages::Range => (d.from.saturating_sub(1)..d.to).collect(),
};
let settings = d.settings();
@@ -628,7 +628,7 @@ impl PdfCraftApp {
return None;
}
let (view, doc) = self.active_ids()?;
let page = self.views[view].current;
let page = self.views[view].current();
if self.views[view].auto_ocr_tried.contains(&page) {
return None;
}
@@ -1184,7 +1184,7 @@ fn recognize_guarded<T>(recognize: impl FnOnce() -> Result<T, String>) -> Result
mod tests {
use super::*;
use crate::{LeftPanel, Mode, QuickTool};
use craft::host::{AppInfo, ManualJobs, Wake};
use craft::host::{AppInfo, ManualJobs};
use pdfcraft_engine::ocr::{Recognizer, Recognizers};
use pdfcraft_engine::{Edit, Session};
@@ -1210,7 +1210,7 @@ mod tests {
fn app_on_manual_jobs() -> (PdfCraftApp, Arc<ManualJobs>) {
let jobs = Arc::new(ManualJobs::new());
let host = craft::host::Host::builder(AppInfo { id: "pdfcraft-test", name: "PdfCraft", version: "0" }).jobs(jobs.clone()).build();
let mut app = PdfCraftApp::with_host(host, crate::AppServices { wake: Wake::none(), ..Default::default() });
let mut app = PdfCraftApp::for_unit_tests_on(Arc::new(host));
app.open_bytes("doc.pdf", None, scan()).unwrap();
app.quick_tool = QuickTool::EditText;
(app, jobs)
+19 -18
View File
@@ -1171,7 +1171,7 @@ impl OcrVerify {
let d = &app.ocr_draft;
let pages: Vec<usize> = match d.pages {
super::ocr_ui::OcrPages::All => Vec::new(),
super::ocr_ui::OcrPages::Current => vec![app.active.map_or(0, |i| app.views.get(i).map_or(0, |v| v.current))],
super::ocr_ui::OcrPages::Current => vec![app.active.map_or(0, |i| app.views.get(i).map_or(0, |v| v.current()))],
super::ocr_ui::OcrPages::Range => (d.from.saturating_sub(1)..d.to).collect(),
};
let settings = d.settings();
@@ -1268,7 +1268,7 @@ pub(crate) fn with_state(app: &mut PdfCraftApp, f: impl FnOnce(&mut OcrVerify, &
/// Apply what the frame's controls asked for. The guards live in the [`OcrVerify`] methods:
/// outside ReviewReady, Accept/Reject/Re-OCR and edits are ignored, not acted on.
fn apply(app: &mut PdfCraftApp, n: Intents) {
fn apply(app: &mut PdfCraftApp, ctx: &egui::Context, n: Intents) {
with_state(app, |v, app| {
if n.exit {
v.open = false;
@@ -1336,7 +1336,7 @@ fn apply(app: &mut PdfCraftApp, n: Intents) {
match v.accept_page(&mut app.session, page) {
Ok(count) if count > 0 => {
if let Some(doc) = v.doc {
refresh_view(app, doc);
refresh_view(app, ctx, doc);
}
app.notify_fmt(tl!("The page's words were applied as one undoable step ({n} words)"), &[("n", &count.to_string())]);
}
@@ -1357,7 +1357,7 @@ fn apply(app: &mut PdfCraftApp, n: Intents) {
v.cancel();
}
if n.accept {
do_accept(v, app);
do_accept(v, app, ctx);
}
if n.reject && v.reject() {
app.notify_tr("OCR results rejected.");
@@ -1368,13 +1368,13 @@ fn apply(app: &mut PdfCraftApp, n: Intents) {
/// Accept: searchable mode applies the review to the open document as one undoable step;
/// editable mode asks where to write the new `<name>_ocr.pdf`. Stale sessions and empty
/// reviews are typed failures the user sees (the edits are kept).
fn do_accept(v: &mut OcrVerify, app: &mut PdfCraftApp) {
fn do_accept(v: &mut OcrVerify, app: &mut PdfCraftApp, ctx: &egui::Context) {
let doc = v.doc;
match app.ocr_draft.output_mode {
OutputMode::Searchable => match v.accept(&mut app.session) {
Ok(count) => {
if let Some(doc) = doc {
refresh_view(app, doc);
refresh_view(app, ctx, doc);
}
if count > 0 {
app.notify_fmt(tl!("Recognized text applied ({n} words, one undoable step)"), &[("n", &count.to_string())]);
@@ -1411,9 +1411,10 @@ fn save_editable(app: &mut PdfCraftApp, bytes: Arc<Vec<u8>>, name: String, doc:
};
#[cfg(not(target_arch = "wasm32"))]
{
// PLAN: assumed `PdfCraftApp::pick_file(&mut self, PickRequest, Option<DocId>, impl FnOnce(&mut PdfCraftApp, PathBuf) + 'static)` (pdf-shell-w14 `app/picks.rs`).
let request = craft::host::PickRequest::save("export").filter("PDF", &["pdf"]).file_name(name.clone());
app.pick_file(request, None, move |app, picked: std::path::PathBuf| {
app.pick_file(request, None, move |app, picked| {
// A cancelled or unavailable picker leaves the review as it was.
let Some(picked) = picked.first_path() else { return };
if is_source(&picked, &source) {
app.notify_tr("That is the source file; choose another destination");
return;
@@ -1460,11 +1461,11 @@ fn write_editable(app: &mut PdfCraftApp, target: &std::path::Path, bytes: Arc<Ve
}
/// Pull the document's changed appearance into its view after an apply.
fn refresh_view(app: &mut PdfCraftApp, doc: DocId) {
fn refresh_view(app: &mut PdfCraftApp, ctx: &egui::Context, doc: DocId) {
if let Some(info) = app.session.get(doc).map(|d| d.info.clone())
&& let Some(view) = app.views.iter_mut().find(|view| view.id == doc)
{
view.document_changed(&info);
view.document_changed(ctx, &info);
}
}
@@ -1967,9 +1968,9 @@ mod tests {
/// save dialog never touches the review either — Accept can simply be tried again.
#[test]
fn editable_save_lands_and_a_failed_or_cancelled_one_keeps_the_review() {
// PLAN: assumed `PdfCraftApp::with_files(Arc<dyn Files>)`, an app on a host whose files are the script (pdf-shell-w13/w14); the process-wide `process_picks` is pdf-shell-w14's.
let files = Arc::new(craft::host::ScriptedFiles::new());
let mut app = PdfCraftApp::with_files(files.clone());
let host = craft::host::Host::builder(crate::APP_INFO).files(files.clone()).build();
let mut app = PdfCraftApp::for_unit_tests_on(Arc::new(host));
let text = app.session.create_from_text("t", "Recognize these scanned words").expect("fixture");
let id = app.session.open("t.pdf", None, text, None).expect("fixture");
let job = app.session.ocr_job(id, &[0], OcrSettings::default()).expect("fixture");
@@ -1983,22 +1984,22 @@ mod tests {
// The source file as the destination is refused: nothing is written, the review stays
// in ReviewReady with the edit, Accept is enabled again.
files.answer(Picked::Paths(vec![PathBuf::from("t.pdf")]));
with_state(&mut app, do_accept);
app.process_picked();
with_state(&mut app, |v, app| do_accept(v, app, &egui::Context::default()));
app.process_picks();
assert_eq!(app.ocr_verify.phase, Phase::ReviewReady, "a refused destination keeps the review");
assert_eq!(app.ocr_verify.text_of((0, 0)), Some("Edited"), "the edits are kept");
// A cancelled save dialog: nothing is written, nothing changes.
files.answer(Picked::Cancelled);
with_state(&mut app, do_accept);
app.process_picked();
with_state(&mut app, |v, app| do_accept(v, app, &egui::Context::default()));
app.process_picks();
assert_eq!(app.ocr_verify.phase, Phase::ReviewReady, "a cancelled save keeps the review");
assert_eq!(app.ocr_verify.text_of((0, 0)), Some("Edited"));
assert_eq!(app.ocr_verify.doc, Some(id), "the review still belongs to its document");
// A real destination: the file lands under `<name>_ocr.pdf` and the review ends.
let target = PathBuf::from("out/t_ocr.pdf");
files.answer(Picked::Paths(vec![target.clone()]));
with_state(&mut app, do_accept);
app.process_picked();
with_state(&mut app, |v, app| do_accept(v, app, &egui::Context::default()));
app.process_picks();
assert!(files.file(&target).is_some(), "the editable copy is written");
assert_eq!(app.ocr_verify.phase, Phase::Idle, "a successful save ends the review");
}
@@ -108,7 +108,7 @@ pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut Ui) {
});
});
apply(app, n);
apply(app, &ctx, n);
}
/// With no reading in hand (before a run, or after a review was accepted or rejected), the
@@ -120,7 +120,7 @@ fn follow_active_document(app: &mut PdfCraftApp) {
}
let active = app.active_ids();
app.ocr_verify.doc = active.map(|(_, id)| id);
app.ocr_verify.current = active.and_then(|(i, _)| app.views.get(i)).map_or(0, |view| view.current);
app.ocr_verify.current = active.and_then(|(i, _)| app.views.get(i)).map_or(0, |view| view.current());
}
/// The Engine choice is probed in the background; the screen asks for frames until the answer
@@ -166,7 +166,7 @@ fn engine_entries() -> Vec<Entry<EngineChoice>> {
.map(|(choice, label, what)| {
let entry = Entry::new(choice, label);
match pdfcraft_engine::ocr::engine_unavailable_reason(choice) {
Some(reason) => entry.disabled_reason(crate::i18n::t(&reason)),
Some(reason) => entry.disabled_reason(crate::i18n::t(&reason).to_string()),
None => entry.description(what),
}
})
@@ -50,8 +50,7 @@ fn thumbnails(ctx: &egui::Context) -> Thumbnails<usize> {
/// The picture of `page` of `doc` as the store holds it, asked at `side` points on its longer
/// side: ready, loading or failed.
pub(super) fn page_state(app: &PdfCraftApp, ctx: &egui::Context, doc: DocId, page: usize, side: f32) -> TextureState {
// PLAN: assumed `DocPages::new(&Session, DocId) -> Option<DocPages<'_>>` (pdf-canvas-w10)
let Some(source) = DocPages::new(&app.session, doc) else { return TextureState::Missing };
let source = DocPages::new(&app.session, doc);
let request = ThumbRequest::for_cell(side, ctx.pixels_per_point());
thumbnails(ctx).state(ctx, &source, &page, &request, Priority::VISIBLE)
}
@@ -265,7 +264,7 @@ pub(super) fn show(app: &mut PdfCraftApp, ui: &mut Ui, n: &mut Intents) {
let thumbs = thumbnails(&ctx);
let look = ThumbPaint::default().states(StateLook::Captioned);
let size = Size::new(f64::from(info.width.max(1.0)), f64::from(info.height.max(1.0)));
let pixels = PixelSize { width: info.width.ceil().max(1.0) as u32, height: info.height.ceil().max(1.0) as u32 };
let pixels = PixelSize::new(info.width.ceil().max(1.0) as u32, info.height.ceil().max(1.0) as u32);
let mut tool = RegionTool::new(word_shapes(app, &info, page), app.ocr_verify.region, size);
// PLAN: assumed a kept `Bind<CanvasView>` lets the canvas own its view, fitted to the page when first shown (no `ToolHostResponse::view` copy).
+7 -6
View File
@@ -331,11 +331,12 @@ fn follow_edits(dialog: &mut HostedParamDialog) {
}
fn bool_row(key: impl Into<String>, label: &str, default: bool) -> Param {
Param::new(key, tl!(label), ParamKind::bool(default))
Param::new(key, tl!(label).to_string(), ParamKind::bool(default))
}
fn ppi_row(block: &str, field: &str, label: &str, default: f64) -> Param {
Param::new(key(block, field), tl!(label), ParamKind::int(Some(9), Some(2400), default.round() as i64)).enabled_when(key(block, DOWNSAMPLE), true)
Param::new(key(block, field), tl!(label).to_string(), ParamKind::int(Some(9), Some(2400), default.round() as i64))
.enabled_when(key(block, DOWNSAMPLE), true)
}
fn choice(options: Vec<(String, String)>, default: &str) -> ParamKind {
@@ -347,7 +348,7 @@ fn image_rows(block: &str, title: &str, defaults: &ImageSettings) -> Vec<Param>
let jpeg = FieldValue::Text("jpeg".into());
let options = [("jpeg", "JPEG"), ("flate", tl!("ZIP")), ("retain", tl!("Retain existing"))];
vec![
Param::section(tl!(title)),
Param::section(tl!(title).to_string()),
bool_row(key(block, DOWNSAMPLE), "Bicubic downsampling to", defaults.downsample),
ppi_row(block, TARGET_PPI, "Resolution (ppi)", defaults.target_ppi),
ppi_row(block, ABOVE_PPI, "For images above (ppi)", defaults.above_ppi),
@@ -537,7 +538,7 @@ pub(crate) fn open_space_audit(app: &mut PdfCraftApp, ctx: &egui::Context, from_
ParamDialog::new(key, tl!("Space Audit"), vec![audit_row(rows.clone())]).read_only(true).values(Bind::bound(fields))
});
if from_optimizer {
crate::dialogs::host::open_over(app, dialog.instance(AUDIT_INSTANCE), dialog_id(OPTIMIZE_KEY));
crate::dialogs::host::open_over(app, dialog.instance(AUDIT_INSTANCE));
} else {
crate::dialogs::host::open(app, dialog);
}
@@ -773,9 +774,9 @@ mod tests {
progress.set(3, 10);
let stage = Arc::new(Mutex::new(OptimizeStage::Images { done: 3, total: 10 }));
let (p, s) = (progress.clone(), stage.clone());
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| {
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |cc| {
let mut app = PdfCraftApp::for_unit_tests();
app.set_option("language", "en").unwrap();
app.set_option(&cc.egui_ctx, "language", "en").unwrap();
app.open_bytes("notes.txt", None, b"hello".to_vec()).unwrap();
let (_, doc) = app.active_ids().unwrap();
app.optimize_run = Some(OptimizeRun { doc, kind: OptimizeKind::Advanced, destination: None, progress: p, stage: s });
+3 -3
View File
@@ -932,12 +932,12 @@ mod tests {
fn the_progress_card_counts_the_sheets_of_a_print_job() {
let jobs = Arc::new(craft::host::ManualJobs::new());
let mut app = PdfCraftApp::for_unit_tests();
app.set_option("language", "en").unwrap();
app.set_option(&egui::Context::default(), "language", "en").unwrap();
app.print_tasks = PrintTasks::new(jobs.clone(), Wake::none());
// PLAN: assumed `Notices::progress(&self, ProgressKey) -> Option<ProgressNotice>` and `Notices::posted(&self) -> Vec<String>` (the posted messages, oldest first), read through `app.notices` (pdf-chrome-w19, L-206).
let card = |app: &PdfCraftApp| app.notices.progress(crate::notices::ProgressKey::Print);
let count = Arc::new(super::job_count::JobCount::default());
let count = Arc::new(crate::JobCount::default());
app.print_tasks.running.push(RunningPrint { ticket: 0, printer: "Office".into(), count: count.clone() });
app.show_print_progress("Office", None);
let started = card(&app).expect("a card shows while the job runs");
@@ -964,7 +964,7 @@ mod tests {
assert!(posted.last().is_some_and(|m| m.contains("Office")), "it names the printer: {posted:?}");
// A job the spooler refuses ends its card too, and says why.
app.print_tasks.running.push(RunningPrint { ticket: 1, printer: "Office".into(), count: Arc::new(super::job_count::JobCount::default()) });
app.print_tasks.running.push(RunningPrint { ticket: 1, printer: "Office".into(), count: Arc::new(crate::JobCount::default()) });
app.print_tasks.jobs.submit(1, Priority::VISIBLE, |_| Err("the spooler refused the job".into()));
jobs.run_all();
app.poll_print();
@@ -200,12 +200,10 @@ fn paper_section(d: &PrintDraft, sizes: &[(f64, f64)], units: Unit, no_printers:
papers.insert(0, ("detecting".to_owned(), lbl(tl!("Detecting paper…"))));
separator += 1;
}
let mut paper_kind = ParamKind::choice(papers, Some(d.paper.to_string()));
let mut paper = Param::new("paper", row_label(tl!("Paper:")), ParamKind::choice(papers, Some(d.paper.to_string())));
if !d.custom_papers.is_empty() {
// PLAN: assumed ParamKind choice .separated_at(usize) (F-2)
paper_kind = paper_kind.separated_at(separator);
paper = paper.separated_at(separator);
}
let mut paper = Param::new("paper", row_label(tl!("Paper:")), paper_kind);
if detecting {
paper = paper.disabled_option("detecting", lbl(tl!("The printer's paper sizes are still being read")));
}
@@ -22,9 +22,10 @@ fn duplex_to_ui(duplex: Option<spool::Duplex>) -> Option<UiDuplex> {
fn duplex_from_ui(duplex: Option<UiDuplex>) -> Option<spool::Duplex> {
duplex.map(|d| match d {
UiDuplex::Off => spool::Duplex::Off,
UiDuplex::LongEdge => spool::Duplex::LongEdge,
UiDuplex::ShortEdge => spool::Duplex::ShortEdge,
// One-sided, and any mode the spooler has no name for, prints one-sided.
_ => spool::Duplex::Off,
})
}
@@ -59,8 +60,8 @@ impl PdfCraftApp {
#[cfg(target_arch = "wasm32")]
let printers = self.sync_listed();
let current = self.views[i].current;
let selected: Vec<usize> = self.views[i].selected.iter().copied().collect();
let current = self.views[i].current();
let selected: Vec<usize> = self.views[i].selected.items.iter().copied().collect();
let mut keep = std::mem::take(&mut self.print_draft);
// Leaving Label gives back the paper it replaced (#3564), before the layout resets below.
if keep.handling == Handling::Label {
@@ -198,6 +199,7 @@ impl PdfCraftApp {
// PLAN: assumed HostedPrint::take_settings_clicked(&mut self) -> bool (F-1)
let settings_clicked = dialog.take_settings_clicked();
let step = dialog.take_preview_step();
let paper_px = dialog.take_paper_px();
let ok = dialog.take_ok();
let no_printers = dialog.state().printers.is_empty() && !dialog.state().discovering();
if refresh {
@@ -262,7 +264,15 @@ impl PdfCraftApp {
let thumbs = Thumbnails::<PrintPage>::in_context(ctx, "print-preview", ThumbnailOptions::new().max_side(PREVIEW_MAX_SIDE as u32));
// PLAN: assumed DocPages::new(&Session, DocId) -> DocPages (pdf-canvas-w10)
let pages = DocPages::new(&self.session, id);
let input = SheetInput { d: &self.print_draft, sizes: &sizes, labels: &labels, settings: &settings_result, sheets: &sheets, too_much_creep };
let input = SheetInput {
d: &self.print_draft,
sizes: &sizes,
labels: &labels,
settings: &settings_result,
sheets: &sheets,
too_much_creep,
paper_px,
};
let (sheet, pager) = sheet::build(input, &thumbs, &pages, ctx);
let d = &self.print_draft;
let new_fields = body::fields_from_draft(d);
+10 -6
View File
@@ -19,6 +19,7 @@ fn lbl(text: impl AsRef<str>) -> Label {
}
/// What the layout of this pass says, for [`build`].
#[derive(Clone, Copy)]
pub(super) struct SheetInput<'a> {
/// The draft; `d.sheet` is already clamped to `sheets`.
pub d: &'a PrintDraft,
@@ -32,6 +33,8 @@ pub(super) struct SheetInput<'a> {
pub sheets: &'a [Sheet],
/// Creep within its field's range was still too much for the booklet.
pub too_much_creep: bool,
/// The page box the preview drew last pass, in physical pixels; `None` before it is drawn.
pub paper_px: Option<[u32; 2]>,
}
/// The preview for the sheet `d.sheet` of `sheets`, and the pager under it.
@@ -44,7 +47,7 @@ pub(super) fn build(
source: &dyn ThumbSource<PrintPage>,
ctx: &egui::Context,
) -> (PrintSheet, Option<PanePager>) {
let SheetInput { d, sizes, labels, settings, sheets, too_much_creep } = input;
let SheetInput { d, sizes, labels, settings, sheets, too_much_creep, paper_px } = input;
let count = sheets.len();
let pager = PanePager { shown: d.sheet + 1, count, shown_label: None, back: d.sheet > 0, next: d.sheet + 1 < count, unit: PagerUnit::Sheet };
let paper = vec2(d.paper_size().0 as f32, d.paper_size().1 as f32);
@@ -56,23 +59,24 @@ pub(super) fn build(
Label::default(),
),
(Ok(_), None) => PrintSheet::message(paper, lbl(tl!("No sheets")), Label::default()),
(Ok(_), Some(shown)) => shown_sheet(d, sizes, labels, shown, thumbs, source, ctx),
(Ok(_), Some(shown)) => shown_sheet(input, shown, thumbs, source, ctx),
};
(sheet, Some(pager))
}
fn shown_sheet(
d: &PrintDraft,
sizes: &[(f64, f64)],
labels: &[String],
input: SheetInput<'_>,
shown: &Sheet,
thumbs: &Thumbnails<PrintPage>,
source: &dyn ThumbSource<PrintPage>,
ctx: &egui::Context,
) -> PrintSheet {
let SheetInput { d, sizes, labels, paper_px, .. } = input;
let ppp = ctx.pixels_per_point();
let on_sheet: Vec<usize> = shown.placed.iter().map(|p| p.page).collect();
let rasters = preview_rasters(d, sizes, labels, ppp, ctx.input(|i| i.max_texture_side) as f32);
// The preview drew its page box in physical pixels; the rasters are sized from it in points.
let pane = paper_px.map(|[w, h]| vec2(w as f32 / ppp, h as f32 / ppp));
let rasters = preview_rasters(d, sizes, labels, ppp, ctx.input(|i| i.max_texture_side) as f32, pane);
let mut states: HashMap<usize, TextureState> = HashMap::new();
for (page, scale) in rasters {
let Some(&size) = sizes.get(page) else { continue };
@@ -109,7 +109,7 @@ impl PdfCraftApp {
pub fn open_enhance_scan(&mut self, ctx: &egui::Context) {
let Some((vi, id)) = self.active_ids() else { return };
let count = self.session.get(id).map_or(1, |d| d.info.pages.len().max(1));
let current = self.views.get(vi).map_or(0, |v| v.current);
let current = self.views.get(vi).map_or(0, |v| v.current());
let draft = self.scan_clean_draft.clone();
let fields = DialogFields::from_pairs([
("pages", PageRangeOptions::field_value(&draft.range)),
@@ -150,7 +150,7 @@ impl PdfCraftApp {
return;
}
let count = self.session.get(id).map_or(0, |d| d.info.pages.len());
let current = self.views.get(vi).map_or(0, |v| v.current);
let current = self.views.get(vi).map_or(0, |v| v.current());
let d = &self.scan_clean_draft;
let pages = d.range.pages(count, current, &[]);
// The engine reads an empty list as every page, so a range that picks none must not reach it.