PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(ui): Update prepares the unmarked pages once, and shows the thumbnail while one renders
alehel1e01497649c9
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 889b83936..1ec6e57d6 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -66,7 +66,7 @@ pub use links::{pub use signature_image::{ImageSignaturePreview, SignatureImage};pub use signature_scan::{PhotoRect, ScanError, SignaturePhoto, Turn};pub use stamp_preview::StampPreview;-pub use text_preview::TextEditPreview;+pub use text_preview::{TextEditPreview, UnmarkedPages};pub use pdfcraft_organize::{BoxSpec, FieldConflicts, PageBox, SplitBy, Transition, TransitionSpec, mime_for_name, split_ranges};diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 248df94d6..c58ba9012 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -3004,13 +3004,14 @@ fn headers_footers_watermarks_and_backgrounds_show_update_and_remove() {/// Update previews its marks on the page without the ones it replaces: a yellow background/// updated to blue isn't previewed as blue over yellow, nor a new watermark over the old one.-/// The other kinds of mark and the page's own content stay, a page without that kind has nothing-/// to prepare, and preparing changes nothing in the document.+/// The other kinds of mark and the page's own content stay, every page is prepared at once (the+/// dialog steps through them), a document without that kind has nothing to prepare, and+/// preparing changes nothing in the document.#[test]fn update_previews_on_the_page_without_the_marks_it_replaces() {let (mut s, id) = session_with(2);let yellow = Background { color: [1.0, 1.0, 0.0], ..Background::default() };- s.apply(id, Edit::AddBackground { pages: vec![0], settings: yellow, replace: false, file: None }).unwrap();+ s.apply(id, Edit::AddBackground { pages: vec![0, 1], settings: yellow, replace: false, file: None }).unwrap();let red = Watermark { text: "SECRET".into(), color: [1.0, 0.0, 0.0], opacity: 1.0, ..Watermark::default() };s.apply(id, Edit::AddWatermark { pages: vec![0], settings: red, replace: false, file: None }).unwrap();let doc = s.get(id).unwrap();@@ -3022,18 +3023,19 @@ fn update_previews_on_the_page_without_the_marks_it_replaces() {let dark = |p: &pdfcraft_render::RenderedPage| p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, _]| *r < 100 && *g < 100 && *b < 100).count();assert_eq!(pixel(&s, id, 0, 5, 5)[..3], [255, 255, 0], "the page has the yellow background");- let page = doc.page_without_marks(0, MarkKind::Background).unwrap().expect("page 1 has a background").render_background(1.0).unwrap();+ let unmarked = doc.without_marks(MarkKind::Background).unwrap().expect("the pages have a background");+ let page = unmarked.render_page(0, 1.0).unwrap();assert_eq!(px(&page, 5, 5), [255, 255, 255], "without the background the page is white");assert!(reds(&page) > 50, "the watermark stays");assert!(dark(&page) > 10, "the page text stays");- let page = doc.page_without_marks(0, MarkKind::Watermark).unwrap().expect("page 1 has a watermark").render_background(1.0).unwrap();+ let page = doc.without_marks(MarkKind::Watermark).unwrap().expect("page 1 has a watermark").render_page(0, 1.0).unwrap();assert_eq!(reds(&page), 0, "without the watermark");assert_eq!(px(&page, 5, 5), [255, 255, 0], "the background stays");- assert!(doc.page_without_marks(1, MarkKind::Background).unwrap().is_none(), "page 2 has none: its thumbnail is the page");- assert!(doc.page_without_marks(0, MarkKind::HeaderFooter).unwrap().is_none(), "the document has no header");- assert!(doc.page_without_marks(9, MarkKind::Background).is_err(), "no page 10");+ assert_eq!(px(&unmarked.render_page(1, 1.0).unwrap(), 5, 5), [255, 255, 255], "made once, for every page: page 2 is white too");+ assert!(doc.without_marks(MarkKind::HeaderFooter).unwrap().is_none(), "the document has no header");+ assert!(unmarked.render_page(9, 1.0).is_err(), "no page 10");let doc = s.get(id).unwrap();assert_eq!((doc.edit_generation(), doc.dirty, doc.can_undo()), (generation, dirty, Some("Add watermark")), "the document is unchanged");}diff --git a/crates/engine/src/text_preview.rs b/crates/engine/src/text_preview.rsindex d19272fce..5f39945a1 100644--- a/crates/engine/src/text_preview.rs+++ b/crates/engine/src/text_preview.rs@@ -19,20 +19,41 @@ impl TextEditPreview {}pub fn render_background(&self, scale: f32) -> Result<RenderedPage, String> {- if !scale.is_finite() || scale <= 0.0 {- return Err("preview scale must be finite and positive".into());- }- guard(|| {- let mut renderer = PageRenderer::new(self.bytes.clone(), self.config.clone());- let out = renderer.render(RenderRequest { page: self.page, scale, ..Default::default() });- if let Some(e) = &out.error {- return Err(e.clone());- }- Ok(out)- })?+ render_one(&self.bytes, &self.config, self.page, scale)}}+/// A document's pages without its marks of one kind ([`Document::without_marks`]).+pub struct UnmarkedPages {+ bytes: Arc<Vec<u8>>,+ config: RenderConfig,+}++impl UnmarkedPages {+ pub fn renderer(&self) -> RenderPool {+ RenderPool::new(self.bytes.clone(), 1, self.config.clone())+ }++ pub fn render_page(&self, page: usize, scale: f32) -> Result<RenderedPage, String> {+ render_one(&self.bytes, &self.config, page, scale)+ }+}++/// `page` of `bytes` at `scale`, on this thread.+fn render_one(bytes: &Arc<Vec<u8>>, config: &RenderConfig, page: usize, scale: f32) -> Result<RenderedPage, String> {+ if !scale.is_finite() || scale <= 0.0 {+ return Err("preview scale must be finite and positive".into());+ }+ guard(|| {+ let mut renderer = PageRenderer::new(bytes.clone(), config.clone());+ let out = renderer.render(RenderRequest { page, scale, ..Default::default() });+ if let Some(e) = &out.error {+ return Err(e.clone());+ }+ Ok(out)+ })?+}+impl Document {/// Background for retyping an added text item, without changing its saved content.pub fn added_text_preview(&self, page: usize, index: usize) -> Result<TextEditPreview, String> {@@ -91,21 +112,24 @@ impl Document {})?}- /// The page without its marks of `kind`: what Update replaces them on, so its preview doesn't- /// draw the new marks over the old ones (or tint the old background). `None` when the page has- /// none, and its thumbnail already is that page. Read-only, like [`Self::text_edit_preview`].- pub fn page_without_marks(&self, page: usize, kind: crate::MarkKind) -> Result<Option<TextEditPreview>, String> {+ /// The document without its marks of `kind`, on every page: what Update replaces them on, so+ /// its preview doesn't draw the new marks over the old ones (or tint the old background).+ /// Made once for all the pages a dialog steps through, as cloning and writing the document+ /// costs about a save. `None` when the document has none, and the thumbnails already are+ /// those pages. Read-only, like [`Self::text_edit_preview`].+ pub fn without_marks(&self, kind: crate::MarkKind) -> Result<Option<UnmarkedPages>, String> {if !self.marks().contains(&kind) {return Ok(None);}guard(|| {let editor = self.editor.as_ref().ok_or("the document can't be read")?;let mut cos = editor.cos.clone();- if pdfcraft_edit::remove_marks(&mut cos, &[page], kind).map_err(|e| e.to_string())? == 0 {+ let n = pdfcraft_model::pages(&cos).len();+ if pdfcraft_edit::remove_marks(&mut cos, &(0..n).collect::<Vec<_>>(), kind).map_err(|e| e.to_string())? == 0 {return Ok(None);}let bytes = Arc::new(pdfcraft_cos::write_incremental(&cos, &pdfcraft_cos::SaveOptions::default()).map_err(|e| e.to_string())?);- Ok(Some(TextEditPreview { page, bytes, config: self.config.clone() }))+ Ok(Some(UnmarkedPages { bytes, config: self.config.clone() }))})?}diff --git a/crates/ui-egui/src/dialogs/marks_ui.rs b/crates/ui-egui/src/dialogs/marks_ui.rsindex 62fb3ce33..2efc10ecc 100644--- a/crates/ui-egui/src/dialogs/marks_ui.rs+++ b/crates/ui-egui/src/dialogs/marks_ui.rs@@ -183,26 +183,29 @@ fn behind(color: [f64; 3], opacity: f64) -> Color32 {rgb32(color.map(|c| 1.0 - a * (1.0 - c)))}-/// In Update, the page previewed without the marks the dialog replaces. Its thumbnail still has-/// them, so the new marks would be drawn over the old ones, and a new background colour would tint-/// the old one. Rendered off the UI thread like the thumbnail, once per page shown.+/// In Update, the pages previewed without the marks the dialog replaces. Their thumbnails still+/// have them, so the new marks would be drawn over the old ones, and a new background colour+/// would tint the old one. The document without them is made once per dialog (it costs about a+/// save), and each page shown is rendered from it off the UI thread, like the thumbnails.#[derive(Default)]pub(crate) struct UnmarkedPage {- /// The document, its edit generation, the page and the kind of mark taken away.- key: Option<(pdfcraft_engine::DocId, u64, usize, MarkKind)>,+ /// The document, its edit generation and the kind of mark taken away.+ key: Option<(pdfcraft_engine::DocId, u64, MarkKind)>,renderer: Option<pdfcraft_render::RenderPool>,- texture: Option<egui::TextureHandle>,- tag: Option<u64>,+ /// The page and scale last asked for.+ asked: Option<(usize, u64)>,+ /// The page and scale the texture shows.+ texture: Option<(usize, u64, egui::TextureHandle)>,}impl UnmarkedPage {pub(crate) fn pending(&self) -> bool {- self.renderer.is_some() && self.texture.is_none()+ self.renderer.is_some() && self.asked.is_some() && self.texture.as_ref().map(|(p, t, _)| (*p, *t)) != self.asked}- /// The picture to preview `page` on in place of its thumbnail: `None` when the thumbnail is- /// that page (not Update, or no marks of `kind` on it, or the page can't be prepared), and- /// `Some(None)` while it renders, when the page is a blank sheet.+ /// The picture to preview `page` on in place of its thumbnail, or `None` for the thumbnail:+ /// not Update, no marks of `kind` in the document, the pages can't be prepared, or `page` is+ /// still rendering (its thumbnail shows until then, rather than a blank sheet).fn picture(&mut self,ctx: &egui::Context,@@ -210,39 +213,39 @@ impl UnmarkedPage {page: usize,kind: MarkKind,replace: bool,- ) -> Option<Option<egui::TextureId>> {- let key = replace.then(|| (id, doc.edit_generation(), page, kind));+ ) -> Option<egui::TextureId> {+ let key = replace.then(|| (id, doc.edit_generation(), kind));if self.key != key {*self = Self { key, ..Default::default() };if replace {- self.renderer = doc.page_without_marks(page, kind).ok().flatten().map(|p| p.renderer());+ self.renderer = doc.without_marks(kind).ok().flatten().map(|p| p.renderer());}}let renderer = self.renderer.as_ref()?;// At the preview's size in pixels.let p = doc.info.pages.get(page)?;let scale = PREVIEW_SIDE * ctx.pixels_per_point() / p.width.max(p.height).max(1.0);- let tag = (scale * 1000.0) as u64;- if self.tag != Some(tag) {- renderer.set_queue(vec![pdfcraft_render::RenderRequest { page, scale, tag, ..Default::default() }]);- self.tag = Some(tag);+ let asked = (page, (scale * 1000.0) as u64);+ if self.asked != Some(asked) {+ renderer.set_queue(vec![pdfcraft_render::RenderRequest { page, scale, tag: asked.1, ..Default::default() }]);+ self.asked = Some(asked);}if let Some(out) = renderer.try_recv() {if out.error.is_some() {- // The thumbnail, as before, rather than no page at all.+ // The thumbnails, as before, rather than no page at all.self.renderer = None;self.texture = None;return None;}- if out.request.tag == tag {+ if (out.request.page, out.request.tag) == asked {let image = crate::canvas::texture_image([out.width as usize, out.height as usize], out.rgba);- self.texture = Some(ctx.load_texture("marks-preview-unmarked", image, egui::TextureOptions::LINEAR));+ self.texture = Some((page, asked.1, ctx.load_texture("marks-preview-unmarked", image, egui::TextureOptions::LINEAR)));}}if self.pending() {ctx.request_repaint_after(std::time::Duration::from_millis(16));}- Some(self.texture.as_ref().map(|t| t.id()))+ self.texture.as_ref().filter(|(p, ..)| *p == page).map(|(.., t)| t.id())}}@@ -448,7 +451,7 @@ pub(crate) fn body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, kind: Mlet target = shown_preview(&d.range, &mut d.preview, current, count);let page = doc.info.pages.get(target).map(|p| (p.width as f64, p.height as f64)).unwrap_or((612.0, 792.0));let unmarked = app.unmarked_page.picture(ui.ctx(), (doc, id), target, kind, d.replace);- let picture = unmarked.unwrap_or_else(|| {+ let picture = unmarked.or_else(|| {app.views.get_mut(i).and_then(|view| {view.need_thumbnail(target, true);view.thumb_id(target)diff --git a/crates/ui-egui/tests/it/marks.rs b/crates/ui-egui/tests/it/marks.rsindex 994e533a9..e0d429efa 100644--- a/crates/ui-egui/tests/it/marks.rs+++ b/crates/ui-egui/tests/it/marks.rs@@ -325,13 +325,13 @@ fn preview_picture(h: &Harness<'static, PdfCraftApp>, uploads: &Uploads) -> Optilet egui::Shape::Mesh(m) = &s.shape else { return None };let r = m.calc_bounds();// The size of the 210-point box left of the label (which is centred down its side), and- // not the stepper's arrow beside the label.+ // not the stepper's arrow beside the label. A landscape page is shorter than the box, so+ // it can sit below the label: within half the box of it.let beside = r.width() > 50.0&& r.height() <= 215.0&& r.right() <= label.left()&& label.left() - r.right() < 260.0- && r.top() <= label.bottom()- && r.bottom() >= label.top();+ && (r.center().y - label.center().y).abs() <= 105.0;if !beside {return None;}@@ -386,6 +386,8 @@ fn update_previews_the_page_without_the_marks_it_replaces() {let mut app = PdfCraftApp::new();app.set_option("language", "en").unwrap();app.open_bytes("doc.pdf", None, pdf.clone()).unwrap();+ // The Pages panel keeps both thumbnails, for stepping to page 2 in Update below.+ app.set_option("panel", "pages").unwrap();app});h.run_steps(4);@@ -425,17 +427,30 @@ fn update_previews_the_page_without_the_marks_it_replaces() {assert!(h.state_mut().execute("edit.background.update"));h.run_steps(2);h.state_mut().marks_draft.bg.color = [0.6, 0.8, 1.0];- let (tint, page) = wait_for_preview(&mut h, &uploads, "a page", |_| true);+ let white = |i: &egui::ColorImage| at(i, 0.5, 0.75) == egui::Color32::WHITE;+ let (tint, page) = wait_for_preview(&mut h, &uploads, "the page without its background", white);assert_eq!(tint, egui::Color32::from_rgb(153, 204, 255), "the new colour tints the page");assert_eq!(at(&page, 0.5, 0.75), egui::Color32::WHITE, "the page is previewed without the yellow background");assert!(count(&page, red) > 200 && count(&page, blue) > 40 && count(&page, dark) > 1000, "the watermark, header and page content stay");+ // Stepping to page 2 shows its thumbnail until it renders without the background, not a+ // blank sheet: the pages are prepared once, and each renders on its own.+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);+ while h.state().views[0].thumb(1).is_none() {+ assert!(std::time::Instant::now() < deadline, "page 2's thumbnail never loaded");+ h.step();+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ h.state_mut().marks_draft.preview = Some(1);+ h.step();+ assert!(preview_picture(&h, &uploads).is_some(), "a page shows while page 2 renders");+ wait_for_preview(&mut h, &uploads, "page 2 without its background", white);h.get_by_label("Cancel").click();h.run_steps(2);assert!(h.state_mut().execute("edit.watermark.update"));h.run_steps(2);h.state_mut().marks_draft.wm.text = "NEW".into();- let (_, page) = wait_for_preview(&mut h, &uploads, "a page", |_| true);+ let (_, page) = wait_for_preview(&mut h, &uploads, "the page without its watermark", |i| count(i, red) == 0);assert_eq!(count(&page, red), 0, "the new watermark isn't previewed over the old one");assert!(at(&page, 0.5, 0.75) == yellow && count(&page, blue) > 40, "the background and header stay");h.get_by_label("Cancel").click();@@ -443,7 +458,7 @@ fn update_previews_the_page_without_the_marks_it_replaces() {assert!(h.state_mut().execute("edit.header_footer.update"));h.run_steps(2);- let (_, page) = wait_for_preview(&mut h, &uploads, "a page", |_| true);+ let (_, page) = wait_for_preview(&mut h, &uploads, "the page without its header", |i| count(i, blue) == 0);assert_eq!(count(&page, blue), 0, "the new header isn't previewed over the old one");assert!(at(&page, 0.5, 0.75) == yellow && count(&page, red) > 200, "the background and watermark stay");}