PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M6: with NeedAppearances, check boxes and radio buttons draw their /MK caption (ISO 32000-2 Table 224) (#4454)
mtlcl4108708f35b37e2
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 097a934f8..360517a87 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -8652,3 +8652,70 @@ fn pdf_with_annots(annots: &[&[u8]]) -> Vec<u8> {bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());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}");+ }+}diff --git a/crates/forms/README.md b/crates/forms/README.mdindex 2c24ddc6c..93b65bd14 100644--- a/crates/forms/README.md+++ b/crates/forms/README.md@@ -60,7 +60,9 @@ let cells: Vec<table::Cell> = grid.cells_for(names)?; // "Table1_1", "Tabledrawing while the objects it was drawn from are the same (`FieldAppearanceCache`), so typing inone field redraws that field, not the form. Check boxes and radio buttons with no appearance fortheir state are drawn from `/MK` (border, background, and when on the `/MK /CA` ZapfDingbats- symbol in the `/DA` colour), and push buttons with none from `/MK`, `/BS` and their caption.+ symbol in the `/DA` colour), and with `/NeedAppearances` so is every one that has an `/MK`,+ over the appearance the file carries; push buttons with none are drawn from `/MK`, `/BS` and+ their caption.- Check boxes and radio buttons switch `/V` and each widget's `/AS`. Widgets with no appearancesget PdfCraft's own (a drawn check mark or dot; no symbol font needed).- Imported `/MaxLen 0` is treated as unlimited (also clearing an inherited limit), while thediff --git a/crates/forms/src/appearance.rs b/crates/forms/src/appearance.rsindex 49fa21e76..c1bb5630a 100644--- a/crates/forms/src/appearance.rs+++ b/crates/forms/src/appearance.rs@@ -1029,9 +1029,10 @@ fn check_mark(style: crate::author::CheckStyle, cx: f64, cy: f64, s: f64, color:}/// How a check box or radio button widget `w` of field `f` looks in state on (`on`) or Off when-/// the file has no appearance for that state: its `/MK` background and border ([`frame`]), and-/// when on, its caption `/MK /CA` (ISO 32000-2 Table 192: the normal caption, which check boxes-/// and radio buttons may use too) as a ZapfDingbats character, as in the check box example of+/// the file has no appearance for that state, or leaves its appearances to the viewer+/// (`/NeedAppearances`): its `/MK` background and border ([`frame`]), and when on, its caption+/// `/MK /CA` (ISO 32000-2 Table 192: the normal caption, which check boxes and radio buttons may+/// use too) as a ZapfDingbats character, as in the check box example of/// 12.7.5.2.3: `4` (a check mark) by default, `l` (a dot) for a radio button. The character is/// drawn in the `/DA` colour, at the `/DA` size or, for an automatic size (`0 Tf`), filling most/// of the box. ZapfDingbats is one of the standard 14 fonts, so no font program is needed.diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rsindex ffd67899c..39cebd8fd 100644--- a/crates/forms/src/lib.rs+++ b/crates/forms/src/lib.rs@@ -1553,8 +1553,9 @@ pub fn need_appearances(doc: &Document) -> bool {/// writer left the appearances to the viewer), and otherwise each widget without a normal/// appearance (`/AP /N`), as typing the value would draw it (#3470). Check boxes and radio buttons/// with no normal appearance for their state (`/AS`) are drawn from their `/MK` background, border-/// and caption, and push buttons with none from their `/MK` and `/BS` (Table 192). `doc` is not-/// changed: saving writes the file as it was.+/// and caption, and with `/NeedAppearances` every one that has an `/MK` is, over its own+/// appearance; push buttons with none are drawn from their `/MK` and `/BS` (Table 192). `doc` is+/// not changed: saving writes the file as it was.pub fn with_field_appearances(doc: &Document) -> Option<Document> {with_field_appearances_cached(doc, &mut FieldAppearanceCache::default())}@@ -1572,19 +1573,25 @@ pub fn with_field_appearances_cached(doc: &Document, cache: &mut FieldAppearance.and_then(|d| d.get(b"AP")).and_then(|ap| doc.resolve(ap).as_dict().and_then(|ap| ap.get(b"N").map(|n| doc.resolve(n))));// A check box or radio button shows the appearance of its state (12.7.5.2.3): `/AS`,- // else a check box's value, else Off. An Off state may go without one (it shows- // nothing); an on state needs one.+ // else the value when it names this widget's on state (any check box value when the+ // widget names none), else Off. An Off state may go without one (it shows nothing);+ // an on state needs one.let state = match f.kind {FieldKind::CheckBox | FieldKind::Radio => {- let value = f.value.first().filter(|v| f.kind == FieldKind::CheckBox && !v.is_empty() && v.as_str() != "Off");+ let mine = |v: &&String| w.on_state.as_ref().map_or(f.kind == FieldKind::CheckBox, |on| on == *v);+ let value = f.value.first().filter(|v| !v.is_empty() && v.as_str() != "Off").filter(mine);Some(w.state.clone().or_else(|| value.cloned()).unwrap_or_else(|| "Off".into()))}_ => None,};+ // With /NeedAppearances a check box or radio button that describes its look in /MK is+ // drawn from it (Table 192), its own appearance or not; one without /MK keeps its own.+ let described = || widget.as_dict().and_then(|d| d.get(b"MK")).is_some_and(|mk| doc.resolve(mk).as_dict().is_some());let missing = match f.kind {FieldKind::Text | FieldKind::Combo | FieldKind::List => normal.is_none() || all,FieldKind::PushButton => normal.is_none(),FieldKind::CheckBox | FieldKind::Radio => match (normal.as_deref(), state.as_deref()) {+ _ if all && described() => true,(None, _) => true,(Some(Object::Dict(states)), Some(s)) => s != "Off" && !states.contains(&name_bytes(s)),_ => false,diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rsindex 903e8b6fc..61dab131e 100644--- a/crates/forms/src/tests.rs+++ b/crates/forms/src/tests.rs@@ -4360,6 +4360,82 @@ fn comb_fields_show_their_cells() {assert!(!plain.contains(" m ") && plain.contains("(A) Tj"), "{plain}");}+/// Check boxes and radio buttons with an `/MK` look and appearances of their own, in a form that+/// sets `/NeedAppearances` (`need`) or not.+fn mk_buttons(need: bool) -> Document {+ let flag = if need { "/NeedAppearances true " } else { "" };+ let widget = |n: &str, rest: &str| format!("<< /Type /Annot /Subtype /Widget /FT /Btn /T ({n}) /F 4 /P 3 0 R {rest} >>");+ let states = |on: &str| format!("/AP << /N << /{on} 15 0 R /Off 16 0 R >> >>");+ document(&[+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R] >>".into(),+ format!(+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R] {flag}/DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>"+ ),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),+ widget("check", &format!("/V /Yes /AS /Yes /DA (/Helv 0 Tf 0 g) /MK << /BC [0 0 0] /CA (4) >> /Rect [50 700 74 724] {}", states("Yes"))), // 6+ widget("cross", &format!("/V /Yes /AS /Yes /DA (/ZaDb 0 Tf 1 0 0 rg) /MK << /CA (8) >> /Rect [100 700 124 724] {}", states("Yes"))),+ widget("diamond", &format!("/V /Yes /AS /Yes /MK << /CA (u) /BG [1 1 0] >> /Rect [150 700 174 724] {}", states("Yes"))),+ widget("square", &format!("/V /Yes /AS /Yes /MK << /CA (n) >> /Rect [200 700 224 724] {}", states("Yes"))),+ widget("star", &format!("/V /Yes /AS /Yes /MK << /CA (H) >> /Rect [250 700 274 724] {}", states("Yes"))), // 10+ widget("off", &format!("/V /Off /AS /Off /MK << /BC [0 0 0] /CA (4) >> /Rect [300 700 324 724] {}", states("Yes"))),+ widget("radio", &format!("/Ff 32768 /V /B /MK << /BC [0 0 1] /CA (l) >> /Rect [350 700 374 724] {}", states("B"))),+ widget("plain", &format!("/V /Yes /AS /Yes /Rect [400 700 424 724] {}", states("Yes"))),+ widget(+ "odd",+ &format!(+ "/V /Yes /AS /Yes /DA (/ZaDb nan Tf 1 x rg) /MK << /CA 42 /BC [(no) /Name] /BG 7 >> /BS << /W -3 >> /Rect [450 700 474 724] {}",+ states("Yes")+ ),+ ),+ "<< /Length 24 >>\nstream\n0 g 4 4 16 16 re f\nendstream".into(), // 15: a filled square+ "<< /Length 4 >>\nstream\nq\nQ\nendstream".into(),+ ])+}++/// ISO 32000-2 Table 224 (`/NeedAppearances`) and Table 192 (`/MK /CA`): a form that leaves its+/// appearances to the viewer shows each check box and radio button with an `/MK` drawn from it,+/// over the appearance the file carries: the caption's ZapfDingbats symbol in the `/DA` colour+/// when on, only the border when off. A widget with no `/MK` keeps its own; the file is untouched.+#[test]+fn need_appearances_draws_check_boxes_and_radio_buttons_from_their_captions() {+ let doc = mk_buttons(true);+ let copy = with_field_appearances(&doc).expect("buttons to draw");+ let all = fields(©);+ for (name, state, symbol, colour) in [+ ("check", "Yes", "(4) Tj", "0 g"),+ ("cross", "Yes", "(8) Tj", "1 0 0 rg"),+ ("diamond", "Yes", "(u) Tj", "0 g"),+ ("square", "Yes", "(n) Tj", "0 g"),+ ("star", "Yes", "(H) Tj", "0 g"),+ ("radio", "B", "(l) Tj", "0 g"),+ ] {+ let shown = state_ap(©, &field(&all, name).widgets[0], state);+ assert!(shown.contains(symbol) && shown.contains(&format!("{colour}\n")), "{name}: {shown}");+ assert!(!shown.contains("4 4 16 16 re f"), "{name} is not the file's filled square: {shown}");+ }+ let check = state_ap(©, &field(&all, "check").widgets[0], "Yes");+ assert!(check.contains("0 0 0 RG\n1 w\n0.5 0.5 23 23 re S"), "the /BC border: {check}");+ assert!(state_ap(©, &field(&all, "diamond").widgets[0], "Yes").contains("1 1 0 rg\n0 0 24 24 re f"), "the /BG background");+ assert!(state_ap(©, &field(&all, "radio").widgets[0], "B").contains("0 0 1 RG"), "the radio's own border");+ let off = state_ap(©, &field(&all, "off").widgets[0], "Off");+ assert!(off.contains("re S") && !off.contains("Tj"), "off: only the border: {off}");+ // Nonsense in /MK, /DA and /BS: the default check, no border, and no panic.+ let odd = state_ap(©, &field(&all, "odd").widgets[0], "Yes");+ assert!(odd.contains("(4) Tj") && !odd.contains("re S"), "{odd}");+ let own = |d: &Document, name: &str| d.get(field(&fields(d), name).widgets[0].obj).as_dict().and_then(|w| w.get(b"AP").cloned());+ assert_eq!(own(©, "plain"), own(&doc, "plain"), "a box without /MK keeps its own look");+ assert_eq!(state_ap(&doc, &field(&fields(&doc), "check").widgets[0], "Yes").trim_end(), "0 g 4 4 16 16 re f", "the file is untouched");+}++/// Without `/NeedAppearances` the file's own check box and radio button appearances are shown+/// as they are, `/MK` or not: no copy is needed.+#[test]+fn without_need_appearances_buttons_keep_their_own_appearances() {+ assert!(with_field_appearances(&mk_buttons(false)).is_none());+}+/// A form for filling many values at once: two summed fields and their calculated total, a/// name two field dictionaries share, a check box, a radio group, a list and a read-only field.fn batch_form() -> Document {diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex c0bb4e60c..de678e6fa 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -818,8 +818,8 @@ milestone = "M2"status = "shipped"commands = []tools = []-evidence = ["crates/render/src/raster.rs::widget_appearance_states", "crates/render/src/raster.rs::highlights_without_an_appearance_are_drawn", "crates/engine/src/tests.rs::comments_without_appearances_are_drawn_but_not_saved", "crates/engine/src/tests.rs::cli_display_adds_missing_appearances_without_changing_the_source", "crates/engine/src/tests.rs::fields_left_to_the_viewer_are_displayed_from_their_values", "crates/forms/src/tests.rs::need_appearances_draws_every_text_and_choice_field_in_the_display_copy", "crates/forms/src/tests.rs::the_field_appearance_cache_sees_every_input", "crates/engine/src/tests.rs::buttons_and_combs_left_to_the_viewer_are_displayed", "crates/forms/src/tests.rs::check_boxes_without_an_appearance_show_their_caption_symbol", "crates/forms/src/tests.rs::push_buttons_without_an_appearance_show_their_caption_and_frame", "crates/render/src/raster.rs::invisible_unknown_annotations_and_popups_paint_nothing", "crates/print/src/tests.rs::invisible_annotations_of_unknown_types_do_not_print", "crates/engine/src/tests.rs::stamps_without_appearances_draw_the_stamp_they_name", "crates/automation/tests/it/automation.rs::page_render_draws_stamps_without_an_appearance"]-notes = "comments without /AP (FreeText, Ink, notes, stamps, shapes, markup) are drawn from their dictionaries in the page view, page_render and page images, including the CLI render command, never saved; a stamp from another program draws the stamp its /Name names (the fourteen standard names of ISO 32000-2 Table 184, Draft when there is none) or, for any other name, a grey frame with both diagonals; text and choice fields are drawn from their values when the form sets /NeedAppearances (every one) or a widget has no /N (#3470), also display-only and cached per widget (a field edit on a 1000-field /NeedAppearances form takes ~13 ms against ~7 ms on a form that needs none) (a read-only document still gets the renderer's Highlight fallback only); check boxes and radio buttons with no appearance for their /AS are drawn display-only from /MK (background, border, and when on the /MK /CA ZapfDingbats symbol in the /DA colour, a check or a dot by default), and push buttons with none from /MK and /BS with their caption; Link borders without /AP and printing are not covered yet; an annotation of a non-standard type with the Invisible flag (ISO 32000-2 Table 167) is neither drawn nor printed, and a popup's own /AP is never painted on the page (its parent's text shows in the popup window, §12.5.6.14)"+evidence = ["crates/render/src/raster.rs::widget_appearance_states", "crates/render/src/raster.rs::highlights_without_an_appearance_are_drawn", "crates/engine/src/tests.rs::comments_without_appearances_are_drawn_but_not_saved", "crates/engine/src/tests.rs::cli_display_adds_missing_appearances_without_changing_the_source", "crates/engine/src/tests.rs::fields_left_to_the_viewer_are_displayed_from_their_values", "crates/forms/src/tests.rs::need_appearances_draws_every_text_and_choice_field_in_the_display_copy", "crates/forms/src/tests.rs::the_field_appearance_cache_sees_every_input", "crates/engine/src/tests.rs::buttons_and_combs_left_to_the_viewer_are_displayed", "crates/forms/src/tests.rs::check_boxes_without_an_appearance_show_their_caption_symbol", "crates/forms/src/tests.rs::push_buttons_without_an_appearance_show_their_caption_and_frame", "crates/forms/src/tests.rs::need_appearances_draws_check_boxes_and_radio_buttons_from_their_captions", "crates/engine/src/tests.rs::need_appearances_buttons_are_displayed_from_their_captions", "crates/render/src/raster.rs::invisible_unknown_annotations_and_popups_paint_nothing", "crates/print/src/tests.rs::invisible_annotations_of_unknown_types_do_not_print", "crates/engine/src/tests.rs::stamps_without_appearances_draw_the_stamp_they_name", "crates/automation/tests/it/automation.rs::page_render_draws_stamps_without_an_appearance"]+notes = "comments without /AP (FreeText, Ink, notes, stamps, shapes, markup) are drawn from their dictionaries in the page view, page_render and page images, including the CLI render command, never saved; a stamp from another program draws the stamp its /Name names (the fourteen standard names of ISO 32000-2 Table 184, Draft when there is none) or, for any other name, a grey frame with both diagonals; text and choice fields are drawn from their values when the form sets /NeedAppearances (every one) or a widget has no /N (#3470), also display-only and cached per widget (a field edit on a 1000-field /NeedAppearances form takes ~13 ms against ~7 ms on a form that needs none) (a read-only document still gets the renderer's Highlight fallback only); check boxes and radio buttons with no appearance for their /AS are drawn display-only from /MK (background, border, and when on the /MK /CA ZapfDingbats symbol in the /DA colour, a check or a dot by default), and when the form sets /NeedAppearances so is every one that has an /MK, over the appearance the file carries (ISO 32000-2 Table 224; one without /MK keeps its own), and push buttons with none from /MK and /BS with their caption; Link borders without /AP and printing are not covered yet; an annotation of a non-standard type with the Invisible flag (ISO 32000-2 Table 167) is neither drawn nor printed, and a popup's own /AP is never painted on the page (its parent's text shows in the popup window, §12.5.6.14)"[[feature]]id = "view.render-error-isolation"