PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge PR #4196: OCR: a recognizer panic or a dead worker ends the run (#3919)
aiongg9f56d9d2a949
diff --cc crates/ui-egui/src/ocr_ui.rsindex a267aa000,7f60be35d..977f90f2f--- a/crates/ui-egui/src/ocr_ui.rs+++ b/crates/ui-egui/src/ocr_ui.rs@@@ -188,95 -165,21 +188,100 @@@ impl PdfCraftAppOcrPages::Range => (d.from.saturating_sub(1)..d.to).collect(),};let settings = d.settings();- let Some(job) = self.session.ocr_job(id, &pages, settings) else { return };+ self.start_ocr_pages(id, &pages, settings, false);+ }++ /// Edit on a scanned page: like Acrobat's "Converting scanned page to Editable Text and+ /// Images", the page's words are recognized first, so that they open for editing (Edit text &+ /// images groups the recognised words into phrases). Runs once per page, for the page in view+ /// while Edit is on (its tab, or the Edit text & images or Add text tool). The page must be a+ /// picture (an image covering at least half of it) with no text of its own: comments and text+ /// boxes over it do not count as text, but real page text does, and such a page (a flyer with a+ /// background picture) is left alone, and is judged again only when the document changes. It+ /// is one undoable step, "Recognize text", and is not run again for that page after Undo.+ pub(crate) fn auto_ocr_scanned_page(&mut self) {+ let Some(scan) = self.scan_to_read() else { return };+ if !pdfcraft_engine::ocr::available() {+ self.views[scan.view].auto_ocr_skipped.insert(scan.page, scan.generation);+ return;+ }+ self.views[scan.view].auto_ocr_tried.insert(scan.page);+ // Only a page with no text of its own is read. Comments and text boxes over the picture do+ // not count as its text (a scan with a few comments is still a scan, as in Acrobat), but+ // a page with real text and a background picture is left alone.+ let mut settings = self.ocr_draft.settings();+ settings.skip_text_pages = true;+ settings.native_text_only = true;+ self.start_ocr_pages(scan.doc, &[scan.page], settings, true);+ }++ /// The page Edit should read now, if there is one: Edit is on outside Read mode with no dialog+ /// open, nothing else is being recognized, the document may be changed, the page in view has+ /// not been read before (nor been found no scan since the document last changed), and an image+ /// covers at least half of it. Needs no OCR models, so the rules can be tested without them;+ /// the page's own text is judged by the run itself.+ fn scan_to_read(&mut self) -> Option<ScanToRead> {+ // Edit is on when its panel is open (the Edit tab) or Edit text & images or Add text is picked,+ // the same test the page view uses for editing content.+ let editing = (self.left_open && self.left == crate::LeftPanel::Tool("edit"))+ || matches!(self.quick_tool, crate::QuickTool::EditText | crate::QuickTool::AddText);+ // Not in Read mode (which leaves the Edit tool picked but is not editing) and not beneath a+ // dialog or prompt: nothing may change the document under those. It is tried again once+ // they are gone.+ if !editing || self.mode == crate::Mode::Read || self.modal_open() || self.ocr_run.is_some() || self.ocr_batch.is_some() {+ return None;+ }+ let (view, doc) = self.active_ids()?;+ let page = self.views[view].current;+ if self.views[view].auto_ocr_tried.contains(&page) {+ return None;+ }+ let document = self.session.get(doc)?;+ if document.read_only_reason.is_some() || !document.allows_modification() {+ return None;+ }+ // A page found not to be a scan is judged again only once the document has changed, not+ // every frame (listing its images parses the page).+ let generation = document.edit_generation();+ if self.views[view].auto_ocr_skipped.get(&page) == Some(&generation) {+ return None;+ }+ let info = document.info.pages.get(page)?;+ let page_area = f64::from(info.width) * f64::from(info.height);+ let covered = document.page_images(page).iter().any(|i| {+ let [x0, y0, x1, y1] = i.visible_rect.unwrap_or(i.rect);+ page_area > 0.0 && ((x1 - x0) * (y1 - y0)).abs() >= 0.5 * page_area+ });+ if !covered {+ self.views[view].auto_ocr_skipped.insert(page, generation);+ return None;+ }+ Some(ScanToRead { view, doc, page, generation })+ }++ /// Recognize `pages` (0-based; empty = all) of document `id` in the background.+ fn start_ocr_pages(&mut self, id: DocId, pages: &[usize], settings: OcrSettings, automatic: bool) {+ // What an automatic run's result must still fit when it arrives (see `AutoOcr`).+ let auto = if automatic {+ pages.first().map(|&page| AutoOcr { page, generation: self.session.get(id).map_or(0, |d| d.edit_generation()) })+ } else {+ None+ };+ let Some(job) = self.session.ocr_job(id, pages, settings) else { return };let progress = Arc::new(Mutex::new(OcrProgress { total: job.pages.len(), ..Default::default() }));let p = progress.clone();+ // A failure is written on the worker thread: in the UI's language.+ let lang = crate::i18n::current();let work = move || {- let result = pdfcraft_engine::ocr::engine().map(|ocr| {- job.run(&ocr, |done, total| {- let Ok(mut s) = p.lock() else { return false };- s.done = done;- s.total = total;- !s.cancel+ crate::i18n::set_current(lang);+ let result = recognize_guarded(|| {+ pdfcraft_engine::ocr::engine().map(|ocr| {+ job.run(&ocr, |done, total| {+ let Ok(mut s) = p.lock() else { return false };+ s.done = done;+ s.total = total;+ !s.cancel+ })})});if let Ok(mut s) = p.lock() {@@@ -415,19 -340,17 +442,28 @@@ impl PdfCraftApp}}let Some(run) = self.ocr_run.as_ref() else { return };- let (doc, progress) = (run.doc, run.progress.clone());+ let (doc, progress, auto) = (run.doc, run.progress.clone(), run.automatic);+ let automatic = auto.is_some();- let Ok(mut s) = progress.lock() else { return };+ let mut s = match progress.lock() {+ Ok(s) => s,+ Err(e) => {+ // As above: without this the run never clears and refuses every later one.+ let e = e.to_string();+ self.ocr_run = None;+ self.notify(failed(&e));+ return;+ }+ };+ // The result of a run Edit started waits while Read mode or a dialog is up: nothing may change+ // the document beneath them, and the run may have been started before they appeared. A run+ // the user asked for completes as before.+ if automatic && s.result.is_some() && (self.mode == crate::Mode::Read || self.modal_open()) {+ drop(s);+ if let Some(ctx) = &self.ctx {+ ctx.request_repaint_after(std::time::Duration::from_millis(200));+ }+ return;+ }let Some(result) = s.result.take() else {let msg = crate::i18n::fmt(tl!("Recognizing text… page {d} of {t}"),@@@ -499,147 -418,43 +546,186 @@@ fn recognize_guarded<T>(recognize: imp#[cfg(test)]mod tests {use super::*;+ use crate::{Dialog, LeftPanel, Mode, QuickTool};+ use pdfcraft_engine::{Edit, Session};++ /// A one-page PDF that is one picture covering the page.+ fn scan() -> Vec<u8> {+ let mut png = std::io::Cursor::new(Vec::new());+ image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(8, 8, image::Rgba([250, 250, 250, 255])))+ .write_to(&mut png, image::ImageFormat::Png)+ .unwrap();+ Session::new().create_from_images(&[("scan.png".into(), png.into_inner())]).unwrap().to_vec()+ }++ fn app_with(pdf: Vec<u8>) -> PdfCraftApp {+ let mut app = PdfCraftApp::new();+ app.open_bytes("doc.pdf", None, pdf).unwrap();+ app.quick_tool = QuickTool::EditText;+ app+ }++ fn found(app: &mut PdfCraftApp) -> Option<usize> {+ app.scan_to_read().map(|s| s.page)+ }++ /// These rules need no OCR models (the run itself judges the page's own text), so they are+ /// tested everywhere, unlike the tests that recognize something.+ #[test]+ fn edit_reads_a_page_that_is_a_picture_and_no_other() {+ assert_eq!(found(&mut app_with(scan())), Some(0));+ let text = Session::new().create_from_text("t", "Real text, no picture").unwrap().to_vec();+ assert_eq!(found(&mut app_with(text)), None, "a page of text is no scan");+ let blank = Session::new().create_blank(595.0, 842.0, 1).unwrap().to_vec();+ assert_eq!(found(&mut app_with(blank)), None, "nor is a blank page");+ }++ #[test]+ fn only_edit_being_on_starts_it() {+ let mut app = app_with(scan());+ app.quick_tool = QuickTool::Select;+ assert_eq!(found(&mut app), None, "another tool");+ // The Edit tab's panel counts, as for the page view, with no tool picked.+ app.left = LeftPanel::Tool("edit");+ app.left_open = true;+ assert_eq!(found(&mut app), Some(0), "the Edit panel");+ app.left_open = false;+ assert_eq!(found(&mut app), None, "the Edit panel closed");+ }++ #[test]+ fn it_waits_for_read_mode_and_dialogs_to_end() {+ let mut app = app_with(scan());+ app.mode = Mode::Read;+ assert_eq!(found(&mut app), None, "Read mode");+ app.mode = Mode::Edit;+ app.dialog = Some(Dialog::JsConsole);+ assert_eq!(found(&mut app), None, "beneath a dialog");+ app.dialog = None;+ assert_eq!(found(&mut app), Some(0), "tried again once they are gone");+ }++ #[test]+ fn a_page_is_read_once_and_a_page_found_no_scan_is_judged_again_after_a_change() {+ let mut app = app_with(scan());+ app.views[0].auto_ocr_tried.insert(0);+ assert_eq!(found(&mut app), None, "a page already read is not read again (Undo sticks)");++ // A blank page is no scan; it is judged again only once the document changes.+ let blank = Session::new().create_blank(595.0, 842.0, 1).unwrap().to_vec();+ let mut app = app_with(blank);+ assert_eq!(found(&mut app), None);+ assert!(app.views[0].auto_ocr_skipped.contains_key(&0), "remembered with the document's generation");+ let id = app.active_ids().unwrap().1;+ let mut png = std::io::Cursor::new(Vec::new());+ image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(8, 8, image::Rgba([250, 250, 250, 255])))+ .write_to(&mut png, image::ImageFormat::Png)+ .unwrap();+ let add = Edit::AddImage { page: 0, rect: Some([0.0, 0.0, 595.0, 842.0]), name: "scan.png".into(), bytes: Arc::new(png.into_inner()) };+ app.session.apply(id, add).unwrap();+ assert_eq!(found(&mut app), Some(0), "a picture over the page makes it a scan");+ }+ /// A finished run Edit started is applied only once Read mode and dialogs are gone; one the user+ /// asked for is applied at once. The result is made up, so no OCR models are needed.+ #[test]+ fn the_result_of_an_automatic_run_waits_for_read_mode_and_dialogs() {+ let word = || pdfcraft_engine::ocr::PlacedWord { text: "scanned".into(), origin: [72.0, 700.0], across: [60.0, 0.0], up: [0.0, 12.0] };+ let finished = |app: &PdfCraftApp, automatic: bool| {+ let generation = app.session.get(app.active_ids().unwrap().1).unwrap().edit_generation();+ let page = pdfcraft_engine::ocr::OcrPage { page: 0, words: vec![word()], already_on_page: 0, skipped: None };+ let progress = Arc::new(Mutex::new(OcrProgress { done: 1, total: 1, result: Some(Ok(vec![page])), cancel: false }));+ OcrRun { doc: app.active_ids().unwrap().1, progress, automatic: automatic.then_some(AutoOcr { page: 0, generation }) }+ };+ let label = |app: &PdfCraftApp| app.session.get(app.active_ids().unwrap().1).unwrap().can_undo().map(String::from);++ let mut app = app_with(scan());+ app.ocr_run = Some(finished(&app, true));+ app.mode = Mode::Read;+ app.poll_ocr();+ assert!(app.ocr_run.is_some() && label(&app).is_none(), "waits in Read mode");+ app.mode = Mode::Edit;+ app.dialog = Some(Dialog::JsConsole);+ app.poll_ocr();+ assert!(app.ocr_run.is_some() && label(&app).is_none(), "waits beneath a dialog");+ app.dialog = None;+ app.poll_ocr();+ assert!(app.ocr_run.is_none(), "taken once they are gone");+ assert_eq!(label(&app).as_deref(), Some("Recognize text"));++ // A run the user asked for is not held back.+ let mut app = app_with(scan());+ app.ocr_run = Some(finished(&app, false));+ app.mode = Mode::Read;+ app.poll_ocr();+ assert_eq!(label(&app).as_deref(), Some("Recognize text"));+ }+ /// A run's result is for the document as it was when the run started. Once the document has+ /// changed, a result of Edit's is dropped, not applied to whatever page now has its index, and+ /// the page may be judged again.+ #[test]+ fn the_result_of_an_automatic_run_is_dropped_once_the_document_has_changed() {+ let mut app = app_with(scan());+ let id = app.active_ids().unwrap().1;+ let generation = app.session.get(id).unwrap().edit_generation();+ let page = pdfcraft_engine::ocr::OcrPage {+ page: 0,+ words: vec![pdfcraft_engine::ocr::PlacedWord { text: "scanned".into(), origin: [72.0, 700.0], across: [60.0, 0.0], up: [0.0, 12.0] }],+ already_on_page: 0,+ skipped: None,+ };+ let progress = Arc::new(Mutex::new(OcrProgress { done: 1, total: 1, result: Some(Ok(vec![page])), cancel: false }));+ app.ocr_run = Some(OcrRun { doc: id, progress, automatic: Some(AutoOcr { page: 0, generation }) });+ app.views[0].auto_ocr_tried.insert(0);+ // The document changes while the run is out.+ let mut png = std::io::Cursor::new(Vec::new());+ image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(8, 8, image::Rgba([250, 250, 250, 255])))+ .write_to(&mut png, image::ImageFormat::Png)+ .unwrap();+ app.session+ .apply(id, Edit::AddImage { page: 0, rect: Some([10.0, 10.0, 50.0, 50.0]), name: "p.png".into(), bytes: Arc::new(png.into_inner()) })+ .unwrap();+ app.poll_ocr();+ assert!(app.ocr_run.is_none(), "the run is over");+ assert_eq!(app.session.get(id).unwrap().can_undo(), Some("Add image"), "its result was not applied");+ assert!(!app.views[0].auto_ocr_tried.contains(&0), "the page may be judged again");+ }++ #[test]+ fn a_panicking_recognizer_ends_the_run_with_an_error() {+ let error = recognize_guarded(|| -> Result<(), String> { panic!("the model file is damaged") }).unwrap_err();+ assert!(error.starts_with("Recognize text failed") && error.contains("the model file is damaged"), "{error}");+ assert_eq!(recognize_guarded(|| Ok::<_, String>(7)), Ok(7));+ }++ /// Poison `m` the way a worker that panics while it holds the lock does.+ fn poison<T: Send + 'static>(m: &Arc<Mutex<T>>) {+ let worker = m.clone();+ let _ = std::thread::spawn(move || {+ let _held = worker.lock();+ panic!("the worker died");+ })+ .join();+ assert!(m.is_poisoned());+ }++ #[test]+ fn a_run_whose_worker_died_ends_instead_of_waiting_forever() {+ let mut app = PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ let progress = Arc::new(Mutex::new(OcrProgress { total: 3, ..Default::default() }));+ poison(&progress);- app.ocr_run = Some(OcrRun { doc: DocId(1), progress });++ app.ocr_run = Some(OcrRun { doc: DocId(1), progress, automatic: None });+ app.poll_ocr();+ assert!(app.ocr_run.is_none(), "the next run isn't refused as already running");+ let toast = app.toast.take().map(|t| t.0).unwrap_or_default();+ assert!(toast.starts_with("Recognize text failed"), "{toast}");++ let batch = Arc::new(Mutex::new(BatchProgress { total: 2, ..Default::default() }));+ poison(&batch);+ app.ocr_batch = Some(batch);+ app.poll_ocr();+ assert!(app.ocr_batch.is_none());+ let toast = app.toast.take().map(|t| t.0).unwrap_or_default();+ assert!(toast.starts_with("Recognize text failed"), "{toast}");+ }}