Merge PR #3542: M12: XFA labels and buttons without a size grow to their content

crates/xfa/src/layout.rs: both sides added a draw_field doc comment; kept #3542's (the more complete one).
This commit is contained in:
aiongg committed 2026-10-22 01:46:05 +00:00
commit 8031d345d4
3 files changed
+169 -7

No files matched your search

+55 -7
View File
@@ -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<f64> {
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());
+106
View File
@@ -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<Item> {
let xdp = format!(
r##"<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
<subform name="form" layout="tb">
<pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<subform name="box" w="7.5in" h="3in">{body}</subform>
</subform>
</template></xdp:xdp>"##
);
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#"<draw name="a" x="1in" y="0" minW="50pt"><value><text>{TEXT}</text></value><font typeface="Arial" size="8pt"/><para hAlign="right"/></draw>"#
));
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#"<draw name="a" x="1in" y="0" minW="{}pt"><value><text>{TEXT}</text></value><font typeface="Arial" size="8pt"/><para hAlign="right"/></draw>"#,
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#"<draw name="a" x="0" y="0"><value><text>{long}</text></value><font typeface="Arial" size="8pt"/></draw>"#));
let lines: std::collections::BTreeSet<i64> =
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#"<draw name="rule" x="0" y="0" h="12pt"><value><text></text></value><border><edge thickness="1pt"/></border></draw>"#);
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#"<field name="help" x="1in" y="0" minW="40pt" minH="12pt"><ui><button/></ui><caption><value><text>{caption}</text></value><font typeface="Arial" size="8pt"/></caption></field>"#
));
let button = items.iter().find_map(|i| if let Item::Widget(w) = i { Some(w) } else { None }).expect("the button");
let natural = pdfcraft_fonts::helvetica_width(caption, 8.0);
assert!(button.rect.w >= natural && button.rect.w < natural + 10.0, "{} for a caption of {natural}", button.rect.w);
// A minimum wider than the caption wins.
let items = positioned(
r#"<field name="help" x="1in" y="0" minW="200pt" minH="12pt"><ui><button/></ui><caption><value><text>Help</text></value><font typeface="Arial" size="8pt"/></caption></field>"#,
);
let button = items.iter().find_map(|i| if let Item::Widget(w) = i { Some(w) } else { None }).expect("the button");
assert!((button.rect.w - 200.0).abs() < 0.05, "{}", button.rect.w);
}
/// A button without a height is as tall as one line of its caption in the caption's own font,
/// with none of a text field's padding, and never shorter than its minimum height.
#[test]
fn a_button_without_a_height_is_as_tall_as_its_caption() {
// A 10pt field font, an 8pt caption: the button is as tall as its caption's line (no
// text-field padding), and never below its minimum height.
let button = |min_h: &str| {
let items = positioned(&format!(
r#"<field name="help" x="1in" y="0" w="100pt" minH="{min_h}"><ui><button/></ui><font typeface="Times New Roman" size="10pt"/><caption><value><text>Help</text></value><font typeface="Arial" size="8pt"/></caption></field>"#
));
items.iter().find_map(|i| if let Item::Widget(w) = i { Some(w.rect.h) } else { None }).expect("the button")
};
assert!((button("2pt") - text::line_height(8.0)).abs() < 0.05, "{}", button("2pt"));
assert!((button("10.5pt") - 10.5).abs() < 0.05, "{}", button("10.5pt"));
}
/// A button's widget is its whole field, at the field's position and size: the field's margins
/// pad the caption, not the box.
#[test]
fn a_buttons_box_is_the_whole_field_whatever_its_margins() {
// The button's box is its field's border: its margins pad the caption, not the box.
let items = positioned(
r#"<field name="help" x="1in" y="10pt" w="100pt" h="20pt"><ui><button/></ui><margin topInset="5pt" leftInset="3pt"/><border><edge/></border><caption><value><text>Help</text></value><font typeface="Arial" size="8pt"/></caption></field>"#,
);
let button = items.iter().find_map(|i| if let Item::Widget(w) = i { Some(w.rect) } else { None }).expect("the button");
assert!((button.w - 100.0).abs() < 0.05 && (button.h - 20.0).abs() < 0.05, "{button:?}");
assert!((button.x - (36.0 + 72.0)).abs() < 0.05, "{button:?}");
}
/// A page area without an `<occur>` repeats for as long as the body needs pages. Before, it was
/// treated like a subform (at most once), so once the first body page was out the layout fell
/// back to the last page area, here one limited to a single use, and drew its content over every
+8
View File
@@ -280,6 +280,14 @@ pub fn layout(rich: &RichText, rect: Rect, para: &Para, base: &Face, embed: &dyn
Block { spans, height: total }
}
/// The width `rich` takes with no line wrapped (its longest paragraph, with the paragraph's
/// margins and first-line indent): how wide a box without an explicit width grows.
pub fn natural_width(rich: &RichText, para: &Para, base: &Face, embed: &dyn Fn(&str) -> String) -> f64 {
let indent = para.text_indent.max(0.0);
let widest = rich.paragraphs.iter().map(|p| words(&p.runs, base, embed).iter().map(|w| w.width).sum::<f64>()).fold(0.0, f64::max);
(para.margin_left + indent + widest + para.margin_right).max(0.0)
}
/// Height `rich` needs at `width` (for boxes without an explicit height).
pub fn measure_height(rich: &RichText, width: f64, para: &Para, base: &Face, embed: &dyn Fn(&str) -> String) -> f64 {
let p = Para { v_align: crate::model::VAlign::Top, ..para.clone() };