PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Forms: run show/hide-a-field button actions (#192)
pauliusiv123-rgbd7b93b56b592
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 88efc67cc..22c1f59e3 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -32,8 +32,8 @@ pub use pdfcraft_edit::{Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, MarkKind, Watermark,};pub use pdfcraft_forms::{- BorderStyle, CheckStyle, Field as FormField, FieldAction, FieldFont, FieldKind as FormFieldKind, FieldProps, FieldValue, Look as FieldLook,- NewField, TabOrder, Trigger as FieldTrigger, Widget as FormWidget, af as form_scripts, flags as field_flags,+ BorderStyle, CheckStyle, Field as FormField, FieldAction, FieldChange, FieldFont, FieldKind as FormFieldKind, FieldProps, FieldValue,+ Look as FieldLook, NewField, TabOrder, Trigger as FieldTrigger, Widget as FormWidget, af as form_scripts, flags as field_flags,};pub use pdfcraft_a11y as a11y;diff --git a/crates/forms/src/af.rs b/crates/forms/src/af.rsindex 7eddf7694..f93d08deb 100644--- a/crates/forms/src/af.rs+++ b/crates/forms/src/af.rs@@ -1088,6 +1088,12 @@ pub enum ButtonAction {Uri(String),/// Go to a page (0-based) in this document.GoTo(usize),+ /// A hide action (§12.6.4.11): hide the listed fields (and their kids), or show them when+ /// `hide` is false.+ ShowHide {+ fields: Vec<String>,+ hide: bool,+ },/// `app.alert("…")`.Alert(String),/// Submit the form to a URL (not sent: PdfCraft never posts form data on its own).diff --git a/crates/forms/src/author.rs b/crates/forms/src/author.rsindex e7f4e8a08..d51abda73 100644--- a/crates/forms/src/author.rs+++ b/crates/forms/src/author.rs@@ -523,6 +523,7 @@ pub fn add_field(doc: &mut Document, page: usize, rect: [f64; 4], kind: &NewFielstate: Some("Off".into()),tab: usize::MAX,locked: false,+ hidden: false,};let ap = appearance::check_box_states(doc, &w, FieldKind::Radio, export);doc.update_dict(widget, |d| d.set(b"AP".to_vec(), Object::Dict(ap)))?;diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rsindex 5c3d3df33..289a21b6b 100644--- a/crates/forms/src/lib.rs+++ b/crates/forms/src/lib.rs@@ -99,6 +99,8 @@ pub struct Widget {pub tab: usize,/// The widget's Locked flag (`/F` bit 8): its properties can't be changed.pub locked: bool,+ /// The widget's Hidden or NoView flag (`/F` bit 2 or 6): it isn't shown and takes no input.+ pub hidden: bool,}/// A terminal form field.@@ -216,11 +218,48 @@ fn button_action(doc: &Document, d: &Dict, widgets: &[ObjRef]) -> Option<af::Butlet target = dest.as_array()?.first()?.as_ref()?;af::ButtonAction::GoTo(page_refs(doc).iter().position(|p| *p == target)?)}+ b"Hide" => {+ // /T: a field name, an annotation (or field) reference, or an array of them.+ let target = |o: &Object| match o {+ Object::Ref(r) => qualified_name(doc, *r).or_else(|| text_of(&doc.resolve(o))),+ other => text_of(other),+ };+ let fields = match a.get(b"T") {+ Some(t) => match &*doc.resolve(t) {+ Object::Array(items) => items.iter().filter_map(target).collect(),+ _ => target(t).into_iter().collect(),+ },+ None => Vec::new(),+ };+ let hide = !a.get(b"H").is_some_and(|h| matches!(&*doc.resolve(h), Object::Bool(false)));+ af::ButtonAction::ShowHide { fields, hide }+ }b"JavaScript" => af::button_script(&script(doc, &action)?),_ => return None,})}+/// The fully qualified name of the field that `r` (a field or one of its widgets) belongs to,+/// from the partial names (`/T`) up its `/Parent` chain.+fn qualified_name(doc: &Document, r: ObjRef) -> Option<String> {+ let mut parts = Vec::new();+ let mut seen = std::collections::HashSet::new();+ let mut cur = Some(r);+ while let Some(c) = cur {+ if seen.len() > 64 || !seen.insert(c) {+ break;+ }+ let obj = doc.get(c);+ let d = obj.as_dict()?;+ if let Some(t) = d.get(b"T").and_then(|o| text_of(&doc.resolve(o))) {+ parts.push(t);+ }+ cur = d.get(b"Parent").and_then(|p| p.as_ref());+ }+ parts.reverse();+ (!parts.is_empty()).then(|| parts.join("."))+}+/// The JavaScript of an action dictionary (`/JS` string or stream).fn script(doc: &Document, action: &Object) -> Option<String> {let a = doc.resolve(action);@@ -554,6 +593,7 @@ fn walk(let wo = doc.get(w);let wd = wo.as_dict()?;let rect = nums(doc, wd.get(b"Rect")).filter(|r| r.len() == 4).unwrap_or_else(|| vec![0.0; 4]);+ let annot_flags = wd.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0);let on_state = wd.get(b"AP").map(|ap| doc.resolve(ap))@@ -567,7 +607,8 @@ fn walk(on_state: on_state.filter(|_| matches!(kind, FieldKind::CheckBox | FieldKind::Radio)),state: wd.name(b"AS").map(|s| String::from_utf8_lossy(s).into_owned()),tab: usize::MAX,- locked: wd.get(b"F").and_then(|f| doc.resolve(f).as_int()).unwrap_or(0) & 128 != 0,+ locked: annot_flags & 128 != 0,+ hidden: annot_flags & (2 | 32) != 0,})}).collect();diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rsindex 9a88905be..4a5314332 100644--- a/crates/forms/src/tests.rs+++ b/crates/forms/src/tests.rs@@ -712,6 +712,40 @@ fn field_actions_round_trip_on_every_trigger() {assert_eq!(fields(&doc).iter().find(|f| f.name == "go").unwrap().button, Some(af::ButtonAction::Named("Print".into())));}+#[test]+fn push_buttons_read_hide_actions() {+ let mut doc = fixture();+ let go = field(&fields(&doc), "go").obj;+ let s = |t: &str| Object::String(PdfString::text(t));+ let city = ObjRef::new(16, 0);+ let null = ObjRef::new(9, 0);+ let button = |doc: &mut Document, t: Object, h: Option<bool>| {+ let mut a = Dict::new();+ a.set(b"S".to_vec(), Object::name("Hide"));+ a.set(b"T".to_vec(), t);+ if let Some(h) = h {+ a.set(b"H".to_vec(), Object::Bool(h));+ }+ doc.update_dict(go, |d| d.set(b"A".to_vec(), Object::Dict(a))).unwrap();+ field(&fields(doc), "go").button.clone()+ };+ let hide = |names: &[&str], hide: bool| Some(af::ButtonAction::ShowHide { fields: names.iter().map(|n| n.to_string()).collect(), hide });+ // A name; /H defaults to true (hide).+ assert_eq!(button(&mut doc, s("name"), None), hide(&["name"], true));+ // A widget reference names its field by its fully qualified name; /H false shows.+ assert_eq!(button(&mut doc, Object::Ref(city), Some(false)), hide(&["address.city"], false));+ // An array of both; a reference to something that isn't a field is skipped.+ assert_eq!(button(&mut doc, Object::Array(vec![s("name"), Object::Ref(city), Object::Ref(null)]), None), hide(&["name", "address.city"], true));+ // A /Parent cycle ends instead of looping.+ let looped = doc.add(Object::Dict(Dict::new()));+ doc.update_dict(looped, |d| {+ d.set(b"T".to_vec(), s("loop"));+ d.set(b"Parent".to_vec(), Object::Ref(looped));+ })+ .unwrap();+ assert_eq!(button(&mut doc, Object::Ref(looped), None), hide(&["loop"], true));+}+#[test]fn detection_finds_blanks_rules_boxes_and_names_them() {use crate::detect::*;diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex bb09e7824..7c2213cc1 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -1408,7 +1408,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {if view.highlight_fields {for f in form.iter() {let required = f.has(pdfcraft_engine::field_flags::REQUIRED);- for w in f.widgets.iter().filter(|w| w.page == Some(i)) {+ for w in f.widgets.iter().filter(|w| w.page == Some(i) && !w.hidden) {let r = w.rect;let sr = xf.user_rect(info, i, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32]);painter.rect_filled(sr, CornerRadius::same(1), Color32::from_rgba_unmultiplied(0x6E, 0x8E, 0xF5, 48));@@ -1757,6 +1757,29 @@ fn run_button(app: &mut PdfCraftApp, index: usize, name: &str, action: pdfcraft_},B::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Button),B::GoTo(p) => app.views[index].go_to_page(p.min(pages.saturating_sub(1))),+ B::ShowHide { fields, hide } => {+ let listed = |n: &String| fields.iter().any(|f| n == f || n.starts_with(&format!("{f}.")));+ // `display.hidden` 1, `display.visible` 0, as a script setting `field.display` would.+ let changes: Vec<pdfcraft_engine::FieldChange> = app+ .session+ .get(app.views[index].id)+ .map(|d| d.form.iter().filter(|f| listed(&f.name)).map(|f| f.name.clone()).collect::<Vec<_>>())+ .unwrap_or_default()+ .into_iter()+ .map(|name| pdfcraft_engine::FieldChange {+ name,+ value: None,+ read_only: None,+ required: None,+ display: Some(if hide { 1 } else { 0 }),+ })+ .collect();+ if !changes.is_empty() {+ let label = if hide { "Hide a field" } else { "Show a field" };+ app.views[index].pending_edit =+ Some(pdfcraft_engine::Edit::Batch { label: label.into(), edits: vec![pdfcraft_engine::Edit::ApplyScriptChanges { changes }] });+ }+ }B::Alert(m) => app.notify(m),B::Submit(url) => {app.notify(format!("{name} submits the form to {url}; PdfCraft doesn't send form data. Save the document to keep your entries."))diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rsindex e33e6029e..65b8f95fc 100644--- a/crates/ui-egui/src/forms_ui.rs+++ b/crates/ui-egui/src/forms_ui.rs@@ -76,11 +76,17 @@ pub(crate) fn page_input(let pointer = ui.input(|i| i.pointer.hover_pos());let Some(p) = pointer.filter(|p| xf.rect.contains(*p)) else { return false };let hit = form.iter().find_map(|f| {- f.widgets.iter().enumerate().find(|(_, w)| w.page == Some(page) && widget_rect(xf, info, page, w.rect).contains(p)).map(|(i, w)| (f, i, w))+ f.widgets+ .iter()+ .enumerate()+ .find(|(_, w)| w.page == Some(page) && !w.hidden && widget_rect(xf, info, page, w.rect).contains(p))+ .map(|(i, w)| (f, i, w))});let Some((f, wi, w)) = hit else { return false };- // Empty signature fields are signed by clicking them (Use a certificate).- let usable = allowed && (fillable(f) || f.kind == FormFieldKind::Signature);+ // Empty signature fields are signed by clicking them (Use a certificate); push buttons run+ // their action.+ let pressable = f.kind == FormFieldKind::PushButton && !f.read_only() && f.button.is_some();+ let usable = allowed && (fillable(f) || pressable || f.kind == FormFieldKind::Signature);ui.ctx().set_cursor_icon(match (usable, f.kind) {(false, _) => egui::CursorIcon::NotAllowed,(true, FormFieldKind::Text) => egui::CursorIcon::Text,@@ -210,7 +216,7 @@ fn calendar(ctx: &egui::Context, view: &mut DocView, field: egui::Rect, fmt: &stpub(crate) fn paint_page(ui: &egui::Ui, painter: &egui::Painter, xf: &PageXform, page: usize, info: &DocInfo, form: &[FormField], view: &DocView) {let pointer = ui.input(|i| i.pointer.hover_pos());for f in form {- for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page)) {+ for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page) && !w.hidden) {let r = widget_rect(xf, info, page, w.rect);let focused = view.forms.focus.as_ref().is_some_and(|x| x.name == f.name && x.widget == wi);if focused {@@ -358,7 +364,7 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, flet mut order: Vec<(usize, &FormField, usize)> = form.iter().filter(|x| fillable(x) && matches!(x.kind, FormFieldKind::Text | FormFieldKind::Combo | FormFieldKind::List))- .flat_map(|x| x.widgets.iter().enumerate().filter(|(_, w)| w.page.is_some()).map(move |(wi, w)| (w.tab, x, wi)))+ .flat_map(|x| x.widgets.iter().enumerate().filter(|(_, w)| w.page.is_some() && !w.hidden).map(move |(wi, w)| (w.tab, x, wi))).collect();order.sort_by_key(|o| o.0);if let Some(pos) = orderdiff --git a/crates/ui-egui/tests/buttons.rs b/crates/ui-egui/tests/buttons.rsindex 718aee08a..f7b2c613b 100644--- a/crates/ui-egui/tests/buttons.rs+++ b/crates/ui-egui/tests/buttons.rs@@ -69,3 +69,66 @@ fn buttons_reset_navigate_and_print() {h.run_steps(4);assert_eq!(h.state().views[0].current, 1, "the NextPage action");}++/// One page: a text field "name" and two push buttons whose Hide actions hide it and show it again.+fn show_hide_fixture() -> Vec<u8> {+ let objs = [+ "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) >> >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>",+ "<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R] >>",+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /V (Ada) /F 4 /Rect [20 340 280 360] /P 3 0 R >>",+ "<< /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (hide) /Rect [20 300 100 320] /P 3 0 R /A << /S /Hide /T (name) >> >>",+ "<< /Type /Annot /Subtype /Widget /FT /Btn /Ff 65536 /T (show) /Rect [120 300 200 320] /P 3 0 R /A << /S /Hide /T 4 0 R /H false >> >>",+ ];+ let mut out = b"%PDF-1.7\n".to_vec();+ let mut offs = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offs.push(out.len());+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());+ }+ let x = out.len();+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offs {+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1).as_bytes());+ out+}++/// Whether the "name" widget (object 4) has the Hidden annotation flag in the saved document.+fn name_hidden(h: &Harness<'static, PdfCraftApp>) -> bool {+ let s = h.state();+ let bytes = s.session.save_bytes(s.views[0].id).unwrap();+ let doc = pdfcraft_cos::Document::open(bytes).unwrap();+ let f = doc.get(pdfcraft_cos::ObjRef::new(4, 0)).as_dict().and_then(|d| d.int(b"F")).unwrap_or(0);+ f & 2 != 0+}++#[test]+fn hide_actions_hide_and_show_fields() {+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {+ let mut app = PdfCraftApp::new();+ app.open_bytes("show-hide.pdf", None, show_hide_fixture()).unwrap();+ app.set_option("zoom", "150").unwrap();+ app+ });+ h.run_steps(6);+ assert!(!name_hidden(&h));+ // A push button with an action shows the pointing hand, not the "not allowed" cursor.+ let hide_at = {+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ let f = doc.form.iter().find(|f| f.name == "hide").unwrap();+ pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen").center()+ };+ h.hover_at(hide_at);+ h.run_steps(2);+ assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand);+ click_field(&mut h, "hide");+ assert!(name_hidden(&h), "the Hide action hid the field");+ // A hidden field takes no clicks: clicking where it was doesn't start editing it.+ click_field(&mut h, "name");+ assert!(h.state().views[0].forms.focus.is_none(), "a hidden field can't be focused");+ click_field(&mut h, "show");+ assert!(!name_hidden(&h), "the Hide action with /H false showed it again");+}diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex 31056b338..3e3eeb2ce 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -2247,11 +2247,11 @@ title = "Show/hide-a-field action"area = "C"tier = "P1"milestone = "M6"-status = "planned"+status = "shipped"commands = []tools = []-evidence = []-notes = ""+evidence = ["crates/ui-egui/tests/buttons.rs::hide_actions_hide_and_show_fields", "crates/forms/src/tests.rs::push_buttons_read_hide_actions"]+notes = "A push button's Hide action (/T names, field or widget references, arrays; /H) hides or shows the fields and their kids; hidden widgets take no clicks, tab stops or highlights. A widget reference acts on its whole field, and only form fields are hidden, not other annotations."[[feature]]id = "edit.action-javascript"