PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge remote-tracking branch 'refs/remotes/origin/main' into fix/background-hidden-by-page-backdrop
alehel9aaac56417a2
diff --cc crates/edit/src/apply.rsindex 81ba9aa8d,427f51f94..ff570d548--- a/crates/edit/src/apply.rs+++ b/crates/edit/src/apply.rs@@@ -5,7 -5,7 +5,7 @@@ use super::place::END, Isolation, add_page_resources, add_resources, begin, check, check_on_top, contents, free_font_name, isolation, page_fonts, page_list, place,place_inside_wrapper, stream_tag, text_op, undrawable, wrapper_role,};- use super::*;-use super::{Document, EditError, Object, added, helvetica_width};++use super::{Document, EditError, Object, added, backdrop, helvetica_width};/// Add a header and footer to `pages` (0-based). With `replace`, existing headers and footers on/// those pages are removed first (Acrobat's Replace Existing).diff --cc crates/engine/src/session/editing.rsindex 00f38a823,f8d5648a2..c78b10ab9--- a/crates/engine/src/session/editing.rs+++ b/crates/engine/src/session/editing.rs@@@ -1,4 -1,11 +1,12 @@@- use super::*;+ #[cfg(test)]+ use super::check_refresh_panic;+ use super::{+ Arc, DocId, Document, Edit, EditCtx, EditError, Label, MAX_UNDO, ObjectKind, OnceLock, RenderPool, SaveOptions, Scope, Session,+ XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, check_permission, comment_list, display_bytes, guard, info_fields, inspect, js, keys_after, note_warnings,+ render_threads, run_edit, scan_colours, scope_of, shown_under_redactions, signatures_of, sync_xfa_state, undrawn_notices, uses_scripts,+ write_incremental, xfa, xfa_sync_datasets,+ };++use crate::{EditNotice, MarkKind};impl Session {/// Apply an edit. On success the previous state is undoable and the view data is refreshed.@@@ -159,20 -166,13 +167,7 @@@if signed && ((rewrites(&next) && !rewrites(&editor.cos)) || (next.is_modified() && next.revisions().is_empty())) {return Err(EditError::SignedRewrite(edit.label().to_string()));}-- // What this edit drew with `?` (a value or comment text its font can't draw, stored as-- // typed): reported, never silent (AGENTS.md §4).- let mut notices: Vec<EditNotice> = if matches!(scope_of(&edit), Scope::Form | Scope::Comments | Scope::Full) {- guard(|| undrawn_notices(&editor.cos, &next)).unwrap_or_default().into_iter().map(EditNotice::Undrawn).collect()- let notices = if matches!(scope_of(&edit), Scope::Form | Scope::Comments | Scope::Full) {- guard(|| undrawn_notices(&editor.cos, &next)).unwrap_or_default()-- } else {-- Vec::new()-- };- // Pages whose own white backdrop Remove background couldn't turn back on: said, not silent.- if matches!(edit, Edit::RemoveMarks { kind: MarkKind::Background }) {- let pages = guard(|| pdfcraft_edit::backdrops_left_off(&next)).unwrap_or_default();- if !pages.is_empty() {- notices.push(EditNotice::BackdropsLeftOff { pages });- }- }++ let notices = edit_notices(&edit, &editor.cos, &next);let previous = std::mem::replace(&mut editor.cos, next);let keys = keys_after(&edit).unwrap_or_else(|| editor.keys.clone());let previous_keys = std::mem::replace(&mut editor.keys, keys);@@@ -526,3 -526,3 +521,21 @@@Ok(())}}++++/// What `edit`, taking `prev` to `next`, wants said: never silent (AGENTS.md §4).++fn edit_notices(edit: &Edit, prev: &pdfcraft_cos::Document, next: &pdfcraft_cos::Document) -> Vec<EditNotice> {++ // What it drew with `?` (a value or comment text its font can't draw, stored as typed).++ let mut notices: Vec<EditNotice> = if matches!(scope_of(edit), Scope::Form | Scope::Comments | Scope::Full) {++ guard(|| undrawn_notices(prev, next)).unwrap_or_default().into_iter().map(EditNotice::Undrawn).collect()++ } else {++ Vec::new()++ };++ // Pages whose own white backdrop Remove background couldn't turn back on.++ if matches!(edit, Edit::RemoveMarks { kind: MarkKind::Background }) {++ let pages = guard(|| pdfcraft_edit::backdrops_left_off(next)).unwrap_or_default();++ if !pages.is_empty() {++ notices.push(EditNotice::BackdropsLeftOff { pages });++ }++ }++ notices++}diff --cc crates/engine/src/tests.rsindex 980eea0fe,6a68916df..898023bd4--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@@ -3002,59 -3149,45 +3149,98 @@@ fn headers_footers_watermarks_and_backgassert_eq!(s.get(id).unwrap().can_undo(), Some("Remove background"));}+/// One 100 × 100 page under a background (`/PCMark /Background`), its own content painting a+/// white backdrop first. With `copy`, that content is a backdrop copy whose tag is `copy`.+fn backdrop_pdf(copy: Option<&str>) -> Vec<u8> {+ let bg = "q 1 0 0 rg 0 0 100 100 re f Q";+ let (tag, fill) = match copy {+ Some(tag) => (format!("/PCBackdrop {tag} "), "n"),+ None => (String::new(), "f"),+ };+ let content = format!("1 g 0 0 100 100 re {fill} 0 g BT /F1 12 Tf 10 50 Td (Hi) Tj ET");+ format!(+ "%PDF-1.7\n\+ 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents [4 0 R 5 0 R] /Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> >> endobj\n\+ 4 0 obj << /PCMark /Background /Length {} >> stream\n{bg}\nendstream endobj\n\+ 5 0 obj << {tag}/Length {} >> stream\n{content}\nendstream endobj\n\+ trailer << /Root 1 0 R >>\n%%EOF",+ bg.len(),+ content.len()+ )+ .into_bytes()+}++/// Remove background says which pages keep their own white backdrop off (it couldn't be turned+/// back on safely), and says nothing when every backdrop comes back.+#[test]+fn remove_background_names_the_pages_whose_own_backdrop_stays_off() {+ let mut s = Session::new();+ // A tag whose hash doesn't match the bytes before the fill: something changed them since.+ let tag = format!("<< /Index 2 /Op (f) /Before <{}> >>", "00".repeat(32));+ let id = s.open("a.pdf", None, Arc::new(backdrop_pdf(Some(&tag))), None).unwrap();+ s.apply(id, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();+ let d = s.get(id).unwrap();+ assert_eq!(d.edit_notices, [EditNotice::BackdropsLeftOff { pages: vec![0] }]);+ let said = d.edit_notices[0].to_string();+ assert!(said.starts_with("page 1 changed after the background was added"), "{said}");+ // An unrelated edit after it says nothing.+ s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();+ assert!(s.get(id).unwrap().edit_notices.is_empty());++ // Added and removed here: the backdrop comes back, and nothing is said.+ let id = s.open("b.pdf", None, Arc::new(backdrop_pdf(None)), None).unwrap();+ s.apply(id, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();+ let background = Background { color: [1.0, 0.0, 0.0], ..Background::default() };+ s.apply(id, Edit::AddBackground { pages: vec![0], settings: background, replace: false, file: None }).unwrap();+ assert_eq!(s.get(id).unwrap().page_backdrops(&[0]), [None], "replaced");+ s.apply(id, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap();+ assert!(s.get(id).unwrap().edit_notices.is_empty());+ assert_eq!(s.get(id).unwrap().page_backdrops(&[0]), [Some(Backdrop::Fill)], "turned back on");+ assert_eq!(page_runs(&[0, 1, 2, 5, 7, 8]), "1-3, 6, 8-9");+ assert_eq!(page_runs(&[]), "");+}++ /// 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, 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, 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();+ let (generation, dirty) = (doc.edit_generation(), doc.dirty);+ let px = |p: &pdfcraft_render::RenderedPage, x: u32, y: u32| -> [u8; 3] {+ p.rgba[(((300 - y) * p.width + x) * 4) as usize..][..3].try_into().unwrap()+ };+ let reds = |p: &pdfcraft_render::RenderedPage| p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, _]| *r > 200 && *g < 80 && *b < 80).count();+ 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 mut 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.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_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_eq!(unmarked.parser_builds(), 1, "parsed once for both pages");+ 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");+ }+#[test]fn marker_indexes_match_after_open_and_save_when_requested() {let (mut source, source_id) = session_with(1);@@@ -8709,69 -9024,69 +9077,69 @@@ fn pdf_with_annots(annots: &[&[u8]]) -bytes}--/// ISO 32000-2 Table 224 (`/NeedAppearances`) and Table 192 (`/MK /CA`): a form that leaves its--/// appearances to the viewer shows its check boxes and radio buttons drawn from `/MK`, over the--/// filled squares the file carries: a checked box its check mark (ZapfDingbats `4`), an unchecked--/// one its empty border, a radio button its dot (`l`), on screen and printed as an image. Without--/// `/NeedAppearances` the file's own squares show. Saving writes the file as it was.--#[test]--fn need_appearances_buttons_are_displayed_from_their_captions() {-- let pdf = |need: bool| {-- let flag = if need { "/NeedAppearances true " } else { "" };-- format!(-- "%PDF-1.7\n\-- 1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >> endobj\n\-- 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\-- 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 400 200] /Annots [6 0 R 7 0 R 8 0 R] >> endobj\n\-- 4 0 obj << /Fields [6 0 R 7 0 R 8 0 R] {flag}/DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> endobj\n\-- 5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\n\-- 6 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (on) /V /Yes /AS /Yes /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (4) >> /Rect [20 100 60 140] /F 4 /P 3 0 R /AP << /N << /Yes 9 0 R /Off 9 0 R >> >> >> endobj\n\-- 7 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (off) /V /Off /AS /Off /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (4) >> /Rect [100 100 140 140] /F 4 /P 3 0 R /AP << /N << /Yes 9 0 R /Off 9 0 R >> >> >> endobj\n\-- 8 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /Ff 32768 /T (radio) /V /B /AS /B /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (l) >> /Rect [180 100 220 140] /F 4 /P 3 0 R /AP << /N << /B 9 0 R /Off 9 0 R >> >> >> endobj\n\-- 9 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 40 40] /Length 18 >> stream\n0 g 4 4 32 32 re f\nendstream endobj\n\-- trailer << /Root 1 0 R >>\n%%EOF"-- )-- .into_bytes()-- };-- let render = |bytes: Arc<Vec<u8>>| {-- let mut r = pdfcraft_render::PageRenderer::new(bytes, pdfcraft_render::RenderConfig::default());-- r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() })-- };-- // Dark pixels of the page (drawn at scale 1, 400 x 200) in the user-space box x0..x1, y0..y1.-- let ink = |page: &pdfcraft_render::RenderedPage, (x0, y0, x1, y1): (u32, u32, u32, u32)| {-- let (px, _) = page.rgba.as_chunks::<4>();-- (200 - y1..200 - y0)-- .flat_map(|y| (x0..x1).map(move |x| (x, y)))-- .filter(|&(x, y)| px.get((y * page.width + x) as usize).is_some_and(|p| p[0] < 128 && p[1] < 128 && p[2] < 128))-- .count()-- };-- // In a widget whose lower-left corner is (x, y): its whole inside, the top-left of its inside-- // (where a check mark leaves the box empty), and the lower-left corner (outside a dot).-- let inside = |x: u32, y: u32| (x + 6, y + 6, x + 34, y + 34);-- let top_left = |x: u32, y: u32| (x + 6, y + 26, x + 14, y + 34);-- let corner = |x: u32, y: u32| (x + 5, y + 5, x + 9, y + 9);-- let mut s = Session::new();-- let id = s.open("form.pdf", None, Arc::new(pdf(true)), None).unwrap();-- let shown = render(s.get(id).unwrap().display.clone());-- let raster = pdfcraft_print::Raster { dpi: 72.0, grayscale: false };-- let pictures = crate::print_raster::rasterize(s.get(id).unwrap(), &[0], &raster, pdfcraft_print::Content::Document).unwrap();-- let printed = render(Arc::new(pictures));-- for (page, how) in [(&shown, "shown"), (&printed, "printed")] {-- let (check, check_corner) = (ink(page, inside(20, 100)), ink(page, top_left(20, 100)));-- assert!(check > 100 && check < 600, "{how}: a check mark, not the 28 x 28 square: {check}");-- assert_eq!(check_corner, 0, "{how}: the check mark leaves the top left empty");-- assert_eq!(ink(page, inside(100, 100)), 0, "{how}: the unchecked box is empty");-- assert!(ink(page, (100, 100, 140, 102)) > 30, "{how}: and keeps its border");-- let dot = ink(page, (188, 108, 212, 132));-- assert!(dot > 300 && ink(page, corner(180, 100)) == 0, "{how}: the radio button's dot: {dot}");-- }-- let saved = s.save_bytes(id).unwrap();-- assert!(saved.windows(18).any(|w| w == b"0 g 4 4 32 32 re f"), "the file keeps its own appearances");---- // Without /NeedAppearances the file's filled squares are shown.-- let id = s.open("plain.pdf", None, Arc::new(pdf(false)), None).unwrap();-- let shown = render(s.get(id).unwrap().display.clone());-- for x in [20, 100, 180] {-- assert!(ink(&shown, inside(x, 100)) > 700, "the file's square at {x}");-- }--}++/// ISO 32000-2 Table 224 (`/NeedAppearances`) and Table 192 (`/MK /CA`): a form that leaves its++/// appearances to the viewer shows its check boxes and radio buttons drawn from `/MK`, over the++/// filled squares the file carries: a checked box its check mark (ZapfDingbats `4`), an unchecked++/// one its empty border, a radio button its dot (`l`), on screen and printed as an image. Without++/// `/NeedAppearances` the file's own squares show. Saving writes the file as it was.++#[test]++fn need_appearances_buttons_are_displayed_from_their_captions() {++ let pdf = |need: bool| {++ let flag = if need { "/NeedAppearances true " } else { "" };++ format!(++ "%PDF-1.7\n\++ 1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >> endobj\n\++ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\++ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 400 200] /Annots [6 0 R 7 0 R 8 0 R] >> endobj\n\++ 4 0 obj << /Fields [6 0 R 7 0 R 8 0 R] {flag}/DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> endobj\n\++ 5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\n\++ 6 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (on) /V /Yes /AS /Yes /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (4) >> /Rect [20 100 60 140] /F 4 /P 3 0 R /AP << /N << /Yes 9 0 R /Off 9 0 R >> >> >> endobj\n\++ 7 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /T (off) /V /Off /AS /Off /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (4) >> /Rect [100 100 140 140] /F 4 /P 3 0 R /AP << /N << /Yes 9 0 R /Off 9 0 R >> >> >> endobj\n\++ 8 0 obj << /Type /Annot /Subtype /Widget /FT /Btn /Ff 32768 /T (radio) /V /B /AS /B /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (l) >> /Rect [180 100 220 140] /F 4 /P 3 0 R /AP << /N << /B 9 0 R /Off 9 0 R >> >> >> endobj\n\++ 9 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 40 40] /Length 18 >> stream\n0 g 4 4 32 32 re f\nendstream endobj\n\++ trailer << /Root 1 0 R >>\n%%EOF"++ )++ .into_bytes()++ };++ let render = |bytes: Arc<Vec<u8>>| {++ let mut r = pdfcraft_render::PageRenderer::new(bytes, pdfcraft_render::RenderConfig::default());++ r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() })++ };++ // Dark pixels of the page (drawn at scale 1, 400 x 200) in the user-space box x0..x1, y0..y1.++ let ink = |page: &pdfcraft_render::RenderedPage, (x0, y0, x1, y1): (u32, u32, u32, u32)| {++ let (px, _) = page.rgba.as_chunks::<4>();++ (200 - y1..200 - y0)++ .flat_map(|y| (x0..x1).map(move |x| (x, y)))++ .filter(|&(x, y)| px.get((y * page.width + x) as usize).is_some_and(|p| p[0] < 128 && p[1] < 128 && p[2] < 128))++ .count()++ };++ // In a widget whose lower-left corner is (x, y): its whole inside, the top-left of its inside++ // (where a check mark leaves the box empty), and the lower-left corner (outside a dot).++ let inside = |x: u32, y: u32| (x + 6, y + 6, x + 34, y + 34);++ let top_left = |x: u32, y: u32| (x + 6, y + 26, x + 14, y + 34);++ let corner = |x: u32, y: u32| (x + 5, y + 5, x + 9, y + 9);++ let mut s = Session::new();++ let id = s.open("form.pdf", None, Arc::new(pdf(true)), None).unwrap();++ let shown = render(s.get(id).unwrap().display.clone());++ let raster = pdfcraft_print::Raster { dpi: 72.0, grayscale: false };++ let pictures = crate::print_raster::rasterize(s.get(id).unwrap(), &[0], &raster, pdfcraft_print::Content::Document).unwrap();++ let printed = render(Arc::new(pictures));++ for (page, how) in [(&shown, "shown"), (&printed, "printed")] {++ let (check, check_corner) = (ink(page, inside(20, 100)), ink(page, top_left(20, 100)));++ assert!(check > 100 && check < 600, "{how}: a check mark, not the 28 x 28 square: {check}");++ assert_eq!(check_corner, 0, "{how}: the check mark leaves the top left empty");++ assert_eq!(ink(page, inside(100, 100)), 0, "{how}: the unchecked box is empty");++ assert!(ink(page, (100, 100, 140, 102)) > 30, "{how}: and keeps its border");++ let dot = ink(page, (188, 108, 212, 132));++ assert!(dot > 300 && ink(page, corner(180, 100)) == 0, "{how}: the radio button's dot: {dot}");++ }++ let saved = s.save_bytes(id).unwrap();++ assert!(saved.windows(18).any(|w| w == b"0 g 4 4 32 32 re f"), "the file keeps its own appearances");++++ // Without /NeedAppearances the file's filled squares are shown.++ let id = s.open("plain.pdf", None, Arc::new(pdf(false)), None).unwrap();++ let shown = render(s.get(id).unwrap().display.clone());++ for x in [20, 100, 180] {++ assert!(ink(&shown, inside(x, 100)) > 700, "the file's square at {x}");++ }++}diff --cc crates/ui-egui/src/app/control.rsindex 14f899de6,c94e77ffb..79bd2fa25--- a/crates/ui-egui/src/app/control.rs+++ b/crates/ui-egui/src/app/control.rs@@@ -120,11 -120,13 +120,16 @@@ impl PdfCraftAppself.execute("page.number");Some(Dialog::NumberPages)}+ "page-properties" => {+ // Same path as the panel, so the selected pages and their order are seeded.+ self.execute("page.properties");+ self.dialog+ }"none" => None,_ => Some(Dialog::About),+ };+ if let Some(Dialog::Marks(kind)) = self.dialog {+ self.marks_draft.opened(kind);}}("tools", _) if value == "full" => self.expand_all_tools(),diff --cc crates/ui-egui/src/dialogs/marks_ui.rsindex 02aa3ac67,92af6279a..085c58111--- a/crates/ui-egui/src/dialogs/marks_ui.rs+++ b/crates/ui-egui/src/dialogs/marks_ui.rs@@@ -3,8 -3,10 +3,10 @@@//! page the range selects, with the marks laid out on it. "Update" opens the same dialog in//! replace mode.+ use std::collections::{HashMap, HashSet};+use egui::{Align, Color32, CornerRadius, Layout, Rect, Stroke, pos2, vec2};-use pdfcraft_engine::{Background, Edit, FontFamily, HeaderFooter, MarkKind, Watermark};+use pdfcraft_engine::{Backdrop, Background, DocId, Edit, FontFamily, HeaderFooter, MarkKind, Watermark};use crate::theme::{self, Tokens};use crate::{PdfCraftApp, icons, widgets};@@@ -299,19 -185,119 +304,132 @@@ fn behind(color: [f64; 3], opacity: f64rgb32(color.map(|c| 1.0 - a * (1.0 - c)))}+/// The preview's tint for a background colour on a page whose own backdrop is `found` (`None`+/// when it has none, or the check hasn't reached it): no colour where the page will still hide+/// the background after OK, because a picture covers it (a scan) or it keeps its white backdrop+/// with Replace unticked.+fn background_tint(d: &MarksDraft, found: Option<Backdrop>) -> Color32 {+ let hidden = match found {+ Some(Backdrop::Image) => true,+ Some(Backdrop::Fill) => !d.bg.replace_backdrop,+ None => false,+ };+ if hidden { Color32::WHITE } else { behind(d.bg.color, d.bg.opacity) }+}++ /// 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). The page shown is drawn from it straight away, at the preview's small size, so neither+ /// a blank sheet nor the old marks show while it renders; the pages a step goes to next render+ /// ahead, off the UI thread (not on the web, where the pool renders on it), so stepping rarely+ /// waits.+ #[derive(Default)]+ pub(crate) struct UnmarkedPage {+ /// The document, its edit generation and the kind of mark taken away.+ key: Option<(pdfcraft_engine::DocId, u64, MarkKind)>,+ pages: Option<pdfcraft_engine::UnmarkedPages>,+ /// Renders the pages next to the one shown, ahead. None on the web, where the pool renders on+ /// the UI thread inside `try_recv`: it would draw them in the same frame too.+ renderer: Option<pdfcraft_render::RenderPool>,+ /// The pages rendered, with the scale (×1000) they were rendered at: the page shown and the+ /// pages next to it.+ textures: HashMap<usize, (u64, egui::TextureHandle)>,+ /// Pages that failed to render when shown, so they aren't tried every frame: their+ /// thumbnails show instead, the other pages still don't.+ failed: HashSet<usize>,+ /// The pages asked of the renderer ahead, and not back yet. Nothing waits for them: a step+ /// is a frame, which takes what has come back first and draws the rest itself.+ ahead: Vec<(usize, u64)>,+ /// Pages (at a scale) that came back from rendering ahead with an error, not asked ahead+ /// again: the error needn't be the page's, so drawing it when shown still decides.+ not_ahead: HashSet<(usize, u64)>,+ }++ impl UnmarkedPage {+ /// 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`+ /// fails to render and was never drawn (a picture of it at another scale is shown rather than+ /// the old marks). `near` are the pages a step goes to from it, rendered ahead.+ fn picture(+ &mut self,+ ctx: &egui::Context,+ (doc, id): (&pdfcraft_engine::Document, pdfcraft_engine::DocId),+ page: usize,+ near: &[usize],+ kind: MarkKind,+ replace: bool,+ ) -> Option<egui::TextureId> {+ let key = replace.then(|| (id, doc.edit_generation(), kind));+ if self.key != key {+ *self = Self { key, ..Default::default() };+ if replace {+ self.pages = doc.without_marks(kind).ok().flatten();+ self.renderer = self.pages.as_ref().filter(|_| !cfg!(target_arch = "wasm32")).map(|p| p.renderer());+ }+ }+ self.pages.as_ref()?;+ let near = if self.renderer.is_some() { near } else { &[][..] };+ // At the preview's size in pixels.+ let scale = |page: usize| {+ let p = doc.info.pages.get(page)?;+ let s = PREVIEW_SIDE * ctx.pixels_per_point() / p.width.max(p.height).max(1.0);+ Some((s, (s * 1000.0) as u64))+ };+ let load = |ctx: &egui::Context, out: pdfcraft_render::RenderedPage| {+ let image = crate::canvas::texture_image([out.width as usize, out.height as usize], out.rgba);+ ctx.load_texture("marks-preview-unmarked", image, egui::TextureOptions::LINEAR)+ };+ while let Some(out) = self.renderer.as_ref().and_then(|r| r.try_recv()) {+ let at = (out.request.page, out.request.tag);+ self.ahead.retain(|a| *a != at);+ // An error rendering ahead needn't be the page's (the pool retires its parser, a+ // request is cancelled): the page is drawn here when it is shown, and that decides.+ // It isn't asked ahead again, so a page that always fails isn't rendered every frame.+ if out.error.is_none() {+ self.textures.insert(at.0, (at.1, load(ctx, out)));+ } else {+ self.not_ahead.insert(at);+ }+ }+ let (s, tag) = scale(page)?;+ if !self.failed.contains(&page)+ && self.textures.get(&page).is_none_or(|(t, _)| *t != tag)+ && let Some(pages) = self.pages.as_mut()+ {+ match pages.render_page(page, s) {+ Ok(out) => {+ self.textures.insert(page, (tag, load(ctx, out)));+ }+ Err(_) => {+ self.failed.insert(page);+ }+ }+ }+ // Ahead: the pages a step goes to, not rendered yet at their scale.+ let wanted: Vec<(usize, u64)> = near+ .iter()+ .filter(|p| !self.failed.contains(p))+ .filter_map(|&p| scale(p).map(|(_, t)| (p, t)))+ .filter(|at| !self.not_ahead.contains(at))+ .filter(|(p, t)| self.textures.get(p).is_none_or(|(have, _)| have != t))+ .collect();+ if let Some(renderer) = self.renderer.as_ref()+ && !wanted.is_empty()+ && wanted != self.ahead+ {+ let requests = wanted+ .iter()+ .filter_map(|&(p, _)| scale(p).map(|(s, tag)| pdfcraft_render::RenderRequest { page: p, scale: s, tag, ..Default::default() }));+ renderer.set_queue(requests.collect());+ self.ahead = wanted;+ }+ self.textures.retain(|p, _| *p == page || near.contains(p));+ // A picture rendered at another scale beats the thumbnail with the old marks.+ self.textures.get(&page).map(|(_, t)| t.id())+ }+ }+/// The page (0-based) the preview shows: the current one when the range selects it, otherwise the/// first page the range selects (the current one again when it selects none).fn preview_page(range: &PageRange, current: usize, count: usize) -> usize {@@@ -513,15 -496,18 +631,19 @@@ pub(crate) fn body(ui: &mut egui::Ui, aui.add_space(8.0);// The preview: the current page (or the page stepped to), or the first one the range selects// if it leaves that out, drawn from its thumbnail at its displayed size (after /Rotate), the- // frame the engine lays the marks out in.+ // frame the engine lays the marks out in. Update draws it without the marks it replaces.let 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 picture = app.views.get_mut(i).and_then(|view| {- view.need_thumbnail(target, true);- view.thumb_id(target)+ let near: Vec<usize> = [false, true].into_iter().filter_map(|forward| step_preview(&d.range, target, count, forward)).collect();+ let unmarked = app.unmarked_page.picture(ui.ctx(), (doc, id), target, &near, kind, d.replace);+ let picture = unmarked.or_else(|| {+ app.views.get_mut(i).and_then(|view| {+ view.need_thumbnail(target, true);+ view.thumb_id(target)+ })});- let tint = if kind == MarkKind::Background && !d.use_file { behind(d.bg.color, d.bg.opacity) } else { Color32::WHITE };+ let tint =+ if kind == MarkKind::Background && !d.use_file { background_tint(d, d.backdrops.found(doc, target).flatten()) } else { Color32::WHITE };let hf = d.hf.clone();let size_h = page.1.max(1.0);let (wm, fit) = (d.wm.clone(), d.fit);diff --cc parity/acrobat-features.tomlindex 93dc595c3,51b4f55ae..a9aaf06d1--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@@ -2530,9 -2530,9 +2530,9 @@@ tier = "P0milestone = "M7"status = "shipped"commands = ["edit.background"]-tools = ["doc_background"]-evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks", "crates/ui-egui/tests/it/marks.rs::update_previews_the_page_without_the_marks_it_replaces", "crates/engine/src/tests.rs::update_previews_on_the_page_without_the_marks_it_replaces"]-notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page; the dialog previews a colour as a tint of the page's own thumbnail (opaque pictures on the page are tinted there too, not in the result), a file as its frame and name; Update previews on the page without the backgrounds it replaces, not tinting the old one"+tools = ["doc_background", "doc_backdrops"]- evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/automation/tests/it/backdrop.rs::a_background_shows_on_a_page_that_paints_its_own_white_backdrop", "crates/ui-egui/tests/it/marks.rs::the_background_dialog_offers_to_replace_a_white_backdrop_and_warns_about_scans", "crates/ui-egui/tests/it/marks.rs::the_background_preview_follows_the_replace_checkbox", "crates/edit/src/backdrop_tests.rs::content_that_is_not_a_page_backdrop_is_left_alone", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks"]- notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page. A page that paints its own opaque white backdrop (browsers' Save as PDF, print drivers) used to hide the background entirely; the dialog now offers to replace that fill (on by default; Remove turns it back on, after edits and redactions too, unless the operators before it changed or it would no longer be painted first, and then says which pages keep it off). The replaced copy's tag holds no page content or reference, so text a redaction or Remove Hidden Information takes off such a page leaves the file. Our own choice: Acrobat's behaviour on such pages has not been observed. Still hidden: scanned pages (warned), backdrops drawn inside a form XObject, by a non-rectangular path, or in a named colour space, and white fills drawn translucent, through a soft mask, a non-Normal blend mode or a transfer function (TR/TR2) as the graphics state stands after every gs, which are real content and stay. The dialog previews a colour as a tint of the page's own thumbnail (opaque pictures on the page are tinted there too, not in the result), a file as its frame and name; a page that will still hide the background (a scan, or a white backdrop with Replace unticked) previews without the colour"++evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/automation/tests/it/backdrop.rs::a_background_shows_on_a_page_that_paints_its_own_white_backdrop", "crates/ui-egui/tests/it/marks.rs::the_background_dialog_offers_to_replace_a_white_backdrop_and_warns_about_scans", "crates/ui-egui/tests/it/marks.rs::the_background_preview_follows_the_replace_checkbox", "crates/edit/src/backdrop_tests.rs::content_that_is_not_a_page_backdrop_is_left_alone", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks", "crates/ui-egui/tests/it/marks.rs::update_previews_the_page_without_the_marks_it_replaces", "crates/engine/src/tests.rs::update_previews_on_the_page_without_the_marks_it_replaces"]++notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page. A page that paints its own opaque white backdrop (browsers' Save as PDF, print drivers) used to hide the background entirely; the dialog now offers to replace that fill (on by default; Remove turns it back on, after edits and redactions too, unless the operators before it changed or it would no longer be painted first, and then says which pages keep it off). The replaced copy's tag holds no page content or reference, so text a redaction or Remove Hidden Information takes off such a page leaves the file. Our own choice: Acrobat's behaviour on such pages has not been observed. Still hidden: scanned pages (warned), backdrops drawn inside a form XObject, by a non-rectangular path, or in a named colour space, and white fills drawn translucent, through a soft mask, a non-Normal blend mode or a transfer function (TR/TR2) as the graphics state stands after every gs, which are real content and stay. The dialog previews a colour as a tint of the page's own thumbnail (opaque pictures on the page are tinted there too, not in the result), a file as its frame and name; a page that will still hide the background (a scan, or a white backdrop with Replace unticked) previews without the colour; Update previews on the page without the backgrounds it replaces, not tinting the old one"[[feature]]id = "edit.background-update-remove"