PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge remote-tracking branch 'origin/main' into fix/2837-preview-page-content
Guillem Hermidab9db0fdb76a8
diff --cc crates/ui-egui/src/marks_ui.rsindex e994c7911,4555b8db6..8bf2e4dfe--- a/crates/ui-egui/src/marks_ui.rs+++ b/crates/ui-egui/src/marks_ui.rs@@@ -1,10 -1,9 +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, HeaderFooter, MarkKind, Watermark};+ use pdfcraft_engine::{Background, Edit, FontFamily, HeaderFooter, MarkKind, Watermark};use crate::theme::{self, Tokens};use crate::{PdfCraftApp, widgets};@@@ -335,22 -313,22 +343,31 @@@ pub(crate) fn body(ui: &mut egui::Ui, aui.label(egui::RichText::new(tl!("Page Range Options")).font(theme::semibold(12.5)));d.range.ui(ui, count);ui.add_space(8.0);- // Preview of the current page.+ // The preview: the current page, 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.+ let target = preview_page(&d.range, 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 tint = if kind == MarkKind::Background && !d.use_file { behind(d.bg.color, d.bg.opacity) } else { Color32::WHITE };let hf = d.hf.clone();+ let size_h = page.1.max(1.0);- let (wm, bg, fit) = (d.wm.clone(), d.bg.clone(), d.fit);+ let (wm, fit) = (d.wm.clone(), d.fit);let file_name = d.use_file.then(|| d.file.as_ref().map(|f| f.0.clone())).flatten();ui.horizontal(|ui| {- preview(ui, t, page, |p, r, s| match kind {+ preview(ui, t, page, picture, tint, |p, r, s| match kind {MarkKind::HeaderFooter => {+ if hf.shrink {+ // The band the page content shrinks into, centred across.+ let (top, bottom) = hf.bands();+ let k = ((size_h - top - bottom) / size_h).clamp(0.0, 1.0) as f32;+ let band = Rect::from_min_max(pos2(r.left(), r.top() + top as f32 * s), pos2(r.right(), r.bottom() - bottom as f32 * s));+ let content = Rect::from_center_size(band.center(), vec2(r.width() * k, band.height().max(0.0)));+ p.rect_filled(content, CornerRadius::ZERO, Color32::from_gray(232));+ }for (k, text) in hf.text.iter().enumerate() {if text.trim().is_empty() {continue;@@@ -557,29 -539,13 +577,34 @@@ mod testsassert_eq!(r.pages(6), [1, 3, 5]);let r = PageRange { all: true, subset: Subset::Odd, ..PageRange::default() };assert_eq!(r.pages(5), [0, 2, 4]);+ // Not all pages: by default up to the last one; a single page is a range too.+ let r = PageRange { all: false, ..PageRange::default() };+ assert_eq!(r.pages(4), [0, 1, 2, 3]);+ let r = PageRange { all: false, from: 1, to: 1, subset: Subset::All };+ assert_eq!(r.pages(38), [0]);}+ #[test]+ fn the_preview_shows_a_page_the_range_selects() {+ let all = PageRange::default();+ assert_eq!(preview_page(&all, 2, 5), 2, "the current page when the range selects it");+ let even = PageRange { all: true, subset: Subset::Even, ..PageRange::default() };+ assert_eq!(preview_page(&even, 0, 5), 1, "otherwise the first page the range selects");+ let later = PageRange { all: false, from: 3, to: 4, subset: Subset::All };+ assert_eq!(preview_page(&later, 0, 5), 2);+ let none = PageRange { all: false, from: 4, to: 2, subset: Subset::All };+ assert_eq!(preview_page(&none, 1, 5), 1, "the current page when the range selects none");+ assert_eq!(preview_page(&all, 0, 0), 0, "no pages at all");+ }++ #[test]+ fn a_background_tints_the_page_it_is_behind() {+ assert_eq!(behind([1.0, 0.0, 0.0], 1.0), Color32::from_rgb(255, 0, 0));+ assert_eq!(behind([1.0, 0.0, 0.0], 0.0), Color32::WHITE);+ assert_eq!(behind([0.0, 0.0, 0.0], 0.5), Color32::from_rgb(128, 128, 128));+ assert_eq!(behind([0.2, 0.4, 0.6], f64::NAN), behind([0.2, 0.4, 0.6], 1.0), "opaque, as the engine has it");+ }+#[test]fn the_watermark_edit_carries_the_offset() {let mut d = MarksDraft::default();diff --cc crates/ui-egui/tests/it/marks.rsindex fa5d7f884,d94594be0..0ec7a99e1--- a/crates/ui-egui/tests/it/marks.rs+++ b/crates/ui-egui/tests/it/marks.rs@@@ -101,124 -139,36 +143,158 @@@ fn backgrounds_and_watermarks_from_a_fiassert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), Some("Add background"));}+/// 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");+}+++ /// 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.+ #[test]+ fn page_range_from_one_to_one_selects_only_the_first_page() {+ let mut h = harness();+ h.state_mut().execute("edit.background");+ h.run_steps(2);+ assert_eq!(h.state().marks_draft.range.pages(3), [0, 1, 2]);+ h.get_by_label("Pages from").click();+ h.run_steps(2);+ let range = h.state().marks_draft.range;+ assert_eq!((range.from, range.to), (1, 3), "from the first page to the last");+ h.state_mut().marks_draft.range.to = 1;+ h.run_steps(3);+ let range = h.state().marks_draft.range;+ assert_eq!((range.from, range.to), (1, 1), "the range stays as typed");+ h.get_by_label("Applies to 1 page");+ h.get_by_label("OK").click();+ h.run_steps(3);+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ assert_eq!(doc.marks(), [MarkKind::Background]);+ // Rendered: page 1 has the (default cream) background, page 2 is still blank.+ let mut r = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), pdfcraft_render::RenderConfig::default());+ let corner = |r: &mut pdfcraft_render::PageRenderer, page: usize| {+ let p = r.render(pdfcraft_render::RenderRequest { page, scale: 1.0, ..Default::default() });+ assert!(p.error.is_none(), "{:?}", p.error);+ p.rgba[..4].to_vec()+ };+ assert_eq!(corner(&mut r, 0), vec![255, 255, 217, 255], "page 1 has the background");+ assert_eq!(corner(&mut r, 1), vec![255, 255, 255, 255], "page 2 does not");+ }diff --cc parity/acrobat-features.tomlindex c5bb50420,6a2d0ccf9..41c30b47c--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@@ -2388,8 -2400,8 +2400,8 @@@ milestone = "M7status = "shipped"commands = ["edit.header_footer"]tools = ["doc_header_footer"]- evidence = ["crates/ui-egui/tests/ui_group/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset", "crates/edit/src/tests.rs::header_and_footer_are_drawn_in_display_space_and_wrap_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/ui-egui/tests/ui_group/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks"]- notes = "Helvetica only (no font choice yet); drawn in display space on rotated pages; artifact-tagged; the dialog previews the text over the page's own thumbnail (the current page, or the first one the range selects), in the interface font and with tokens unexpanded"-evidence = ["crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset", "crates/edit/src/tests.rs::header_and_footer_are_drawn_in_display_space_and_wrap_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove"]-notes = "Standard faces only: Helvetica, Times or Courier (#3754; no bold, italic or embedded fonts yet); drawn in display space on rotated pages; artifact-tagged"++evidence = ["crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset", "crates/edit/src/tests.rs::header_and_footer_are_drawn_in_display_space_and_wrap_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks"]++notes = "Standard faces only: Helvetica, Times or Courier (#3754; no bold, italic or embedded fonts yet); drawn in display space on rotated pages; artifact-tagged; the dialog previews the text over the page's own thumbnail (the current page, or the first one the range selects), in the interface font and with tokens unexpanded"[[feature]]id = "edit.header-footer-update-remove"@@@ -2448,8 -2460,8 +2460,8 @@@ milestone = "M7status = "shipped"commands = ["edit.watermark"]tools = ["doc_watermark"]- evidence = ["crates/edit/src/tests.rs::watermarks_rotate_fade_and_can_go_behind", "crates/ui-egui/tests/ui_group/marks.rs::watermark_and_background_dialogs", "crates/automation/tests/automation.rs::headers_watermarks_and_backgrounds_through_tools", "crates/ui-egui/tests/ui_group/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks"]-evidence = ["crates/edit/src/tests.rs::watermarks_rotate_fade_and_can_go_behind", "crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/automation/tests/it/automation.rs::headers_watermarks_and_backgrounds_through_tools"]-notes = "Helvetica; fit-to-page or a size"++evidence = ["crates/edit/src/tests.rs::watermarks_rotate_fade_and_can_go_behind", "crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/automation/tests/it/automation.rs::headers_watermarks_and_backgrounds_through_tools", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks"]+notes = "Helvetica; fit-to-page or a size; the dialog previews it over the page's own thumbnail, always on top (a watermark behind the page is not drawn under its content there)"[[feature]]id = "edit.watermark-add-file"@@@ -2496,8 -2508,8 +2508,8 @@@ milestone = "M7status = "shipped"commands = ["edit.background"]tools = ["doc_background"]- evidence = ["crates/ui-egui/tests/ui_group/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/ui_group/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/ui-egui/tests/ui_group/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks"]-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"]-notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to 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/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"[[feature]]id = "edit.background-update-remove"