diff --git a/crates/xfa/src/layout.rs b/crates/xfa/src/layout.rs index 7527caab89..34fe7f29f9 100644 --- a/crates/xfa/src/layout.rs +++ b/crates/xfa/src/layout.rs @@ -897,6 +897,8 @@ impl Layouter<'_> { } } + /// The width and height `node` takes in `avail_w`: its own size, else what its content needs + /// (containers are measured once per width and depth, and measuring stops at its caps). fn size_of(&self, node: &Node, avail_w: f64, ctx: &Ctx, depth: usize) -> (f64, f64) { let c = node.common(); let spent = self.measures.get().saturating_add(1); @@ -928,6 +930,9 @@ impl Layouter<'_> { size } + /// The size (width, height) of `node` within `avail_w`, uncached ([`Self::size_of`] caches it). + /// Without a width, a container, a text draw or a button is as wide as its content (at most + /// `avail_w`) and anything else takes `avail_w`; without a height, it is as tall as its content. fn measure(&self, node: &Node, avail_w: f64, ctx: &Ctx, depth: usize) -> (f64, f64) { let c = node.common(); // The node's own SOM: its repeating children count their instances under it, and a @@ -936,7 +941,8 @@ impl Layouter<'_> { let ctx = ctx.with_som(c, 0); let som = ctx.som.clone(); // A container without a width is as wide as its content (a radio group beside its - // question, say); a leaf without one takes what is available. + // question, say), and so is a text label or a button (as wide as its caption), within + // what is available; any other field without one takes what is available. let w = match c.w { Some(w) => w, None => match node { @@ -944,7 +950,13 @@ impl Layouter<'_> { let inner = (avail_w - c.margin.horizontal()).max(1.0); (self.content_width(node, inner, &ctx, depth) + c.margin.horizontal()).min(avail_w) } - Node::Field(_) | Node::Draw(_) => avail_w, + Node::Draw(d) => self.natural_width(&d.value, &ctx.font, &ctx.para).map_or(avail_w, |t| (t + c.margin.horizontal()).min(avail_w)), + Node::Field(f) if f.ui == Ui::Button => f + .caption + .as_ref() + .and_then(|cap| self.natural_width(&cap.value, &ctx.font.apply(&cap.font), &ctx.para.apply(&cap.para))) + .map_or(avail_w, |t| (t + c.margin.horizontal() + f.ui_margin.horizontal()).min(avail_w)), + Node::Field(_) => avail_w, }, }; let w = clamp_opt(w, c.min_w, c.max_w); @@ -1028,6 +1040,22 @@ impl Layouter<'_> { } } + /// How wide text `v` is unwrapped, in `font` and `para`, with a hair to spare so that laying + /// it out at that width keeps it on its lines; `None` for what isn't text, or text that draws + /// nothing. + fn natural_width(&self, v: &Value, font: &Font, para: &Para) -> Option { + let rich = match v { + Value::Text(t) => text::plain(t), + Value::Rich(r) => r.clone(), + _ => return None, + }; + // No text (a bordered spacer or rule): nothing to size to, so it keeps what it has room for. + let w = text::natural_width(&rich, para, &Face::of(font), &|id| self.embed(id)); + (w > 0.0).then_some(w + 0.01) + } + + /// How tall value `v` is laid out `w` wide: text wrapped in the context's font and paragraph, + /// an image at its aspect ratio, and nothing for lines, rectangles and empty values. fn value_height(&self, v: &Value, w: f64, ctx: &Ctx) -> f64 { match v { Value::Text(t) => text::measure_height(&text::plain(t), w, &ctx.para, &Face::of(&ctx.font), &|id| self.embed(id)), @@ -1037,6 +1065,8 @@ impl Layouter<'_> { } } + /// Where field `f`'s caption goes and how much room it takes from the field's box, or `None` + /// when it has no caption that takes room (a button's is drawn inside its box). fn caption_reserve(&self, f: &Field, inner_w: f64, ctx: &Ctx) -> Option<(Placement, f64)> { let cap = f.caption.as_ref()?; if !cap.presence.occupies() || f.ui == Ui::Button { @@ -1061,11 +1091,26 @@ impl Layouter<'_> { Some((placement, reserve)) } + /// The height of field `f`'s content within `inner_w` (inside its margins): its widget (a check + /// box, a button's caption, or one line of text or three when multi-line, more for a text field + /// that grows) plus a caption above or below it, or the taller of the two for one beside it. fn field_height(&self, f: &Field, inner_w: f64, ctx: &Ctx) -> f64 { let font = ctx.font.apply(&f.common.font); let lines = if f.multiline { 3.0 } else { 1.0 }; let ui = match f.ui { Ui::CheckButton => f.check_size.unwrap_or(10.0).max(text::line_height(font.size)), + // A button shows its caption: as tall as the caption's text in its own font. + Ui::Button if f.caption.as_ref().is_some_and(|c| !c.value.is_empty()) => { + let cap = f.caption.as_ref().map_or(0.0, |c| { + let rich = match &c.value { + Value::Rich(r) => r.clone(), + other => text::plain(&other.plain().unwrap_or_default()), + }; + let w = (inner_w - f.ui_margin.horizontal()).max(1.0); + text::measure_height(&rich, w, &ctx.para.apply(&c.para), &Face::of(&ctx.font.apply(&c.font)), &|id| self.embed(id)) + }); + cap + f.ui_margin.vertical() + } _ => (text::line_height(font.size) * lines).max(self.grown_text_height(f, inner_w, ctx)) + 4.0 + f.ui_margin.vertical(), }; match self.caption_reserve(f, inner_w, ctx) { @@ -1473,6 +1518,8 @@ impl Layouter<'_> { self.push(Item::Image { rect: fitted, data: Arc::new(data.to_vec()), content_type: content_type.to_string() }) } + /// A field name made from `base` that no earlier field of the form has: the first keeps it, + /// later ones get `_2`, `_3`, …. fn unique_name(&mut self, base: &str) -> String { let base = clean_name(base); let n = self.names.entry(base.clone()).or_insert(0); @@ -1480,8 +1527,9 @@ impl Layouter<'_> { if *n == 1 { base } else { format!("{base}_{n}") } } - /// Lay out field `f` in `rect`: its caption, its widget of the right kind, and its value - /// from the data. + /// Draw field `f` at `rect`: its border (a button's is its widget's box), its caption, then its + /// widget, or its value as plain text when it is non-interactive, a barcode, or a text field + /// taller than its content area. `radio` is set for a group's radio button; `sib` is its SOM index. fn draw_field( &mut self, f: &Field, @@ -1658,13 +1706,13 @@ impl Layouter<'_> { } Ui::Button => { let caption = f.caption.as_ref().and_then(|c| c.value.plain()).unwrap_or_default().trim().to_string(); - // A button's box is its field border; without one it is invisible (a link - // over text, say). + // A button's box is its field border, around the whole field (its margins pad + // the caption, not the box); without one it is invisible (a link over text, say). let border = match &f.common.border { Some(b) => widget_border(Some(b), false), None => WidgetBorder { color: None, fill: None, shape: BorderShape::None, width: 0.0 }, }; - (WidgetKind::Button { caption }, ui, border, None, f.tooltip.clone()) + (WidgetKind::Button { caption }, rect, border, None, f.tooltip.clone()) } Ui::DateTimeEdit => { let pattern = date_pattern(f.picture.as_deref()); diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index 0d40418597..1413acb667 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -1367,6 +1367,112 @@ fn repeating_subforms_inside_positioned_content_get_their_instances() { assert!(((after.rect.y - rows[2].rect.y) - step).abs() < 0.01, "after: {:?}, last row: {:?}", after.rect, rows[2].rect); } +/// A positioned subform holding `body`, laid out; its page's items. +fn positioned(body: &str) -> Vec { + let xdp = format!( + r##""## + ); + layout_xml(&xdp).unwrap().pages.into_iter().next().unwrap().items +} + +/// A text draw without a width is as wide as its text, so right-aligned text starts at its x; a +/// minimum width wider than the text still wins, and text longer than the room left still wraps. +#[test] +fn a_label_without_a_width_is_as_wide_as_its_text() { + const TEXT: &str = "PERSONNEL ONLY: from date (YYYYMMDD):"; + let natural = pdfcraft_fonts::helvetica_width(TEXT, 8.0); + // Right-aligned, with a minimum narrower than the text: the box is as wide as the text and + // starts where it is placed, so the text does too (not at the far right of the subform). + let items = positioned(&format!( + r#"{TEXT}"# + )); + let span = items.iter().find_map(|i| if let Item::Text(s) = i { Some(s) } else { None }).expect("the text"); + assert!((span.x - (36.0 + 72.0)).abs() < 0.05, "starts at its x: {}", span.x); + // With a minimum wider than the text, the box is that wide and the text ends at its right. + let items = positioned(&format!( + r#"{TEXT}"#, + natural + 40.0 + )); + let span = items.iter().find_map(|i| if let Item::Text(s) = i { Some(s) } else { None }).expect("the text"); + assert!((span.x + span.face.width(&span.text) - (36.0 + 72.0 + natural + 40.0)).abs() < 0.05, "ends at its right: {}", span.x); + // Text longer than the room left still wraps at the container's width. + let long = "word ".repeat(200); + let items = positioned(&format!(r#"{long}"#)); + let lines: std::collections::BTreeSet = + items.iter().filter_map(|i| if let Item::Text(s) = i { Some((s.baseline * 100.0).round() as i64) } else { None }).collect(); + assert!(lines.len() > 1, "wraps: {} line(s)", lines.len()); + // And within the room it has: no line's drawn text runs past the subform's right edge. + let right = items + .iter() + .filter_map(|i| if let Item::Text(s) = i { Some(s.x + s.face.width(s.text.trim_end())) } else { None }) + .fold(f64::NEG_INFINITY, f64::max); + assert!(right <= 36.0 + 7.5 * 72.0 + 0.05, "the text stays within the available width: {right}"); +} + +/// A draw without a width and without text (a bordered spacer or rule) keeps the width it has +/// room for: with no text to size it to, it doesn't shrink to its margins. +#[test] +fn an_empty_draw_without_a_width_keeps_the_width_it_has_room_for() { + let items = positioned(r#""#); + let widest = + items.iter().filter_map(|i| if let Item::Line { from, to, .. } = i { Some((to.0 - from.0).abs()) } else { None }).fold(0.0_f64, f64::max); + assert!((widest - 540.0).abs() < 0.5, "the border spans the 7.5in box: {widest}"); +} + +/// A button without a width is as wide as its caption, not the subform it sits in, unless its +/// minimum width is wider. +#[test] +fn a_button_without_a_width_is_as_wide_as_its_caption() { + // No width, a minimum narrower than its caption: as wide as the caption, not the subform. + let caption = "Open the instructions for this form"; + let items = positioned(&format!( + r#"