From 42f09c156cc87bdb1b6b5f665ee443c18f91cdb7 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:56:58 -0400 Subject: [PATCH 001/359] M6: a drop-down shows its arrow, and its list looks like the field --- crates/ui-egui/src/forms_ui.rs | 62 +++++++++++++++++++++++++++------- crates/ui-egui/tests/forms.rs | 50 +++++++++++++++++++++++++++ parity/acrobat-features.toml | 4 +-- 3 files changed, 102 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index 612b985e65..f684c28934 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -13,7 +13,6 @@ use pdfcraft_engine::{Edit, FieldValue, FormField, FormFieldKind, FormWidget, fi use pdfcraft_render::DocInfo; use crate::canvas::{DocView, PageXform}; -use crate::theme::Tokens; const FOCUS_BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6); /// Background of the in-place text field editor, the same in every theme. @@ -363,10 +362,27 @@ pub(crate) fn paint_page(ui: &egui::Ui, painter: &egui::Painter, xf: &PageXform, } else if fillable(f) && pointer.is_some_and(|p| r.contains(p)) { painter.rect_stroke(r, CornerRadius::same(1), Stroke::new(1.0, FOCUS_BLUE.gamma_multiply(0.8)), egui::StrokeKind::Outside); } + if f.kind == FormFieldKind::Combo && fillable(f) { + paint_drop_down_arrow(painter, r); + } } } } +/// A drop-down's arrow at the right of its box, which says the field opens a list (its page +/// appearance shows only the value). Drawn on screen only, not into the file. +fn paint_drop_down_arrow(painter: &egui::Painter, r: Rect) { + let width = (r.height() * 0.45).clamp(5.0, 12.0); + let inset = (r.height() * 0.25).clamp(2.0, 6.0); + // Too narrow a box keeps its value visible instead. + if r.width() < width * 3.0 { + return; + } + let (x, y, half) = (r.max.x - inset - width / 2.0, r.center().y, width / 2.0); + let points = vec![egui::pos2(x - half, y - half / 2.0), egui::pos2(x + half, y - half / 2.0), egui::pos2(x, y + half / 2.0)]; + painter.add(egui::Shape::convex_polygon(points, Color32::BLACK, Stroke::NONE)); +} + /// The size, in points, a text field shows `text` at on screen: its `/DA` size, or for auto size /// (`0 Tf`) the page appearance's fit, measured in the font the screen draws with so the text /// stays inside the box (the interface font runs wider than the page's Helvetica). @@ -490,7 +506,6 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, f let xf = view.page_xform(page)?; let rect = widget_rect(&xf, info, page, w.rect); let zoom = xf.rect.width() / xf.pw.max(1.0); - let t = Tokens::get(ctx); let mut edit = None; let mut close = false; let mut next: Option = None; // Tab / Shift+Tab @@ -581,24 +596,47 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, f } } FormFieldKind::Combo => { - let resp = egui::Area::new(egui::Id::new(("form-choices", view.id.0))) - .order(egui::Order::Foreground) - .fixed_pos(rect.left_bottom() + vec2(0.0, 2.0)) - .show(ctx, |ui| { - egui::Frame::popup(ui.style()).show(ui, |ui| { - ui.set_min_width(rect.width().max(160.0)); - ui.label(egui::RichText::new(&f.name).small().color(t.text_faint)); - egui::ScrollArea::vertical().max_height(260.0).show(ui, |ui| { + // The list opens under the field and looks like it, as other viewers draw it: as wide as + // the box, in its text size, black on white, without the field's internal name. + let size = (field_text_size(&ctx.layer_painter(egui::LayerId::background()), f, w, "") * zoom).clamp(6.0, 48.0); + let row = (size * 1.3).ceil(); + let resp = egui::Area::new(egui::Id::new(("form-choices", view.id.0))).order(egui::Order::Foreground).fixed_pos(rect.left_bottom()).show( + ctx, + |ui| { + ui.style_mut().visuals = egui::Visuals::light(); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + egui::Frame::new().fill(Color32::WHITE).stroke(Stroke::new(1.0, Color32::from_gray(64))).show(ui, |ui| { + let width = rect.width().max(24.0); + ui.set_width(width); + egui::ScrollArea::vertical().max_height(row * 9.0).show(ui, |ui| { for (export, display) in &f.options { let on = f.value.first() == Some(export); - if ui.selectable_label(on, display).clicked() { + let (r, item) = ui.allocate_exact_size(vec2(ui.available_width(), row), egui::Sense::click()); + item.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, on, display)); + let (fill, ink) = if on { + (Color32::from_rgb(0x2F, 0x6F, 0xE0), Color32::WHITE) + } else if item.hovered() { + (Color32::from_gray(222), Color32::BLACK) + } else { + (Color32::WHITE, Color32::BLACK) + }; + ui.painter().rect_filled(r, CornerRadius::ZERO, fill); + ui.painter().with_clip_rect(r).text( + egui::pos2(r.min.x + 3.0, r.center().y), + egui::Align2::LEFT_CENTER, + display, + egui::FontId::proportional(size), + ink, + ); + if item.clicked() { edit = Some(Edit::SetFieldValue { name: f.name.clone(), value: FieldValue::Choice(vec![export.clone()]) }); close = true; } } }); }); - }); + }, + ); let clicked_away = ctx.input(|i| i.pointer.any_click()) && !resp.response.contains_pointer() && !ctx.input(|i| i.pointer.hover_pos()).is_some_and(|p| rect.contains(p)); diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rs index e153dcca94..7913701ac7 100644 --- a/crates/ui-egui/tests/forms.rs +++ b/crates/ui-egui/tests/forms.rs @@ -1072,3 +1072,53 @@ fn auto_size_fields_shrink_and_wrap_typed_text_to_fit_their_box() { // An explicit size is kept, as in Acrobat: the text may then run past the box. assert_eq!(on_screen_fit(&h, "fixed", long).0, 10.0); } + +fn field_rect(h: &Harness<'static, PdfCraftApp>, name: &str) -> egui::Rect { + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + let f = doc.form.iter().find(|f| f.name == name).unwrap(); + pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen") +} + +/// Filled triangles painted inside `within`, at any depth of the frame's shapes. +fn triangles_in(h: &Harness<'static, PdfCraftApp>, within: egui::Rect) -> Vec> { + fn walk(shape: &egui::Shape, within: egui::Rect, out: &mut Vec>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, within, out)), + egui::Shape::Path(p) if p.points.len() == 3 && p.fill != egui::Color32::TRANSPARENT && p.points.iter().all(|q| within.contains(*q)) => { + out.push(p.points.clone()) + } + _ => {} + } + } + let mut out = Vec::new(); + for c in &h.output().shapes { + walk(&c.shape, within, &mut out); + } + out +} + +#[test] +fn a_drop_down_shows_its_arrow_and_text_fields_do_not() { + let mut h = harness(); + h.run_steps(2); + let country = field_rect(&h, "country"); + let arrows = triangles_in(&h, country); + assert_eq!(arrows.len(), 1, "one arrow in the drop-down: {arrows:?}"); + let tip = arrows[0].iter().fold(egui::Pos2::ZERO, |a, p| egui::pos2(a.x.max(p.x), a.y.max(p.y))); + assert!(tip.x > country.center().x, "at the right of the box"); + assert!(triangles_in(&h, field_rect(&h, "city")).is_empty(), "a text field has none"); +} + +#[test] +fn a_drop_downs_list_opens_as_wide_as_the_field_without_its_internal_name() { + let mut h = harness(); + click_field(&mut h, "country", 0); + let country = field_rect(&h, "country"); + assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "country").is_none(), "the field's name isn't shown"); + let item = egui_kittest::kittest::Queryable::get_by_label(&h, "France").rect(); + assert!((item.left() - country.left()).abs() <= 2.0 && item.right() <= country.right() + 1.0, "{item:?} in {country:?}"); + egui_kittest::kittest::Queryable::get_by_label(&h, "France").click(); + h.run_steps(4); + assert_eq!(value(&h, "country"), ["fr"]); +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 7aca7d5c8b..c9439bf218 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4440,8 +4440,8 @@ milestone = "M6" status = "shipped" commands = ["form.fields"] tools = ["form_fill"] -evidence = ["crates/ui-egui/tests/forms.rs::check_boxes_radios_and_choices", "crates/forms/src/tests.rs::choices_accept_exports_or_display_text"] -notes = "combo and list boxes, multi-select lists; editable combo boxes accept free text" +evidence = ["crates/ui-egui/tests/forms.rs::check_boxes_radios_and_choices", "crates/ui-egui/tests/forms.rs::a_drop_downs_list_opens_as_wide_as_the_field_without_its_internal_name", "crates/forms/src/tests.rs::choices_accept_exports_or_display_text"] +notes = "combo and list boxes, multi-select lists; editable combo boxes accept free text. A combo box shows its arrow on screen and opens its list under the field, as wide as the box and in its text size, black on white; the list takes no arrow keys yet" [[feature]] id = "form.push-buttons" From 034a1080b0bf8156a52a767c87b5ff064893b464 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Mon, 19 Oct 2026 18:17:04 -0400 Subject: [PATCH 002/359] M6: a long drop-down list keeps its scroll bar in view --- crates/ui-egui/src/forms_ui.rs | 19 +++++++++++++++++++ crates/ui-egui/tests/forms.rs | 16 ++++++++++++++++ parity/acrobat-features.toml | 2 +- 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index f684c28934..2e86d2c5fe 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -605,6 +605,25 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, f |ui| { ui.style_mut().visuals = egui::Visuals::light(); ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + // A scroll bar that stays shown beside the items, so a longer list says so and + // where it is scrolled to; it replaces the fade at the bottom edge. + ui.spacing_mut().scroll = egui::style::ScrollStyle { + bar_width: 8.0, + dormant_background_opacity: 1.0, + active_background_opacity: 1.0, + interact_background_opacity: 1.0, + dormant_handle_opacity: 1.0, + active_handle_opacity: 1.0, + interact_handle_opacity: 1.0, + ..egui::style::ScrollStyle::solid() + }; + ui.spacing_mut().scroll.fade.strength = 0.0; + // The bar's track and handle, gray on the white list. + let v = ui.visuals_mut(); + v.extreme_bg_color = Color32::from_gray(236); + v.widgets.inactive.bg_fill = Color32::from_gray(168); + v.widgets.hovered.bg_fill = Color32::from_gray(132); + v.widgets.active.bg_fill = Color32::from_gray(100); egui::Frame::new().fill(Color32::WHITE).stroke(Stroke::new(1.0, Color32::from_gray(64))).show(ui, |ui| { let width = rect.width().max(24.0); ui.set_width(width); diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rs index 7913701ac7..25db3e404d 100644 --- a/crates/ui-egui/tests/forms.rs +++ b/crates/ui-egui/tests/forms.rs @@ -1122,3 +1122,19 @@ fn a_drop_downs_list_opens_as_wide_as_the_field_without_its_internal_name() { h.run_steps(4); assert_eq!(value(&h, "country"), ["fr"]); } + +#[test] +fn a_long_drop_down_list_keeps_its_scroll_bar_beside_the_items() { + let mut h = harness(); + let options: Vec = (0..30).map(|i| format!("{i:02}00")).collect(); + assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldProps { + name: "country".into(), + props: Box::new(pdfcraft_engine::FieldProps { options: Some(options), ..Default::default() }), + })); + h.run_steps(3); + click_field(&mut h, "country", 0); + let country = field_rect(&h, "country"); + let first = egui_kittest::kittest::Queryable::get_by_label(&h, "0000").rect(); + // A scroll bar that stays shown takes its own room, so people see there is more below. + assert!(first.right() <= country.right() - 6.0, "{first:?} leaves room for the bar in {country:?}"); +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index c9439bf218..c37e458946 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4441,7 +4441,7 @@ status = "shipped" commands = ["form.fields"] tools = ["form_fill"] evidence = ["crates/ui-egui/tests/forms.rs::check_boxes_radios_and_choices", "crates/ui-egui/tests/forms.rs::a_drop_downs_list_opens_as_wide_as_the_field_without_its_internal_name", "crates/forms/src/tests.rs::choices_accept_exports_or_display_text"] -notes = "combo and list boxes, multi-select lists; editable combo boxes accept free text. A combo box shows its arrow on screen and opens its list under the field, as wide as the box and in its text size, black on white; the list takes no arrow keys yet" +notes = "combo and list boxes, multi-select lists; editable combo boxes accept free text. A combo box shows its arrow on screen and opens its list under the field, as wide as the box and in its text size, black on white, with a scroll bar shown beside a longer list; the list takes no arrow keys yet" [[feature]] id = "form.push-buttons" From 5d1303d12e7d62a467eba9e8827fce05aeea7697 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Mon, 19 Oct 2026 18:27:36 -0400 Subject: [PATCH 003/359] M6: a drop-down's list follows the pointer and the keys, with a classic scroll bar --- crates/ui-egui/src/editing.rs | 1 + crates/ui-egui/src/forms_ui.rs | 271 +++++++++++++++++++++++++-------- crates/ui-egui/tests/forms.rs | 84 ++++++++++ parity/acrobat-features.toml | 4 +- 4 files changed, 298 insertions(+), 62 deletions(-) diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 91480ac7b5..c70e2fa56f 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -1421,6 +1421,7 @@ mod revert_draft_tests { calendar: None, calendar_rect: None, calendar_text: None, + list: Default::default(), } } diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index 2e86d2c5fe..8c3b059527 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -40,6 +40,24 @@ pub struct Focus { /// The text the calendar last saw, so it moves to a typed date once, when the typing becomes /// a whole date, and otherwise keeps the month its arrows turned to. pub calendar_text: Option, + /// Drop-downs: where the open list is scrolled to and which item is current. + pub list: ChoiceList, +} + +/// A drop-down's open list: the first item shown, the item the keys or the pointer are on, and +/// where on the scroll bar's thumb a drag took hold. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ChoiceList { + pub first: usize, + pub current: Option, + pub grab: Option, + /// Wheel movement not yet a whole row. + pub wheel: f32, + /// The item the pointer was last over: entering another makes that one current, so a + /// resting pointer doesn't take the highlight back from the arrow keys. + pub pointer_on: Option, + /// Set on the first frame, from the field's value. + pub placed: bool, } #[derive(Clone, Debug, Default)] @@ -93,6 +111,7 @@ fn open_focus(f: &FormField, widget: usize) -> Focus { calendar: None, calendar_rect: None, calendar_text: None, + list: ChoiceList::default(), } } @@ -596,66 +615,15 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, f } } FormFieldKind::Combo => { - // The list opens under the field and looks like it, as other viewers draw it: as wide as - // the box, in its text size, black on white, without the field's internal name. - let size = (field_text_size(&ctx.layer_painter(egui::LayerId::background()), f, w, "") * zoom).clamp(6.0, 48.0); - let row = (size * 1.3).ceil(); - let resp = egui::Area::new(egui::Id::new(("form-choices", view.id.0))).order(egui::Order::Foreground).fixed_pos(rect.left_bottom()).show( - ctx, - |ui| { - ui.style_mut().visuals = egui::Visuals::light(); - ui.spacing_mut().item_spacing = vec2(0.0, 0.0); - // A scroll bar that stays shown beside the items, so a longer list says so and - // where it is scrolled to; it replaces the fade at the bottom edge. - ui.spacing_mut().scroll = egui::style::ScrollStyle { - bar_width: 8.0, - dormant_background_opacity: 1.0, - active_background_opacity: 1.0, - interact_background_opacity: 1.0, - dormant_handle_opacity: 1.0, - active_handle_opacity: 1.0, - interact_handle_opacity: 1.0, - ..egui::style::ScrollStyle::solid() - }; - ui.spacing_mut().scroll.fade.strength = 0.0; - // The bar's track and handle, gray on the white list. - let v = ui.visuals_mut(); - v.extreme_bg_color = Color32::from_gray(236); - v.widgets.inactive.bg_fill = Color32::from_gray(168); - v.widgets.hovered.bg_fill = Color32::from_gray(132); - v.widgets.active.bg_fill = Color32::from_gray(100); - egui::Frame::new().fill(Color32::WHITE).stroke(Stroke::new(1.0, Color32::from_gray(64))).show(ui, |ui| { - let width = rect.width().max(24.0); - ui.set_width(width); - egui::ScrollArea::vertical().max_height(row * 9.0).show(ui, |ui| { - for (export, display) in &f.options { - let on = f.value.first() == Some(export); - let (r, item) = ui.allocate_exact_size(vec2(ui.available_width(), row), egui::Sense::click()); - item.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, on, display)); - let (fill, ink) = if on { - (Color32::from_rgb(0x2F, 0x6F, 0xE0), Color32::WHITE) - } else if item.hovered() { - (Color32::from_gray(222), Color32::BLACK) - } else { - (Color32::WHITE, Color32::BLACK) - }; - ui.painter().rect_filled(r, CornerRadius::ZERO, fill); - ui.painter().with_clip_rect(r).text( - egui::pos2(r.min.x + 3.0, r.center().y), - egui::Align2::LEFT_CENTER, - display, - egui::FontId::proportional(size), - ink, - ); - if item.clicked() { - edit = Some(Edit::SetFieldValue { name: f.name.clone(), value: FieldValue::Choice(vec![export.clone()]) }); - close = true; - } - } - }); - }); - }, - ); + let mut st = view.forms.focus.as_ref().map(|x| x.list).unwrap_or_default(); + let (chosen, resp) = choice_list(ctx, view.id.0, f, w, rect, zoom, &mut st); + if let Some(fx) = view.forms.focus.as_mut() { + fx.list = st; + } + if let Some((export, _)) = chosen.and_then(|i| f.options.get(i)) { + edit = Some(Edit::SetFieldValue { name: f.name.clone(), value: FieldValue::Choice(vec![export.clone()]) }); + close = true; + } let clicked_away = ctx.input(|i| i.pointer.any_click()) && !resp.response.contains_pointer() && !ctx.input(|i| i.pointer.hover_pos()).is_some_and(|p| rect.contains(p)); @@ -732,6 +700,189 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, f edit.or_else(|| view.pending_edit.take()) } +/// Items a drop-down's list shows before it scrolls. +const LIST_ROWS: usize = 9; + +/// A drop-down's open list, under the field and drawn like it, as other viewers draw theirs: as +/// wide as the box, its items in the field's text size and alignment, black on white with a blue +/// highlight that follows the pointer and the arrow keys, and a scroll bar with step buttons when +/// there are more than nine items. Returns the item chosen (a click, or Enter on the current one) +/// and the list's response. +fn choice_list( + ctx: &egui::Context, + view: u64, + f: &FormField, + w: &FormWidget, + rect: Rect, + zoom: f32, + st: &mut ChoiceList, +) -> (Option, egui::InnerResponse<()>) { + let n = f.options.len(); + let shown = n.min(LIST_ROWS); + let max_first = n.saturating_sub(shown); + let size = (field_text_size(&ctx.layer_painter(egui::LayerId::background()), f, w, "") * zoom).clamp(6.0, 48.0); + let row = (size * 1.45).round().max(8.0); + let bar = if n > shown { (row * 0.7).round().clamp(12.0, 22.0) } else { 0.0 }; + let width = rect.width().max(24.0 + bar); + if !st.placed { + st.current = f.value.first().and_then(|v| f.options.iter().position(|(e, _)| e == v)); + st.first = st.current.map_or(0, |c| c.min(max_first)); + st.placed = true; + } + // Consumed, so the keys move through the list rather than the page. + let key = |k| ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, k)); + let moved = if n == 0 { + None + } else if key(egui::Key::ArrowUp) { + Some(st.current.map_or(0, |c| c.saturating_sub(1))) + } else if key(egui::Key::ArrowDown) { + Some(st.current.map_or(0, |c| (c + 1).min(n - 1))) + } else if key(egui::Key::PageUp) { + Some(st.current.map_or(0, |c| c.saturating_sub(shown))) + } else if key(egui::Key::PageDown) { + Some(st.current.map_or(0, |c| (c + shown).min(n - 1))) + } else if key(egui::Key::Home) { + Some(0) + } else if key(egui::Key::End) { + Some(n - 1) + } else { + None + }; + if let Some(m) = moved { + st.current = Some(m); + st.first = if m < st.first { + m + } else if m >= st.first + shown { + m + 1 - shown + } else { + st.first + }; + } + let mut chosen = key(egui::Key::Enter).then_some(st.current).flatten(); + let align = match f.quadding { + 1 => egui::Align::Center, + 2 => egui::Align::Max, + _ => egui::Align::Min, + }; + let resp = egui::Area::new(egui::Id::new(("form-choices", view))).order(egui::Order::Foreground).fixed_pos(rect.left_bottom()).show(ctx, |ui| { + let (outer, area) = ui.allocate_exact_size(vec2(width, shown as f32 * row + 2.0), egui::Sense::hover()); + let p = ui.painter(); + p.rect_filled(outer, CornerRadius::ZERO, Color32::WHITE); + // The wheel scrolls the list, a row at a time, and not the page under it. + if area.hovered() && n > shown { + st.wheel += ctx.input(|i| i.smooth_scroll_delta.y); + ctx.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO); + let steps = (st.wheel / row).trunc(); + if steps != 0.0 { + st.wheel -= steps * row; + st.first = (st.first as f32 - steps).clamp(0.0, max_first as f32) as usize; + } + } + let mut pointer_on = None; + let font = egui::FontId::proportional(size); + for k in 0..shown { + let i = st.first + k; + let Some((_, display)) = f.options.get(i) else { break }; + let r = Rect::from_min_size(outer.min + vec2(1.0, 1.0 + k as f32 * row), vec2(width - 2.0 - bar, row)); + let item = ui.interact(r, ui.id().with(("choice", i)), egui::Sense::click()); + item.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, st.current == Some(i), display)); + if item.hovered() { + pointer_on = Some(i); + if st.pointer_on != Some(i) { + st.current = Some(i); + } + } + if item.clicked() { + chosen = Some(i); + } + let on = st.current == Some(i); + if on { + p.rect_filled(r, CornerRadius::ZERO, Color32::from_rgb(0x1F, 0x65, 0xD6)); + } + let galley = p.layout_no_wrap(display.clone(), font.clone(), if on { Color32::WHITE } else { Color32::BLACK }); + let inner = r.shrink2(vec2(3.0, 0.0)); + let x = match align { + egui::Align::Center => inner.center().x - galley.size().x / 2.0, + egui::Align::Max => inner.max.x - galley.size().x, + egui::Align::Min => inner.min.x, + }; + p.with_clip_rect(r).galley(egui::pos2(x, r.center().y - galley.size().y / 2.0), galley, Color32::BLACK); + } + st.pointer_on = pointer_on; + if bar > 0.0 { + scroll_bar(ui, Rect::from_min_max(egui::pos2(outer.max.x - 1.0 - bar, outer.min.y + 1.0), outer.max - vec2(1.0, 1.0)), shown, n, st); + } + p.rect_stroke(outer, CornerRadius::ZERO, Stroke::new(1.0, Color32::BLACK), egui::StrokeKind::Inside); + }); + (chosen, resp) +} + +/// A list's classic scroll bar: step buttons at each end, a thumb sized to the share of the +/// items shown that can be dragged, and a track that pages when clicked. +fn scroll_bar(ui: &egui::Ui, track: Rect, shown: usize, n: usize, st: &mut ChoiceList) { + let max_first = n.saturating_sub(shown); + if max_first == 0 { + return; + } + let side = track.width(); + let up = Rect::from_min_size(track.min, vec2(side, side)); + let down = Rect::from_min_max(egui::pos2(track.min.x, track.max.y - side), track.max); + let trough = Rect::from_min_max(egui::pos2(track.min.x, up.max.y), egui::pos2(track.max.x, down.min.y)); + let thumb_len = (trough.height() * shown as f32 / n as f32).max(side * 0.75).min(trough.height()); + let travel = (trough.height() - thumb_len).max(1.0); + let thumb_at = |first: usize| trough.min.y + travel * first as f32 / max_first as f32; + let id = ui.id().with("choice-bar"); + let p = ui.painter(); + p.rect_filled(track, CornerRadius::ZERO, Color32::from_gray(240)); + for (r, step, pointing_up) in [(up, -1i64, true), (down, 1, false)] { + let b = ui.interact(r, id.with(pointing_up), egui::Sense::click()); + if b.clicked() { + st.first = (st.first as i64 + step).clamp(0, max_first as i64) as usize; + } + p.rect_filled(r.shrink(1.0), CornerRadius::ZERO, if b.hovered() { Color32::from_gray(205) } else { Color32::from_gray(222) }); + p.rect_stroke(r.shrink(1.0), CornerRadius::ZERO, Stroke::new(1.0, Color32::from_gray(150)), egui::StrokeKind::Inside); + let (c, h) = (r.center(), (side * 0.18).max(2.0)); + let tip = if pointing_up { -h } else { h }; + let points = vec![egui::pos2(c.x - h * 1.4, c.y - tip / 2.0), egui::pos2(c.x + h * 1.4, c.y - tip / 2.0), egui::pos2(c.x, c.y + tip / 2.0)]; + p.add(egui::Shape::convex_polygon(points, Color32::from_gray(40), Stroke::NONE)); + } + let thumb = Rect::from_min_size(egui::pos2(trough.min.x, thumb_at(st.first)), vec2(side, thumb_len)); + let t = ui.interact(thumb, id.with("thumb"), egui::Sense::drag()); + let pointer = ui.input(|i| i.pointer.interact_pos()); + if t.drag_started() { + st.grab = pointer.map(|q| q.y - thumb.min.y); + } + if t.dragged() + && let (Some(q), Some(grab)) = (pointer, st.grab) + { + let share = ((q.y - grab - trough.min.y) / travel).clamp(0.0, 1.0); + st.first = (share * max_first as f32).round() as usize; + } + if t.drag_stopped() { + st.grab = None; + } + let page = ui.interact(trough, id.with("trough"), egui::Sense::click()); + if page.clicked() + && let Some(q) = pointer + && !thumb.contains(q) + { + st.first = if q.y < thumb.min.y { st.first.saturating_sub(shown) } else { (st.first + shown).min(max_first) }; + } + let thumb = Rect::from_min_size(egui::pos2(trough.min.x, thumb_at(st.first)), vec2(side, thumb_len)).shrink2(vec2(1.0, 0.5)); + p.rect_filled(thumb, CornerRadius::ZERO, if t.dragged() || t.hovered() { Color32::from_gray(176) } else { Color32::from_gray(196) }); + p.rect_stroke(thumb, CornerRadius::ZERO, Stroke::new(1.0, Color32::from_gray(140)), egui::StrokeKind::Inside); + // Grip lines across the middle of the thumb. + if thumb.height() > side { + for k in -1..=1 { + let y = thumb.center().y + k as f32 * 3.0; + p.line_segment( + [egui::pos2(thumb.min.x + side * 0.3, y), egui::pos2(thumb.max.x - side * 0.3, y)], + Stroke::new(1.0, Color32::from_gray(120)), + ); + } + } +} + /// Where a field's widget is on screen (tests and automation). pub fn field_screen_rect(view: &DocView, info: &DocInfo, f: &FormField, widget: usize) -> Option { let w = f.widgets.get(widget)?; diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rs index 25db3e404d..3bd77e9ec3 100644 --- a/crates/ui-egui/tests/forms.rs +++ b/crates/ui-egui/tests/forms.rs @@ -1138,3 +1138,87 @@ fn a_long_drop_down_list_keeps_its_scroll_bar_beside_the_items() { // A scroll bar that stays shown takes its own room, so people see there is more below. assert!(first.right() <= country.right() - 6.0, "{first:?} leaves room for the bar in {country:?}"); } + +/// Where `text` is drawn in the last frame, if anywhere. +fn text_rect(h: &Harness<'static, PdfCraftApp>, text: &str) -> Option { + fn walk(shape: &egui::Shape, text: &str) -> Option { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| walk(s, text)), + egui::Shape::Text(t) if t.galley.text() == text => Some(egui::Rect::from_min_size(t.pos, t.galley.size())), + _ => None, + } + } + h.output().shapes.iter().find_map(|c| walk(&c.shape, text)) +} + +fn long_country(h: &mut Harness<'static, PdfCraftApp>) { + let options: Vec = (0..30).map(|i| format!("{i:02}00")).collect(); + assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldProps { + name: "country".into(), + props: Box::new(pdfcraft_engine::FieldProps { options: Some(options), ..Default::default() }), + })); + h.run_steps(3); +} + +#[test] +fn a_drop_downs_list_aligns_its_items_as_the_field_does() { + let mut h = harness(); + assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldProps { + name: "country".into(), + props: Box::new(pdfcraft_engine::FieldProps { quadding: Some(1), ..Default::default() }), + })); + h.run_steps(3); + click_field(&mut h, "country", 0); + let country = field_rect(&h, "country"); + let france = text_rect(&h, "France").expect("drawn"); + assert!((france.center().x - country.center().x).abs() <= 2.0, "centered as the field is: {france:?} in {country:?}"); +} + +#[test] +fn the_arrow_keys_move_through_a_drop_downs_list_and_enter_chooses() { + let mut h = harness(); + click_field(&mut h, "country", 0); + h.key_press(egui::Key::ArrowDown); + h.run_steps(1); + h.key_press(egui::Key::ArrowDown); + h.run_steps(1); + assert!(value(&h, "country").is_empty(), "the arrows only move through the list"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(value(&h, "country"), ["fr"]); + assert!(h.state().views[0].forms.focus.is_none(), "Enter closes the list"); + // Reopened, the list starts from the field's value. + click_field(&mut h, "country", 0); + h.key_press(egui::Key::ArrowUp); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(value(&h, "country"), ["ca"]); +} + +#[test] +fn a_long_drop_down_list_scrolls_by_its_arrow_button_and_to_its_end() { + let mut h = harness(); + long_country(&mut h); + click_field(&mut h, "country", 0); + assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0900").is_none(), "nine rows show"); + let country = field_rect(&h, "country"); + let first = egui_kittest::kittest::Queryable::get_by_label(&h, "0000").rect(); + // The bar's down button, at the bottom of the bar beside the ninth row. + let bar = country.right() - first.right(); + let down = egui::pos2(country.right() - bar / 2.0, first.top() + first.height() * 9.0 - bar / 2.0); + h.hover_at(down); + h.run_steps(1); + h.drag_at(down); + h.run_steps(1); + h.drop_at(down); + h.run_steps(2); + assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0900").is_some(), "one row on"); + assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_none()); + h.key_press(egui::Key::End); + h.run_steps(2); + assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "2900").is_some(), "End goes to the last item"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(value(&h, "country"), ["2900"]); +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index c37e458946..764cc6c87a 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4440,8 +4440,8 @@ milestone = "M6" status = "shipped" commands = ["form.fields"] tools = ["form_fill"] -evidence = ["crates/ui-egui/tests/forms.rs::check_boxes_radios_and_choices", "crates/ui-egui/tests/forms.rs::a_drop_downs_list_opens_as_wide_as_the_field_without_its_internal_name", "crates/forms/src/tests.rs::choices_accept_exports_or_display_text"] -notes = "combo and list boxes, multi-select lists; editable combo boxes accept free text. A combo box shows its arrow on screen and opens its list under the field, as wide as the box and in its text size, black on white, with a scroll bar shown beside a longer list; the list takes no arrow keys yet" +evidence = ["crates/ui-egui/tests/forms.rs::check_boxes_radios_and_choices", "crates/ui-egui/tests/forms.rs::a_drop_downs_list_opens_as_wide_as_the_field_without_its_internal_name", "crates/ui-egui/tests/forms.rs::the_arrow_keys_move_through_a_drop_downs_list_and_enter_chooses", "crates/forms/src/tests.rs::choices_accept_exports_or_display_text"] +notes = "combo and list boxes, multi-select lists; editable combo boxes accept free text. A combo box shows its arrow on screen and opens its list under the field, as wide as the box, in its text size and alignment, black on white with a highlight that follows the pointer; more than nine items get a scroll bar with step buttons, the wheel scrolls it, and the arrow keys, Page Up/Down, Home and End move through it, Enter choosing. The list is drawn in the interface font, not the field's (no serif interface font ships yet)" [[feature]] id = "form.push-buttons" From 21695302733b3ba0189863fcf18bb0d534be0e7f Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:37:32 -0400 Subject: [PATCH 004/359] M6: the mouse wheel scrolls a drop-down's list wherever the pointer is on it --- crates/ui-egui/src/forms_ui.rs | 2 +- crates/ui-egui/tests/forms.rs | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index 8c3b059527..f5b3901fbe 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -769,7 +769,7 @@ fn choice_list( let p = ui.painter(); p.rect_filled(outer, CornerRadius::ZERO, Color32::WHITE); // The wheel scrolls the list, a row at a time, and not the page under it. - if area.hovered() && n > shown { + if area.contains_pointer() && n > shown { st.wheel += ctx.input(|i| i.smooth_scroll_delta.y); ctx.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO); let steps = (st.wheel / row).trunc(); diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rs index 3bd77e9ec3..e02cc2c537 100644 --- a/crates/ui-egui/tests/forms.rs +++ b/crates/ui-egui/tests/forms.rs @@ -1222,3 +1222,26 @@ fn a_long_drop_down_list_scrolls_by_its_arrow_button_and_to_its_end() { h.run_steps(3); assert_eq!(value(&h, "country"), ["2900"]); } + +#[test] +fn the_mouse_wheel_scrolls_a_long_drop_down_list_and_not_the_page() { + let mut h = harness(); + long_country(&mut h); + click_field(&mut h, "country", 0); + let first = egui_kittest::kittest::Queryable::get_by_label(&h, "0000").rect(); + let page = h.state().views[0].page_screen_rect(0); + h.hover_at(first.center() + egui::vec2(0.0, first.height() * 4.0)); + h.run_steps(1); + for _ in 0..3 { + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }); + h.run_steps(2); + } + h.run_steps(6); + assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_none(), "the list scrolled down"); + assert_eq!(h.state().views[0].page_screen_rect(0), page, "the page stayed where it was"); +} From acd8a5765c91edd038430749bbf677a67cb05f33 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:45:29 -0400 Subject: [PATCH 005/359] M6: an open form field keeps the arrow keys, Home and End from moving the page --- crates/ui-egui/src/canvas.rs | 5 +++++ crates/ui-egui/tests/forms.rs | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index eb9244a284..0e90b81f5b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2294,6 +2294,11 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_s view.find = None; } } + // An open form field takes the arrows, Page Up / Page Down, Home and End (a drop-down's or a + // list box's items), so the page under it stays put. + if view.forms.focus.is_some() { + return; + } if key(Key::Home) { view.go_to_page(0); } diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rs index e02cc2c537..94822e50d0 100644 --- a/crates/ui-egui/tests/forms.rs +++ b/crates/ui-egui/tests/forms.rs @@ -1245,3 +1245,45 @@ fn the_mouse_wheel_scrolls_a_long_drop_down_list_and_not_the_page() { assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_none(), "the list scrolled down"); assert_eq!(h.state().views[0].page_screen_rect(0), page, "the page stayed where it was"); } + +#[test] +fn each_arrow_key_press_moves_a_drop_downs_list_one_item() { + let mut h = harness(); + long_country(&mut h); + click_field(&mut h, "country", 0); + h.key_press(egui::Key::Home); + h.run_steps(2); + h.key_press(egui::Key::ArrowDown); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(value(&h, "country"), ["0100"], "one item down from the first"); +} + +#[test] +fn an_open_drop_down_keeps_the_arrow_keys_and_home_from_moving_the_page() { + let mut h = harness(); + long_country(&mut h); + // A page taller than the window, so the keys would scroll it. + h.state_mut().set_option("zoom", "300").unwrap(); + for _ in 0..30 { + h.run_steps(2); + if !h.state().render_pending() { + break; + } + } + click_field(&mut h, "country", 0); + // The pointer rests on the list, as it does after reaching for it. + let row = egui_kittest::kittest::Queryable::get_by_label(&h, "0300").rect(); + h.hover_at(row.center()); + h.run_steps(2); + let page = h.state().views[0].page_screen_rect(0); + h.key_press(egui::Key::Home); + h.run_steps(2); + h.key_press(egui::Key::ArrowDown); + h.run_steps(4); + assert_eq!(h.state().views[0].page_screen_rect(0), page, "the page stayed where it was"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(value(&h, "country"), ["0100"], "one item down from the first"); +} From 98b292ac2b846af7a8418cd15dbeb70f22e1af61 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:51:54 -0400 Subject: [PATCH 006/359] M6: drop a drop-down test the page-scroll one covers --- crates/ui-egui/tests/forms.rs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rs index 94822e50d0..ab6c03239e 100644 --- a/crates/ui-egui/tests/forms.rs +++ b/crates/ui-egui/tests/forms.rs @@ -1246,20 +1246,6 @@ fn the_mouse_wheel_scrolls_a_long_drop_down_list_and_not_the_page() { assert_eq!(h.state().views[0].page_screen_rect(0), page, "the page stayed where it was"); } -#[test] -fn each_arrow_key_press_moves_a_drop_downs_list_one_item() { - let mut h = harness(); - long_country(&mut h); - click_field(&mut h, "country", 0); - h.key_press(egui::Key::Home); - h.run_steps(2); - h.key_press(egui::Key::ArrowDown); - h.run_steps(2); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(value(&h, "country"), ["0100"], "one item down from the first"); -} - #[test] fn an_open_drop_down_keeps_the_arrow_keys_and_home_from_moving_the_page() { let mut h = harness(); From eaf977b4ab109a448d6d0c9b3a4127423e9eba97 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:16:30 -0400 Subject: [PATCH 007/359] M6: a resting pointer leaves a drop-down's highlight to the keys --- crates/ui-egui/src/forms_ui.rs | 19 +++++++++---------- crates/ui-egui/tests/forms.rs | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index f5b3901fbe..dbc5037228 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -53,9 +53,10 @@ pub struct ChoiceList { pub grab: Option, /// Wheel movement not yet a whole row. pub wheel: f32, - /// The item the pointer was last over: entering another makes that one current, so a - /// resting pointer doesn't take the highlight back from the arrow keys. - pub pointer_on: Option, + /// Where the pointer was last frame: only a pointer that moves makes the item under it + /// current, so a resting one keeps no claim on the highlight when the keys scroll the list + /// beneath it. + pub pointer_at: Option, /// Set on the first frame, from the field's value. pub placed: bool, } @@ -778,7 +779,8 @@ fn choice_list( st.first = (st.first as f32 - steps).clamp(0.0, max_first as f32) as usize; } } - let mut pointer_on = None; + let pointer = ctx.input(|i| i.pointer.hover_pos()); + let pointer_moved = pointer != st.pointer_at; let font = egui::FontId::proportional(size); for k in 0..shown { let i = st.first + k; @@ -786,11 +788,8 @@ fn choice_list( let r = Rect::from_min_size(outer.min + vec2(1.0, 1.0 + k as f32 * row), vec2(width - 2.0 - bar, row)); let item = ui.interact(r, ui.id().with(("choice", i)), egui::Sense::click()); item.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, st.current == Some(i), display)); - if item.hovered() { - pointer_on = Some(i); - if st.pointer_on != Some(i) { - st.current = Some(i); - } + if item.hovered() && pointer_moved { + st.current = Some(i); } if item.clicked() { chosen = Some(i); @@ -808,7 +807,7 @@ fn choice_list( }; p.with_clip_rect(r).galley(egui::pos2(x, r.center().y - galley.size().y / 2.0), galley, Color32::BLACK); } - st.pointer_on = pointer_on; + st.pointer_at = pointer; if bar > 0.0 { scroll_bar(ui, Rect::from_min_max(egui::pos2(outer.max.x - 1.0 - bar, outer.min.y + 1.0), outer.max - vec2(1.0, 1.0)), shown, n, st); } diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rs index ab6c03239e..fd1f8267ad 100644 --- a/crates/ui-egui/tests/forms.rs +++ b/crates/ui-egui/tests/forms.rs @@ -1273,3 +1273,19 @@ fn an_open_drop_down_keeps_the_arrow_keys_and_home_from_moving_the_page() { h.run_steps(3); assert_eq!(value(&h, "country"), ["0100"], "one item down from the first"); } + +#[test] +fn a_pointer_resting_on_a_list_the_keys_scroll_keeps_the_highlight_on_the_keys() { + let mut h = harness(); + long_country(&mut h); + click_field(&mut h, "country", 0); + let row = egui_kittest::kittest::Queryable::get_by_label(&h, "0300").rect(); + h.hover_at(row.center()); + h.run_steps(2); + // End scrolls the list, so another item comes under the resting pointer. + h.key_press(egui::Key::End); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(value(&h, "country"), ["2900"], "the item End went to, not the one under the pointer"); +} From b0ef0e143c588383f6186ce89351af0f8b6e4cbd Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:42:33 -0400 Subject: [PATCH 008/359] M6: doc comments for the functions this change touches --- crates/ui-egui/src/canvas.rs | 3 +++ crates/ui-egui/src/editing.rs | 1 + crates/ui-egui/src/forms_ui.rs | 2 ++ crates/ui-egui/tests/forms.rs | 21 +++++++++++++++++++++ 4 files changed, 27 insertions(+) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 0e90b81f5b..5e30ab006e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2219,6 +2219,9 @@ impl PageXform { } } +/// The document view's keyboard shortcuts: find, rotation, zoom (or the page grid's size), +/// history, Escape, and the paging and scrolling keys. An open form field keeps the paging +/// and scrolling keys for itself. pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_speed::ScrollSpeed) { use egui::{Key, KeyboardShortcut, Modifiers}; if ctx.input_mut(|i| i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::F))) { diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index c70e2fa56f..7be091e76f 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -1409,6 +1409,7 @@ mod revert_draft_tests { use crate::forms_ui::Focus; use pdfcraft_engine::FieldValue; + /// An open editor on the first widget of the field "name", holding `text` as typed. fn focus(text: &str) -> Focus { Focus { name: "name".into(), diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index dbc5037228..e373206805 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -100,6 +100,8 @@ fn fillable(f: &FormField) -> bool { !f.read_only() && !matches!(f.kind, FormFieldKind::PushButton | FormFieldKind::Signature) } +/// Editor state for opening widget `widget` of `f`: it starts from the field's value, asks +/// for keyboard focus, and gives a drop-down a fresh list that places itself from that value. fn open_focus(f: &FormField, widget: usize) -> Focus { Focus { name: f.name.clone(), diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rs index fd1f8267ad..933efb9869 100644 --- a/crates/ui-egui/tests/forms.rs +++ b/crates/ui-egui/tests/forms.rs @@ -1073,6 +1073,7 @@ fn auto_size_fields_shrink_and_wrap_typed_text_to_fit_their_box() { assert_eq!(on_screen_fit(&h, "fixed", long).0, 10.0); } +/// Where the first widget of field `name` is on screen in the first view. fn field_rect(h: &Harness<'static, PdfCraftApp>, name: &str) -> egui::Rect { let s = h.state(); let doc = s.session.get(s.views[0].id).unwrap(); @@ -1082,6 +1083,8 @@ fn field_rect(h: &Harness<'static, PdfCraftApp>, name: &str) -> egui::Rect { /// Filled triangles painted inside `within`, at any depth of the frame's shapes. fn triangles_in(h: &Harness<'static, PdfCraftApp>, within: egui::Rect) -> Vec> { + /// Collects the filled three-point paths of `shape` that lie inside `within`, descending into + /// nested shape lists. fn walk(shape: &egui::Shape, within: egui::Rect, out: &mut Vec>) { match shape { egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, within, out)), @@ -1098,6 +1101,7 @@ fn triangles_in(h: &Harness<'static, PdfCraftApp>, within: egui::Rect) -> Vec, text: &str) -> Option { + /// The rectangle of the text shape in `shape` that reads exactly `text`, searching nested + /// shape lists. fn walk(shape: &egui::Shape, text: &str) -> Option { match shape { egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| walk(s, text)), @@ -1151,6 +1161,7 @@ fn text_rect(h: &Harness<'static, PdfCraftApp>, text: &str) -> Option) { let options: Vec = (0..30).map(|i| format!("{i:02}00")).collect(); assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldProps { @@ -1160,6 +1171,7 @@ fn long_country(h: &mut Harness<'static, PdfCraftApp>) { h.run_steps(3); } +/// A centered drop-down (quadding 1) centers the items of its open list too. #[test] fn a_drop_downs_list_aligns_its_items_as_the_field_does() { let mut h = harness(); @@ -1174,6 +1186,8 @@ fn a_drop_downs_list_aligns_its_items_as_the_field_does() { assert!((france.center().x - country.center().x).abs() <= 2.0, "centered as the field is: {france:?} in {country:?}"); } +/// The arrow keys move through an open drop-down's list without changing the value, Enter +/// chooses the current item and closes the list, and a reopened list starts from the value. #[test] fn the_arrow_keys_move_through_a_drop_downs_list_and_enter_chooses() { let mut h = harness(); @@ -1196,6 +1210,8 @@ fn the_arrow_keys_move_through_a_drop_downs_list_and_enter_chooses() { assert_eq!(value(&h, "country"), ["ca"]); } +/// Pressing the scroll bar's down button moves a long drop-down list on one row, and End goes +/// to the last item, which Enter then chooses. #[test] fn a_long_drop_down_list_scrolls_by_its_arrow_button_and_to_its_end() { let mut h = harness(); @@ -1223,6 +1239,7 @@ fn a_long_drop_down_list_scrolls_by_its_arrow_button_and_to_its_end() { assert_eq!(value(&h, "country"), ["2900"]); } +/// The mouse wheel over an open long drop-down scrolls its list and leaves the page where it was. #[test] fn the_mouse_wheel_scrolls_a_long_drop_down_list_and_not_the_page() { let mut h = harness(); @@ -1246,6 +1263,8 @@ fn the_mouse_wheel_scrolls_a_long_drop_down_list_and_not_the_page() { assert_eq!(h.state().views[0].page_screen_rect(0), page, "the page stayed where it was"); } +/// With a page taller than the window and the pointer resting on an open drop-down's list, +/// Home and the down arrow move through the list and leave the page where it was. #[test] fn an_open_drop_down_keeps_the_arrow_keys_and_home_from_moving_the_page() { let mut h = harness(); @@ -1274,6 +1293,8 @@ fn an_open_drop_down_keeps_the_arrow_keys_and_home_from_moving_the_page() { assert_eq!(value(&h, "country"), ["0100"], "one item down from the first"); } +/// When End scrolls a drop-down's list under a resting pointer, Enter chooses the item End +/// went to, not the one that came under the pointer. #[test] fn a_pointer_resting_on_a_list_the_keys_scroll_keeps_the_highlight_on_the_keys() { let mut h = harness(); From df693a24be7a09200a5d63e91f5138e78dff52f4 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Tue, 20 Oct 2026 18:59:24 -0400 Subject: [PATCH 009/359] M9: empty signature fields show a Sign tab An empty signature field that a click would sign now carries a small accent tab, with the signature icon and "Sign", inside its top-left corner while the Select tool is active (not while preparing a form). It follows the field click's own checks: the document allows filling, the field isn't read-only, and its widget is shown. The tab drops its label, then itself, on a field too small at the current zoom. Like the validation badges it is screen-only chrome, never written into the file, exports or printing. The label reuses the catalog's "Sign". The tab sits inside the field, so clicking it starts signing that field and hovering it shows the pointing hand. Unit tests cover which fields get a tab (signed, invisible, other-page, unplaced, non-finite and huge rectangles, read-only fields, refused filling, hidden or moved widgets) and the layout; a kittest frame test checks the painted tab, the cursor and the click. --- crates/ui-egui/src/canvas.rs | 347 ++++++++++++++++++++++++++++++++++- parity/acrobat-features.toml | 4 +- 2 files changed, 347 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index eb9244a284..72491f214a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -343,6 +343,87 @@ pub(crate) fn signature_badges(signatures: &[pdfcraft_engine::SignatureInfo], pa .collect() } +/// The empty signature fields on one page that get a sign tab, as their widget rectangles +/// (user space). Each is unsigned and visible, on this page, with a rectangle that passes the +/// same screen-space guard as [`signature_badges`]. A click must also be able to sign it, as +/// in `forms_ui::page_input`: the document allows filling (`can_fill`), and the form field of +/// that name is a signature field that isn't read-only, with a shown widget at that place. +pub(crate) fn sign_tabs( + signatures: &[pdfcraft_engine::SignatureInfo], + form: &[pdfcraft_engine::FormField], + page: usize, + can_fill: bool, +) -> Vec<[f64; 4]> { + let mut empty = signatures + .iter() + .filter(|s| can_fill && !s.signed && s.visible && s.page == Some(page)) + .filter_map(|s| s.rect.filter(|r| r.iter().all(|v| v.is_finite() && v.abs() < f32::MAX as f64)).map(|r| (s.field.as_str(), r))) + .peekable(); + if empty.peek().is_none() { + return Vec::new(); + } + // The widgets a click signs, by field name and exact rectangle, from one pass over the form: + // a file with thousands of fields costs no more per frame than the field hit test does. + let signable: HashSet<(&str, [u64; 4])> = form + .iter() + .filter(|f| f.kind == pdfcraft_engine::FormFieldKind::Signature && !f.read_only()) + .flat_map(|f| f.widgets.iter().filter(|w| w.page == Some(page) && !w.hidden).map(move |w| (f.name.as_str(), w.rect.map(f64::to_bits)))) + .collect(); + empty.filter(|(name, r)| signable.contains(&(*name, r.map(f64::to_bits)))).map(|(_, r)| r).collect() +} + +/// Height of a sign tab, in points. +const SIGN_TAB_HEIGHT: f32 = 18.0; +/// Size of the signature icon on a sign tab. +const SIGN_TAB_ICON: f32 = 12.0; +/// Gap between a sign tab and its field's edges. +const SIGN_TAB_INSET: f32 = 3.0; +/// Room left and right of a sign tab's contents, and between its icon and label. +const SIGN_TAB_PAD: f32 = 5.0; + +/// Where one sign tab is drawn on screen: its chip, the icon's square and, when the label fits, +/// the point where the label starts (its left edge, on the chip's center line). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct SignTab { + pub rect: Rect, + pub icon: Rect, + pub label: Option, +} + +/// Lays out a sign tab inside the top-left corner of `field` (the widget on screen) for a label +/// `label_width` points wide. The tab takes at most half the field's width: it drops the label +/// when only the icon fits, and is left out on a field too small (or not finite) for even that. +pub(crate) fn sign_tab_layout(field: Rect, label_width: f32) -> Option { + if !field.is_finite() || field.height() < SIGN_TAB_HEIGHT + 2.0 * SIGN_TAB_INSET { + return None; + } + let room = field.width() / 2.0 - SIGN_TAB_INSET; + let full = SIGN_TAB_PAD + SIGN_TAB_ICON + SIGN_TAB_PAD + label_width + SIGN_TAB_PAD; + let with_label = label_width.is_finite() && label_width > 0.0 && full <= room; + let width = if with_label { full } else { SIGN_TAB_HEIGHT }; + if width > room { + return None; + } + let rect = Rect::from_min_size(field.min + vec2(SIGN_TAB_INSET, SIGN_TAB_INSET), vec2(width, SIGN_TAB_HEIGHT)); + let icon_x = if with_label { rect.left() + SIGN_TAB_PAD } else { rect.center().x - SIGN_TAB_ICON / 2.0 }; + let icon = Rect::from_min_size(pos2(icon_x, rect.center().y - SIGN_TAB_ICON / 2.0), Vec2::splat(SIGN_TAB_ICON)); + let label = with_label.then(|| pos2(icon.right() + SIGN_TAB_PAD, rect.center().y)); + Some(SignTab { rect, icon, label }) +} + +/// Paints the sign tab of an empty signature field whose widget is at `field` on screen: an +/// accent chip with the signature icon and "Sign" in white, as the app's primary buttons are. +/// Screen-only chrome, like the validation badges. +fn paint_sign_tab(ui: &egui::Ui, painter: &egui::Painter, field: Rect, t: &Tokens) { + let galley = ui.fonts_mut(|f| f.layout_no_wrap(tl!("Sign").to_string(), theme::semibold(11.0), Color32::WHITE)); + let Some(tab) = sign_tab_layout(field, galley.size().x) else { return }; + painter.rect_filled(tab.rect, CornerRadius::same(4), t.accent); + icons::paint(ui, tab.icon, "signature", SIGN_TAB_ICON, Color32::WHITE); + if let Some(at) = tab.label { + painter.galley(at - vec2(0.0, galley.size().y / 2.0), galley, Color32::WHITE); + } +} + /// The name shown for a document tab, the window title and the Combine picker. /// A snapshot reads like its source document, plus the snapshot suffix that tells /// the tabs apart. Without a title the file name (which already carries the suffix) @@ -2354,8 +2435,8 @@ const SUPPRESS_SECS: f64 = 0.25; /// Short rolling extension while egui still has an unprocessed wheel tail. const SUPPRESS_TAIL_SECS: f64 = 0.05; -// The viewer moves between docking and the central panel as modes change; keep its scroll -// identity tied to the document instead of either parent UI. +/// The viewer moves between docking and the central panel as modes change; keep its scroll +/// identity tied to the document instead of either parent UI. fn page_scroll( ui: &mut egui::Ui, scroll: egui::ScrollArea, @@ -2365,6 +2446,8 @@ fn page_scroll( ui.scope_builder(egui::UiBuilder::new().id(id), |ui| scroll.show_viewport(ui, draw)).inner } +/// The document area of view `index`: its pages with their overlays and viewer chrome (form +/// fields, comments, signature badges and sign tabs), and the page input of the active tool. pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); // Keyboard scrolling applies to this frame's page view only, never later. @@ -3550,6 +3633,14 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { view.flash = None; } } + // An empty field a click would sign carries a small tab saying so, shown only while + // a click on the field signs it (the Select tool, not while preparing a form). Like + // the validation badges, it never enters the file, exports or printing. + if tool == QuickTool::Select && !preparing { + for [x0, y0, x1, y1] in sign_tabs(&doc.signatures, &form, i, can_fill) { + paint_sign_tab(ui, painter, xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]), &t); + } + } // Validation is viewer chrome over the signer's original artwork, which // may still say "Signature Not Verified". These badges never enter document // streams, image/text exports, vector printing or Print as Image. @@ -5314,6 +5405,258 @@ fn grayscale(mut img: egui::ColorImage) -> egui::ColorImage { img } +#[cfg(test)] +mod sign_tab_tests { + use super::*; + use pdfcraft_engine::{FormField, FormFieldKind, FormWidget, SignatureInfo}; + + /// The widget rectangle the unit tests use (user space). + const RECT: [f64; 4] = [20.0, 110.0, 140.0, 180.0]; + + /// An unsigned, visible signature listing for field `name` with its widget on `page` at + /// `rect`. Each test changes the one thing it is about. + fn listing(name: &str, page: usize, rect: [f64; 4]) -> SignatureInfo { + SignatureInfo { + field: name.into(), + signed: false, + page: Some(page), + rect: Some(rect), + visible: true, + signer: None, + certificate: None, + chain: Vec::new(), + date: None, + signing_time: None, + reason: None, + location: None, + contact: None, + sub_filter: None, + doc_timestamp: false, + certify: None, + revision: 1, + signed_len: 0, + digest: None, + algorithm: None, + timestamp: false, + timestamp_time: None, + status: pdfcraft_engine::SignatureStatus::Unknown, + modification: pdfcraft_engine::sign::Modification::None, + details: Vec::new(), + } + } + + /// The signature form field `name` with one shown widget on `page` at `rect`. + fn field(name: &str, page: usize, rect: [f64; 4]) -> FormField { + FormField { + name: name.into(), + obj: pdfcraft_cos::ObjRef::new(4, 0), + kind: FormFieldKind::Signature, + value: Vec::new(), + default: Vec::new(), + flags: 0, + max_len: None, + options: Vec::new(), + da: String::new(), + quadding: 0, + tooltip: None, + widgets: vec![FormWidget { + obj: pdfcraft_cos::ObjRef::new(4, 0), + page: Some(page), + rect, + on_state: None, + state: None, + tab: 0, + locked: false, + hidden: false, + rotation: 0, + caption: None, + list: None, + }], + actions: Default::default(), + button: None, + } + } + + /// The cases (by name) whose single listing and form still got a tab on page 0. + fn tabbed<'a>(cases: &[(&'a str, SignatureInfo, Vec, bool)]) -> Vec<&'a str> { + cases.iter().filter(|(_, s, form, can_fill)| !sign_tabs(std::slice::from_ref(s), form, 0, *can_fill).is_empty()).map(|c| c.0).collect() + } + + /// An empty, visible signature field that a click signs gets one tab, at its widget, on its + /// own page only. + #[test] + fn sign_tabs_mark_an_empty_field_that_a_click_signs() { + let tabs = sign_tabs(&[listing("Approver", 0, RECT)], &[field("Approver", 0, RECT)], 0, true); + assert_eq!(tabs, vec![RECT]); + let later = [listing("Witness", 1, RECT)]; + assert_eq!(sign_tabs(&later, &[field("Witness", 1, RECT)], 1, true), vec![RECT]); + assert!(sign_tabs(&later, &[field("Witness", 1, RECT)], 0, true).is_empty(), "not on the page before"); + } + + /// Signed, invisible, other-page and unplaced fields get no tab. Each case is checked on its + /// own, so a failure names every case that wrongly got one. + #[test] + fn sign_tabs_skip_signed_invisible_other_page_and_unplaced_fields() { + let form = || vec![field("Approver", 0, RECT)]; + let cases = [ + ("signed", SignatureInfo { signed: true, ..listing("Approver", 0, RECT) }, form(), true), + ("invisible", SignatureInfo { visible: false, ..listing("Approver", 0, RECT) }, form(), true), + ("on another page", listing("Approver", 1, RECT), vec![field("Approver", 1, RECT)], true), + ("on no page", SignatureInfo { page: None, ..listing("Approver", 0, RECT) }, form(), true), + ("without a rectangle", SignatureInfo { rect: None, ..listing("Approver", 0, RECT) }, form(), true), + ]; + assert_eq!(tabbed(&cases), Vec::<&str>::new()); + } + + /// NaN, infinite and gigantic rectangles never reach the painter, even when the form's + /// widget carries the same numbers. + #[test] + fn sign_tabs_skip_rectangles_that_cannot_reach_the_screen() { + let hostile = |name: &'static str, rect: [f64; 4]| (name, listing("Approver", 0, rect), vec![field("Approver", 0, rect)], true); + let cases = [ + hostile("NaN", [f64::NAN, 110.0, 140.0, 180.0]), + hostile("infinite", [20.0, f64::INFINITY, 140.0, 180.0]), + hostile("minus infinite", [20.0, 110.0, f64::NEG_INFINITY, 180.0]), + hostile("huge", [20.0, 110.0, 1e300, 180.0]), + ]; + assert_eq!(tabbed(&cases), Vec::<&str>::new()); + } + + /// Fields a click would not sign get no tab: a read-only field, a document that refuses + /// filling, a listing with no form field of its name, a field of another kind of that name, + /// and a widget that is hidden or elsewhere. + #[test] + fn sign_tabs_skip_fields_that_a_click_cannot_sign() { + let empty = || listing("Approver", 0, RECT); + let with = |change: fn(&mut FormField)| { + let mut f = field("Approver", 0, RECT); + change(&mut f); + vec![f] + }; + let cases = [ + ("read-only", empty(), with(|f| f.flags = pdfcraft_engine::field_flags::READ_ONLY), true), + ("filling refused", empty(), with(|_| {}), false), + ("no form field", empty(), Vec::new(), true), + ("another kind", empty(), with(|f| f.kind = FormFieldKind::Text), true), + ("hidden widget", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.hidden = true)), true), + ("widget elsewhere", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.rect = [160.0, 110.0, 280.0, 180.0])), true), + ]; + assert_eq!(tabbed(&cases), Vec::<&str>::new()); + } + + /// A roomy field gets the whole tab inside its top-left corner: the icon, then the label, + /// on no more than half the field's width. + #[test] + fn sign_tab_layout_puts_icon_and_label_in_the_top_left_corner() { + let field = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 120.0)); + let tab = sign_tab_layout(field, 30.0).expect("fits"); + assert_eq!(tab.rect.min, field.min + vec2(SIGN_TAB_INSET, SIGN_TAB_INSET)); + assert_eq!(tab.rect.height(), SIGN_TAB_HEIGHT); + assert!(field.contains_rect(tab.rect) && tab.rect.width() <= field.width() / 2.0, "{tab:?}"); + assert!(tab.rect.contains_rect(tab.icon), "{tab:?}"); + let at = tab.label.expect("the label fits"); + assert!(at.x >= tab.icon.right() && at.x + 30.0 <= tab.rect.right(), "{tab:?}"); + assert_eq!(at.y, tab.rect.center().y); + } + + /// A field with room for the icon but not the label gets the icon alone, and one too small + /// for even that, or with a rectangle that isn't finite, gets no tab. A label that can't be + /// measured is left out instead of drawn at a NaN position. + #[test] + fn sign_tab_layout_drops_the_label_then_the_tab_on_small_fields() { + let narrow = Rect::from_min_size(Pos2::ZERO, vec2(60.0, 40.0)); + let icon_only = sign_tab_layout(narrow, 30.0).expect("the icon fits"); + assert_eq!(icon_only.label, None); + assert!(narrow.contains_rect(icon_only.rect) && icon_only.rect.contains_rect(icon_only.icon), "{icon_only:?}"); + let cases = [ + ("too short", Rect::from_min_size(Pos2::ZERO, vec2(400.0, 20.0))), + ("too narrow", Rect::from_min_size(Pos2::ZERO, vec2(30.0, 40.0))), + ("infinite", Rect::from_min_max(Pos2::ZERO, pos2(f32::INFINITY, 40.0))), + ("NaN", Rect::from_min_max(pos2(f32::NAN, 0.0), pos2(400.0, 40.0))), + ]; + let laid_out: Vec<&str> = cases.iter().filter(|(_, r)| sign_tab_layout(*r, 30.0).is_some()).map(|c| c.0).collect(); + assert_eq!(laid_out, Vec::<&str>::new()); + let roomy = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 120.0)); + assert_eq!(sign_tab_layout(roomy, f32::NAN).map(|t| t.label), Some(None)); + } + + /// One page with three signature fields: Approver is empty, Witness is signed (a signature + /// dictionary as its value is enough to list it as signed) and Locked is empty but read-only. + const SIGN_FIELDS: &[u8] = b"%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R] >> >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [4 0 R 5 0 R 6 0 R] >> endobj +4 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Approver) /Rect [20 110 140 180] /P 3 0 R /F 4 >> endobj +5 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Witness) /V << /Type /Sig >> /Rect [160 110 280 180] /P 3 0 R /F 4 >> endobj +6 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Locked) /Ff 1 /Rect [20 20 140 90] /P 3 0 R /F 4 >> endobj +trailer << /Root 1 0 R >> +%%EOF"; + + /// Every shape painted in the last frame, with nested lists flattened. + fn painted(h: &egui_kittest::Harness<'static, PdfCraftApp>) -> Vec { + let mut stack: Vec = h.output().shapes.iter().map(|c| c.shape.clone()).collect(); + let mut out = Vec::new(); + while let Some(shape) = stack.pop() { + match shape { + egui::Shape::Vec(inner) => stack.extend(inner), + shape => out.push(shape), + } + } + out + } + + /// Where the named field's first widget is on screen. + fn field_on_screen(h: &egui_kittest::Harness<'static, PdfCraftApp>, name: &str) -> Rect { + let app = h.state(); + let view = &app.views[0]; + let doc = app.session.get(view.id).expect("open"); + let f = doc.form.iter().find(|f| f.name == name).expect("field"); + crate::forms_ui::field_screen_rect(view, &doc.info, f, 0).expect("on screen") + } + + /// In the real shell, an empty signature field shows its accent tab with "Sign" in its + /// top-left corner, and the signed and read-only fields show none. The tab is part of the + /// field: hovering it shows the pointing hand, and clicking it starts signing that field. + #[test] + fn empty_signature_fields_show_a_sign_tab_that_signs_them() { + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("sign-fields.pdf", None, SIGN_FIELDS.to_vec()).unwrap(); + app.set_option("left", "closed").unwrap(); + app.set_option("panel", "none").unwrap(); + app + }); + h.run_steps(6); + let accent = Tokens::get(&h.ctx).accent; + let shapes = painted(&h); + let chips: Vec = shapes + .iter() + .filter_map(|s| match s { + egui::Shape::Rect(r) if r.fill == accent => Some(r.rect), + _ => None, + }) + .collect(); + let (approver, witness, locked) = (field_on_screen(&h, "Approver"), field_on_screen(&h, "Witness"), field_on_screen(&h, "Locked")); + let tab = chips.iter().copied().find(|c| approver.contains_rect(*c)).unwrap_or_else(|| panic!("no tab in {approver:?}: {chips:?}")); + assert!(tab.min.x - approver.min.x < 8.0 && tab.min.y - approver.min.y < 8.0, "in the top-left corner: {tab:?} in {approver:?}"); + let label = shapes.iter().any(|s| matches!(s, egui::Shape::Text(t) if t.galley.text() == "Sign" && tab.contains(t.pos))); + assert!(label, "the tab says Sign"); + assert!(!chips.iter().any(|c| witness.intersects(*c)), "a signed field has no tab: {chips:?}"); + assert!(!chips.iter().any(|c| locked.intersects(*c)), "a read-only field has no tab: {chips:?}"); + + h.hover_at(tab.center()); + h.run_steps(1); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand); + h.drag_at(tab.center()); + h.run_steps(1); + h.drop_at(tab.center()); + h.run_steps(3); + assert_eq!(h.state().dialog, Some(crate::Dialog::Sign)); + assert_eq!(h.state().sign_draft.as_ref().and_then(|d| d.field.clone()).as_deref(), Some("Approver")); + } +} + #[cfg(test)] mod tests { #[test] diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 7aca7d5c8b..64216ff736 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5984,8 +5984,8 @@ milestone = "M9" status = "shipped" commands = ["sign.digital"] tools = ["sign_document"] -evidence = ["crates/sign/tests/pdf.rs::signing_an_existing_field_and_counter_signing", "crates/ui-egui/tests/signing.rs::clicking_an_empty_signature_field_signs_it"] -notes = "" +evidence = ["crates/sign/tests/pdf.rs::signing_an_existing_field_and_counter_signing", "crates/ui-egui/tests/signing.rs::clicking_an_empty_signature_field_signs_it", "crates/ui-egui/src/canvas.rs::empty_signature_fields_show_a_sign_tab_that_signs_them", "crates/ui-egui/src/canvas.rs::sign_tabs_skip_fields_that_a_click_cannot_sign"] +notes = "Clicking an empty signature field signs it (Use a certificate for that field). With the Select tool, each empty field a click would sign (filling allowed, the field not read-only, its widget shown) carries a small accent tab with the signature icon and Sign in its top-left corner. The tab is screen-only chrome, never written into the file, exports or printing; it drops its label, then itself, on a field too small at the current zoom, and is hidden while preparing a form. Missing: the tab is painted only, with no accessibility node or keyboard focus of its own" [[feature]] id = "sign.invisible-signature" From ea57770e24722bab37ec6cf3d1401ff57340df0b Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:54:11 -0400 Subject: [PATCH 010/359] M9: size the Sign tab to its field The tab was a fixed 18 pt chip that needed a 24 pt field: too big on a 29 pt signature box and missing on a 19 pt one. It is now 0.4 of the field's height on screen, from 10 to 18 pt, and its inset, icon, padding, label font and corners scale with it (3, 12, 5, 11 and 4 pt on the 18 pt tab). The label shows from 14 pt up while the whole tab fits in half the field's width; otherwise the tab is a square icon chip, and it is left out only when that chip doesn't fit or the field isn't finite. Which fields get a tab, the click and the tool condition are unchanged. The layout tests now cover an 18 pt tab with its label, an 11.6 pt and a 10 pt icon chip on 29 pt and 19 pt fields, no tab on a 12 pt field, the label and then the tab dropping as a field narrows, and the scaled font and corners. --- crates/ui-egui/src/canvas.rs | 159 +++++++++++++++++++++++------------ parity/acrobat-features.toml | 2 +- 2 files changed, 108 insertions(+), 53 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 72491f214a..ad046803c9 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -372,54 +372,69 @@ pub(crate) fn sign_tabs( empty.filter(|(name, r)| signable.contains(&(*name, r.map(f64::to_bits)))).map(|(_, r)| r).collect() } -/// Height of a sign tab, in points. -const SIGN_TAB_HEIGHT: f32 = 18.0; -/// Size of the signature icon on a sign tab. -const SIGN_TAB_ICON: f32 = 12.0; -/// Gap between a sign tab and its field's edges. -const SIGN_TAB_INSET: f32 = 3.0; -/// Room left and right of a sign tab's contents, and between its icon and label. -const SIGN_TAB_PAD: f32 = 5.0; +/// The largest sign tab's height, in points. Every other size is a share of the tab's height, +/// taken from this one: a 3 pt inset, a 12 pt icon, 5 pt padding, an 11 pt label and 4 pt corners. +const SIGN_TAB_MAX: f32 = 18.0; +/// The smallest sign tab's height, in points: a field too small for this chip gets no tab. +const SIGN_TAB_MIN: f32 = 10.0; +/// The share of its field's height on screen that a sign tab takes, between the two sizes. +const SIGN_TAB_SHARE: f32 = 0.4; +/// The smallest sign tab that carries the label; below it the tab is the icon alone. +const SIGN_TAB_LABEL_MIN: f32 = 14.0; +/// The label's font size on the largest sign tab; it shrinks with the tab. +const SIGN_TAB_FONT: f32 = 11.0; /// Where one sign tab is drawn on screen: its chip, the icon's square and, when the label fits, -/// the point where the label starts (its left edge, on the chip's center line). +/// the point where the label starts (its left edge, on the chip's center line), with the +/// label's font size and the chip's corner radius at this tab's size. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct SignTab { pub rect: Rect, pub icon: Rect, pub label: Option, + pub font: f32, + pub radius: f32, } -/// Lays out a sign tab inside the top-left corner of `field` (the widget on screen) for a label -/// `label_width` points wide. The tab takes at most half the field's width: it drops the label -/// when only the icon fits, and is left out on a field too small (or not finite) for even that. +/// Lays out a sign tab inside the top-left corner of `field` (the widget on screen), for a label +/// `label_width` points wide at [`SIGN_TAB_FONT`], its size on the largest tab. The tab is +/// [`SIGN_TAB_SHARE`] of the field's height, from [`SIGN_TAB_MIN`] to [`SIGN_TAB_MAX`], and its +/// inset, icon, padding, label and corners scale with it. It carries the label from +/// [`SIGN_TAB_LABEL_MIN`] up when the whole tab fits in half the field's width, and is a square +/// icon chip otherwise. It is left out when even that chip doesn't fit, or the field isn't finite. pub(crate) fn sign_tab_layout(field: Rect, label_width: f32) -> Option { - if !field.is_finite() || field.height() < SIGN_TAB_HEIGHT + 2.0 * SIGN_TAB_INSET { + if !field.is_finite() { return None; } - let room = field.width() / 2.0 - SIGN_TAB_INSET; - let full = SIGN_TAB_PAD + SIGN_TAB_ICON + SIGN_TAB_PAD + label_width + SIGN_TAB_PAD; - let with_label = label_width.is_finite() && label_width > 0.0 && full <= room; - let width = if with_label { full } else { SIGN_TAB_HEIGHT }; - if width > room { + // Finite, so the clamp has a number to work on (and its bounds are constants in order). + let h = (field.height() * SIGN_TAB_SHARE).clamp(SIGN_TAB_MIN, SIGN_TAB_MAX); + let scale = h / SIGN_TAB_MAX; + let (inset, icon_side, pad) = (3.0 * scale, 12.0 * scale, 5.0 * scale); + if field.height() < h + 2.0 * inset || h > field.width() / 2.0 { return None; } - let rect = Rect::from_min_size(field.min + vec2(SIGN_TAB_INSET, SIGN_TAB_INSET), vec2(width, SIGN_TAB_HEIGHT)); - let icon_x = if with_label { rect.left() + SIGN_TAB_PAD } else { rect.center().x - SIGN_TAB_ICON / 2.0 }; - let icon = Rect::from_min_size(pos2(icon_x, rect.center().y - SIGN_TAB_ICON / 2.0), Vec2::splat(SIGN_TAB_ICON)); - let label = with_label.then(|| pos2(icon.right() + SIGN_TAB_PAD, rect.center().y)); - Some(SignTab { rect, icon, label }) + let full = pad + icon_side + pad + label_width * scale + pad; + let with_label = h >= SIGN_TAB_LABEL_MIN && label_width.is_finite() && label_width > 0.0 && full <= field.width() / 2.0; + let width = if with_label { full } else { h }; + let rect = Rect::from_min_size(field.min + Vec2::splat(inset), vec2(width, h)); + let icon_x = if with_label { rect.left() + pad } else { rect.center().x - icon_side / 2.0 }; + let icon = Rect::from_min_size(pos2(icon_x, rect.center().y - icon_side / 2.0), Vec2::splat(icon_side)); + let label = with_label.then(|| pos2(icon.right() + pad, rect.center().y)); + Some(SignTab { rect, icon, label, font: SIGN_TAB_FONT * scale, radius: 4.0 * scale }) } /// Paints the sign tab of an empty signature field whose widget is at `field` on screen: an /// accent chip with the signature icon and "Sign" in white, as the app's primary buttons are. -/// Screen-only chrome, like the validation badges. +/// The label is measured at its largest size to lay the tab out and drawn at the tab's size; +/// text scales with its size, and the padding takes up any rounding. Screen-only chrome, like +/// the validation badges. fn paint_sign_tab(ui: &egui::Ui, painter: &egui::Painter, field: Rect, t: &Tokens) { - let galley = ui.fonts_mut(|f| f.layout_no_wrap(tl!("Sign").to_string(), theme::semibold(11.0), Color32::WHITE)); - let Some(tab) = sign_tab_layout(field, galley.size().x) else { return }; - painter.rect_filled(tab.rect, CornerRadius::same(4), t.accent); - icons::paint(ui, tab.icon, "signature", SIGN_TAB_ICON, Color32::WHITE); + let measure = |size: f32| ui.fonts_mut(|f| f.layout_no_wrap(tl!("Sign").to_string(), theme::semibold(size), Color32::WHITE)); + let Some(tab) = sign_tab_layout(field, measure(SIGN_TAB_FONT).size().x) else { return }; + painter.rect_filled(tab.rect, egui::epaint::CornerRadiusF32::same(tab.radius), t.accent); + icons::paint(ui, tab.icon, "signature", tab.icon.width(), Color32::WHITE); if let Some(at) = tab.label { + let galley = measure(tab.font); painter.galley(at - vec2(0.0, galley.size().y / 2.0), galley, Color32::WHITE); } } @@ -5544,42 +5559,82 @@ mod sign_tab_tests { assert_eq!(tabbed(&cases), Vec::<&str>::new()); } - /// A roomy field gets the whole tab inside its top-left corner: the icon, then the label, - /// on no more than half the field's width. - #[test] - fn sign_tab_layout_puts_icon_and_label_in_the_top_left_corner() { - let field = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 120.0)); - let tab = sign_tab_layout(field, 30.0).expect("fits"); - assert_eq!(tab.rect.min, field.min + vec2(SIGN_TAB_INSET, SIGN_TAB_INSET)); - assert_eq!(tab.rect.height(), SIGN_TAB_HEIGHT); - assert!(field.contains_rect(tab.rect) && tab.rect.width() <= field.width() / 2.0, "{tab:?}"); - assert!(tab.rect.contains_rect(tab.icon), "{tab:?}"); - let at = tab.label.expect("the label fits"); - assert!(at.x >= tab.icon.right() && at.x + 30.0 <= tab.rect.right(), "{tab:?}"); - assert_eq!(at.y, tab.rect.center().y); + /// Whether two layout sizes match, to a hundredth of a point. + fn near(a: f32, b: f32) -> bool { + (a - b).abs() < 0.01 } - /// A field with room for the icon but not the label gets the icon alone, and one too small - /// for even that, or with a rectangle that isn't finite, gets no tab. A label that can't be - /// measured is left out instead of drawn at a NaN position. + /// What a field `width` by `height` points on screen shows, for a label 30 pt wide on the + /// largest tab: "label" (the full tab), "icon" (the square chip) or "none". + fn shows(width: f32, height: f32) -> &'static str { + match sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(width, height)), 30.0) { + Some(tab) if tab.label.is_some() => "label", + Some(_) => "icon", + None => "none", + } + } + + /// The tab is 0.4 of the field's height on screen, at most 18 pt: a tall, wide field gets the + /// 18 pt tab with its label 3 pt inside the corner, and a 29 pt field (a 22 pt box at fit + /// width) an 11.6 pt icon chip, too small for the label, with the inset and icon scaled to it. #[test] - fn sign_tab_layout_drops_the_label_then_the_tab_on_small_fields() { - let narrow = Rect::from_min_size(Pos2::ZERO, vec2(60.0, 40.0)); - let icon_only = sign_tab_layout(narrow, 30.0).expect("the icon fits"); - assert_eq!(icon_only.label, None); - assert!(narrow.contains_rect(icon_only.rect) && icon_only.rect.contains_rect(icon_only.icon), "{icon_only:?}"); + fn sign_tab_layout_scales_the_chip_with_the_field_height() { + let large = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 60.0)); + let tab = sign_tab_layout(large, 30.0).expect("fits"); + assert!(near(tab.rect.height(), 18.0) && tab.rect.min == large.min + vec2(3.0, 3.0), "{tab:?}"); + assert!(near(tab.icon.width(), 12.0) && tab.rect.contains_rect(tab.icon), "{tab:?}"); + let at = tab.label.expect("the label fits"); + assert!(at.x >= tab.icon.right() && at.x + 30.0 <= tab.rect.right() && at.y == tab.rect.center().y, "{tab:?}"); + + let short = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 29.0)); + let tab = sign_tab_layout(short, 30.0).expect("fits"); + assert!(near(tab.rect.height(), 11.6) && near(tab.rect.width(), 11.6) && tab.label.is_none(), "{tab:?}"); + let inset = tab.rect.min - short.min; + assert!(near(inset.x, 11.6 / 6.0) && near(inset.y, 11.6 / 6.0) && short.contains_rect(tab.rect), "{tab:?}"); + assert!(near(tab.icon.width(), 11.6 * 2.0 / 3.0) && tab.rect.contains_rect(tab.icon), "{tab:?}"); + } + + /// A 19 pt field (a 14 pt box at fit width) still gets the smallest chip, 10 pt with the icon + /// alone. A 12 pt field is too short for even that, and a rectangle that isn't finite gets + /// nothing. A label that can't be measured is left out instead of drawn at a NaN position. + #[test] + fn sign_tab_layout_keeps_a_small_icon_on_short_fields_and_none_below() { + let field = Rect::from_min_size(pos2(100.0, 200.0), vec2(400.0, 19.0)); + let tab = sign_tab_layout(field, 30.0).expect("the smallest chip fits"); + assert!(near(tab.rect.height(), 10.0) && near(tab.rect.width(), 10.0) && tab.label.is_none(), "{tab:?}"); + assert!(field.contains_rect(tab.rect) && tab.rect.contains_rect(tab.icon), "{tab:?}"); let cases = [ - ("too short", Rect::from_min_size(Pos2::ZERO, vec2(400.0, 20.0))), - ("too narrow", Rect::from_min_size(Pos2::ZERO, vec2(30.0, 40.0))), + ("12 pt tall", Rect::from_min_size(Pos2::ZERO, vec2(400.0, 12.0))), ("infinite", Rect::from_min_max(Pos2::ZERO, pos2(f32::INFINITY, 40.0))), ("NaN", Rect::from_min_max(pos2(f32::NAN, 0.0), pos2(400.0, 40.0))), ]; let laid_out: Vec<&str> = cases.iter().filter(|(_, r)| sign_tab_layout(*r, 30.0).is_some()).map(|c| c.0).collect(); assert_eq!(laid_out, Vec::<&str>::new()); - let roomy = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 120.0)); + let roomy = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 60.0)); assert_eq!(sign_tab_layout(roomy, f32::NAN).map(|t| t.label), Some(None)); } + /// The label's font and the chip's corners shrink with the tab: 11 pt and 4 pt on the largest + /// tab, 8.8 pt and 3.2 pt on the 14.4 pt tab of a 36 pt field. + #[test] + fn sign_tab_layout_scales_the_label_font_and_corners_with_the_chip() { + let large = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 60.0)), 30.0).expect("fits"); + assert!(near(large.font, 11.0) && near(large.radius, 4.0), "{large:?}"); + let small = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 36.0)), 30.0).expect("fits"); + assert!(near(small.font, 8.8) && near(small.radius, 3.2) && small.label.is_some(), "{small:?}"); + } + + /// As a 36 pt field (a 14.4 pt tab, its label 24 pt wide at that size) narrows, the tab keeps + /// its label while the whole tab fits in half the width (91.2 pt), then shows the icon alone + /// while the chip does (28.8 pt), then nothing. + #[test] + fn sign_tab_layout_drops_the_label_then_the_tab_as_the_field_narrows() { + let widths = [400.0, 92.0, 90.0, 29.0, 28.0]; + assert_eq!(widths.map(|w| shows(w, 36.0)), ["label", "label", "icon", "icon", "none"]); + let tab = sign_tab_layout(Rect::from_min_size(Pos2::ZERO, vec2(92.0, 36.0)), 30.0).expect("fits"); + assert!(near(tab.rect.height(), 14.4) && tab.rect.width() <= 46.0, "{tab:?}"); + } + /// One page with three signature fields: Approver is empty, Witness is signed (a signature /// dictionary as its value is enough to list it as signed) and Locked is empty but read-only. const SIGN_FIELDS: &[u8] = b"%PDF-1.7 diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 64216ff736..1ae6b43191 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5985,7 +5985,7 @@ status = "shipped" commands = ["sign.digital"] tools = ["sign_document"] evidence = ["crates/sign/tests/pdf.rs::signing_an_existing_field_and_counter_signing", "crates/ui-egui/tests/signing.rs::clicking_an_empty_signature_field_signs_it", "crates/ui-egui/src/canvas.rs::empty_signature_fields_show_a_sign_tab_that_signs_them", "crates/ui-egui/src/canvas.rs::sign_tabs_skip_fields_that_a_click_cannot_sign"] -notes = "Clicking an empty signature field signs it (Use a certificate for that field). With the Select tool, each empty field a click would sign (filling allowed, the field not read-only, its widget shown) carries a small accent tab with the signature icon and Sign in its top-left corner. The tab is screen-only chrome, never written into the file, exports or printing; it drops its label, then itself, on a field too small at the current zoom, and is hidden while preparing a form. Missing: the tab is painted only, with no accessibility node or keyboard focus of its own" +notes = "Clicking an empty signature field signs it (Use a certificate for that field). With the Select tool, each empty field a click would sign (filling allowed, the field not read-only, its widget shown) carries a small accent tab in its top-left corner, sized to the field (0.4 of its height on screen, from 10 to 18 pt): the signature icon and Sign from 14 pt up, the icon alone below that or when the label would take more than half the field's width, and no tab on a field too small for the 10 pt chip. The tab is screen-only chrome, never written into the file, exports or printing, and is hidden while preparing a form. Missing: the tab is painted only, with no accessibility node or keyboard focus of its own" [[feature]] id = "sign.invisible-signature" From 0b253d72c1fad6fde254deedbe97efe42054b83b Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:15:35 +0200 Subject: [PATCH 011/359] Allow Ctrl+wheel zoom in an unfocused window (#3736) --- crates/ui-egui/src/canvas.rs | 39 ++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index eb9244a284..ee40339df3 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2468,8 +2468,10 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { let zoom_delta = crate::motion::zoom_delta(ui.ctx()); // Exclude the previous frame's scrollbar tracks from gesture activation. let navigation_rect = if view.viewport_screen.is_positive() { avail.intersect(view.viewport_screen) } else { avail }; - let navigation_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled() && ui.input(|i| i.focused); - if zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0 && navigation_enabled && ui.rect_contains_pointer(navigation_rect) { + // Wheel zoom works in a visible window without focus, as wheel scrolling does; the other gestures need focus. + let zoom_enabled = app.dialog.is_none() && app.close_request.is_none() && !app.palette_open && ui.is_enabled(); + let navigation_enabled = zoom_enabled && ui.input(|i| i.focused); + if zoom_delta.is_finite() && zoom_delta > 0.0 && zoom_delta != 1.0 && zoom_enabled && ui.rect_contains_pointer(navigation_rect) { let z = view.zoom * zoom_delta; match ui.input(|i| i.pointer.hover_pos()) { Some(p) => view.zoom_at(z, p), @@ -6204,6 +6206,39 @@ trailer << /Root 1 0 R >> assert_eq!(app.views[0].edit_lines.get(&0).map(|(g, _)| *g), Some(generation), "the boxes follow the edit while input is blocked"); } + /// Ctrl+wheel zooms a visible window that another application has focus over, as plain + /// wheel scrolling does; the palette still blocks it. + #[test] + fn ctrl_wheel_zooms_an_unfocused_window() { + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + let bytes = app.session.create_blank(300.0, 400.0, 1).unwrap(); + app.open_bytes("blank.pdf", None, bytes.as_ref().clone()).unwrap(); + app + }); + h.run_steps(3); + let center = h.state().views[0].viewport_rect().center(); + h.hover_at(center); + h.input_mut().focused = false; + h.run_steps(2); + let ctrl_wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::COMMAND, + }; + h.state_mut().palette_open = true; + let before = h.state().views[0].zoom; + h.event(ctrl_wheel.clone()); + h.run_steps(10); + assert_eq!(h.state().views[0].zoom, before, "the palette still blocks zoom"); + h.state_mut().palette_open = false; + h.run_steps(2); + h.event(ctrl_wheel); + h.run_steps(10); + assert!(h.state().views[0].zoom > before, "Ctrl+wheel zooms without window focus"); + } + #[test] fn virtualized_organizer_keeps_insert_gaps_at_document_positions() { use egui_kittest::kittest::Queryable; From 515ba9677f87d1c10cc6148fdb8f1716156c47fb Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:58:00 -0400 Subject: [PATCH 012/359] M9: a click on a sign tab signs its field where another field overlaps it --- crates/ui-egui/src/canvas.rs | 157 ++++++++++++++++++++++++--------- crates/ui-egui/src/forms_ui.rs | 26 ++++-- 2 files changed, 132 insertions(+), 51 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index cbea2fe56a..ad514f4cc9 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -343,17 +343,17 @@ pub(crate) fn signature_badges(signatures: &[pdfcraft_engine::SignatureInfo], pa .collect() } -/// The empty signature fields on one page that get a sign tab, as their widget rectangles -/// (user space). Each is unsigned and visible, on this page, with a rectangle that passes the -/// same screen-space guard as [`signature_badges`]. A click must also be able to sign it, as -/// in `forms_ui::page_input`: the document allows filling (`can_fill`), and the form field of -/// that name is a signature field that isn't read-only, with a shown widget at that place. -pub(crate) fn sign_tabs( - signatures: &[pdfcraft_engine::SignatureInfo], +/// The empty signature fields on one page that get a sign tab, as their names and widget +/// rectangles (user space). Each is unsigned and visible, on this page, with a rectangle that +/// passes the same screen-space guard as [`signature_badges`]. A click must also be able to sign +/// it, as in `forms_ui::page_input`: the document allows filling (`can_fill`), and the form field +/// of that name is a signature field that isn't read-only, with a shown widget at that place. +pub(crate) fn sign_tabs<'a>( + signatures: &'a [pdfcraft_engine::SignatureInfo], form: &[pdfcraft_engine::FormField], page: usize, can_fill: bool, -) -> Vec<[f64; 4]> { +) -> Vec<(&'a str, [f64; 4])> { let mut empty = signatures .iter() .filter(|s| can_fill && !s.signed && s.visible && s.page == Some(page)) @@ -369,7 +369,7 @@ pub(crate) fn sign_tabs( .filter(|f| f.kind == pdfcraft_engine::FormFieldKind::Signature && !f.read_only()) .flat_map(|f| f.widgets.iter().filter(|w| w.page == Some(page) && !w.hidden).map(move |w| (f.name.as_str(), w.rect.map(f64::to_bits)))) .collect(); - empty.filter(|(name, r)| signable.contains(&(*name, r.map(f64::to_bits)))).map(|(_, r)| r).collect() + empty.filter(|(name, r)| signable.contains(&(*name, r.map(f64::to_bits)))).collect() } /// The largest sign tab's height, in points. Every other size is a share of the tab's height, @@ -423,18 +423,26 @@ pub(crate) fn sign_tab_layout(field: Rect, label_width: f32) -> Option Some(SignTab { rect, icon, label, font: SIGN_TAB_FONT * scale, radius: 4.0 * scale }) } -/// Paints the sign tab of an empty signature field whose widget is at `field` on screen: an -/// accent chip with the signature icon and "Sign" in white, as the app's primary buttons are. -/// The label is measured at its largest size to lay the tab out and drawn at the tab's size; -/// text scales with its size, and the padding takes up any rounding. Screen-only chrome, like -/// the validation badges. -fn paint_sign_tab(ui: &egui::Ui, painter: &egui::Painter, field: Rect, t: &Tokens) { - let measure = |size: f32| ui.fonts_mut(|f| f.layout_no_wrap(tl!("Sign").to_string(), theme::semibold(size), Color32::WHITE)); - let Some(tab) = sign_tab_layout(field, measure(SIGN_TAB_FONT).size().x) else { return }; +/// The sign tab's label, "Sign", laid out at `size` points. +fn sign_tab_label(ui: &egui::Ui, size: f32) -> std::sync::Arc { + ui.fonts_mut(|f| f.layout_no_wrap(tl!("Sign").to_string(), theme::semibold(size), Color32::WHITE)) +} + +/// The sign tab of an empty signature field whose widget is at `field` on screen, laid out for +/// its label measured at its largest size: where it is painted and where a click on it signs. +fn sign_tab_at(ui: &egui::Ui, field: Rect) -> Option { + sign_tab_layout(field, sign_tab_label(ui, SIGN_TAB_FONT).size().x) +} + +/// Paints a sign tab laid out by [`sign_tab_at`]: an accent chip with the signature icon and +/// "Sign" in white, as the app's primary buttons are. The label is drawn at the tab's size; text +/// scales with its size, and the padding takes up any rounding. Screen-only chrome, like the +/// validation badges. +fn paint_sign_tab(ui: &egui::Ui, painter: &egui::Painter, tab: &SignTab, t: &Tokens) { painter.rect_filled(tab.rect, egui::epaint::CornerRadiusF32::same(tab.radius), t.accent); icons::paint(ui, tab.icon, "signature", tab.icon.width(), Color32::WHITE); if let Some(at) = tab.label { - let galley = measure(tab.font); + let galley = sign_tab_label(ui, tab.font); painter.galley(at - vec2(0.0, galley.size().y / 2.0), galley, Color32::WHITE); } } @@ -3247,6 +3255,19 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { view.current = i; open_boxes = true; } + // An empty field a click would sign carries a small tab saying so, shown only while + // a click on the field signs it (the Select tool, not while preparing a form). The tab + // is drawn over every field, so a click on it signs its field (`forms_ui::page_input`). + let tabs: Vec<(&str, SignTab)> = if tool == QuickTool::Select && !preparing { + sign_tabs(&doc.signatures, &form, i, can_fill) + .into_iter() + .filter_map(|(name, [x0, y0, x1, y1])| { + sign_tab_at(ui, xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32])).map(|tab| (name, tab)) + }) + .collect() + } else { + Vec::new() + }; // `over_field`: a form field is under the pointer and has set its cursor. let (on_field, over_field) = if preparing { let field_tool = match tool { @@ -3266,7 +3287,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { && !(editing_content && can_modify && crate::content_ui::select_grabs(ui, &xf, i, info, &added, view)) && !comments::select_grabs(ui, &pcx, view) { - crate::forms_ui::page_input(ui, &resp, &xf, i, info, &form, can_fill, view) + crate::forms_ui::page_input(ui, &resp, &xf, i, info, &form, &tabs, can_fill, view) } else { FieldPointer::Away }; @@ -3674,13 +3695,10 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { view.flash = None; } } - // An empty field a click would sign carries a small tab saying so, shown only while - // a click on the field signs it (the Select tool, not while preparing a form). Like - // the validation badges, it never enters the file, exports or printing. - if tool == QuickTool::Select && !preparing { - for [x0, y0, x1, y1] in sign_tabs(&doc.signatures, &form, i, can_fill) { - paint_sign_tab(ui, painter, xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]), &t); - } + // The sign tabs (above). Like the validation badges, they never enter the file, + // exports or printing. + for (_, tab) in &tabs { + paint_sign_tab(ui, painter, tab, &t); } // Validation is viewer chrome over the signer's original artwork, which // may still say "Signature Not Verified". These badges never enter document @@ -5540,10 +5558,10 @@ mod sign_tab_tests { /// own page only. #[test] fn sign_tabs_mark_an_empty_field_that_a_click_signs() { - let tabs = sign_tabs(&[listing("Approver", 0, RECT)], &[field("Approver", 0, RECT)], 0, true); - assert_eq!(tabs, vec![RECT]); + let approver = [listing("Approver", 0, RECT)]; + assert_eq!(sign_tabs(&approver, &[field("Approver", 0, RECT)], 0, true), vec![("Approver", RECT)]); let later = [listing("Witness", 1, RECT)]; - assert_eq!(sign_tabs(&later, &[field("Witness", 1, RECT)], 1, true), vec![RECT]); + assert_eq!(sign_tabs(&later, &[field("Witness", 1, RECT)], 1, true), vec![("Witness", RECT)]); assert!(sign_tabs(&later, &[field("Witness", 1, RECT)], 0, true).is_empty(), "not on the page before"); } @@ -5708,29 +5726,58 @@ trailer << /Root 1 0 R >> crate::forms_ui::field_screen_rect(view, &doc.info, f, 0).expect("on screen") } - /// In the real shell, an empty signature field shows its accent tab with "Sign" in its - /// top-left corner, and the signed and read-only fields show none. The tab is part of the - /// field: hovering it shows the pointing hand, and clicking it starts signing that field. - #[test] - fn empty_signature_fields_show_a_sign_tab_that_signs_them() { - let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(|_cc| { + /// One page where the text field Name, first in the form's order, covers the top-left corner + /// of the empty signature field Approver, where its sign tab is drawn. + const SIGN_UNDER_TEXT: &[u8] = b"%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R] >> >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Annots [4 0 R 5 0 R] >> endobj +4 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /T (Name) /Rect [10 120 130 190] /P 3 0 R /F 4 >> endobj +5 0 obj << /Type /Annot /Subtype /Widget /FT /Sig /T (Approver) /Rect [20 110 140 180] /P 3 0 R /F 4 >> endobj +trailer << /Root 1 0 R >> +%%EOF"; + + /// The real shell with `bytes` open, the side panes closed, after the first frames. + fn shell(bytes: &'static [u8]) -> egui_kittest::Harness<'static, PdfCraftApp> { + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_eframe(move |_cc| { let mut app = PdfCraftApp::new(); app.set_option("language", "en").unwrap(); - app.open_bytes("sign-fields.pdf", None, SIGN_FIELDS.to_vec()).unwrap(); + app.open_bytes("sign-fields.pdf", None, bytes.to_vec()).unwrap(); app.set_option("left", "closed").unwrap(); app.set_option("panel", "none").unwrap(); app }); h.run_steps(6); + h + } + + /// The accent chips painted in the last frame: the sign tabs. + fn chips(h: &egui_kittest::Harness<'static, PdfCraftApp>) -> Vec { let accent = Tokens::get(&h.ctx).accent; - let shapes = painted(&h); - let chips: Vec = shapes + painted(h) .iter() .filter_map(|s| match s { egui::Shape::Rect(r) if r.fill == accent => Some(r.rect), _ => None, }) - .collect(); + .collect() + } + + /// Clicks at `at` and lets the shell answer. + fn click_at(h: &mut egui_kittest::Harness<'static, PdfCraftApp>, at: Pos2) { + h.drag_at(at); + h.run_steps(1); + h.drop_at(at); + h.run_steps(3); + } + + /// In the real shell, an empty signature field shows its accent tab with "Sign" in its + /// top-left corner, and the signed and read-only fields show none. The tab is part of the + /// field: hovering it shows the pointing hand, and clicking it starts signing that field. + #[test] + fn empty_signature_fields_show_a_sign_tab_that_signs_them() { + let mut h = shell(SIGN_FIELDS); + let (shapes, chips) = (painted(&h), chips(&h)); let (approver, witness, locked) = (field_on_screen(&h, "Approver"), field_on_screen(&h, "Witness"), field_on_screen(&h, "Locked")); let tab = chips.iter().copied().find(|c| approver.contains_rect(*c)).unwrap_or_else(|| panic!("no tab in {approver:?}: {chips:?}")); assert!(tab.min.x - approver.min.x < 8.0 && tab.min.y - approver.min.y < 8.0, "in the top-left corner: {tab:?} in {approver:?}"); @@ -5742,13 +5789,37 @@ trailer << /Root 1 0 R >> h.hover_at(tab.center()); h.run_steps(1); assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand); - h.drag_at(tab.center()); - h.run_steps(1); - h.drop_at(tab.center()); - h.run_steps(3); + click_at(&mut h, tab.center()); assert_eq!(h.state().dialog, Some(crate::Dialog::Sign)); assert_eq!(h.state().sign_draft.as_ref().and_then(|d| d.field.clone()).as_deref(), Some("Approver")); } + + /// A sign tab is drawn over every field, so a click on it signs its field even where a field + /// earlier in the form's order overlaps it, which would otherwise take the click. Beside the + /// tab, the overlapping field still takes clicks as before. + #[test] + fn a_sign_tab_signs_its_field_where_an_earlier_field_overlaps_it() { + let mut h = shell(SIGN_UNDER_TEXT); + let (name, approver) = (field_on_screen(&h, "Name"), field_on_screen(&h, "Approver")); + let tab = chips(&h).into_iter().find(|c| approver.contains_rect(*c)).expect("Approver has a tab"); + assert!(name.contains_rect(tab), "the text field covers the tab: {tab:?} in {name:?}"); + + h.hover_at(tab.center()); + h.run_steps(1); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::PointingHand); + click_at(&mut h, tab.center()); + assert_eq!(h.state().dialog, Some(crate::Dialog::Sign)); + assert_eq!(h.state().sign_draft.as_ref().and_then(|d| d.field.clone()).as_deref(), Some("Approver")); + assert!(h.state().views[0].forms.focus.is_none(), "the text field didn't open"); + + let beside = pos2(tab.right() + 6.0, tab.center().y); + assert!(name.contains(beside) && approver.contains(beside), "beside the tab, both fields are under the pointer"); + h.state_mut().dialog = None; + h.state_mut().sign_draft = None; + h.run_steps(1); + click_at(&mut h, beside); + assert_eq!(h.state().views[0].forms.focus.as_ref().map(|f| f.name.as_str()), Some("Name"), "the earlier field takes the click"); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index 27c97a240e..d5aab8dc38 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -12,7 +12,7 @@ use egui::{Color32, CornerRadius, Rect, Stroke, vec2}; use pdfcraft_engine::{Edit, FieldValue, FormField, FormFieldKind, FormWidget, field_flags, form_appearance}; use pdfcraft_render::DocInfo; -use crate::canvas::{DocView, PageXform}; +use crate::canvas::{DocView, PageXform, SignTab}; use crate::theme::Tokens; const FOCUS_BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6); @@ -110,7 +110,18 @@ pub(crate) enum FieldPointer { Owned, } -/// Clicks on form widgets of one page. +/// The first shown widget of `f` on `page` under the pointer at `p`, with its index. +fn widget_at<'a>(xf: &PageXform, info: &DocInfo, page: usize, f: &'a FormField, p: egui::Pos2) -> Option<(&'a FormField, usize, &'a FormWidget)> { + 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)) +} + +/// Clicks on form widgets of one page. The pointer is on the first widget under it in the form's +/// order, except on a sign tab (`tabs`, with the signature field each one signs), which is drawn +/// over every field and so is on its own field. #[allow(clippy::too_many_arguments)] pub(crate) fn page_input( ui: &egui::Ui, @@ -119,18 +130,17 @@ pub(crate) fn page_input( page: usize, info: &DocInfo, form: &[FormField], + tabs: &[(&str, SignTab)], allowed: bool, view: &mut DocView, ) -> FieldPointer { let pointer = ui.input(|i| i.pointer.hover_pos()); let Some(p) = pointer.filter(|p| xf.rect.contains(*p)) else { return FieldPointer::Away }; - let hit = form.iter().find_map(|f| { - 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)) + // A tab lies inside its field's widget, so that widget is under the pointer too. + let on_tab = tabs.iter().find(|(_, tab)| tab.rect.contains(p)).and_then(|(name, _)| { + form.iter().filter(|f| f.name == *name && f.kind == FormFieldKind::Signature).find_map(|f| widget_at(xf, info, page, f, p)) }); + let hit = on_tab.or_else(|| form.iter().find_map(|f| widget_at(xf, info, page, f, p))); let Some((f, wi, w)) = hit else { return FieldPointer::Away }; // Empty signature fields are signed by clicking them (Use a certificate); push buttons run // their action. From 2f7f99d21a1c2137bc18928a9bccbfa71b1b767e Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:11:27 -0400 Subject: [PATCH 013/359] M9: a sign tab stays on the page, and the one painted last takes the click --- crates/ui-egui/src/canvas.rs | 45 ++++++++++++++++++++++++++++++---- crates/ui-egui/src/forms_ui.rs | 11 ++++++--- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ad514f4cc9..493533b581 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -428,10 +428,18 @@ fn sign_tab_label(ui: &egui::Ui, size: f32) -> std::sync::Arc { ui.fonts_mut(|f| f.layout_no_wrap(tl!("Sign").to_string(), theme::semibold(size), Color32::WHITE)) } -/// The sign tab of an empty signature field whose widget is at `field` on screen, laid out for -/// its label measured at its largest size: where it is painted and where a click on it signs. -fn sign_tab_at(ui: &egui::Ui, field: Rect) -> Option { - sign_tab_layout(field, sign_tab_label(ui, SIGN_TAB_FONT).size().x) +/// The sign tab of an empty signature field whose widget is at `field` on screen, on the page at +/// `page`, laid out for its label measured at its largest size: where it is painted and where a +/// click on it signs. +fn sign_tab_at(ui: &egui::Ui, field: Rect, page: Rect) -> Option { + sign_tab_on_page(field, page, sign_tab_label(ui, SIGN_TAB_FONT).size().x) +} + +/// [`sign_tab_layout`] in the part of `field` that is on `page`: form fields take clicks on the +/// page only, so a widget that straddles the page's edge gets its tab where a click reaches it, +/// or none when that part has no room for one. +pub(crate) fn sign_tab_on_page(field: Rect, page: Rect, label_width: f32) -> Option { + sign_tab_layout(field.intersect(page), label_width) } /// Paints a sign tab laid out by [`sign_tab_at`]: an accent chip with the signature icon and @@ -3262,7 +3270,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { sign_tabs(&doc.signatures, &form, i, can_fill) .into_iter() .filter_map(|(name, [x0, y0, x1, y1])| { - sign_tab_at(ui, xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32])).map(|tab| (name, tab)) + sign_tab_at(ui, xf.user_rect(info, i, [x0 as f32, y0 as f32, x1 as f32, y1 as f32]), xf.rect).map(|tab| (name, tab)) }) .collect() } else { @@ -5692,6 +5700,33 @@ mod sign_tab_tests { assert!(near(tab.rect.height(), 14.4) && tab.rect.width() <= 46.0, "{tab:?}"); } + /// A field that straddles the page's edge gets its tab in the part on the page, where clicks + /// reach it, or none when that part has no room for one. + #[test] + fn a_sign_tab_stays_on_the_page() { + let page = Rect::from_min_size(pos2(100.0, 50.0), vec2(600.0, 800.0)); + let straddling = Rect::from_min_size(pos2(60.0, 20.0), vec2(300.0, 90.0)); + let tab = sign_tab_on_page(straddling, page, 30.0).expect("the part on the page has room"); + assert!(page.contains_rect(tab.rect), "{tab:?} on {page:?}"); + assert_eq!(tab.rect.height(), SIGN_TAB_MAX, "sized to the 60 px on the page"); + let sliver = Rect::from_min_size(pos2(60.0, 20.0), vec2(300.0, 36.0)); + assert_eq!(sign_tab_on_page(sliver, page, 30.0), None, "6 px on the page"); + let off = Rect::from_min_size(pos2(60.0, 900.0), vec2(300.0, 90.0)); + assert_eq!(sign_tab_on_page(off, page, 30.0), None, "wholly off the page"); + } + + /// Where two sign tabs overlap, a click takes the one painted last, which is on top. + #[test] + fn the_sign_tab_painted_last_takes_the_click() { + let tab = |x: f32| sign_tab_layout(Rect::from_min_size(pos2(x, 0.0), vec2(300.0, 60.0)), 30.0).expect("fits"); + let tabs = [("Approver", tab(0.0)), ("Witness", tab(10.0))]; + let both = tabs[1].1.rect.left_center() + vec2(2.0, 0.0); + assert!(tabs[0].1.rect.contains(both), "the tabs overlap there"); + assert_eq!(crate::forms_ui::tab_under(&tabs, both), Some("Witness")); + assert_eq!(crate::forms_ui::tab_under(&tabs, tabs[0].1.rect.left_center() + vec2(2.0, 0.0)), Some("Approver")); + assert_eq!(crate::forms_ui::tab_under(&tabs, pos2(-5.0, -5.0)), None); + } + /// One page with three signature fields: Approver is empty, Witness is signed (a signature /// dictionary as its value is enough to list it as signed) and Locked is empty but read-only. const SIGN_FIELDS: &[u8] = b"%PDF-1.7 diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index d5aab8dc38..13cd15506d 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -119,6 +119,12 @@ fn widget_at<'a>(xf: &PageXform, info: &DocInfo, page: usize, f: &'a FormField, .map(|(i, w)| (f, i, w)) } +/// The field whose sign tab is under `p`, of `tabs` in the order they are painted: where tabs +/// overlap, the one painted last is on top. +pub(crate) fn tab_under<'a>(tabs: &[(&'a str, SignTab)], p: egui::Pos2) -> Option<&'a str> { + tabs.iter().rev().find(|(_, tab)| tab.rect.contains(p)).map(|(name, _)| *name) +} + /// Clicks on form widgets of one page. The pointer is on the first widget under it in the form's /// order, except on a sign tab (`tabs`, with the signature field each one signs), which is drawn /// over every field and so is on its own field. @@ -137,9 +143,8 @@ 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 FieldPointer::Away }; // A tab lies inside its field's widget, so that widget is under the pointer too. - let on_tab = tabs.iter().find(|(_, tab)| tab.rect.contains(p)).and_then(|(name, _)| { - form.iter().filter(|f| f.name == *name && f.kind == FormFieldKind::Signature).find_map(|f| widget_at(xf, info, page, f, p)) - }); + let on_tab = tab_under(tabs, p) + .and_then(|name| form.iter().filter(|f| f.name == name && f.kind == FormFieldKind::Signature).find_map(|f| widget_at(xf, info, page, f, p))); let hit = on_tab.or_else(|| form.iter().find_map(|f| widget_at(xf, info, page, f, p))); let Some((f, wi, w)) = hit else { return FieldPointer::Away }; // Empty signature fields are signed by clicking them (Use a certificate); push buttons run From 596b28a19d4ded74e223a79be8fdedb7b3a41cd2 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:16:26 -0400 Subject: [PATCH 014/359] M9: no sign tab on a widget that is read-only on its own --- crates/ui-egui/src/canvas.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 344f286665..5567b387d8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -362,7 +362,8 @@ pub(crate) fn signature_badges(signatures: &[pdfcraft_engine::SignatureInfo], pa /// rectangles (user space). Each is unsigned and visible, on this page, with a rectangle that /// passes the same screen-space guard as [`signature_badges`]. A click must also be able to sign /// it, as in `forms_ui::page_input`: the document allows filling (`can_fill`), and the form field -/// of that name is a signature field that isn't read-only, with a shown widget at that place. +/// of that name is a signature field that isn't read-only, with a shown widget at that place +/// that isn't read-only on its own. pub(crate) fn sign_tabs<'a>( signatures: &'a [pdfcraft_engine::SignatureInfo], form: &[pdfcraft_engine::FormField], @@ -382,7 +383,9 @@ pub(crate) fn sign_tabs<'a>( let signable: HashSet<(&str, [u64; 4])> = form .iter() .filter(|f| f.kind == pdfcraft_engine::FormFieldKind::Signature && !f.read_only()) - .flat_map(|f| f.widgets.iter().filter(|w| w.page == Some(page) && !w.hidden).map(move |w| (f.name.as_str(), w.rect.map(f64::to_bits)))) + .flat_map(|f| { + f.widgets.iter().filter(|w| w.page == Some(page) && !w.hidden && !w.read_only).map(move |w| (f.name.as_str(), w.rect.map(f64::to_bits))) + }) .collect(); empty.filter(|(name, r)| signable.contains(&(*name, r.map(f64::to_bits)))).collect() } @@ -5860,6 +5863,7 @@ mod sign_tab_tests { tab: 0, locked: false, hidden: false, + read_only: false, rotation: 0, caption: None, list: None, @@ -5916,7 +5920,7 @@ mod sign_tab_tests { /// Fields a click would not sign get no tab: a read-only field, a document that refuses /// filling, a listing with no form field of its name, a field of another kind of that name, - /// and a widget that is hidden or elsewhere. + /// and a widget that is hidden, read-only on its own or elsewhere. #[test] fn sign_tabs_skip_fields_that_a_click_cannot_sign() { let empty = || listing("Approver", 0, RECT); @@ -5931,6 +5935,7 @@ mod sign_tab_tests { ("no form field", empty(), Vec::new(), true), ("another kind", empty(), with(|f| f.kind = FormFieldKind::Text), true), ("hidden widget", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.hidden = true)), true), + ("read-only widget", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.read_only = true)), true), ("widget elsewhere", empty(), with(|f| f.widgets.iter_mut().for_each(|w| w.rect = [160.0, 110.0, 280.0, 180.0])), true), ]; assert_eq!(tabbed(&cases), Vec::<&str>::new()); From f266edb8262d35aabc9fb4936607e6f772a159f4 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:53:08 -0400 Subject: [PATCH 015/359] M6: page keys still work with a check box or radio button focused, as main's form focus allows --- crates/ui-egui/src/canvas.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 742dcf5922..4d534380a5 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2530,8 +2530,9 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_s } } // An open form field takes the arrows, Page Up / Page Down, Home and End (a drop-down's or a - // list box's items), so the page under it stays put. - if view.forms.focus.is_some() { + // list box's items), so the page under it stays put. A focused check box or radio button + // uses none of them, so the page keys still work there. + if view.forms.focus.is_some() && form_box.is_none() { return; } if key(Key::Home) { From db7b36f8c7e661584f4bab2b5b6b6d9201e88ac3 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Thu, 22 Oct 2026 08:33:35 -0400 Subject: [PATCH 016/359] M6: an auto-sized drop-down's list draws its items at the field's text size --- crates/ui-egui/src/forms_ui.rs | 5 ++- crates/ui-egui/tests/forms.rs | 67 ++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index 1d523fef94..cc5e56886d 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -849,7 +849,10 @@ fn choice_list( let n = f.options.len(); let shown = n.min(LIST_ROWS); let max_first = n.saturating_sub(shown); - let size = (field_text_size(&ctx.layer_painter(egui::LayerId::background()), f, w, "") * zoom).clamp(6.0, 48.0); + // Auto-sized text is fitted to what the field shows (its chosen item's shown name), so the + // list's items come out at the size the field's value is drawn at. + let value_text = f.value.first().map_or("", |v| f.options.iter().find(|(e, _)| e == v).map_or(v.as_str(), |(_, d)| d.as_str())); + let size = (field_text_size(&ctx.layer_painter(egui::LayerId::background()), f, w, value_text) * zoom).clamp(6.0, 48.0); let row = (size * 1.45).round().max(8.0); let bar = if n > shown { (row * 0.7).round().clamp(12.0, 22.0) } else { 0.0 }; let width = rect.width().max(24.0 + bar); diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rs index 6d0cbd0927..2a5cf8c24b 100644 --- a/crates/ui-egui/tests/forms.rs +++ b/crates/ui-egui/tests/forms.rs @@ -1525,6 +1525,73 @@ fn the_mouse_wheel_scrolls_a_long_drop_down_list_and_not_the_page() { assert_eq!(h.state().views[0].page_screen_rect(0), page, "the page stayed where it was"); } +/// An auto-sized drop-down's list draws its items at the size the field shows its value at, so a +/// long chosen item fits the list as it fits the field instead of growing past it. +#[test] +fn an_auto_sized_drop_downs_list_shows_its_items_at_the_fields_text_size() { + let mut h = harness(); + let long = "The Commonwealth of the Northern Mariana Islands"; + assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldProps { + name: "country".into(), + props: Box::new(pdfcraft_engine::FieldProps { options: Some(vec!["Canada".into(), long.into()]), ..Default::default() }), + })); + assert!( + h.state_mut().apply_edit(pdfcraft_engine::Edit::SetFieldValue { + name: "country".into(), + value: pdfcraft_engine::FieldValue::Choice(vec![long.into()]) + }) + ); + h.run_steps(3); + click_field(&mut h, "country", 0); + let field = field_rect(&h, "country"); + let item = text_rect(&h, long).expect("the long item in the open list"); + assert!(item.width() <= field.width(), "the item fits as the field's value does: {} wide in a {} field", item.width(), field.width()); +} + +/// In single-page view, where the wheel turns pages, the wheel over an open drop-down's list +/// scrolls the list and leaves the page as it is; over the page itself it still turns it. +#[test] +fn in_single_page_view_the_wheel_over_an_open_list_scrolls_the_list_not_the_page() { + let mut h = harness(); + long_country(&mut h); + assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::InsertBlankPage { at: 1, width: 300.0, height: 400.0 })); + h.state_mut().set_option("continuous", "off").unwrap(); + h.key_press(egui::Key::Home); + for _ in 0..60 { + h.run_steps(2); + if !h.state().render_pending() && h.state().views[0].page_screen_rect(0).is_some() { + break; + } + } + let wheel = |h: &mut Harness<'static, PdfCraftApp>, at: egui::Pos2| { + h.hover_at(at); + h.run_steps(1); + for _ in 0..3 { + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: egui::vec2(0.0, -1.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }); + h.run_steps(2); + } + h.run_steps(6); + }; + // The control: over the page, the wheel turns it. + let page = h.state().views[0].page_screen_rect(0).expect("page 1 on screen"); + wheel(&mut h, page.center()); + assert_eq!(h.state().views[0].current, 1, "over the page, the wheel turns it"); + h.key_press(egui::Key::Home); + h.run_steps(6); + assert_eq!(h.state().views[0].current, 0); + // Over the open list, it scrolls the list instead. + click_field(&mut h, "country", 0); + let first = egui_kittest::kittest::Queryable::get_by_label(&h, "0000").rect(); + wheel(&mut h, first.center() + egui::vec2(0.0, first.height() * 4.0)); + assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_none(), "the list scrolled down"); + assert_eq!(h.state().views[0].current, 0, "the page didn't turn"); +} + /// With a page taller than the window and the pointer resting on an open drop-down's list, /// Home and the down arrow move through the list and leave the page where it was. #[test] From 5d2b0bc06387b4793e88bbcc9445f5b419be1498 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Thu, 22 Oct 2026 09:22:21 -0400 Subject: [PATCH 017/359] M6: Escape in an open drop-down closes only its list, and a note on the list's fixed colors --- crates/ui-egui/src/canvas.rs | 13 ++++++++----- crates/ui-egui/src/forms_ui.rs | 2 ++ crates/ui-egui/tests/forms.rs | 18 ++++++++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4d534380a5..3c485620df 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2519,8 +2519,13 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_s view.view_history(true); } let key = |k| (arrows || !matches!(k, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown)) && ctx.input(|i| i.key_pressed(k)); + // An open form field (a drop-down's or a list box's items) takes the arrows, Page Up / Page + // Down, Home, End and Escape. A focused check box or radio button uses none of them, so the + // page keys still work there. + let field_open = view.forms.focus.is_some() && form_box.is_none(); // An open menu takes Escape first and closes; the selection stays for the next one (#3535). - if key(Key::Escape) && !egui::Popup::is_any_open(ctx) { + // So does an open field, whose list closes. + if key(Key::Escape) && !egui::Popup::is_any_open(ctx) && !field_open { if view.camera.is_some() || view.camera_done.is_some() { view.pending_action = Some(ViewAction::CancelCamera); } else if view.selection.is_some() { @@ -2529,10 +2534,8 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context, speed: crate::scroll_s view.find = None; } } - // An open form field takes the arrows, Page Up / Page Down, Home and End (a drop-down's or a - // list box's items), so the page under it stays put. A focused check box or radio button - // uses none of them, so the page keys still work there. - if view.forms.focus.is_some() && form_box.is_none() { + // The open field's keys leave the page under it where it is. + if field_open { return; } if key(Key::Home) { diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index cc5e56886d..8dda436955 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -899,6 +899,8 @@ fn choice_list( let resp = egui::Area::new(egui::Id::new(("form-choices", view))).order(egui::Order::Foreground).fixed_pos(rect.left_bottom()).show(ctx, |ui| { let (outer, area) = ui.allocate_exact_size(vec2(width, shown as f32 * row + 2.0), egui::Sense::hover()); let p = ui.painter(); + // The list is drawn as the form's own, a white list in the field's font with a blue + // highlight, in light and dark themes alike, so its colors are fixed, not the app's tokens. p.rect_filled(outer, CornerRadius::ZERO, Color32::WHITE); // The wheel scrolls the list, a row at a time, and not the page under it. if area.contains_pointer() && n > shown { diff --git a/crates/ui-egui/tests/forms.rs b/crates/ui-egui/tests/forms.rs index 2a5cf8c24b..3871c46e05 100644 --- a/crates/ui-egui/tests/forms.rs +++ b/crates/ui-egui/tests/forms.rs @@ -1525,6 +1525,24 @@ fn the_mouse_wheel_scrolls_a_long_drop_down_list_and_not_the_page() { assert_eq!(h.state().views[0].page_screen_rect(0), page, "the page stayed where it was"); } +/// Escape in an open drop-down closes its list and nothing else: the find bar, which Escape +/// closes when no field is open, stays open. +#[test] +fn escape_closes_an_open_drop_downs_list_and_leaves_the_page_alone() { + let mut h = harness(); + long_country(&mut h); + h.state_mut().views[0].open_find(); + h.run_steps(3); + assert!(h.state().views[0].find.is_some()); + click_field(&mut h, "country", 0); + assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_some(), "the list is open"); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(egui_kittest::kittest::Queryable::query_by_label(&h, "0000").is_none(), "Escape closed the list"); + assert!(h.state().views[0].forms.focus.is_none(), "and the field"); + assert!(h.state().views[0].find.is_some(), "the find bar stays open"); +} + /// An auto-sized drop-down's list draws its items at the size the field shows its value at, so a /// long chosen item fits the list as it fits the field instead of growing past it. #[test] From 166727d9f22f46c8e97b1a8cb87ac7acc8fd5bf5 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Thu, 22 Oct 2026 09:23:06 -0400 Subject: [PATCH 018/359] M9: the parity note says how to list the fields a sign tab marks headlessly --- parity/acrobat-features.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index cf784aac57..9b32d011c9 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -6014,7 +6014,7 @@ status = "shipped" commands = ["sign.digital"] tools = ["sign_document"] evidence = ["crates/sign/tests/pdf.rs::signing_an_existing_field_and_counter_signing", "crates/ui-egui/tests/signing.rs::clicking_an_empty_signature_field_signs_it", "crates/ui-egui/src/canvas.rs::empty_signature_fields_show_a_sign_tab_that_signs_them", "crates/ui-egui/src/canvas.rs::sign_tabs_skip_fields_that_a_click_cannot_sign"] -notes = "Clicking an empty signature field signs it (Use a certificate for that field). With the Select tool, each empty field a click would sign (filling allowed, the field not read-only, its widget shown) carries a small accent tab in its top-left corner, sized to the field (0.4 of its height on screen, from 10 to 18 pt): the signature icon and Sign from 14 pt up, the icon alone below that or when the label would take more than half the field's width, and no tab on a field too small for the 10 pt chip. The tab is screen-only chrome, never written into the file, exports or printing, and is hidden while preparing a form. Missing: the tab is painted only, with no accessibility node or keyboard focus of its own" +notes = "Clicking an empty signature field signs it (Use a certificate for that field). With the Select tool, each empty field a click would sign (filling allowed, the field not read-only, its widget shown) carries a small accent tab in its top-left corner, sized to the field (0.4 of its height on screen, from 10 to 18 pt): the signature icon and Sign from 14 pt up, the icon alone below that or when the label would take more than half the field's width, and no tab on a field too small for the 10 pt chip. The tab is screen-only chrome, never written into the file, exports or printing, and is hidden while preparing a form. Headless, the fields it marks are the ones sign_list reports unsigned and visible on a page, with their rect, that form_fields doesn't report read-only. Missing: the tab is painted only, with no accessibility node or keyboard focus of its own" [[feature]] id = "sign.invisible-signature" From 85aeef9407b17acabdff9c31556122a319c6243b Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:27:35 +0200 Subject: [PATCH 019/359] Search: centre the active match in the viewport (#3530) --- crates/ui-egui/src/canvas.rs | 49 +++++++++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f8df86fb33..c535cac69f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -485,8 +485,8 @@ pub struct DocView { viewport_w: f32, viewport_h: f32, page_count: usize, - /// Page heights in points (view space), for mapping text positions to scroll offsets. - page_heights: Vec, + /// Page sizes (width, height) in points (view space), for mapping text positions to scroll offsets. + page_sizes: Vec<(f32, f32)>, /// Screen rects of the pages drawn last frame (hit-testing, tests, automation). screen_rects: Vec<(usize, Rect)>, screen_xforms: Vec<(usize, PageXform)>, @@ -786,7 +786,7 @@ impl DocView { viewport_w: 800.0, viewport_h: 600.0, page_count: info.pages.len(), - page_heights: info.pages.iter().map(|p| p.height).collect(), + page_sizes: info.pages.iter().map(|p| (p.width, p.height)).collect(), screen_rects: Vec::new(), screen_xforms: Vec::new(), viewport_screen: Rect::NOTHING, @@ -861,7 +861,7 @@ impl DocView { self.invalidate_content(); self.frame_geometry_changed = true; self.page_count = info.pages.len(); - self.page_heights = info.pages.iter().map(|p| p.height).collect(); + self.page_sizes = info.pages.iter().map(|p| (p.width, p.height)).collect(); let last = self.page_count.saturating_sub(1); self.current = self.current.min(last); self.selected.retain(|p| *p <= last); @@ -1249,16 +1249,40 @@ impl DocView { self.flash_match(p); } + /// The centre of the current match as a fraction of its displayed page `[x, y]` (0..1 from + /// the top-left corner, after the view rotation, as [`Self::goto_point`] takes it). + fn match_centre(&self) -> Option<[f32; 2]> { + let f = self.find.as_ref()?; + let (p, r) = f.matches.get(f.current?)?; + let glyphs = self.texts.get(p)?.glyphs.get(r.clone())?; + let [x0, y0, x1, y1] = glyphs.iter().map(|g| g.rect).reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])])?; + let &(w, h) = self.page_sizes.get(*p).filter(|(w, h)| *w > 0.0 && *h > 0.0)?; + let (u, v) = ((((x0 + x1) / 2.0) / w).clamp(0.0, 1.0), (((y0 + y1) / 2.0) / h).clamp(0.0, 1.0)); + // Turned clockwise by the view rotation, as `PageInfo::dest_fraction` does. + Some(match self.rotation % 360 { + 90 => [1.0 - v, u], + 180 => [1.0 - u, 1.0 - v], + 270 => [v, 1.0 - u], + _ => [u, v], + }) + } + fn flash_match(&mut self, page: usize) { let frac = self .find .as_ref() .and_then(|f| f.current.and_then(|c| f.matches.get(c))) .and_then(|(p, r)| self.texts.get(p).and_then(|t| t.glyphs.get(r.start)).map(|g| g.rect[1])) - .zip(self.page_heights.get(page).copied()) + .zip(self.page_sizes.get(page).map(|&(_, h)| h)) .map(|(y, h)| ((y - 60.0) / h).clamp(0.0, 1.0)) .unwrap_or(0.0); self.goto = Some((page, frac)); + // Then put the match's centre at the window's centre, as Acrobat does (#3530) and as a + // /FitR destination's rectangle is: a page wider or taller than the window no longer + // leaves it off to one side or near an edge. + if let Some([fx, fy]) = self.match_centre() { + self.goto_point = Some((page, Some(fx), Some(fy), vec2(self.viewport_w, self.viewport_h) / 2.0)); + } self.current = page; self.reset_coarse_state(); } @@ -5969,7 +5993,8 @@ trailer << /Root 1 0 R >> // Chrome refreshes the idle page box; navigation must not overwrite a draft // that may still be focused. DocView does not own the editor's focus state. assert_eq!(v.page_input, "draft in progress"); - assert!(v.goto_point.is_none(), "an earlier link destination cannot override the search offset"); + let middle = vec2(v.viewport_w, v.viewport_h) / 2.0; + assert_eq!(v.goto_point, Some((3, Some(40.0 / 300.0), Some(0.675), middle)), "the match centre goes to the middle of the viewport"); v.go_to_match(1); assert_eq!(v.back, vec![0], "same-page matches do not duplicate history"); assert!(v.view_history(false)); @@ -5983,6 +6008,18 @@ trailer << /Root 1 0 R >> } } + #[test] + fn search_centres_the_match_on_a_rotated_view() { + // The match's centre is 40 pt from the left and 270 pt down a 300 × 400 page. + for (rotation, fx, fy) in [(90, 1.0 - 0.675, 40.0 / 300.0), (180, 1.0 - 40.0 / 300.0, 1.0 - 0.675), (270, 0.675, 1.0 - 40.0 / 300.0)] { + let mut v = history_search_view(); + v.rotation = rotation; + v.find_step(true); + let middle = vec2(v.viewport_w, v.viewport_h) / 2.0; + assert_eq!(v.goto_point, Some((3, Some(fx), Some(fy), middle)), "view rotated {rotation}°"); + } + } + #[test] fn automatic_search_updates_do_not_record_history_or_discard_forward() { let mut v = history_search_view(); From 2f9207589ec2c5206b00928bfab53ab74ab2d45d Mon Sep 17 00:00:00 2001 From: Lcoding15 <125505497+Lcoding15@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:27:42 +0200 Subject: [PATCH 020/359] M3: a find step keeps its match in the middle while a zoom is still on (#3530) Building on the centring of #3547, a step to a match could still leave the match off screen after zooming, now and then: - A zoom pending in the same frame (Ctrl+wheel, pinch, a zoom button or key) took the layout's anchor branch, so the step's `goto` waited for the next frame and its page-top offset (60 pt from the top, scaled by the zoom) undid the centring. At 600% that is below the window. - egui eases a Ctrl-wheel notch over about a quarter of a second. Every frame of that set a new zoom anchor at the pointer, which moved the match just stepped to away from the middle again. A step whose match centre is known now scrolls by that point alone and drops a pending zoom anchor. Until the first frame without a zoom gesture after the step is laid out, any zoom (`zoom_at`, so the wheel, pinch, buttons and keys) and a changing fit zoom anchor on the match at the window's centre. Another jump lets go of it. Match centres that are not finite (a hostile page's glyphs spanning -inf..inf) fall back to the page jump instead of a NaN scroll target. Tests: search_position.rs steps through needles on pages larger and smaller than the window at 10-3200%, in every page display, from the Search panel, in a fixed pseudo-random mix of zooms and steps (some in the same frame) and during real eased Ctrl-wheel zooms. With #3547 alone three of them fail; on main all four original ones do. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/ui-egui/src/canvas.rs | 76 +++++- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/search_position.rs | 257 +++++++++++++++++++++ parity/acrobat-features.toml | 4 +- 5 files changed, 330 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/tests/it/search_position.rs diff --git a/ROADMAP.md b/ROADMAP.md index bc057209c2..a1422260cc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -684,3 +684,4 @@ Newest first: the date, what moved, and the new overall estimate. - **2026-10-21 (M4, #3865):** A new bookmark records where the reader is: the top-left of the selected text, or the top of the window, as `/XYZ left top null` (zoom kept), instead of the page top (`Edit::AddBookmark` takes `left` and `top`; `bookmark_add` takes `top` and `left`; `PageInfo::xyz_for_view`). - **2026-10-18 (renderer, hayro patches 19/35):** A mesh shading (types 4–7) is sampled over its own triangles instead of the whole path: a BricsCAD plan with 310 one-triangle `sh` fills took 2 s per 1024 px tile at every zoom (and hit the 20 s watchdog on a busy machine); now about 70 ms, so zooming into dense topology drawings stays fluid. Estimates unchanged. +- **2026-10-22 (M3, #3530, builds on PR #3547):** A find step keeps its match in the middle of the window after zooming: a zoom pending in the same frame no longer puts the page-top jump off to the next frame, and the rest of an eased ⌘/Ctrl-wheel zoom anchors on the match instead of the pointer. Synthetic UI regressions step through matches on pages larger and smaller than the window at 10–3200% and in every page display. Estimates unchanged. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c535cac69f..6be6a0b93b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -494,6 +494,11 @@ pub struct DocView { viewport_screen: Rect, /// Pending zoom anchor: page, fractional position (also in gutters), and viewport offset. zoom_anchor: Option<(usize, f32, f32, Vec2)>, + /// The match a find step just went to: its page and its centre as fractions of the displayed + /// page. A zoom before the step has been laid out, or the rest of an eased ⌘-wheel zoom + /// still arriving, keeps it at the window's centre instead of the point under the pointer + /// (#3530). Let go in the first frame without a zoom gesture once the step is laid out. + find_hold: Option<(usize, f32, f32)>, /// The page view has been shown, so its scroll offset in egui's memory is this document's. shown: bool, /// Turns wheel input into page turns in single-page view. @@ -791,6 +796,7 @@ impl DocView { screen_xforms: Vec::new(), viewport_screen: Rect::NOTHING, zoom_anchor: None, + find_hold: None, shown: false, wheel: Default::default(), precise_scroll_until: 0.0, @@ -875,6 +881,7 @@ impl DocView { self.goto = None; self.goto_point = None; self.zoom_anchor = None; + self.find_hold = None; self.flash = None; // A thumbnail drag holds page indexes from before the change. self.panel_drag = None; @@ -1277,11 +1284,19 @@ impl DocView { .map(|(y, h)| ((y - 60.0) / h).clamp(0.0, 1.0)) .unwrap_or(0.0); self.goto = Some((page, frac)); + self.find_hold = None; // Then put the match's centre at the window's centre, as Acrobat does (#3530) and as a // /FitR destination's rectangle is: a page wider or taller than the window no longer // leaves it off to one side or near an edge. - if let Some([fx, fy]) = self.match_centre() { + // Finite only: a hostile page's glyphs can span -inf..inf, and NaN survives `clamp`. + if let Some([fx, fy]) = self.match_centre().filter(|c| c.iter().all(|v| v.is_finite())) { self.goto_point = Some((page, Some(fx), Some(fy), vec2(self.viewport_w, self.viewport_h) / 2.0)); + // The point alone, both axes in one frame. A pending zoom anchor would hold the old + // place for that frame and put `goto` off to the next, where its page-top offset + // undid the centring; a zoom after the step anchors on the match instead. + self.goto = None; + self.zoom_anchor = None; + self.find_hold = Some((page, fx, fy)); } self.current = page; self.reset_coarse_state(); @@ -1326,8 +1341,9 @@ impl DocView { } self.forward.clear(); } - // Partial wheel motion belongs to the old place. + // Partial wheel motion belongs to the old place, and so does a find step's match. self.reset_coarse_state(); + self.find_hold = None; self.goto = Some((page, 0.0)); self.current = page; } @@ -1736,15 +1752,18 @@ impl DocView { if zoom == self.zoom && self.fit == Fit::None { return; } + // Just after a find step, around the match at the window's centre (#3530). + let held = self.find_hold.map(|(p, fx, fy)| (p, fx, fy, vec2(self.viewport_w, self.viewport_h) / 2.0)); // In gutters/gaps, anchor relative to the nearest page rather than jumping to its top. // Fractions outside 0..1 preserve the pointer's position outside the page as well. - let anchor = + let anchor = held.or_else(|| { self.screen_rects.iter().min_by(|(_, a), (_, b)| a.distance_sq_to_pos(screen_pos).total_cmp(&b.distance_sq_to_pos(screen_pos))).map( |(p, r)| { let f = (screen_pos - r.min) / r.size(); (*p, f.x, f.y, screen_pos - self.viewport_screen.min) }, - ); + ) + }); self.zoom = zoom; self.fit = Fit::None; match anchor { @@ -2735,7 +2754,10 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { }) .or_else(|| view.screen_rects.iter().find(|(_, r)| r.min.y >= top_y).map(|(p, r)| (*p, 0.0f32, (r.min.y - top_y).max(0.0)))) .or_else(|| view.screen_rects.last().map(|(p, r)| (*p, 1.0f32, (r.max.y - top_y).max(0.0)))); - if let Some((page, fy, rel_y)) = anchor { + if let Some((page, fx, fy)) = view.find_hold { + // A fit zoom that changes just after a find step keeps the match in the middle too. + view.zoom_anchor = Some((page, fx, fy, avail.size() / 2.0)); + } else if let Some((page, fy, rel_y)) = anchor { view.zoom_anchor = Some((page, 0.5, fy, vec2(avail.width() / 2.0, rel_y))); } else { view.zoom_anchor = Some((view.current, 0.5, 0.0, vec2(avail.width() / 2.0, MARGIN))); @@ -2769,6 +2791,9 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { Some(p) => view.zoom_at(z, p), None => view.set_zoom(z), } + } else if view.goto_point.is_none() { + // The find step has been laid out and no zoom is easing on: zoom at the pointer again. + view.find_hold = None; } view.viewport_screen = avail; let auto_delta = if unobstructed { @@ -5987,7 +6012,7 @@ trailer << /Root 1 0 R >> v.go_to_match(0); } assert_eq!(v.back, vec![0], "explicit search jump must remember its origin"); - assert_eq!(v.goto, Some((3, 0.5)), "keep the match offset instead of the page top"); + assert_eq!(v.goto, None, "the match's point alone: a zoom that frame cannot put a page-top offset off to the next"); assert_eq!(v.current, 3); assert_eq!(v.current_page_label(None), "4"); // Chrome refreshes the idle page box; navigation must not overwrite a draft @@ -6020,6 +6045,43 @@ trailer << /Root 1 0 R >> } } + #[test] + fn a_zoom_just_after_a_find_step_keeps_the_match_in_the_middle() { + let mut v = history_search_view(); + v.screen_rects = vec![(0, Rect::from_min_size(pos2(100.0, 20.0), vec2(300.0, 400.0)))]; + // A zoom anchored at the pointer was pending when the step came: the step drops it. + v.zoom_at(2.0, pos2(150.0, 50.0)); + assert!(v.zoom_anchor.is_some()); + v.find_step(true); + assert_eq!((v.goto, v.zoom_anchor), (None, None), "the step alone decides where the view goes"); + let middle = vec2(v.viewport_w, v.viewport_h) / 2.0; + let target = Some((3, Some(40.0 / 300.0), Some(0.675), middle)); + assert_eq!(v.goto_point, target); + // The rest of an eased wheel zoom, or a zoom in the same frame, anchors on the match + // at the window's centre, not on the pointer. + v.zoom_at(3.0, pos2(150.0, 50.0)); + assert_eq!(v.zoom_anchor, Some((3, 40.0 / 300.0, 0.675, middle))); + // Another jump lets go of the match: the next zoom is at the pointer again. + v.go_to_page(1); + v.zoom_at(4.0, pos2(150.0, 50.0)); + assert_eq!(v.zoom_anchor.map(|a| a.0), Some(0), "anchored on the page under the pointer"); + } + + #[test] + fn a_match_with_unbounded_glyphs_falls_back_to_its_page() { + let mut v = history_search_view(); + // A hostile page: a glyph from -inf to inf, whose centre is NaN. + if let Some(text) = v.texts.get_mut(&3).and_then(Arc::get_mut) { + text.glyphs[0].rect = [f32::NEG_INFINITY, 260.0, f32::INFINITY, 280.0]; + } + v.zoom_at(2.0, pos2(150.0, 50.0)); + v.find_step(true); + assert!(v.goto_point.is_none(), "no NaN scroll target"); + assert_eq!(v.goto.map(|g| g.0), Some(3), "the match's page instead"); + v.zoom_at(3.0, pos2(150.0, 50.0)); + assert!(v.zoom_anchor.is_none_or(|a| a.1.is_finite() && a.2.is_finite()), "no NaN zoom anchor"); + } + #[test] fn automatic_search_updates_do_not_record_history_or_discard_forward() { let mut v = history_search_view(); @@ -6027,7 +6089,7 @@ trailer << /Root 1 0 R >> v.find = Some(Find { query: "match".into(), ..Default::default() }); v.rerun_find(); assert_eq!(v.current, 3); - assert_eq!(v.goto, Some((3, 0.5))); + assert_eq!((v.goto, v.goto_point.map(|g| g.0)), (None, Some(3)), "the match's point on its page"); assert!(v.back.is_empty()); assert_eq!(v.forward, vec![4]); v.current = 0; diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 7c04df20e3..0af2c96153 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -61,6 +61,7 @@ mod reading_colors; mod recovery; mod redact; mod reload; +mod search_position; mod signing; mod stamps; mod text_select; diff --git a/crates/ui-egui/tests/it/search_position.rs b/crates/ui-egui/tests/it/search_position.rs new file mode 100644 index 0000000000..d45fbc85d0 --- /dev/null +++ b/crates/ui-egui/tests/it/search_position.rs @@ -0,0 +1,257 @@ +//! Find goes to where the match is (#3530): after zooming in or out, every step to a match (⌘G, +//! ⇧⌘G, a click in the Search panel's results) leaves the highlighted match on screen, near the +//! middle of the window, on pages larger and smaller than the window, and also when a zoom and a +//! step land in the same frame. + +use egui_kittest::Harness; +use pdfcraft_ui_egui::PdfCraftApp; + +/// The word searched for, placed (x, y in PDF user space) on each page. +const NEEDLE: &str = "needle"; + +/// A page size, or a point on a page, in points. +type Size = (u32, u32); +type Point = (u32, u32); + +/// Page sizes (points) and where on each page the needle is: the corners, the middle and the +/// edges of large pages, as well as a small page that fits the window. +fn pages() -> Vec<(Size, Vec)> { + vec![ + ((612, 792), vec![(60, 720), (480, 60)]), + ((1700, 2400), vec![(40, 2340), (1560, 2340), (820, 1200), (40, 40), (1560, 40)]), + ((2400, 1200), vec![(2300, 1140), (60, 600), (1200, 60)]), + ((612, 792), vec![(300, 400)]), + ] +} + +/// A PDF of [`pages`]: lines of filler text down every page, and the needles. +fn fixture() -> Vec { + let pages = pages(); + let n = pages.len(); + let font = 3 + 2 * n; + let kids: Vec = (0..n).map(|i| format!("{} 0 R", 3 + 2 * i)).collect(); + let mut objs = vec!["<< /Type /Catalog /Pages 2 0 R >>".to_string(), format!("<< /Type /Pages /Kids [{}] /Count {n} >>", kids.join(" "))]; + for (i, ((w, h), needles)) in pages.iter().enumerate() { + let mut body = String::from("BT /F1 9 Tf 11 TL"); + // Filler text a needle search must step over; it never contains the needle. + body.push_str(&format!(" 20 {} Td", h.saturating_sub(100))); + for line in 0..(h.saturating_sub(200) / 11) { + body.push_str(&format!(" (filler line {line} of the quick brown fox jumps over the lazy dog) '")); + } + body.push_str(" ET"); + for (x, y) in needles { + body.push_str(&format!(" BT /F1 14 Tf {x} {y} Td ({NEEDLE}) Tj ET")); + } + objs.push(format!( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w} {h}] /Contents {} 0 R /Resources << /Font << /F1 {font} 0 R >> >> >>", + 4 + 2 * i + )); + objs.push(format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len())); + } + objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string()); + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + 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{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +fn needles() -> usize { + pages().iter().map(|(_, n)| n.len()).sum() +} + +/// The app with the fixture open and a search for the needle that has found every match. +fn harness() -> Harness<'static, PdfCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("search.pdf", None, fixture()).expect("opens"); + app.set_option("left", "closed").unwrap(); + app + }); + h.run_steps(4); + settle(&mut h); + h.state_mut().views[0].open_find(); + h.state_mut().views[0].find.as_mut().unwrap().query = NEEDLE.into(); + h.state_mut().views[0].rerun_find(); + // Find runs in the background: wait by a deadline, not a frame count. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while std::time::Instant::now() < deadline && h.state().views[0].find.as_ref().unwrap().matches.len() < needles() { + h.run_steps(2); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(h.state().views[0].find.as_ref().unwrap().matches.len(), needles(), "every needle is found"); + settle(&mut h); + h +} + +/// Run frames until rendering has finished and the layout holds still. +fn settle(h: &mut Harness<'static, PdfCraftApp>) { + for _ in 0..200 { + h.run_steps(2); + if !h.state().render_pending() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } +} + +/// Fail unless the current match is drawn inside the window, and, where the page lets the view +/// scroll that far, near its middle (#3530 asks for the middle, as Acrobat does). +fn assert_match_shown(h: &Harness<'static, PdfCraftApp>, what: &str) { + let v = &h.state().views[0]; + let f = v.find.as_ref().unwrap(); + let i = f.current.unwrap_or_else(|| panic!("{what}: no current match")); + let (page, range) = f.matches[i].clone(); + let window = v.viewport_rect(); + let at = |g: usize| v.glyph_screen_pos(page, g).unwrap_or_else(|| panic!("{what}: match {i} (page {}) is not on screen", page + 1)); + let (first, last) = (at(range.start), at(range.end - 1)); + // At the highest zooms one word is wider than the window: then its middle is what shows. + let ends = if last.x - first.x < window.width() * 0.8 { vec![first, last] } else { vec![first.lerp(last, 0.5)] }; + for p in ends { + assert!(window.contains(p), "{what}: match {i} (page {}) at {p:?} is outside the window {window:?} (zoom {})", page + 1, v.zoom); + } + let Some(page_rect) = v.page_screen_rect(page) else { return }; + let centre = first.lerp(last, 0.5); + // Glyph centres, not the match's box: their middle is off the box's by up to half a glyph. + let slack = 4.0 + 0.25 * (last.x - first.x).abs(); + // Off the middle only as far as the content's ends stop the scroll. + let room_x = (page_rect.left() < window.left() - 1.0 || centre.x > window.center().x) + && (page_rect.right() > window.right() + 1.0 || centre.x < window.center().x); + let room_y = (page_rect.top() < window.top() - 1.0 || centre.y > window.center().y) + && (page_rect.bottom() > window.bottom() + 1.0 || centre.y < window.center().y); + if room_x { + assert!((centre.x - window.center().x).abs() < slack, "{what}: match {i} at x {} is not centred in {window:?} (zoom {})", centre.x, v.zoom); + } + if room_y { + assert!((centre.y - window.center().y).abs() < slack, "{what}: match {i} at y {} is not centred in {window:?} (zoom {})", centre.y, v.zoom); + } +} + +/// Step through every match forward and back at each zoom, as ⌘G and ⇧⌘G do. +#[test] +fn every_match_is_shown_after_zooming() { + let mut h = harness(); + let n = needles(); + for zoom in [0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0] { + h.state_mut().views[0].set_zoom(zoom); + settle(&mut h); + for forward in [true, false] { + for _ in 0..n { + h.state_mut().views[0].find_step(forward); + settle(&mut h); + assert_match_shown(&h, &format!("zoom {zoom}, step {}", if forward { "forward" } else { "back" })); + } + } + } +} + +/// A click on a result in the Search panel goes to it at any zoom. +#[test] +fn search_panel_results_are_shown_after_zooming() { + let mut h = harness(); + for zoom in [0.33, 3.0, 12.0] { + h.state_mut().views[0].set_zoom(zoom); + settle(&mut h); + for i in (0..needles()).rev() { + h.state_mut().views[0].go_to_match(i); + settle(&mut h); + assert_match_shown(&h, &format!("zoom {zoom}, result {i}")); + } + } +} + +/// Zooms and steps mixed in a fixed pseudo-random order, as a reader zooms in and out between +/// searches; some steps land in the same frame as a zoom, before the zoom has been laid out. +#[test] +fn zooming_and_stepping_in_any_order_shows_the_match() { + let mut h = harness(); + let mut seed: u32 = 0x5eed_3530; + let mut next = |m: u32| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) % m + }; + for round in 0..80 { + let same_frame = next(3) == 0; + match next(4) { + 0 => h.state_mut().views[0].zoom_step(true), + 1 => h.state_mut().views[0].zoom_step(false), + 2 => { + let z = [0.2, 0.75, 1.5, 6.0, 10.0][next(5) as usize]; + h.state_mut().views[0].set_zoom(z); + } + _ => {} + } + if !same_frame { + settle(&mut h); + } + if next(2) == 0 { + let i = next(needles() as u32) as usize; + h.state_mut().views[0].go_to_match(i); + } else { + let forward = next(2) == 0; + h.state_mut().views[0].find_step(forward); + } + settle(&mut h); + assert_match_shown(&h, &format!("round {round}{}", if same_frame { " (zoom in the same frame)" } else { "" })); + } +} + +/// ⌘/Ctrl with the wheel zooms over several frames (egui eases a notch over about a quarter of a +/// second). A step to a match while that zoom is still easing goes to the match, and the rest of +/// the zoom keeps it where it went instead of holding the point under the pointer still. +#[test] +fn a_step_during_a_wheel_zoom_keeps_the_match_on_screen() { + let mut h = harness(); + h.state_mut().set_option("animation_effects", "on").unwrap(); + h.state_mut().views[0].set_zoom(3.0); + settle(&mut h); + let n = needles(); + for (i, dy) in (0..n).zip([60.0, -60.0].into_iter().cycle()) { + // The pointer well away from the middle, where the zoom would otherwise be anchored. + let w = h.state().views[0].viewport_rect(); + h.hover_at(w.min + egui::vec2(80.0, 80.0)); + h.run_steps(1); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::COMMAND, + }); + h.run_steps(2); + let before = h.state().views[0].zoom; + h.state_mut().views[0].find_step(true); + // Let the zoom finish easing, then the rendering. + h.run_steps(60); + settle(&mut h); + assert!((h.state().views[0].zoom - before).abs() > 1e-3, "step {i}: the zoom was still easing when the step came"); + assert_match_shown(&h, &format!("step {i} during a wheel zoom ({dy})")); + } +} + +/// Single page and two-up, scrolling or a page (spread) at a time: each step shows its match. +#[test] +fn every_page_display_shows_the_match_after_zooming() { + use pdfcraft_ui_egui::canvas::PageLayout; + let mut h = harness(); + for (layout, continuous) in [(PageLayout::Single, false), (PageLayout::TwoUp, true), (PageLayout::TwoUp, false)] { + h.state_mut().views[0].set_display(layout, continuous); + for zoom in [0.5, 4.0] { + h.state_mut().views[0].set_zoom(zoom); + settle(&mut h); + for _ in 0..needles() { + h.state_mut().views[0].find_step(true); + settle(&mut h); + assert_match_shown(&h, &format!("{layout:?}, continuous {continuous}, zoom {zoom}")); + } + } + } +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 45dda39822..d712550159 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -1406,8 +1406,8 @@ milestone = "M3" status = "shipped" commands = ["edit.find"] tools = [] -evidence = ["crates/ui-egui/tests/it/ui.rs::find_counts_matches_across_pages"] -notes = "" +evidence = ["crates/ui-egui/tests/it/ui.rs::find_counts_matches_across_pages", "crates/ui-egui/tests/it/search_position.rs::every_match_is_shown_after_zooming", "crates/ui-egui/tests/it/search_position.rs::zooming_and_stepping_in_any_order_shows_the_match", "crates/ui-egui/tests/it/search_position.rs::a_step_during_a_wheel_zoom_keeps_the_match_on_screen", "crates/ui-egui/tests/it/search_position.rs::every_page_display_shows_the_match_after_zooming"] +notes = "Each step (⌘G, ⇧⌘G, Enter, a Search panel result) centres the match in the window on both axes at any zoom, view rotation and page display, as far as the content's ends allow (#3530); a zoom still easing on, or one in the same frame, anchors on the match instead of the pointer. A word wider than the window shows its middle." [[feature]] id = "view.find-options" From e72147c210e4901e09201e523327a6c5ce39cba5 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:12:42 -0400 Subject: [PATCH 021/359] M12: screen-only and print-only XFA objects are shown and printed as the form says --- crates/engine/src/tests.rs | 39 +++++++ crates/xfa/src/layout.rs | 109 ++++++++++++++++-- crates/xfa/src/model.rs | 45 ++++++++ crates/xfa/src/parse.rs | 23 ++++ crates/xfa/src/pdf.rs | 218 ++++++++++++++++++++++++++++++++++- crates/xfa/src/tests.rs | 186 ++++++++++++++++++++++++++++++ parity/acrobat-features.toml | 4 +- 7 files changed, 612 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ed4e6efa1c..ce69daf5a0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2593,6 +2593,45 @@ fn printing_lays_out_sheets_that_render() { assert_eq!(s4.print_pdf(id4, &print::Settings { pages: vec![0], ..Default::default() }), Err(EditError::NotPermitted("printing"))); } +/// A dynamic XFA form's screen-only and print-only objects (`relevant`): on screen, the +/// screen-only field and draw show and the print-only ones don't; printed, the screen-only field +/// is left off and the print-only one is on paper. (Draws follow the layers' state on screen +/// when printed until printing applies the layers' print usage; other viewers read it from the +/// file.) +#[test] +fn xfa_screen_only_and_print_only_objects_show_and_print_where_the_form_says() { + let field = |name: &str, attrs: &str| { + format!( + r#"{name} value"# + ) + }; + let draw = |name: &str, attrs: &str| { + format!(r#"{name} text"#) + }; + let xdp = format!( + r##" +"##, + field("screenField", r#"relevant="-print""#), + field("paperField", r#"presence="invisible" relevant="+print""#), + draw("screenDraw", r#"relevant="-print""#), + draw("paperDraw", r#"presence="invisible" relevant="+print""#), + ); + let mut s = Session::new(); + let id = s.open("form.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(&xdp)), None).expect("opens"); + let screen = page_texts(&s, id).join("\n"); + assert!(screen.contains("screenField value") && screen.contains("screenDraw text"), "on screen: {screen}"); + assert!(!screen.contains("paperField value") && !screen.contains("paperDraw text"), "on screen: {screen}"); + let sheet = s.print_pdf(id, &print::Settings { pages: vec![0], ..Default::default() }).unwrap(); + let mut out = Session::new(); + let printed = out.open("print.pdf", None, Arc::new(sheet), None).unwrap(); + let paper = page_texts(&out, printed).join("\n"); + assert!(!paper.contains("screenField value"), "printed: {paper}"); + assert!(paper.contains("paperField value"), "printed: {paper}"); +} + /// A one-page document whose red square is in a layer; `off` switches the layer off by default. fn red_layer_pdf(off: bool) -> Vec { let content = "/OC /L1 BDC 1 0 0 rg 0 0 100 100 re f EMC"; diff --git a/crates/xfa/src/layout.rs b/crates/xfa/src/layout.rs index 23342168e7..c5f2449bd0 100644 --- a/crates/xfa/src/layout.rs +++ b/crates/xfa/src/layout.rs @@ -39,11 +39,30 @@ const PAGE_COUNT_MARK: char = '\u{E000}'; #[derive(Clone, Debug, PartialEq)] pub enum Item { - Fill { rect: Rect, color: [f64; 3] }, - Line { from: (f64, f64), to: (f64, f64), width: f64, color: [f64; 3], dashed: bool }, + Fill { + rect: Rect, + color: [f64; 3], + }, + Line { + from: (f64, f64), + to: (f64, f64), + width: f64, + color: [f64; 3], + dashed: bool, + }, Text(Span), - Image { rect: Rect, data: Arc>, content_type: String }, + Image { + rect: Rect, + data: Arc>, + content_type: String, + }, Widget(Box), + /// An item drawn only on screen or only in print (XFA `relevant`, `presence`): written in an + /// optional content group whose usage says so. + Only { + views: Views, + item: Box, + }, } #[derive(Clone, Debug, PartialEq)] @@ -126,6 +145,8 @@ pub struct Widget { pub action: Option, /// Check boxes: the on and off values of the data; radio buttons: the on value. pub items: Vec, + /// Where the field is shown: on screen, in print, or both (its annotation flags). + pub views: Views, } #[derive(Clone, Debug, Default, PartialEq)] @@ -211,6 +232,8 @@ struct Layouter<'t> { /// The fields and draws of the block being placed: (first item, one past the last, top, /// bottom) on the last page. A page break keeps each whole (see `split_block`). leaves: Vec<(usize, usize, f64, f64)>, + /// Where what is being drawn shows, as the objects it is inside say ([`Common::views`]). + views: Views, } /// How many instances of a repeating subform to lay out: what the data holds once it holds @@ -256,6 +279,7 @@ pub fn layout(tpl: &Template, data: Option<&DataNode>) -> Result measured: RefCell::new(HashMap::new()), measures: Cell::new(0), leaves: Vec::new(), + views: Views::ALL, }; let ctx = Ctx { font: Font::default(), para: Para::default(), som: String::new() }; l.new_page()?; @@ -335,12 +359,19 @@ fn solid_extent(item: &Item) -> Option<(f64, f64)> { Item::Image { rect, .. } => Some((rect.y, rect.bottom())), Item::Widget(w) => Some((w.rect.y, w.rect.bottom())), Item::Fill { .. } | Item::Line { .. } => None, + Item::Only { item, .. } => solid_extent(item), } } /// `item` as the part above `cut` and the part below: solid items go whole to the side their /// top is on, fills and lines crossing the cut are cut in two. fn divide(item: Item, cut: f64) -> (Option, Option) { + if let Item::Only { views, item } = item { + // Each part shows where the whole did. + let wrap = |i: Item| Item::Only { views, item: Box::new(i) }; + let (a, b) = divide(*item, cut); + return (a.map(wrap), b.map(wrap)); + } if let Some((top, _)) = solid_extent(&item) { return if top < cut - 0.01 { (Some(item), None) } else { (None, Some(item)) }; } @@ -375,6 +406,9 @@ fn divide(item: Item, cut: f64) -> (Option, Option) { /// `item` moved by (`dx`, `dy`). fn moved(mut item: Item, dx: f64, dy: f64) -> Item { + if let Item::Only { views, item: inner } = item { + return Item::Only { views, item: Box::new(moved(*inner, dx, dy)) }; + } match &mut item { Item::Fill { rect, .. } | Item::Image { rect, .. } => { rect.x += dx; @@ -392,6 +426,8 @@ fn moved(mut item: Item, dx: f64, dy: f64) -> Item { w.rect.x += dx; w.rect.y += dy; } + // Taken apart above. + Item::Only { .. } => {} } item } @@ -505,12 +541,25 @@ impl Layouter<'_> { Ok(()) } + /// Put `item` on the last page, shown where what it is inside is shown ([`Self::views`]): a + /// field's widget carries that itself, anything else drawn only on screen or only in print + /// goes in an [`Item::Only`], and what shows nowhere isn't put at all. fn push(&mut self, item: Item) -> Result<(), XfaError> { self.check_measures()?; self.items += 1; if self.items > MAX_ITEMS { return Err(XfaError::TooLarge("the form has too many objects to lay out".into())); } + let views = self.views; + let item = match item { + Item::Widget(mut w) => { + w.views = views; + Item::Widget(w) + } + other if views == Views::ALL => other, + _ if !views.any() => return Ok(()), + other => Item::Only { views, item: Box::new(other) }, + }; if let Some(p) = self.pages.last_mut() { p.items.push(item); } @@ -570,10 +619,12 @@ impl Layouter<'_> { let ctx = Ctx { font: Font::default(), para: Para::default(), som: area.name.clone().map(|n| format!("{n}[0]")).unwrap_or_default() }; let page_rect = Rect::new(0.0, 0.0, area.width, area.height); let sibs = SomIndices::of(&area.items); - for (i, item) in area.items.iter().enumerate() { - self.draw_positioned_child(item, page_rect, &ctx, 1, sibs.at(i))?; - } - Ok(()) + // The master page's own objects: shown where they say, whatever the body was drawing + // when it needed this page. + let body = std::mem::replace(&mut self.views, Views::ALL); + let drawn = area.items.iter().enumerate().try_for_each(|(i, item)| self.draw_positioned_child(item, page_rect, &ctx, 1, sibs.at(i))); + self.views = body; + drawn } /// Move to the next content area, or the next page. @@ -766,7 +817,18 @@ impl Layouter<'_> { // ───────────────────────────────────────────────────────────────────────── flow /// Flow `node` (a subform; anything else is ignored) into the content areas. + /// Flow subform `node` (each instance the data asks for) into the content areas, shown where + /// it and what it is inside say ([`Common::views`]); hidden from both, it still takes its room. fn flow_subform(&mut self, node: &Node, avail: Option<(f64, f64)>, ctx: &Ctx, depth: usize, sib: usize) -> Result<(), XfaError> { + let views = self.views.and(node.common().views()); + let outer = std::mem::replace(&mut self.views, views); + let flowed = self.flow_subform_in(node, avail, ctx, depth, sib); + self.views = outer; + flowed + } + + /// [`Self::flow_subform`] once where the subform shows is set. + fn flow_subform_in(&mut self, node: &Node, avail: Option<(f64, f64)>, ctx: &Ctx, depth: usize, sib: usize) -> Result<(), XfaError> { if depth > MAX_DEPTH { return Ok(()); } @@ -1265,10 +1327,24 @@ impl Layouter<'_> { // ───────────────────────────────────────────────────────────────────────── drawing + /// Draw table row `row` at `rect` in columns `cols`, shown where it and what it is inside say + /// ([`Common::views`]). fn draw_row(&mut self, row: &Subform, cols: &[f64], rect: Rect, ctx: &Ctx, depth: usize, sib: usize) -> Result<(), XfaError> { if depth > MAX_DEPTH { return Ok(()); } + let views = self.views.and(row.common.views()); + if !views.any() { + return Ok(()); + } + let outer = std::mem::replace(&mut self.views, views); + let drawn = self.draw_row_cells(row, cols, rect, ctx, depth, sib); + self.views = outer; + drawn + } + + /// [`Self::draw_row`]'s border and cells, once where the row shows is set. + fn draw_row_cells(&mut self, row: &Subform, cols: &[f64], rect: Rect, ctx: &Ctx, depth: usize, sib: usize) -> Result<(), XfaError> { if let Some(b) = &row.common.border { self.draw_border(b, rect)?; } @@ -1295,14 +1371,29 @@ impl Layouter<'_> { self.draw_node(k, Rect::new(inner.x + x, inner.y + y, w, h), ctx, depth + 1, sib) } + /// Draw `node` at `rect`, shown where it and what it is inside say ([`Common::views`]): an + /// invisible object that `relevant` prints is drawn for print only, and one shown nowhere + /// draws nothing. fn draw_node(&mut self, node: &Node, rect: Rect, ctx: &Ctx, depth: usize, sib: usize) -> Result<(), XfaError> { if depth > MAX_DEPTH { return Ok(()); } let c = node.common(); - if c.presence == Presence::Invisible { + if let Some(other) = &c.relevant_other { + self.warn_once(format!("the form limits some objects to views other than print (relevant \"{other}\"); they are drawn as if it didn't")); + } + let views = self.views.and(c.views()); + if !views.any() { return Ok(()); } + let outer = std::mem::replace(&mut self.views, views); + let drawn = self.draw_node_in(node, rect, ctx, depth, sib); + self.views = outer; + drawn + } + + /// [`Self::draw_node`] once where the node shows is set. + fn draw_node_in(&mut self, node: &Node, rect: Rect, ctx: &Ctx, depth: usize, sib: usize) -> Result<(), XfaError> { match node { Node::Draw(d) => { let start = self.item_count(); @@ -1804,6 +1895,8 @@ impl Layouter<'_> { default: template_default, action, items, + // `push` sets where it shows. + views: Views::ALL, }))) } } diff --git a/crates/xfa/src/model.rs b/crates/xfa/src/model.rs index b60180b7fa..4c645dcab1 100644 --- a/crates/xfa/src/model.rs +++ b/crates/xfa/src/model.rs @@ -306,6 +306,37 @@ impl Para { } } +/// Where an object is drawn: on screen, when the form is printed, or both (see +/// [`Common::views`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Views { + pub screen: bool, + pub print: bool, +} + +impl Views { + /// On screen and in print: what an object with nothing to say is. + pub const ALL: Views = Views { screen: true, print: true }; + + /// Where an object inside a container drawn in `self` is drawn, when it alone would be drawn + /// in `other`: only where both are. + pub fn and(self, other: Views) -> Views { + Views { screen: self.screen && other.screen, print: self.print && other.print } + } + + /// Drawn somewhere. + pub fn any(self) -> bool { + self.screen || self.print + } +} + +impl Default for Views { + /// On screen and in print. + fn default() -> Self { + Views::ALL + } +} + /// What every container and leaf shares: name, box, presence, margins, border, text defaults. #[derive(Clone, Debug, Default, PartialEq)] pub struct Common { @@ -321,6 +352,12 @@ pub struct Common { pub min_h: Option, pub max_h: Option, pub presence: Presence, + /// What `relevant` says about printing: `Some(true)` for `+print` (printed even when its + /// presence hides it on screen), `Some(false)` for `-print` (never printed), `None` when it + /// says nothing (printed as it is shown). + pub relevant: Option, + /// The first `relevant` token about a view other than print, which is left aside. + pub relevant_other: Option, pub margin: Margin, pub border: Option, pub font: FontSpec, @@ -339,6 +376,14 @@ pub enum Node { } impl Common { + /// Where the object itself is drawn, before what its containers say: on screen when it is + /// visible, and in print when `relevant` says so (`+print` even when hidden or invisible, + /// `-print` never), else when it is visible. + pub fn views(&self) -> Views { + let screen = self.presence == Presence::Visible; + Views { screen, print: self.relevant.unwrap_or(screen) } + } + /// The top-left corner of a positioned box of `w` by `h`, from `x`, `y` and the anchor. pub fn top_left(&self, w: f64, h: f64) -> (f64, f64) { (self.x.unwrap_or(0.0) - w * self.anchor.h, self.y.unwrap_or(0.0) - h * self.anchor.v) diff --git a/crates/xfa/src/parse.rs b/crates/xfa/src/parse.rs index fc9ad1a245..27c1c4c35a 100644 --- a/crates/xfa/src/parse.rs +++ b/crates/xfa/src/parse.rs @@ -178,7 +178,28 @@ fn parse_para(n: Option) -> ParaSpec { } } +/// `relevant`: a space-separated list of views, each `+name` (or `name`) or `-name`. What it says +/// about printing (`Some(true)` for `+print`, `Some(false)` for `-print`; the last one counts), and +/// the first token about any other view, which is left aside. +fn parse_relevant(s: Option<&str>) -> (Option, Option) { + let (mut print, mut other) = (None, None); + for token in s.unwrap_or_default().split_whitespace().take(64) { + match token { + "+print" | "print" => print = Some(true), + "-print" => print = Some(false), + _ => { + if other.is_none() { + other = Some(token.chars().take(64).collect()); + } + } + } + } + (print, other) +} + +/// What element `n` shares with every container and leaf ([`Common`]). fn parse_common(n: XmlNode) -> Common { + let (relevant, relevant_other) = parse_relevant(n.attribute("relevant")); Common { name: n.attribute("name").map(str::to_string).filter(|s| !s.is_empty()), id: n.attribute("id").map(str::to_string), @@ -192,6 +213,8 @@ fn parse_common(n: XmlNode) -> Common { min_h: attr_measure(n, "minH"), max_h: attr_measure(n, "maxH"), presence: Presence::parse(n.attribute("presence")), + relevant, + relevant_other, margin: parse_margin(child(n, "margin")), border: parse_border(child(n, "border")), font: parse_font(child(n, "font")), diff --git a/crates/xfa/src/pdf.rs b/crates/xfa/src/pdf.rs index 8e0c47d888..7b9981962b 100644 --- a/crates/xfa/src/pdf.rs +++ b/crates/xfa/src/pdf.rs @@ -160,6 +160,15 @@ pub struct Written { /// layer reads this key). pub const IMAGE_FIELD_KEY: &[u8] = b"PCXfaImage"; +/// On an optional content group PdfCraft made for what a form shows only on screen (`/Screen`) +/// or only in print (`/Print`): a later layout of the form finds and reuses it. +pub const RELEVANT_KEY: &[u8] = b"PCXfaRelevant"; + +/// The optional content groups of [`RELEVANT_KEY`], by index: what the key says, the group's +/// resource name on the pages, its `/Name`, and its view and print states. +const GROUPS: [(&str, &str, &str, &str, &str); 2] = + [("Screen", "PCXfaScreen", "Form: screen only", "ON", "OFF"), ("Print", "PCXfaPrint", "Form: print only", "OFF", "ON")]; + /// On an image XObject written for a picture: the SHA-256 (hex) of the picture's bytes. A /// re-layout (after every script event) finds the XObjects on the pages it replaces by this, /// and reuses them instead of decoding and embedding the same picture again. Nothing is kept @@ -182,6 +191,11 @@ struct Emitter<'a> { warnings: Vec, /// The signatures the file holds, by the SOM path of the field signed. signed: HashMap, + /// The screen-only and print-only optional content groups ([`GROUPS`]): an earlier layout's, + /// or made when first needed. + groups: [Option; 2], + /// Which of [`Self::groups`] this layout drew in. + used: [bool; 2], } /// A signature field of the file that has been signed. @@ -244,13 +258,23 @@ impl Emitter<'_> { format!("/{} {} Tf {} rg", face.resource_name(), n(face.size), rgb(face.color)).into_bytes() } + /// Write laid-out widget `w` on `page` as an AcroForm widget annotation (and its field), its + /// flags saying whether it shows on screen and in print, and return the annotation. fn widget(&mut self, w: &Widget, page: &Page, page_ref: ObjRef) -> Result, XfaError> { let r = w.rect; let (x0, y0, x1, y1) = (r.x, page.height - r.bottom(), r.right(), page.height - r.y); let mut d = Dict::new(); d.set(b"Type".to_vec(), Object::name("Annot")); d.set(b"Subtype".to_vec(), Object::name("Widget")); - d.set(b"F".to_vec(), Object::Int(4)); + // Print (4) when it prints, NoView (32) when it isn't shown on screen, Hidden (2) when + // it is shown nowhere. + let flags = match (w.views.screen, w.views.print) { + (true, true) => 4, + (true, false) => 0, + (false, true) => 4 | 32, + (false, false) => 2, + }; + d.set(b"F".to_vec(), Object::Int(flags)); d.set(b"P".to_vec(), Object::Ref(page_ref)); d.set(b"Rect".to_vec(), Object::Array([x0, y0, x1, y1].iter().map(|v| Object::Real(*v)).collect())); d.set(b"DA".to_vec(), Object::String(PdfString::literal(Self::da(&w.face)))); @@ -573,6 +597,37 @@ impl Emitter<'_> { } } + /// Optional content group `g` of [`GROUPS`] (0 screen only, 1 print only), marked as drawn in: + /// an earlier layout's, or a new one whose `/Usage` says where it shows. + fn group(&mut self, g: usize) -> ObjRef { + if let Some(u) = self.used.get_mut(g) { + *u = true; + } + if let Some(r) = self.groups.get(g).copied().flatten() { + return r; + } + let (key, _, name, view, print) = GROUPS.get(g).copied().unwrap_or(GROUPS[0]); + let state = |event: &str, key: &str, value: &str| { + let mut s = Dict::new(); + s.set(key.as_bytes().to_vec(), Object::name(value)); + (event.as_bytes().to_vec(), Object::Dict(s)) + }; + let mut usage = Dict::new(); + for (k, v) in [state("View", "ViewState", view), state("Print", "PrintState", print)] { + usage.set(k, v); + } + let mut d = Dict::new(); + d.set(b"Type".to_vec(), Object::name("OCG")); + d.set(b"Name".to_vec(), Object::String(PdfString::text(name))); + d.set(b"Usage".to_vec(), Object::Dict(usage)); + d.set(RELEVANT_KEY.to_vec(), Object::name(key)); + let r = self.doc.add(Object::Dict(d)); + if let Some(slot) = self.groups.get_mut(g) { + *slot = Some(r); + } + r + } + /// Write one laid-out page under `pages_ref`: its fills, lines, text and pictures in a /// content stream, the fonts and images it uses as resources, and its widgets as /// annotations. Returns the page object. @@ -583,7 +638,25 @@ impl Emitter<'_> { let mut xobjects = Dict::new(); let mut annots = Vec::new(); let h = page.height; + // The group whose marked content is open, and the groups the page uses. + let mut open: Option = None; + let mut properties = Dict::new(); for (i, item) in page.items.iter().enumerate() { + let (group, item) = match item { + Item::Only { views, item } => (Some(if views.screen { 0 } else { 1 }), item.as_ref()), + other => (None, other), + }; + // A field's widget is an annotation, not page content: the marked content runs on. + if !matches!(item, Item::Widget(_)) && group != open { + if open.is_some() { + content.extend_from_slice(b"EMC\n"); + } + if let Some((g, (_, resource, ..))) = group.and_then(|g| GROUPS.get(g).map(|k| (g, k))) { + properties.set(resource.as_bytes().to_vec(), Object::Ref(self.group(g))); + content.extend(format!("/OC /{resource} BDC\n").bytes()); + } + open = group; + } match item { Item::Fill { rect, color } => { content.extend(format!("{} rg {} {} {} {} re f\n", rgb(*color), n(rect.x), n(h - rect.bottom()), n(rect.w), n(rect.h)).bytes()); @@ -641,8 +714,13 @@ impl Emitter<'_> { annots.push(Object::Ref(r)); } } + // Taken apart above: an item is never wrapped twice. + Item::Only { .. } => {} } } + if open.is_some() { + content.extend_from_slice(b"EMC\n"); + } let mut font_dict = Dict::new(); for (name, base) in fonts { font_dict.set(name.as_bytes().to_vec(), standard_font(base)); @@ -652,6 +730,9 @@ impl Emitter<'_> { if !xobjects.is_empty() { res.set(b"XObject".to_vec(), Object::Dict(xobjects)); } + if !properties.is_empty() { + res.set(b"Properties".to_vec(), Object::Dict(properties)); + } let mut cd = Dict::new(); cd.set(b"Type".to_vec(), Object::name("XObject")); let contents = self.doc.add(Object::Stream(Stream::flate(Dict::new(), &content))); @@ -714,6 +795,7 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result // Pictures embedded by earlier passes, from the pages this pass replaces. let images = earlier_images(doc, pages_ref); let signed = signed_fields(doc, &catalog); + let groups = earlier_groups(doc, &catalog); let mut em = Emitter { doc, images, @@ -723,6 +805,8 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result field_count: 0, warnings: Vec::new(), signed, + groups, + used: [false; 2], }; let mut kids = Vec::new(); for page in &form.pages { @@ -738,7 +822,11 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result } })?; } - let Emitter { doc, fields, field_count, warnings, .. } = em; + let Emitter { doc, fields, field_count, warnings, groups, used, .. } = em; + let drawn: Vec = groups.iter().zip(used).filter(|(_, u)| *u).filter_map(|(g, _)| *g).collect(); + if !drawn.is_empty() { + catalog_changed |= register_groups(doc, &mut catalog, &groups, used)?; + } let count = kids.len(); doc.update_dict(pages_ref, |d| { d.set(b"Type".to_vec(), Object::name("Pages")); @@ -792,6 +880,126 @@ pub fn write_form(doc: &mut Document, form: &Form) -> Result Ok(Written { pages: count, fields: field_count, warnings }) } +/// The screen-only and print-only groups an earlier layout of the form made ([`RELEVANT_KEY`]), +/// found among the document's optional content groups. +fn earlier_groups(doc: &Document, catalog: &Dict) -> [Option; 2] { + let mut out = [None; 2]; + let ocgs = catalog + .get(b"OCProperties") + .map(|p| doc.resolve(p)) + .and_then(|p| p.as_dict().and_then(|p| p.get(b"OCGs").map(|o| doc.resolve(o)))) + .and_then(|o| o.as_array().cloned()) + .unwrap_or_default(); + for r in ocgs.iter().filter_map(Object::as_ref).take(MAX_GROUPS_SEARCHED) { + let key = doc.get(r).as_dict().and_then(|d| d.name(RELEVANT_KEY).map(<[u8]>::to_vec)); + if let Some(g) = key.and_then(|k| GROUPS.iter().position(|(name, ..)| name.as_bytes() == k.as_slice())) + && let Some(slot) = out.get_mut(g) + && slot.is_none() + { + *slot = Some(r); + } + } + out +} + +/// Most optional content groups looked at for an earlier layout's. +const MAX_GROUPS_SEARCHED: usize = 10_000; + +/// Add the screen-only and print-only `groups` this layout drew in (`used`) to the document's +/// optional content properties, keeping its own layers as they are: each goes in `/OCGs`; in the +/// default configuration the print-only one starts off (the screen-only one starts on when the +/// base state is off); and both join `/AS` usage applications for the View and Print events (an +/// existing one for that event and category, or a new one), so a viewer shows each where it +/// belongs. Nothing already there is added again. Returns whether `catalog` itself changed (a +/// direct `/OCProperties`); an indirect one is updated where it is. +fn register_groups(doc: &mut Document, catalog: &mut Dict, groups: &[Option; 2], used: [bool; 2]) -> Result { + let mine: Vec<(usize, ObjRef)> = + groups.iter().zip(used).enumerate().filter(|(_, (_, u))| *u).filter_map(|(i, (g, _))| g.map(|r| (i, r))).collect(); + let indirect = catalog.get(b"OCProperties").and_then(Object::as_ref); + let mut props = catalog.get(b"OCProperties").map(|p| doc.resolve(p)).and_then(|p| p.as_dict().cloned()).unwrap_or_default(); + // A list in `dict` under `key` (direct or not), with `add` appended where missing. + let add_refs = |doc: &mut Document, dict: &mut Dict, key: &[u8], add: &[ObjRef]| -> Result<(), XfaError> { + let at = dict.get(key).and_then(Object::as_ref); + let mut list = dict.get(key).map(|l| doc.resolve(l)).and_then(|l| l.as_array().cloned()).unwrap_or_default(); + for r in add { + if !list.iter().any(|o| o.as_ref() == Some(*r)) { + list.push(Object::Ref(*r)); + } + } + match at { + Some(a) => doc.set(a, Object::Array(list)), + None => dict.set(key.to_vec(), Object::Array(list)), + } + Ok(()) + }; + let all: Vec = mine.iter().map(|(_, r)| *r).collect(); + add_refs(doc, &mut props, b"OCGs", &all)?; + let d_at = props.get(b"D").and_then(Object::as_ref); + let mut d = props.get(b"D").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default(); + let base_off = d.name(b"BaseState") == Some(&b"OFF"[..]); + for (g, r) in &mine { + match (*g, base_off) { + (1, false) => add_refs(doc, &mut d, b"OFF", &[*r])?, + (0, true) => add_refs(doc, &mut d, b"ON", &[*r])?, + _ => {} + } + } + // The usage applications: one per event, with its own category. + let as_at = d.get(b"AS").and_then(Object::as_ref); + let mut apps = d.get(b"AS").map(|x| doc.resolve(x)).and_then(|x| x.as_array().cloned()).unwrap_or_default(); + for event in ["View", "Print"] { + let matches = |doc: &Document, o: &Object| { + doc.resolve(o).as_dict().is_some_and(|a| { + a.name(b"Event") == Some(event.as_bytes()) + && a.get(b"Category") + .map(|c| doc.resolve(c)) + .and_then(|c| c.as_array().cloned()) + .is_some_and(|c| c.len() == 1 && c.first().and_then(Object::as_name).is_some_and(|n| n == event.as_bytes())) + }) + }; + match apps.iter().position(|o| matches(doc, o)) { + Some(i) => { + let entry = apps.get(i).cloned().unwrap_or(Object::Null); + let mut app = doc.resolve(&entry).as_dict().cloned().unwrap_or_default(); + add_refs(doc, &mut app, b"OCGs", &all)?; + match entry.as_ref() { + Some(r) => doc.set(r, Object::Dict(app)), + None => { + if let Some(slot) = apps.get_mut(i) { + *slot = Object::Dict(app); + } + } + } + } + None => { + let mut app = Dict::new(); + app.set(b"Event".to_vec(), Object::name(event)); + app.set(b"OCGs".to_vec(), Object::Array(all.iter().map(|r| Object::Ref(*r)).collect())); + app.set(b"Category".to_vec(), Object::Array(vec![Object::name(event)])); + apps.push(Object::Dict(app)); + } + } + } + match as_at { + Some(a) => doc.set(a, Object::Array(apps)), + None => d.set(b"AS".to_vec(), Object::Array(apps)), + } + match d_at { + Some(a) => doc.set(a, Object::Dict(d)), + None => props.set(b"D".to_vec(), Object::Dict(d)), + } + match indirect { + Some(r) => { + doc.set(r, Object::Dict(props)); + Ok(false) + } + None => { + catalog.set(b"OCProperties".to_vec(), Object::Dict(props)); + Ok(true) + } + } +} + /// What [`strip`] took out, for the user to be told (the packets held more than the fields). #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Stripped { @@ -975,6 +1183,12 @@ pub fn strip(doc: &mut Document) -> Result { None => catalog.set(b"AcroForm".to_vec(), Object::Dict(acro)), } catalog.remove(b"NeedsRendering"); + // The screen-only and print-only layers stay, as the pages use them; only their key goes. + for r in earlier_groups(doc, &catalog).into_iter().flatten() { + doc.update_dict(r, |d| { + d.remove(RELEVANT_KEY); + })?; + } // Reader usage rights are void once the form changed: Reader says so on opening the file // and drops them, so they go now, with a note. if let Some(perms) = catalog.get(b"Perms").map(|p| doc.resolve(p)) diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 411529b177..899b667edc 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -350,6 +350,192 @@ fn form_text_the_standard_fonts_cannot_draw_is_reported() { assert!(!render_into(&mut doc).unwrap().warnings.iter().any(|w| w.contains("standard fonts"))); } +/// A template whose page shows objects only on screen (`relevant="-print"`), only in print +/// (`presence="invisible" relevant="+print"`) and everywhere, as fields and as draws, some of +/// them inside a screen-only subform. `others` is put in the catalog (its own layers). +fn relevant_template() -> String { + let field = |name: &str, attrs: &str| { + format!(r#"{name}"#) + }; + let draw = |name: &str, attrs: &str| format!(r#"{name} text"#); + format!( + r##" +"##, + field("everywhere", ""), + field("screenOnly", r#"relevant="-print""#), + field("printOnly", r#"presence="invisible" relevant="+print""#), + field("nowhere", r#"presence="invisible""#), + draw("shown", ""), + draw("screenDraw", r#"relevant="-print""#), + draw("paperDraw", r#"presence="invisible" relevant="+print""#), + draw("otherView", r#"relevant="-screen""#), + field("inScreenBox", ""), + field("printInScreenBox", r#"relevant="+print""#), + ) +} + +/// `relevant` decides printing (`+print` prints even what its presence hides on screen, `-print` +/// never prints) and presence decides the screen, inside containers too: a field's widget says +/// where it shows, and a draw shown only on screen or only in print is wrapped as such. A token +/// about another view is left aside with one warning. +#[test] +fn relevant_and_presence_say_where_fields_and_draws_show() { + let form = layout_xml(&relevant_template()).unwrap(); + let page = &form.pages[0]; + let views_of = |name: &str| widgets(page).iter().find(|w| w.name == name).map(|w| w.views); + let (screen, print) = (Views { screen: true, print: false }, Views { screen: false, print: true }); + assert_eq!(views_of("everywhere"), Some(Views::ALL)); + assert_eq!(views_of("screenOnly"), Some(screen)); + assert_eq!(views_of("printOnly"), Some(print), "an invisible field that +print prints is drawn for print only"); + assert_eq!(views_of("nowhere"), None, "an invisible field is still drawn nowhere"); + assert_eq!(views_of("inScreenBox"), Some(screen), "inside a screen-only subform"); + assert_eq!(views_of("printInScreenBox"), Some(screen), "+print can't print what its container keeps off paper"); + // Draws: wrapped where they show only on screen or only in print. + let text = |want: &str| { + page.items.iter().find_map(|i| match i { + Item::Text(s) if s.text.contains(want) => Some(Views::ALL), + Item::Only { views, item } => matches!(item.as_ref(), Item::Text(s) if s.text.contains(want)).then_some(*views), + _ => None, + }) + }; + assert_eq!(text("shown text"), Some(Views::ALL)); + assert_eq!(text("screenDraw text"), Some(screen)); + assert_eq!(text("paperDraw text"), Some(print)); + assert_eq!(text("otherView text"), Some(Views::ALL), "a view other than print is left aside"); + let warned: Vec<&String> = form.warnings.iter().filter(|w| w.contains("relevant")).collect(); + assert_eq!(warned.len(), 1, "{:?}", form.warnings); + assert!(warned[0].contains("-screen"), "{warned:?}"); +} + +/// A master page's own objects show where they say, even when the page was started by a +/// screen-only subform that ran onto it: its footer isn't made screen-only too. +#[test] +fn a_master_page_started_by_a_screen_only_subform_keeps_its_own_objects_everywhere() { + let rows: String = (0..30).map(|i| format!(r#"Row {i}"#)).collect(); + let xdp = format!( + r##" +"## + ); + let form = layout_xml(&xdp).unwrap(); + assert!(form.pages.len() >= 2, "{} pages", form.pages.len()); + for (i, page) in form.pages.iter().enumerate() { + let footer = page.items.iter().any(|it| matches!(it, Item::Text(s) if s.text.contains("Footer"))); + assert!(footer, "page {i}'s footer shows everywhere, not wrapped as screen-only"); + assert!(page.items.iter().any(|it| matches!(it, Item::Only { .. })), "page {i} has the screen-only rows"); + } +} + +/// The widgets' annotation flags, the draws' optional content and the catalog's layers: shown +/// everywhere prints (`/F 4`), screen only doesn't print (`/F 0`), print only is NoView too +/// (`/F 36`); screen-only and print-only draws are marked content in groups whose `/Usage` and the +/// default configuration's `/AS` say where they show, the print-only one off on screen; the +/// document's own layer stays as it was; and laying the form out again adds nothing twice. +#[test] +fn screen_only_and_print_only_objects_are_written_with_flags_and_layers() { + let xdp = relevant_template(); + let mut bytes = shell(&xdp); + // A layer of the document's own, off, listed in /Order. + let s = String::from_utf8_lossy(&bytes).into_owned(); + let s = s.replacen( + "/AcroForm << /XFA 5 0 R /Fields [] >> >>", + "/AcroForm << /XFA 5 0 R /Fields [] >> /OCProperties << /OCGs [<< /Type /OCG /Name (Mine) >>] /D << /Order [] /OFF [] >> >> >>", + 1, + ); + assert_ne!(s.as_bytes(), bytes.as_slice(), "the shell's catalog was found"); + bytes = s.into_bytes(); + let mut doc = Document::open(Arc::new(bytes)).unwrap(); + render_into(&mut doc).unwrap(); + let check = |doc: &Document| { + // Widget flags by field name. + let catalog = doc.get(doc.root().unwrap()); + let acro = doc.resolve(catalog.as_dict().unwrap().get(b"AcroForm").unwrap()); + let fields = doc.resolve(acro.as_dict().unwrap().get(b"Fields").unwrap()).as_array().unwrap().clone(); + let flags: std::collections::BTreeMap = fields + .iter() + .map(|f| doc.resolve(f)) + .filter_map(|f| { + let d = f.as_dict()?; + Some((d.get(b"T").and_then(Object::as_string)?.to_text(), d.int(b"F").unwrap_or(-1))) + }) + .collect(); + assert_eq!(flags.get("everywhere"), Some(&4)); + assert_eq!(flags.get("screenOnly"), Some(&0)); + assert_eq!(flags.get("printOnly"), Some(&36)); + // The groups, the configuration and the usage applications. + let props = doc.resolve(catalog.as_dict().unwrap().get(b"OCProperties").unwrap()).as_dict().unwrap().clone(); + let ocgs = doc.resolve(props.get(b"OCGs").unwrap()).as_array().unwrap().clone(); + assert_eq!(ocgs.len(), 3, "the document's own layer and the two groups, each once"); + let mine = doc.resolve(ocgs.first().unwrap()); + assert_eq!(mine.as_dict().unwrap().get(b"Name").and_then(Object::as_string).map(|s| s.to_text()).as_deref(), Some("Mine")); + let group = |key: &[u8]| { + ocgs.iter() + .filter_map(Object::as_ref) + .find(|r| doc.get(*r).as_dict().is_some_and(|d| d.name(crate::pdf::RELEVANT_KEY) == Some(key))) + .unwrap() + }; + let (screen, print) = (group(b"Screen"), group(b"Print")); + let state = |r: pdfcraft_cos::ObjRef, event: &[u8], key: &[u8]| { + let g = doc.get(r); + let usage = g.as_dict().unwrap().get(b"Usage").unwrap().as_dict().unwrap().clone(); + usage.get(event).unwrap().as_dict().unwrap().name(key).unwrap().to_vec() + }; + assert_eq!((state(screen, b"View", b"ViewState"), state(screen, b"Print", b"PrintState")), (b"ON".to_vec(), b"OFF".to_vec())); + assert_eq!((state(print, b"View", b"ViewState"), state(print, b"Print", b"PrintState")), (b"OFF".to_vec(), b"ON".to_vec())); + let d = doc.resolve(props.get(b"D").unwrap()).as_dict().unwrap().clone(); + let refs = |o: Option<&Object>| doc.resolve(o.unwrap()).as_array().unwrap().iter().filter_map(Object::as_ref).collect::>(); + assert_eq!(refs(d.get(b"OFF")), [print], "only the print-only group starts off"); + assert!(refs(d.get(b"Order")).is_empty(), "the document's /Order is left as it was"); + let apps = doc.resolve(d.get(b"AS").unwrap()).as_array().unwrap().clone(); + assert_eq!(apps.len(), 2, "one usage application per event"); + for (app, event) in apps.iter().zip([&b"View"[..], b"Print"]) { + let app = doc.resolve(app).as_dict().unwrap().clone(); + assert_eq!(app.name(b"Event"), Some(event)); + assert_eq!(refs(app.get(b"OCGs")), [screen, print]); + } + // The page's marked content and resources. + let kids = doc + .resolve(doc.resolve(catalog.as_dict().unwrap().get(b"Pages").unwrap()).as_dict().unwrap().get(b"Kids").unwrap()) + .as_array() + .unwrap() + .clone(); + let page = doc.resolve(kids.first().unwrap()).as_dict().unwrap().clone(); + let res = doc.resolve(page.get(b"Resources").unwrap()).as_dict().unwrap().clone(); + let properties = res.get(b"Properties").unwrap().as_dict().unwrap().clone(); + assert_eq!((properties.reference(b"PCXfaScreen"), properties.reference(b"PCXfaPrint")), (Some(screen), Some(print))); + let Object::Stream(c) = &*doc.resolve(page.get(b"Contents").unwrap()) else { panic!("a content stream") }; + let ops = String::from_utf8_lossy(&c.decoded().unwrap()).into_owned(); + let inside = |group: &str, text: &str| { + let start = ops.find(&format!("/OC /{group} BDC")).unwrap_or(usize::MAX); + let at = ops.find(text).unwrap_or(0); + let end = ops.get(start.min(ops.len())..).and_then(|rest| rest.find("EMC")).map(|e| start + e).unwrap_or(0); + start < at && at < end + }; + assert!(inside("PCXfaScreen", "(screenDraw text)") && inside("PCXfaPrint", "(paperDraw text)"), "{ops}"); + // Shown everywhere: outside any marked content (here, before the first). + assert!(ops.find("(shown text)") < ops.find("/OC /"), "{ops}"); + }; + check(&doc); + // Laid out again: the same groups, nothing added twice. + let (tpl, _) = parse(&xdp).unwrap(); + rerender(&mut doc, &tpl).unwrap(); + check(&doc); + // Stripping the XFA keeps the layers the pages use, without PdfCraft's key. + strip(&mut doc).unwrap(); + let catalog = doc.get(doc.root().unwrap()); + let props = doc.resolve(catalog.as_dict().unwrap().get(b"OCProperties").unwrap()).as_dict().unwrap().clone(); + let ocgs = doc.resolve(props.get(b"OCGs").unwrap()).as_array().unwrap().clone(); + assert_eq!(ocgs.len(), 3); + assert!(ocgs.iter().all(|g| !doc.resolve(g).as_dict().unwrap().contains(crate::pdf::RELEVANT_KEY))); +} + #[test] fn documents_without_xfa_are_not_touched() { let mut doc = Document::new_empty(); diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 4ec39848c5..9e388d0f7b 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5249,8 +5249,8 @@ milestone = "M12" status = "partial" commands = ["file.open"] tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run"] -evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn"] -notes = "Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, captions, rich text, JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes, radio groups, drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; metrics are approximate and Acrobat fidelity is eyeballed on real forms, not measured (#60)" +evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/xfa/src/tests.rs::relevant_and_presence_say_where_fields_and_draws_show", "crates/xfa/src/tests.rs::screen_only_and_print_only_objects_are_written_with_flags_and_layers", "crates/xfa/src/tests.rs::a_master_page_started_by_a_screen_only_subform_keeps_its_own_objects_everywhere", "crates/engine/src/tests.rs::xfa_screen_only_and_print_only_objects_show_and_print_where_the_form_says"] +notes = "Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, captions, objects shown only on screen or only in print (relevant -print and +print, inside containers too: fields by their annotation flags, draws in optional content groups whose view and print usage say so; PdfCraft's own printing doesn't yet apply a layer's print usage, so a screen-only or print-only draw prints as it shows on screen, and a hidden object relevant prints isn't laid out), rich text, JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes, radio groups, drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; metrics are approximate and Acrobat fidelity is eyeballed on real forms, not measured (#60)" [[feature]] id = "form.xfa-formcalc" From c65ede1d85921251911f0d1247306edc76c8dd5c Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:09:48 -0400 Subject: [PATCH 022/359] M12: fill in page counts inside screen- or print-only text, and warn about other views on flowed subforms and rows --- crates/xfa/src/layout.rs | 30 ++++++++++++++++++++++-------- crates/xfa/src/tests.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 8 deletions(-) diff --git a/crates/xfa/src/layout.rs b/crates/xfa/src/layout.rs index c5f2449bd0..25db6e2e0c 100644 --- a/crates/xfa/src/layout.rs +++ b/crates/xfa/src/layout.rs @@ -292,16 +292,22 @@ pub fn layout(tpl: &Template, data: Option<&DataNode>) -> Result let count = total.to_string(); for p in &mut l.pages { for it in &mut p.items { - if let Item::Text(s) = it - && s.text.contains(PAGE_COUNT_MARK) - { - s.text = s.text.replace(PAGE_COUNT_MARK, &count); - } + fill_page_count(it, &count); } } Ok(Form { pages: l.pages, fields: l.fields, warnings: l.warnings }) } +/// Put the page count `count` where text `it` holds [`PAGE_COUNT_MARK`], text drawn only on +/// screen or only in print ([`Item::Only`]) included. +fn fill_page_count(it: &mut Item, count: &str) { + match it { + Item::Text(s) if s.text.contains(PAGE_COUNT_MARK) => s.text = s.text.replace(PAGE_COUNT_MARK, count), + Item::Only { item, .. } => fill_page_count(item, count), + _ => {} + } +} + // Bytes of embedded field values copied out on this thread, for tests that bound layout work. #[cfg(test)] thread_local! { @@ -516,6 +522,14 @@ impl Layouter<'_> { } } + /// Say once when `c`'s `relevant` names a view other than print, which is drawn as if it + /// didn't: for drawn objects, flowed subforms and table rows alike. + fn warn_other_views(&mut self, c: &Common) { + if let Some(other) = &c.relevant_other { + self.warn_once(format!("the form limits some objects to views other than print (relevant \"{other}\"); they are drawn as if it didn't")); + } + } + fn page_no(&self) -> usize { self.pages.len() } @@ -820,6 +834,7 @@ impl Layouter<'_> { /// Flow subform `node` (each instance the data asks for) into the content areas, shown where /// it and what it is inside say ([`Common::views`]); hidden from both, it still takes its room. fn flow_subform(&mut self, node: &Node, avail: Option<(f64, f64)>, ctx: &Ctx, depth: usize, sib: usize) -> Result<(), XfaError> { + self.warn_other_views(node.common()); let views = self.views.and(node.common().views()); let outer = std::mem::replace(&mut self.views, views); let flowed = self.flow_subform_in(node, avail, ctx, depth, sib); @@ -1333,6 +1348,7 @@ impl Layouter<'_> { if depth > MAX_DEPTH { return Ok(()); } + self.warn_other_views(&row.common); let views = self.views.and(row.common.views()); if !views.any() { return Ok(()); @@ -1379,9 +1395,7 @@ impl Layouter<'_> { return Ok(()); } let c = node.common(); - if let Some(other) = &c.relevant_other { - self.warn_once(format!("the form limits some objects to views other than print (relevant \"{other}\"); they are drawn as if it didn't")); - } + self.warn_other_views(c); let views = self.views.and(c.views()); if !views.any() { return Ok(()); diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 899b667edc..e6cad95523 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -411,6 +411,46 @@ fn relevant_and_presence_say_where_fields_and_draws_show() { assert!(warned[0].contains("-screen"), "{warned:?}"); } +/// A page count shown only on screen or only in print is filled in like any other, and a view +/// other than print named on a flowed subform or a table row is warned about as on a draw. +#[test] +fn restricted_page_counts_are_filled_in_and_other_views_warned_about_everywhere() { + let xfa_ns = r#"xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/""#; + let body = format!( + r##" + +

Pages:

+
+ + Flowed + Cell +
"## + ); + let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap(); + let texts: Vec = form.pages[0] + .items + .iter() + .filter_map(|i| match i { + Item::Only { item, .. } => match item.as_ref() { + Item::Text(s) => Some(s.text.clone()), + _ => None, + }, + _ => None, + }) + .collect(); + assert!(texts.iter().any(|t| t.contains("Pages:") && t.contains('1')), "{texts:?}"); + assert!( + form.pages + .iter() + .flat_map(|p| &p.items) + .all(|i| !matches!(i, Item::Only { item, .. } if matches!(item.as_ref(), Item::Text(s) if s.text.contains('\u{E000}')))), + "no page-count mark left" + ); + for token in ["-screen", "-preview"] { + assert!(form.warnings.iter().any(|w| w.contains(token)), "{token}: {:?}", form.warnings); + } +} + /// A master page's own objects show where they say, even when the page was started by a /// screen-only subform that ran onto it: its footer isn't made screen-only too. #[test] From 214a5b5978271a45ccf9631b17059c2b0f11c760 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:20:49 -0400 Subject: [PATCH 023/359] M12: an exclusion group's buttons show where each one's relevant and presence say --- crates/xfa/src/layout.rs | 14 +++++++++++++- crates/xfa/src/tests.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/xfa/src/layout.rs b/crates/xfa/src/layout.rs index 25db6e2e0c..f85bc56cb3 100644 --- a/crates/xfa/src/layout.rs +++ b/crates/xfa/src/layout.rs @@ -1588,6 +1588,8 @@ impl Layouter<'_> { } } + /// Draw exclusion group `g` at `rect`: its border, then each of its buttons where its layout + /// puts it, as one radio group, the one its data selects turned on. fn draw_group(&mut self, g: &ExclGroup, rect: Rect, ctx: &Ctx, depth: usize, sib: usize) -> Result<(), XfaError> { if let Some(b) = &g.common.border { self.draw_border(b, rect)?; @@ -1629,10 +1631,20 @@ impl Layouter<'_> { let sibs = SomIndices::of(&nodes); for (i, r) in placed { if let Some(f) = g.fields.get(i) { + // Each button shows where it and the group say ([`Common::views`]), as any field + // drawn through [`Self::draw_node`] does. + self.warn_other_views(&f.common); + let views = self.views.and(f.common.views()); + if !views.any() { + continue; + } let on = f.items.first().cloned().filter(|s| !s.trim().is_empty()).unwrap_or_else(|| (i + 1).to_string()); let tip = f.tooltip.clone().or_else(|| g.tooltip.clone()); let chosen = selected.as_deref() == Some(on.as_str()); - self.draw_field(f, Rect::new(inner.x + r.x, inner.y + r.y, r.w, r.h), &ctx, Some((&group, &on, tip, chosen)), sibs.at(i))?; + let outer = std::mem::replace(&mut self.views, views); + let drawn = self.draw_field(f, Rect::new(inner.x + r.x, inner.y + r.y, r.w, r.h), &ctx, Some((&group, &on, tip, chosen)), sibs.at(i)); + self.views = outer; + drawn?; } } Ok(()) diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index e6cad95523..5972381015 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -411,6 +411,38 @@ fn relevant_and_presence_say_where_fields_and_draws_show() { assert!(warned[0].contains("-screen"), "{warned:?}"); } +/// The buttons of an exclusion group show where each one's own `relevant` and presence say, +/// inside what the group says, as other fields do; a view other than print is warned about. +#[test] +fn exclusion_group_buttons_show_where_each_says() { + let button = |name: &str, on: &str, attrs: &str| { + format!(r#"{on}"#) + }; + let body = format!( + r#" + {}{}{}{}{} + {} + "#, + button("plain", "1", ""), + button("screenOnly", "2", r#"relevant="-print""#), + button("printOnly", "3", r#"presence="invisible" relevant="+print""#), + button("nowhere", "4", r#"presence="invisible""#), + button("otherView", "5", r#"relevant="-preview""#), + button("printInScreenGroup", "1", r#"relevant="+print""#), + ); + let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap(); + let views_of = |name: &str| widgets(&form.pages[0]).iter().find(|w| w.som.ends_with(&format!(".{name}[0]"))).map(|w| w.views); + let (screen, print) = (Views { screen: true, print: false }, Views { screen: false, print: true }); + assert_eq!(views_of("plain"), Some(Views::ALL)); + assert_eq!(views_of("screenOnly"), Some(screen)); + assert_eq!(views_of("printOnly"), Some(print), "an invisible button that +print prints is drawn for print only"); + assert_eq!(views_of("nowhere"), None, "an invisible button is drawn nowhere"); + assert_eq!(views_of("otherView"), Some(Views::ALL), "a view other than print is left aside"); + assert_eq!(views_of("printInScreenGroup"), Some(screen), "+print can't print what its group keeps off paper"); + let warned: Vec<&String> = form.warnings.iter().filter(|w| w.contains("relevant")).collect(); + assert!(warned.len() == 1 && warned[0].contains("-preview"), "{:?}", form.warnings); +} + /// A page count shown only on screen or only in print is filled in like any other, and a view /// other than print named on a flowed subform or a table row is warned about as on a draw. #[test] From 23e1821144b1c265123518f1baa4d07a7a8c4a58 Mon Sep 17 00:00:00 2001 From: Eric Kaden <608341+EricKaden@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:34:12 -0400 Subject: [PATCH 024/359] M12: XFA enter and exit scripts run whenever a field gains or loses focus A field's exit scripts run each time it loses focus, changed or not, and its enter scripts each time it gains it (Session::field_focus, the app's per-frame focus check, and the form_focus tool). Scripts that change nothing leave no edit; an exit its value change already ran is not run again; a radio button runs its own scripts. --- crates/automation/src/a11y.rs | 26 ++++++++ crates/automation/src/lib.rs | 1 + crates/automation/src/tools.rs | 14 ++++ crates/automation/tests/it/automation.rs | 43 +++++++++++++ crates/engine/src/js.rs | 39 +++++++++++ crates/engine/src/lib.rs | 33 ++++++++-- crates/engine/src/tests.rs | 82 ++++++++++++++++++++++++ crates/engine/src/xfa.rs | 54 +++++++++++++++- crates/ui-egui/src/editing.rs | 34 ++++++++++ crates/ui-egui/src/forms_ui.rs | 4 ++ crates/ui-egui/tests/it/xfa.rs | 42 ++++++++++++ crates/xfa/src/fixtures.rs | 37 +++++++++++ crates/xfa/src/lib.rs | 2 +- crates/xfa/src/script.rs | 21 ++++++ crates/xfa/src/tests.rs | 23 +++++++ parity/acrobat-features.toml | 6 +- 16 files changed, 450 insertions(+), 11 deletions(-) diff --git a/crates/automation/src/a11y.rs b/crates/automation/src/a11y.rs index a7334f2069..c70bac2016 100644 --- a/crates/automation/src/a11y.rs +++ b/crates/automation/src/a11y.rs @@ -696,6 +696,32 @@ impl Automation { Ok(json!({ "field": a.str("field")?, "event": a.str("event")?, "console": out.console, "errors": out.errors })) } + /// `form_focus`: field `field` (its 1-based `widget`) gains (`enter`) or loses (`exit`) + /// focus, running its XFA scripts for that event; returns whether the form changed and what + /// the scripts showed or asked for. + pub(crate) fn form_focus(&mut self, a: &Args) -> Result { + use pdfcraft_engine::js::FieldFocus; + let focus = match a.str("event")? { + "enter" => FieldFocus::Enter, + "exit" => FieldFocus::Exit, + other => return Err(ToolError::InvalidArgs(format!("event must be enter or exit, not {other:?}"))), + }; + let name = a.str("field")?; + let doc = self.doc(a)?; + let field = doc.form.iter().find(|f| f.name == name).ok_or_else(|| failed(format!("there is no field named {name:?} (see form_fields)")))?; + let widget = a.opt_int("widget")?.unwrap_or(1); + let widget = usize::try_from(widget) + .ok() + .and_then(|w| w.checked_sub(1)) + .filter(|w| *w < field.widgets.len().max(1)) + .ok_or_else(|| ToolError::InvalidArgs(format!("widget must be 1 to {} for {name:?}", field.widgets.len().max(1))))?; + let id = doc.id; + let changed = self.session.field_focus(id, name, widget, focus).map_err(failed)?; + let out = self.session.take_js_output(id); + let reqs: Vec = out.requests.iter().map(request_json).collect(); + Ok(json!({ "changed": changed, "alerts": out.alerts, "console": out.console, "requests": reqs, "errors": out.errors })) + } + pub(crate) fn form_merge_data(&mut self, a: &Args) -> Result { let mut files = Vec::new(); for p in a.strs("paths")? { diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 1dae412e41..29d780b5ef 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -801,6 +801,7 @@ impl Automation { } "form_fields" => self.form_fields(&a)?, "form_fill" => self.form_fill(&a)?, + "form_focus" => self.form_focus(&a)?, "form_set_image" => { let path = self.resolve(a.str("path")?, false)?; let bytes = std::fs::read(&path).map_err(|e| failed(format!("{}: {e}", path.display())))?; diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 1e009c1170..65aaac2cc5 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -358,6 +358,20 @@ pub fn tools() -> Vec { "Set several fields at once (one undo step). values maps field names (from form_fields) to: a string for text fields, combo boxes and radio groups (an option), true/false for check boxes, an array of strings for multi-select lists. Appearances are regenerated so every viewer shows the values. A value whose characters the field's font can't draw (Chinese in a Helvetica field) is still saved; `warnings` in the result names the field and character: PdfCraft draws `?` there and asks other viewers to redraw the field from its value.", ) .with(schema(json!({ "doc": doc(), "values": { "type": "object", "description": "Field name → value." } }), &["doc", "values"])), + t( + "form_focus", + "Move the focus into or out of a field", + "A field gains (event enter) or loses (event exit) focus, as when someone clicks or tabs into or out of it, and the dynamic XFA form's enter or exit scripts for it run (other forms have none, and nothing happens). widget picks the radio button or copy of the field (1-based, default 1; see form_fields). What the scripts change is one undoable edit, and none when they change nothing. Changing a field's value (form_fill) runs its exit scripts already, so the next exit of that field doesn't run them again. Returns changed, and the scripts' alerts, console output, requests and errors.", + ) + .with(schema( + json!({ + "doc": doc(), + "field": { "type": "string", "description": "Field name (from form_fields)." }, + "event": { "type": "string", "enum": ["enter", "exit"] }, + "widget": { "type": "integer", "minimum": 1, "description": "Widget of the field (1-based, default 1): a radio button of the group, or a copy of the field." }, + }), + &["doc", "field", "event"], + )), t("form_reset", "Clear form", "Reset fields to their default values: all of them, or only those listed. Undoable.") .destructive() .with(schema(json!({ "doc": doc(), "fields": { "type": "array", "items": { "type": "string" } } }), &["doc"])), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 9fd5c4269a..a2c0c216c5 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -6803,6 +6803,49 @@ fn repeated_xfa_print_buttons_work_through_tools_and_after_reopen() { check(&mut a, doc); } +/// form_focus runs a field's XFA enter and exit scripts on every focus change; scripts that +/// change nothing leave no edit, a radio button's own scripts run for its widget, and unknown +/// fields, widgets and events are refused. +#[test] +fn xfa_focus_scripts_run_through_form_focus() { + let dir = workdir("xfa-focus"); + std::fs::write(dir.join("focus.pdf"), pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::focus_template())).unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "focus.pdf" }))["doc"].as_u64().unwrap(); + let value = |a: &mut Automation, n: &str| { + let f = ok(a, "form_fields", json!({ "doc": doc })); + f["fields"].as_array().unwrap().iter().find(|f| f["name"] == n).map(|f| f["value"].clone()).unwrap() + }; + for _ in 0..3 { + assert_eq!(ok(&mut a, "form_focus", json!({ "doc": doc, "field": "probe", "event": "enter" }))["changed"], true); + assert_eq!(ok(&mut a, "form_focus", json!({ "doc": doc, "field": "probe", "event": "exit" }))["changed"], true); + } + assert_eq!((value(&mut a, "enters"), value(&mut a, "exits")), (json!("3"), json!("3"))); + ok(&mut a, "edit_undo", json!({ "doc": doc })); + assert_eq!(value(&mut a, "exits"), "2", "each run is one undo step"); + // A script that only shows a message changes nothing: no edit (the document stays saved and + // what was undone can still be redone), and the message comes back. + ok(&mut a, "doc_save", json!({ "doc": doc, "path": "saved.pdf" })); + let quiet = ok(&mut a, "form_focus", json!({ "doc": doc, "field": "quiet", "event": "exit" })); + assert_eq!((quiet["changed"].clone(), quiet["alerts"].clone()), (json!(false), json!(["left quiet"])), "{quiet}"); + let state = &ok(&mut a, "doc_info", json!({ "doc": doc }))["document"]; + assert_eq!((state["dirty"].clone(), state["redo"].clone()), (json!(false), json!("Run form script")), "{state}"); + // The second radio button has an enter script of its own. + let fields = ok(&mut a, "form_fields", json!({ "doc": doc })); + let group = fields["fields"].as_array().unwrap().iter().find(|f| f["type"] == "radio").unwrap()["name"].clone(); + assert_eq!(ok(&mut a, "form_focus", json!({ "doc": doc, "field": group, "event": "enter" }))["changed"], false); + assert_eq!(ok(&mut a, "form_focus", json!({ "doc": doc, "field": group, "event": "enter", "widget": 2 }))["changed"], true); + assert_eq!(value(&mut a, "picks"), "1"); + for bad in [ + json!({ "doc": doc, "field": "nowhere", "event": "enter" }), + json!({ "doc": doc, "field": group, "event": "enter", "widget": 3 }), + json!({ "doc": doc, "field": "probe", "event": "enter", "widget": 0 }), + json!({ "doc": doc, "field": "probe", "event": "click" }), + ] { + assert!(a.call("form_focus", &bad).is_err(), "{bad}"); + } +} + #[test] fn xfa_scripts_run_for_buttons_and_field_changes_through_tools() { let dir = workdir("xfa-scripts"); diff --git a/crates/engine/src/js.rs b/crates/engine/src/js.rs index a59743dbbb..f3f3a581a6 100644 --- a/crates/engine/src/js.rs +++ b/crates/engine/src/js.rs @@ -11,6 +11,15 @@ pub use pdfcraft_js::{Limits, Outcome, Request}; use crate::{DocId, Edit, EditError, Session}; +/// A field gaining or losing focus ([`Session::field_focus`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FieldFocus { + /// The field gained focus: its `enter` scripts run. + Enter, + /// The field lost focus: its `exit` scripts run. + Exit, +} + /// What scripts produced for the viewer since it last looked. #[derive(Clone, Debug, Default, PartialEq)] pub struct JsOutput { @@ -221,6 +230,36 @@ impl Session { self.docs.iter_mut().find(|d| d.id == id).map(|d| std::mem::take(&mut d.js_output)).unwrap_or_default() } + /// Widget `widget` of field `name` in document `id` gained or lost focus: on a laid-out XFA form, + /// run the field's `enter` or `exit` scripts, as one undoable edit when they change something + /// (and none when they don't). An exit that the field's new value already ran (the value's + /// change runs it) isn't run a second time. Returns whether the document changed; what the + /// scripts showed or asked for is in [`Session::take_js_output`]. + pub fn field_focus(&mut self, id: DocId, name: &str, widget: usize, focus: FieldFocus) -> Result { + if self.js_off { + return Ok(false); + } + let doc = self.doc_mut(id)?; + let Some(tpl) = doc.xfa_template.clone().filter(|t| pdfcraft_xfa::has_focus_scripts(t)) else { return Ok(false) }; + let Some(cos) = doc.editor.as_ref().map(|e| &e.cos) else { return Ok(false) }; + let Some(som) = doc.form.iter().find(|f| f.name == name).and_then(|f| crate::xfa::widget_som(cos, f, widget)) else { return Ok(false) }; + let activity = match focus { + FieldFocus::Enter => "enter", + FieldFocus::Exit => "exit", + }; + if !crate::xfa::has_event(cos, &tpl, &som, activity) { + doc.xfa_exited.remove(&som); + return Ok(false); + } + // Gaining focus starts afresh; losing it runs the exit unless the change just did. + if doc.xfa_exited.remove(&som) && focus == FieldFocus::Exit { + return Ok(false); + } + let before = doc.generation; + self.apply(id, Edit::XfaEvent { som, activity: activity.into() })?; + Ok(self.get(id).is_some_and(|d| d.generation != before)) + } + /// Run `script` in document `id`, for a button (`target`: the field, event "Mouse Up") or /// the console (no target). Field changes and `resetForm` are applied as one undoable step; /// everything else the script asked for is returned. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68fc076b97..14c2e93d23 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -428,6 +428,10 @@ pub struct Document { xfa_template: Option>, /// A script of the XFA form ran away, so its scripts are off (see [`Document::xfa_scripts_off`]). xfa_scripts_off: bool, + /// SOM paths of the XFA fields whose exit scripts ran with a value change ([`xfa::on_changes`]) + /// since they last gained focus: their exit on losing focus has run already + /// ([`Session::field_focus`]). + xfa_exited: std::collections::HashSet, /// A content-only refresh keeps `info` from before the edit; an edit may have added or /// embedded fonts, so the font list is read again on demand ([`Session::refresh_fonts`]). fonts_stale: bool, @@ -2385,6 +2389,8 @@ struct EditCtx { xfa_datasets: Option, /// A form script ran too long and was abandoned: the document's scripts go off. xfa_ran_away: bool, + /// An XFA enter or exit event whose scripts changed nothing: no edit to keep. + xfa_unchanged: bool, /// The edit took the XFA out of the form: what went with it, for the document's warnings. xfa_removed: Vec, /// Pages in the document, for `xfa.layout.pageCount()`. @@ -2419,6 +2425,7 @@ impl EditCtx { xfa_out: Default::default(), xfa_datasets: None, xfa_ran_away: false, + xfa_unchanged: false, xfa_removed: Vec::new(), pages: 0, date: now.map(pdfcraft_cos::pdf_date), @@ -2585,10 +2592,14 @@ fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Edit::XfaEvent { som, activity } => { let tpl = cx.xfa.clone().ok_or_else(|| EditError::Invalid("this is not a laid-out XFA form, or JavaScript is off".into()))?; let mut run = xfa::XfaRun { page_count: cx.pages, out: &mut cx.xfa_out, datasets: cx.xfa_datasets, ran_away: false }; - let ran = xfa::on_event(doc, &tpl, som, activity, &mut run); + let ran = if matches!(activity.as_str(), "enter" | "exit") { + xfa::on_focus(doc, &tpl, som, activity, &mut run).map(|changes| changes.is_empty()) + } else { + xfa::on_event(doc, &tpl, som, activity, &mut run).map(|()| false) + }; cx.xfa_datasets = run.datasets; cx.xfa_ran_away |= run.ran_away; - ran.map_err(EditError::Invalid)?; + cx.xfa_unchanged = ran.map_err(EditError::Invalid)?; } Edit::SetFieldImage { name, image } => { let (img, _) = embed_image(doc, name, image)?; @@ -3789,6 +3800,7 @@ impl Session { xfa, xfa_template: None, xfa_scripts_off: false, + xfa_exited: Default::default(), fonts_stale: false, xfa_warnings: Vec::new(), edit_notices: Vec::new(), @@ -3851,6 +3863,17 @@ impl Session { // `next` is a copy: if the edit fails or crashes, the document is unchanged. guard(|| run_edit(&mut next, &edit, &mut cx)) .unwrap_or_else(|m| Err(EditError::Invalid(format!("{} failed unexpectedly ({m}); the document was not changed", edit.label()))))?; + // A field's enter or exit scripts that changed nothing leave no edit behind (no undo step, + // nothing unsaved); what they showed or asked for still goes out. + if cx.xfa_unchanged { + doc.js_output.append(cx.xfa_out); + if cx.xfa_ran_away { + doc.xfa_template = None; + doc.xfa_scripts_off = true; + doc.js_output.errors.push(XFA_SCRIPTS_OFF.into()); + } + return Ok(()); + } // Redaction removed what its own interpreter places under the marks. The marks were drawn // over the page as the renderer shows it, so the renderer has the last word. if let Edit::ApplyRedactions { pages } = &edit { @@ -3889,7 +3912,8 @@ impl Session { }; // An XFA form's scripts answer the change: exit and validate scripts of the field, then // every calculation (and a reset recalculates). They read the data, so it is brought up - // to date first. + // to date first. The fields whose exit scripts ran are noted once the edit is kept. + let mut exited: Vec = Vec::new(); if let Some(tpl) = cx.xfa.clone() { if is_xfa && matches!(scope_of(&edit), Scope::Form | Scope::Full | Scope::Content) { let datasets = &mut cx.xfa_datasets; @@ -3913,7 +3937,7 @@ impl Session { let mut run = xfa::XfaRun { page_count: cx.pages, out: &mut cx.xfa_out, datasets: cx.xfa_datasets, ran_away: false }; // Every changed field's scripts, then the calculations once (after a reset, // only those). - let ran = guard(|| xfa::on_changes(&mut next, &tpl, &changed, &mut run)) + let ran = guard(|| xfa::on_changes(&mut next, &tpl, &changed, &mut run, &mut exited)) .unwrap_or_else(|m| Err(format!("the form's scripts failed unexpectedly ({m})"))); cx.xfa_datasets = run.datasets; cx.xfa_ran_away |= run.ran_away; @@ -3984,6 +4008,7 @@ impl Session { doc.dirty = true; doc.generation += 1; doc.edit_notices = notices; + doc.xfa_exited.extend(exited); if !cx.xfa_removed.is_empty() { let removed: Vec = cx.xfa_removed.iter().map(|n| format!("{XFA_REMOVED_PREFIX}{n}")).collect(); doc.xfa_warnings.retain(|w| w.starts_with(XFA_REMOVED_PREFIX)); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ed4e6efa1c..d928e429ce 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4675,6 +4675,88 @@ fn measurement_edits_are_transactional_and_honour_annotation_permissions() { ); } +/// The synthetic focus form ([`pdfcraft_xfa::fixtures::focus_template`]). +fn focus_form() -> Arc> { + Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::focus_template())) +} + +/// The value of field `name` in document `id`. +fn field_text(s: &Session, id: DocId, name: &str) -> String { + s.get(id).and_then(|d| d.form.iter().find(|f| f.name == name).and_then(|f| f.value.first().cloned())).unwrap_or_default() +} + +/// A field's exit scripts run every time it loses focus, changed or not, and its enter scripts +/// every time it gains it; each run that changes the form is one undo step. +#[test] +fn xfa_enter_and_exit_scripts_run_on_every_focus_change() { + use crate::js::FieldFocus::{Enter, Exit}; + let mut s = Session::new(); + let id = s.open("form.pdf", None, focus_form(), None).expect("opens"); + for _ in 0..3 { + assert!(s.field_focus(id, "probe", 0, Enter).unwrap(), "the enter script counted"); + assert!(s.field_focus(id, "probe", 0, Exit).unwrap(), "the exit script counted"); + } + assert_eq!((field_text(&s, id, "exits"), field_text(&s, id, "enters")), ("3".into(), "3".into())); + assert!(s.get(id).unwrap().dirty); + s.undo(id).unwrap(); + assert_eq!(field_text(&s, id, "exits"), "2", "each run is its own undo step"); +} + +/// A value typed into a field runs its exit with the change; losing focus then doesn't run it +/// again. The next visit runs it as usual. +#[test] +fn an_exit_the_fields_change_ran_does_not_run_twice() { + use crate::js::FieldFocus::{Enter, Exit}; + let mut s = Session::new(); + let id = s.open("form.pdf", None, focus_form(), None).expect("opens"); + s.field_focus(id, "probe", 0, Enter).unwrap(); + s.apply(id, Edit::SetFieldValue { name: "probe".into(), value: FieldValue::Text("x".into()) }).unwrap(); + assert_eq!(field_text(&s, id, "exits"), "1", "the change ran the exit"); + assert!(!s.field_focus(id, "probe", 0, Exit).unwrap(), "not again on losing focus"); + assert_eq!(field_text(&s, id, "exits"), "1"); + s.field_focus(id, "probe", 0, Enter).unwrap(); + s.field_focus(id, "probe", 0, Exit).unwrap(); + assert_eq!(field_text(&s, id, "exits"), "2", "the next visit's exit runs"); +} + +/// Scripts that change nothing leave no edit: the document stays saved, with nothing to undo, +/// and what they showed still reaches the viewer. A field without such scripts runs nothing. +#[test] +fn focus_scripts_that_change_nothing_leave_the_document_clean() { + use crate::js::FieldFocus::{Enter, Exit}; + let mut s = Session::new(); + let id = s.open("form.pdf", None, focus_form(), None).expect("opens"); + s.field_focus(id, "quiet", 0, Enter).unwrap(); + assert!(!s.field_focus(id, "quiet", 0, Exit).unwrap(), "nothing changed"); + let doc = s.get(id).unwrap(); + assert!(!doc.dirty && doc.can_undo().is_none(), "no edit kept"); + let out = s.take_js_output(id); + assert_eq!(out.alerts.iter().map(String::as_str).collect::>(), ["left quiet"]); + // A field without focus scripts, and a field that doesn't exist. + assert!(!s.field_focus(id, "exits", 0, Exit).unwrap()); + assert!(!s.field_focus(id, "nowhere", 0, Enter).unwrap()); + assert!(!s.get(id).unwrap().dirty); +} + +/// Each radio button of a group is a field of its own: reaching the second button runs its +/// enter script, reaching the first (which has none) runs nothing. Choosing the button changes +/// the group's value, which runs the group's scripts, not the button's: leaving the button +/// still runs its exit. +#[test] +fn a_radio_buttons_own_focus_scripts_run() { + use crate::js::FieldFocus::{Enter, Exit}; + let mut s = Session::new(); + let id = s.open("form.pdf", None, focus_form(), None).expect("opens"); + let group = s.get(id).unwrap().form.iter().find(|f| f.widgets.len() == 2).map(|f| f.name.clone()).expect("the radio group"); + assert!(!s.field_focus(id, &group, 0, Enter).unwrap(), "the first button has no enter script"); + assert!(s.field_focus(id, &group, 1, Enter).unwrap(), "the second button's ran"); + assert!(!s.field_focus(id, &group, 2, Enter).unwrap(), "there is no third button"); + assert_eq!(field_text(&s, id, "picks"), "1"); + s.apply(id, Edit::SetFieldValue { name: group.clone(), value: FieldValue::Radio(Some("L".into())) }).unwrap(); + assert!(s.field_focus(id, &group, 1, Exit).unwrap(), "the button's exit runs on leaving it"); + assert_eq!(field_text(&s, id, "drops"), "1"); +} + #[test] fn dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally() { let original = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::template(3))); diff --git a/crates/engine/src/xfa.rs b/crates/engine/src/xfa.rs index 6ce76548f5..8743ac94ed 100644 --- a/crates/engine/src/xfa.rs +++ b/crates/engine/src/xfa.rs @@ -826,14 +826,24 @@ pub(crate) fn on_open(doc: &mut pdfcraft_cos::Document, tpl: &Template, run: &mu /// After fields `names` took new values: each one's change, exit and validate scripts, then /// the calculations once (or only those, after a reset). A validate script that answers false, /// or fails, shows its message; the value stays, as Acrobat marks the field invalid rather -/// than reverting it. -pub(crate) fn on_changes(doc: &mut pdfcraft_cos::Document, tpl: &Template, names: &[String], run: &mut XfaRun) -> Result<(), String> { +/// than reverting it. The SOM paths whose exit scripts ran go into `exited`. +pub(crate) fn on_changes( + doc: &mut pdfcraft_cos::Document, + tpl: &Template, + names: &[String], + run: &mut XfaRun, + exited: &mut Vec, +) -> Result<(), String> { let mut r = Runner::new(doc, tpl, run, OPEN_BUDGET_MS); for name in names { let som = r.by_som().iter().find(|(_, f)| *f == name).map(|(s, _)| s.clone()); let Some(som) = som else { continue }; let value = r.fields().get(name).map(|f| f.value.join("\n")).unwrap_or_default(); - for ev in r.events_of(&som, "change").into_iter().chain(r.events_of(&som, "exit")) { + let exits = r.events_of(&som, "exit"); + if !exits.is_empty() { + exited.push(som.clone()); + } + for ev in r.events_of(&som, "change").into_iter().chain(exits) { r.run(&ev, &value)?; } for ev in r.events_of(&som, "validate") { @@ -874,6 +884,44 @@ pub(crate) fn on_event(doc: &mut pdfcraft_cos::Document, tpl: &Template, som: &s r.finish().map(|_| ()) } +/// A field gaining (`enter`) or losing (`exit`) focus: its scripts for that activity, then, when +/// they changed something, the calculations. Returns what changed; nothing (and no error) when +/// the field has no such script, so a focus change with nothing to run leaves the form alone. +pub(crate) fn on_focus(doc: &mut pdfcraft_cos::Document, tpl: &Template, som: &str, activity: &str, run: &mut XfaRun) -> Result { + let mut r = Runner::new(doc, tpl, run, EVENT_BUDGET_MS); + let events = r.events_of(som, activity); + if events.is_empty() { + return Ok(Changes::default()); + } + // The field's value, as the script's event sees it (`xfa.event.prevText`, `newText`). + let value = r.by_som().get(som).cloned().and_then(|name| r.fields().get(&name).map(|f| f.value.join("\n"))).unwrap_or_default(); + for ev in events { + r.run(&ev, &value)?; + } + if !r.changes.is_empty() { + // The calculations that follow get a budget of their own. + r.clock = Clock::start(OPEN_BUDGET_MS); + r.calculates()?; + } + r.finish() +} + +/// The SOM path of widget `widget` of field `field`: each radio button of a group has its own, +/// and a field's copies on several pages share one. +pub(crate) fn widget_som(doc: &pdfcraft_cos::Document, field: &pdfcraft_forms::Field, widget: usize) -> Option { + let som_of = |obj: pdfcraft_cos::ObjRef| { + let object = doc.get(obj); + object.as_dict()?.get(pdfcraft_xfa::SOM_KEY).map(|s| doc.resolve(s))?.as_string().map(|s| s.to_text()) + }; + field.widgets.get(widget).and_then(|w| som_of(w.obj)).or_else(|| som_of(field.obj)) +} + +/// Does the live form give SOM path `som` an `activity` script? +pub(crate) fn has_event(doc: &pdfcraft_cos::Document, tpl: &Template, som: &str, activity: &str) -> bool { + let live = pdfcraft_xfa::form_tree(tpl, pdfcraft_xfa::data_of(doc).as_ref(), &pdfcraft_xfa::overrides(doc)); + live.events.iter().any(|e| e.som == som && e.activity == activity) +} + /// The SOM path of a generated field whose template has a click script. pub(crate) fn clickable_som(doc: &pdfcraft_cos::Document, tpl: &Template, field: &pdfcraft_forms::Field) -> Option { // Page-master copies have distinct PDF field names but share a SOM path. Reversing diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 2fdc2e9d02..5e64b1e8dc 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -252,6 +252,9 @@ impl PdfCraftApp { pub(crate) fn process_pending_edits(&mut self) -> bool { let Some(i) = self.active else { return true }; let applied = self.apply_queued_edit(i); + // After the queued edit: a value typed into the field the focus left has been taken (and + // its change has run the field's exit) before the focus scripts run. + self.run_focus_scripts(i); if !applied { // Nor may a shortcut pressed with it (⌘S right after Enter) run behind the refusal. self.deferred_commands.clear(); @@ -467,6 +470,37 @@ impl PdfCraftApp { false } + /// XFA enter and exit scripts for where the focus went on tab `i` since it was last looked at, + /// however it moved (a click, Tab or Shift+Tab, Escape, a click on the page, a script): the + /// field it left runs its exit, then the field it reached runs its enter. The engine skips an + /// exit the field's committed change already ran. A tab that closes runs nothing: its + /// document is going away, and a script changing it then would only ask to save it. + fn run_focus_scripts(&mut self, i: usize) { + let Some(view) = self.views.get_mut(i) else { return }; + let now = view.forms.focus.as_ref().map(|f| (f.name.clone(), f.widget)); + if view.forms.focused == now { + return; + } + let left = std::mem::replace(&mut view.forms.focused, now.clone()); + let id = view.id; + use pdfcraft_engine::js::FieldFocus; + for ((name, widget), focus) in [left.map(|l| (l, FieldFocus::Exit)), now.map(|n| (n, FieldFocus::Enter))].into_iter().flatten() { + match self.session.field_focus(id, &name, widget, focus) { + Ok(changed) => { + if changed + && let Some(info) = self.session.get(id).map(|d| d.info.clone()) + && let Some(view) = self.views.get_mut(i) + { + view.document_changed(&info); + } + let out = self.session.take_js_output(id); + self.handle_js(id, out); + } + Err(e) => self.notify_error(e), + } + } + } + /// Apply the edit queued on tab `i` (the active one). Returns false only when it was a /// field's typing and the field refused it (#166): the editor reopens with the text, and the /// user has been told why, so the typing isn't lost and the caller can stop. diff --git a/crates/ui-egui/src/forms_ui.rs b/crates/ui-egui/src/forms_ui.rs index 76e0926721..42754753aa 100644 --- a/crates/ui-egui/src/forms_ui.rs +++ b/crates/ui-egui/src/forms_ui.rs @@ -67,6 +67,10 @@ pub struct FormView { /// The widget holding egui's keyboard focus for the focused check box or radio button, and /// whether it takes the arrows (radio buttons). The page keys still work around it. pub(crate) keys: Option<(egui::Id, bool)>, + /// The field and widget that had focus when it was last looked at: when the focus moves, the + /// one it left runs its XFA exit scripts and the one it reached its enter scripts + /// (`PdfCraftApp::run_focus_scripts`). + pub(crate) focused: Option<(String, usize)>, } /// A form message for the app to show, with document data kept separate so the visible diff --git a/crates/ui-egui/tests/it/xfa.rs b/crates/ui-egui/tests/it/xfa.rs index e66658b0e1..7ac6deea67 100644 --- a/crates/ui-egui/tests/it/xfa.rs +++ b/crates/ui-egui/tests/it/xfa.rs @@ -146,6 +146,48 @@ fn xfa_buttons_run_their_scripts_in_the_app() { assert!(h.query_by_label_contains("Hello 2").is_some(), "script console: {:?}", h.state().js_console.log); } +/// Every way the focus moves (a click, Tab, Shift+Tab, Escape) runs the field it left's exit +/// script and the field it reached's enter script, changed or not; typing a change and tabbing +/// out runs the exit once, not twice. A script's message shows as a notice. +#[test] +fn xfa_enter_and_exit_scripts_run_whenever_the_focus_moves() { + use egui::{Key, Modifiers}; + let mut h = open(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::focus_template())); + wait_for_pages(&mut h); + let counts = |h: &Harness<'static, PdfCraftApp>| { + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + let v = |n: &str| doc.form.iter().find(|f| f.name == n).and_then(|f| f.value.first().cloned()).unwrap_or_default(); + (v("enters"), v("exits")) + }; + let focus = |h: &Harness<'static, PdfCraftApp>| h.state().views[0].forms.focus.as_ref().map(|f| f.name.clone()); + let press = |h: &mut Harness<'static, PdfCraftApp>, modifiers, key| { + h.key_press_modifiers(modifiers, key); + h.run_steps(4); + }; + click_field(&mut h, "probe"); + assert_eq!(counts(&h), ("1".into(), "0".into()), "a click in runs the enter"); + for _ in 0..2 { + press(&mut h, Modifiers::NONE, Key::Tab); + assert_eq!(focus(&h).as_deref(), Some("quiet")); + press(&mut h, Modifiers::SHIFT, Key::Tab); + assert_eq!(focus(&h).as_deref(), Some("probe")); + } + press(&mut h, Modifiers::NONE, Key::Escape); + assert_eq!(focus(&h), None); + assert_eq!(counts(&h), ("3".into(), "3".into()), "three unchanged visits, three exits; console: {:?}", h.state().js_console.log); + // A change typed in: tabbing out runs the exit once. + click_field(&mut h, "probe"); + h.event(egui::Event::Text("typed".into())); + h.run_steps(2); + press(&mut h, Modifiers::NONE, Key::Tab); + assert_eq!(counts(&h), ("4".into(), "4".into())); + // Leaving `quiet` shows its message. + assert_eq!(focus(&h).as_deref(), Some("quiet")); + press(&mut h, Modifiers::NONE, Key::Escape); + assert!(h.query_by_label_contains("left quiet").is_some(), "console: {:?}", h.state().js_console.log); +} + #[test] fn messages_from_scripts_run_on_open_show_right_away() { let tpl = pdfcraft_xfa::fixtures::scripted_template() diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs index a0307a6944..7ca2d9d0c4 100644 --- a/crates/xfa/src/fixtures.rs +++ b/crates/xfa/src/fixtures.rs @@ -658,3 +658,40 @@ if (this.rawValue == "1") { "## .to_string() } + +/// A form whose text field `probe` counts its enters in `enters` and its exits in `exits`, whose +/// text field `quiet` only shows a message when it is left, and whose radio button `size.large` +/// counts its enters in `picks` and its exits in `drops` (each button of a radio group is a field +/// with scripts of its own). +pub fn focus_template() -> String { + let js = "application/x-javascript"; + let count = |name: &str| format!(r#""#); + let counter = |name: &str| { + format!(r#"0"#) + }; + format!( + r##" + + + +"##, + count("enters"), + count("exits"), + count("picks"), + count("drops"), + counter("exits"), + counter("enters"), + counter("picks"), + counter("drops") + ) +} diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs index 93e668257f..3ccefe3c71 100644 --- a/crates/xfa/src/lib.rs +++ b/crates/xfa/src/lib.rs @@ -101,7 +101,7 @@ pub use parse::{measure, parse}; pub use pdf::{CLICK_KEY, LAYOUT_KEY, SOM_KEY, Stripped, XfaShape, existing_layout, strip, xfa_shape}; pub use script::{ FormNode, LiveForm, MAX_FORM_NODES, NodeKind, OVERRIDES_KEY, Overrides, ScriptEvent, apply_overrides, data_of, field_grows_with_text, - fields_by_som, form_tree, has_scripts, overrides, refresh_value, rerender, set_overrides, template_of, + fields_by_som, form_tree, has_focus_scripts, has_scripts, overrides, refresh_value, rerender, set_overrides, template_of, }; #[derive(Debug, thiserror::Error)] diff --git a/crates/xfa/src/script.rs b/crates/xfa/src/script.rs index cb555dc81d..2bc1f2f8ad 100644 --- a/crates/xfa/src/script.rs +++ b/crates/xfa/src/script.rs @@ -459,6 +459,27 @@ pub fn has_scripts(tpl: &Template) -> bool { any(&tpl.root.scripts) || walk(&tpl.root.children, 1) || tpl.root.page_set.as_ref().is_some_and(|ps| ps.areas.iter().any(|a| walk(&a.items, 1))) } +/// Does any field of the template (in the body, an exclusion group or a master page) have an +/// `enter` or `exit` script? Forms without one have nothing to run when the focus moves. +pub fn has_focus_scripts(tpl: &Template) -> bool { + /// Has field `f` a non-blank enter or exit script? + fn field(f: &Field) -> bool { + f.scripts.iter().any(|s| matches!(s.activity.as_str(), "enter" | "exit") && !s.text.trim().is_empty()) + } + /// Has any field among `nodes` (and their containers, `depth` levels down) one? + fn walk(nodes: &[Node], depth: usize) -> bool { + depth <= MAX_DEPTH + && nodes.iter().any(|n| match n { + Node::Subform(sf) => walk(&sf.children, depth + 1), + Node::Area(a) => walk(&a.children, depth + 1), + Node::Field(f) => field(f), + Node::ExclGroup(g) => g.fields.iter().any(field), + Node::Draw(_) => false, + }) + } + walk(&tpl.root.children, 1) || tpl.root.page_set.as_ref().is_some_and(|ps| ps.areas.iter().any(|a| walk(&a.items, 1))) +} + /// The template with `ov` applied to its objects (instance 0 of each; scripts that hide one /// instance of a repeating subform hide them all). pub fn apply_overrides(tpl: &Template, ov: &Overrides) -> Template { diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 411529b177..4b9e11de3a 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -2832,3 +2832,26 @@ fn long_names_repeated_by_an_index_are_capped() { let data = build_data(&doc, &fields); assert!(data.len() < 2_000_000, "{} bytes of data built", data.len()); } + +/// Forms with an `enter` or `exit` script, in the body, a radio group or a page master, have +/// something to run when the focus moves; forms with other scripts only, or blank ones, don't. +#[test] +fn focus_scripts_are_found_wherever_the_template_has_them() { + let has = |xml: &str| has_focus_scripts(&parse(xml).unwrap().0); + assert!(has(&crate::fixtures::focus_template())); + let clicks = + crate::fixtures::focus_template().replace(r#"activity="enter""#, r#"activity="click""#).replace(r#"activity="exit""#, r#"activity="click""#); + assert!(!has(&clicks), "click scripts only"); + let large = r#"L