Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge remote-tracking branch 'origin/main' into fix/background-hidden-by-page-backdrop

alehelfdc6175de86b
diff --cc crates/automation/tests/it/main.rs
index 82ce8551b,d94aa9f7c..ee74968a9
--- a/crates/automation/tests/it/main.rs
+++ b/crates/automation/tests/it/main.rs
@@@ -1,8 -1,8 +1,9 @@@
//! The crate's integration tests, linked into one test binary.
+ mod attachment_key;
mod automation;
mod automation_roots;
+mod backdrop;
mod batch;
mod button_caption;
mod form_bulk;
diff --cc crates/ui-egui/src/marks_ui.rs
index e9652be1a,8bf2e4dfe..b5f2d5bf2
--- a/crates/ui-egui/src/marks_ui.rs
+++ b/crates/ui-egui/src/marks_ui.rs
@@@ -1,9 -1,10 +1,10 @@@
//! Add Header and Footer, Add Watermark and Add Background dialogs (Acrobat: Edit a PDF ▸ …;
- //! dialog snapshots d13, d14, d12d). Each has the shared Page Range Options and a schematic
- //! preview of the current page. "Update" opens the same dialog in replace mode.
+ //! dialog snapshots d13, d14, d12d). Each has the shared Page Range Options and a preview of a
+ //! page the range selects, with the marks laid out on it. "Update" opens the same dialog in
+ //! replace mode.
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, widgets};
diff --cc crates/ui-egui/tests/it/marks.rs
index aaeddfd7e,0ec7a99e1..626513f30
--- a/crates/ui-egui/tests/it/marks.rs
+++ b/crates/ui-egui/tests/it/marks.rs
@@@ -139,112 -143,128 +143,235 @@@ fn backgrounds_and_watermarks_from_a_fi
assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), Some("Add background"));
}
+/// Three pages: a white backdrop of its own (as browsers write), a page-sized picture (a scan)
+/// and bare paper.
+fn backdrop_fixture() -> Vec<u8> {
+ let stream = |data: &str| format!("<< /Length {} >> stream\n{data}\nendstream", data.len());
+ let objs = [
+ "<< /Type /Catalog /Pages 2 0 R >>".to_string(),
+ "<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 300 400] /Resources << /XObject << /Im0 9 0 R >> >> >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Contents 6 0 R >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Contents 7 0 R >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Contents 8 0 R >>".into(),
+ stream("q 1 1 1 rg 0 0 300 400 re f Q 0 g 20 20 50 50 re f"),
+ stream("q 300 0 0 400 0 0 cm /Im0 Do Q"),
+ stream("0 g 20 20 50 50 re f"),
+ "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >> stream\n\u{80}\nendstream"
+ .into(),
+ ];
+ let mut out = String::from("%PDF-1.7\n");
+ for (i, o) in objs.iter().enumerate() {
+ out.push_str(&format!("{} 0 obj {o} endobj\n", i + 1));
+ }
+ out.push_str("trailer << /Root 1 0 R >>\n%%EOF");
+ out.into_bytes()
+}
+
+#[test]
+fn the_background_dialog_offers_to_replace_a_white_backdrop_and_warns_about_scans() {
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("doc.pdf", None, backdrop_fixture()).unwrap();
+ app
+ });
+ h.run_steps(4);
+ let backdrop = |h: &Harness<'static, PdfCraftApp>, page| {
+ let s = h.state();
+ s.session.get(s.views[0].id).unwrap().page_backdrop(page)
+ };
+ assert_eq!(backdrop(&h, 0), Some(pdfcraft_engine::Backdrop::Fill));
+ h.state_mut().execute("edit.background");
+ h.run_steps(3);
+ let replace = "Page 1 paints its own white backdrop, which would hide the background. Replace it";
+ h.get_by_label("A picture covers page 2 (a scan?), so the background won't show there.");
+ assert!(h.state().marks_draft.bg.replace_backdrop, "on by default");
+ // Left unticked, the backdrop stays and still hides the background.
+ h.get_by_label(replace).click();
+ h.run_steps(2);
+ h.get_by_label("OK").click();
+ h.run_steps(3);
+ assert_eq!(backdrop(&h, 0), Some(pdfcraft_engine::Backdrop::Fill));
+ assert!(h.state_mut().execute("edit.undo"));
+ h.run_steps(2);
+ // Reopened, the choice starts on again; ticked, the backdrop is replaced and the scan is
+ // reported, not touched.
+ h.state_mut().execute("edit.background");
+ h.run_steps(3);
+ h.get_by_label(replace);
+ assert!(h.state().marks_draft.bg.replace_backdrop, "on again when the dialog opens");
+ h.get_by_label("OK").click();
+ h.run_steps(3);
+ assert_eq!(backdrop(&h, 0), None);
+ assert_eq!(backdrop(&h, 1), Some(pdfcraft_engine::Backdrop::Image));
+ // Nothing left to replace: the offer is gone. A choice left off from an earlier dialog
+ // doesn't carry into Update, which restores the backdrop first and would otherwise keep it
+ // with no checkbox shown.
+ h.state_mut().marks_draft.bg.replace_backdrop = false;
+ h.state_mut().execute("edit.background.update");
+ h.run_steps(3);
+ assert!(h.query_by_label(replace).is_none());
+ h.get_by_label("OK").click();
+ h.run_steps(3);
+ assert_eq!(backdrop(&h, 0), None, "Update keeps the backdrop replaced");
+}
+
+/// Remove background says which pages keep their own white backdrop off: here one whose
+/// backdrop copy changed before the fill since the background replaced it.
+#[test]
+fn remove_background_says_which_pages_keep_their_own_backdrop_off() {
+ let copy = "1 1 1 rg 0 0 300 400 re n 0 g 20 20 50 50 re f";
+ let bg = "q 1 0 0 rg 0 0 300 400 re f Q";
+ let fixture = 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 /MediaBox [0 0 300 400] >> endobj\n\
+ 3 0 obj << /Type /Page /Parent 2 0 R /Contents [4 0 R 5 0 R] >> endobj\n\
+ 4 0 obj << /PCMark /Background /Length {} >> stream\n{bg}\nendstream endobj\n\
+ 5 0 obj << /PCBackdrop << /Index 2 /Op (f) /Before <{}> >> /Length {} >> stream\n{copy}\nendstream endobj\n\
+ trailer << /Root 1 0 R >>\n%%EOF",
+ bg.len(),
+ "00".repeat(32),
+ copy.len()
+ );
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.open_bytes("doc.pdf", None, fixture.into_bytes()).unwrap();
+ app
+ });
+ h.run_steps(4);
+ assert_eq!(marks(&h), [MarkKind::Background]);
+ h.state_mut().execute("edit.background.remove");
+ h.run_steps(2);
+ assert!(marks(&h).is_empty());
+ let toast = h.state().toast.as_ref().map(|(t, _)| t.clone()).unwrap_or_default();
+ assert_eq!(toast, "Page 1 changed after the background was added, so its own white backdrop stays off. It looks the same on white paper.");
+}
+
+ /// Two 300 × 400 pages with content (a dark bar), the second turned a quarter (/Rotate 90), so it
+ /// is shown landscape, 400 × 300.
+ fn content_fixture() -> Vec<u8> {
+ let bar = "0 0 0 rg 40 300 220 60 re f";
+ format!(
+ "%PDF-1.7
+ 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
+ 2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 300 400] >> endobj
+ 3 0 obj << /Type /Page /Parent 2 0 R /Contents 5 0 R >> endobj
+ 4 0 obj << /Type /Page /Parent 2 0 R /Rotate 90 /Contents 5 0 R >> endobj
+ 5 0 obj << /Length {} >>
+ stream
+ {bar}
+ endstream
+ endobj
+ trailer << /Root 1 0 R >>
+ %%EOF",
+ bar.len()
+ )
+ .into_bytes()
+ }
+
+ /// The pictures of page `page` (its thumbnail) painted last frame: paint order, bounds, tint.
+ fn page_pictures(h: &Harness<'static, PdfCraftApp>, page: usize) -> Vec<(usize, egui::Rect, egui::Color32)> {
+ let Some(tex) = h.state().views[0].thumb(page).map(|t| t.id()) else { return Vec::new() };
+ h.output()
+ .shapes
+ .iter()
+ .enumerate()
+ .filter_map(|(k, s)| match &s.shape {
+ egui::Shape::Mesh(m) if m.texture_id == tex => Some((k, m.calc_bounds(), m.vertices.first()?.color)),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// The preview's picture of `page`, once its thumbnail has arrived (it renders off the UI thread).
+ fn wait_for_picture(h: &mut Harness<'static, PdfCraftApp>, page: usize) -> (usize, egui::Rect, egui::Color32) {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
+ loop {
+ h.step();
+ if let [one] = page_pictures(h, page)[..] {
+ return one;
+ }
+ assert!(std::time::Instant::now() < deadline, "the preview never showed page {}'s picture", page + 1);
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ }
+
+ /// A text painted on the page last frame (the dialog's text boxes show it too): its paint order
+ /// and its laid-out rectangle.
+ fn painted(h: &Harness<'static, PdfCraftApp>, text: &str, page: egui::Rect) -> (usize, egui::Rect) {
+ h.output()
+ .shapes
+ .iter()
+ .enumerate()
+ .find_map(|(k, s)| match &s.shape {
+ egui::Shape::Text(t) if t.galley.text() == text => {
+ Some((k, t.galley.rect.translate(t.pos.to_vec2()))).filter(|(_, r)| page.contains(r.center()))
+ }
+ _ => None,
+ })
+ .unwrap_or_else(|| panic!("{text:?} is painted on the page"))
+ }
+
+ fn near(a: f32, b: f32, what: &str) {
+ assert!((a - b).abs() < 1.0, "{what}: {a} against {b}");
+ }
+
+ #[test]
+ fn the_preview_shows_the_page_the_range_selects_under_the_marks() {
+ use pdfcraft_ui_egui::marks::{PageRange, Subset};
+ let mut h = harness_with(content_fixture());
+ assert!(h.state_mut().execute("edit.header_footer"));
+ h.run_steps(2);
+ {
+ let d = &mut h.state_mut().marks_draft;
+ d.hf.text[1] = "TOP".into();
+ d.hf.text[5] = "END".into();
+ // Page 2 alone, not the current page: the preview follows the range (#2837).
+ d.range = PageRange { all: false, from: 2, to: 2, subset: Subset::All };
+ }
+ let (at, page, tint) = wait_for_picture(&mut h, 1);
+ h.get_by_label("Preview: page 2 of 2");
+ assert_eq!(tint, egui::Color32::WHITE);
+ assert!((page.width() / page.height() - 4.0 / 3.0).abs() < 0.01, "page 2 is shown turned, as displayed: {page:?}");
+ // The marks are drawn over the page, where the engine puts them on its displayed box
+ // (default margins: 36 pt top and bottom, 72 pt left and right).
+ let s = page.width() / 400.0;
+ let (top_at, top) = painted(&h, "TOP", page);
+ let (end_at, end) = painted(&h, "END", page);
+ assert!(at < top_at && at < end_at, "the page is under the marks");
+ near(top.center().x, page.center().x, "centre header, across");
+ near(top.center().y, page.top() + 36.0 * s, "centre header, down");
+ near(end.right(), page.right() - 72.0 * s, "right footer, across");
+ near(end.center().y, page.bottom() - 36.0 * s, "right footer, down");
+ h.get_by_label("Cancel").click();
+ h.run_steps(2);
+
+ // The watermark sits on the page's centre.
+ assert!(h.state_mut().execute("edit.watermark"));
+ h.run_steps(2);
+ {
+ let d = &mut h.state_mut().marks_draft;
+ d.wm.text = "DRAFT".into();
+ d.wm.rotation = 0.0;
+ }
+ let (at, page, _) = wait_for_picture(&mut h, 1);
+ let (mark_at, mark) = painted(&h, "DRAFT", page);
+ assert!(at < mark_at, "the page is under the watermark");
+ near(mark.center().x, page.center().x, "watermark, across");
+ near(mark.center().y, page.center().y, "watermark, down");
+ h.get_by_label("Cancel").click();
+ h.run_steps(2);
+
+ // A background colour shows where the page is white: it tints the page's picture.
+ assert!(h.state_mut().execute("edit.background"));
+ h.run_steps(2);
+ let (_, _, tint) = wait_for_picture(&mut h, 1);
- assert_eq!(tint, egui::Color32::from_rgb(255, 255, 217), "the default pale yellow, opaque");
++ let [red, green, blue] = pdfcraft_engine::Background::default().color.map(|c| (c * 255.0).round() as u8);
++ assert_eq!(tint, egui::Color32::from_rgb(red, green, blue), "the default background colour, opaque");
+ }
+
/// Pages from 1 to 1 stays one page: the dialog used to turn "to" back into the last page on
/// every frame while both were 1, so only page 1 could not be chosen alone. The field starts on
/// the last page.
diff --cc parity/acrobat-features.toml
index 98b5096c6,511bb7589..da57e884c
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@@ -2507,9 -2530,9 +2530,9 @@@ tier = "P0
milestone = "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"]
-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"
+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/edit/src/backdrop_tests.rs::content_that_is_not_a_page_backdrop_is_left_alone"]
- 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; the dialog preview is a schematic, not the page"
++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/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. 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"
[[feature]]
id = "edit.background-update-remove"