xfa-layout-engine 1.0.0-beta.3

Box-model and pagination layout engine for XFA forms. Experimental — part of the PDFluent XFA stack, under active development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Core types for XFA layout — Box Model, measurements, and layout primitives.
//!
//! Implements XFA 3.3 §4 (Box Model) types.

/// Shared default horizontal text padding, applied per side when paragraph
/// margins are not explicitly set.
pub const DEFAULT_TEXT_PADDING: f64 = 0.0;

/// A 2D point in layout coordinates (points, 1pt = 1/72 inch).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Point {
    pub x: f64,
    pub y: f64,
}

/// A 2D size in points.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Size {
    pub width: f64,
    pub height: f64,
}

/// An axis-aligned rectangle in layout space.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Rect {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

impl Rect {
    pub fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    pub fn right(&self) -> f64 {
        self.x + self.width
    }

    pub fn bottom(&self) -> f64 {
        self.y + self.height
    }

    /// Check whether a point (px, py) lies inside this rectangle.
    pub fn contains(&self, px: f64, py: f64) -> bool {
        px >= self.x && px <= self.right() && py >= self.y && py <= self.bottom()
    }
}

/// Inset values (margins, padding) for the four sides.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Insets {
    pub top: f64,
    pub right: f64,
    pub bottom: f64,
    pub left: f64,
}

impl Insets {
    pub fn uniform(value: f64) -> Self {
        Self {
            top: value,
            right: value,
            bottom: value,
            left: value,
        }
    }

    pub fn horizontal(&self) -> f64 {
        self.left + self.right
    }

    pub fn vertical(&self) -> f64 {
        self.top + self.bottom
    }
}

/// A measurement with a unit, parsed from XFA attributes.
///
/// XFA Spec 3.3 §2.2 (p36-38) — Measurements:
///   Absolute: in (inches, default), cm, mm, pt (1/72 inch).
///   Relative (XFA 2.8+): em (em width in current font), % (percentage of space width).
///   Note: bare numbers default to inches for dimensions but points for font sizes.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Measurement {
    pub value: f64,
    pub unit: MeasurementUnit,
}

impl Measurement {
    /// Convert this measurement to points (the internal unit).
    ///
    /// Note: `Em` and `Percent` are relative units that depend on the current
    /// font context. Here we use a default 12pt font for em and approximate
    /// percentage as a fraction of the default space width (~3pt at 12pt).
    pub fn to_points(&self) -> f64 {
        match self.unit {
            MeasurementUnit::Points => self.value,
            MeasurementUnit::Inches => self.value * 72.0,
            MeasurementUnit::Centimeters => self.value * 72.0 / 2.54,
            MeasurementUnit::Millimeters => self.value * 72.0 / 25.4,
            MeasurementUnit::Em => self.value * 12.0, // default 12pt font
            // XFA §2.2: % = percentage of space (U+0020) width in current font.
            // Approximate: space width ≈ 25% of em → 3pt at 12pt default.
            MeasurementUnit::Percent => self.value / 100.0 * 3.0,
        }
    }

    /// Parse a measurement string like "10mm", "1in", "72pt", "2.5cm".
    pub fn parse(s: &str) -> Option<Self> {
        let s = s.trim();
        if s.is_empty() {
            return None;
        }
        // Find where the numeric part ends
        let num_end = s
            .find(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
            .unwrap_or(s.len());
        let value: f64 = s[..num_end].parse().ok()?;
        let unit_str = s[num_end..].trim();
        let unit = match unit_str {
            "" | "in" => MeasurementUnit::Inches,
            "pt" => MeasurementUnit::Points,
            "cm" => MeasurementUnit::Centimeters,
            "mm" => MeasurementUnit::Millimeters,
            "em" => MeasurementUnit::Em,
            "%" => MeasurementUnit::Percent,
            _ => return None,
        };
        Some(Measurement { value, unit })
    }
}

impl Default for Measurement {
    fn default() -> Self {
        Self {
            value: 0.0,
            unit: MeasurementUnit::Points,
        }
    }
}

/// Units for measurements in XFA.
///
/// XFA Spec 3.3 §2.2 (p37) — Absolute: in, cm, mm, pt.
/// Relative (XFA 2.8+): em, % (percentage of space width in current font).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MeasurementUnit {
    Inches,
    Centimeters,
    Millimeters,
    Points,
    Em,
    /// Percentage of the width of a space (U+0020) in the current font.
    Percent,
}

/// Horizontal text alignment (XFA `<para hAlign>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextAlign {
    /// Left-aligned (default).
    #[default]
    Left,
    /// Centered.
    Center,
    /// Right-aligned.
    Right,
    /// Justified (treated as left for simple text rendering).
    Justify,
}

/// Layout strategy for a container.
///
/// XFA Spec 3.3 §2.6 (p43) — Two layout strategies:
///   Positioned: objects at fixed x,y coordinates (default for most containers).
///   Flowing: objects placed sequentially — tb, lr-tb, rl-tb, table, row.
///   pageArea always uses positioned layout only.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LayoutStrategy {
    /// Fixed x,y coordinates (default for subforms).
    #[default]
    Positioned,
    /// Top-to-bottom flow (layout="tb").
    TopToBottom,
    /// Left-to-right, top-to-bottom wrapping (layout="lr-tb").
    LeftToRightTB,
    /// Right-to-left, top-to-bottom wrapping (layout="rl-tb").
    RightToLeftTB,
    /// Table layout (layout="table").
    Table,
    /// Row within a table (layout="row").
    Row,
}

/// Vertical text alignment (XFA `<para vAlign>`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerticalAlign {
    #[default]
    Top,
    Middle,
    Bottom,
}

/// Caption placement relative to content.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CaptionPlacement {
    #[default]
    Left,
    Top,
    Right,
    Bottom,
    Inline,
}

/// The XFA Box Model for a form element.
///
/// XFA Spec 3.3 §2.6 (p49-50) — Nominal extent is w × h.
/// Inside: margins → border inset → caption region → content region.
/// The Nominal Content Region is the area after margins are applied.
///
/// §8 Growability (p275-276): a container is growable if it omits h and/or w:
/// - h=✓ w=✓ → fixed, not growable (minH/maxH/minW/maxW ignored)
/// - h=✓ w=∅ → growable along X only (minH/maxH ignored)
/// - h=∅ w=✓ → growable along Y only (minW/maxW ignored)
/// - h=∅ w=∅ → growable along both axes
///   Default: minH=0, minW=0, maxH=infinity, maxW=infinity.
///
/// See spec figure "Relationship between nominal extent and borders,
/// margins, captions, and content" (p50).
///
/// TODO(§2.6): border inset not modeled separately — currently merged with margins.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct BoxModel {
    /// Nominal width (None = growable).
    pub width: Option<f64>,
    /// Nominal height (None = growable).
    pub height: Option<f64>,
    /// Explicit x position (for positioned layout).
    pub x: f64,
    /// Explicit y position (for positioned layout).
    pub y: f64,
    /// Margins.
    pub margins: Insets,
    /// Border thickness (simplified to uniform for now).
    pub border_width: f64,
    /// Minimum width constraint.
    pub min_width: f64,
    /// Maximum width constraint.
    pub max_width: f64,
    /// Minimum height constraint.
    pub min_height: f64,
    /// Maximum height constraint.
    pub max_height: f64,
    /// Caption region.
    pub caption: Option<Caption>,
}

/// A caption for a form field.
#[derive(Debug, Clone, PartialEq)]
pub struct Caption {
    pub placement: CaptionPlacement,
    /// Reserved space for the caption (None = auto).
    pub reserve: Option<f64>,
    pub text: String,
}

impl BoxModel {
    /// The available content width after subtracting margins, borders, and caption.
    pub fn content_width(&self) -> f64 {
        let total = self.width.unwrap_or(self.max_width);
        let mut available = total - self.margins.horizontal() - self.border_width * 2.0;
        if let Some(ref cap) = self.caption {
            if matches!(
                cap.placement,
                CaptionPlacement::Left | CaptionPlacement::Right
            ) {
                available -= cap.reserve.unwrap_or(0.0);
            }
        }
        available.max(0.0)
    }

    /// The available content height after subtracting margins, borders, and caption.
    pub fn content_height(&self) -> f64 {
        let total = self.height.unwrap_or(self.max_height);
        let mut available = total - self.margins.vertical() - self.border_width * 2.0;
        if let Some(ref cap) = self.caption {
            if matches!(
                cap.placement,
                CaptionPlacement::Top | CaptionPlacement::Bottom
            ) {
                available -= cap.reserve.unwrap_or(0.0);
            }
        }
        available.max(0.0)
    }

    /// The outer extent (total bounding box).
    pub fn outer_size(&self, content: Size) -> Size {
        let mut w = content.width + self.margins.horizontal() + self.border_width * 2.0;
        let mut h = content.height + self.margins.vertical() + self.border_width * 2.0;
        if let Some(ref cap) = self.caption {
            match cap.placement {
                CaptionPlacement::Left | CaptionPlacement::Right => {
                    w += cap.reserve.unwrap_or(0.0);
                }
                CaptionPlacement::Top | CaptionPlacement::Bottom => {
                    h += cap.reserve.unwrap_or(0.0);
                }
                CaptionPlacement::Inline => {}
            }
        }
        // Apply min/max constraints
        if let Some(fixed_w) = self.width {
            w = fixed_w;
        } else {
            w = w.clamp(self.min_width, self.max_width);
        }
        if let Some(fixed_h) = self.height {
            h = fixed_h;
        } else {
            h = h.clamp(self.min_height, self.max_height);
        }
        Size {
            width: w,
            height: h,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn measurement_parse() {
        let m = Measurement::parse("10mm").unwrap();
        assert_eq!(m.unit, MeasurementUnit::Millimeters);
        assert!((m.to_points() - 28.3464).abs() < 0.01);

        let m = Measurement::parse("72pt").unwrap();
        assert_eq!(m.to_points(), 72.0);

        let m = Measurement::parse("1in").unwrap();
        assert_eq!(m.to_points(), 72.0);

        let m = Measurement::parse("2.54cm").unwrap();
        assert!((m.to_points() - 72.0).abs() < 0.01);
    }

    #[test]
    fn box_model_content_area() {
        let bm = BoxModel {
            width: Some(200.0),
            height: Some(100.0),
            margins: Insets {
                top: 5.0,
                right: 10.0,
                bottom: 5.0,
                left: 10.0,
            },
            border_width: 1.0,
            max_width: f64::MAX,
            max_height: f64::MAX,
            ..Default::default()
        };
        // content_width = 200 - 20 (margins) - 2 (border) = 178
        assert_eq!(bm.content_width(), 178.0);
        // content_height = 100 - 10 (margins) - 2 (border) = 88
        assert_eq!(bm.content_height(), 88.0);
    }

    #[test]
    fn box_model_with_caption() {
        let bm = BoxModel {
            width: Some(200.0),
            height: Some(100.0),
            caption: Some(Caption {
                placement: CaptionPlacement::Left,
                reserve: Some(50.0),
                text: "Label".to_string(),
            }),
            max_width: f64::MAX,
            max_height: f64::MAX,
            ..Default::default()
        };
        // content_width = 200 - 0 (margins) - 0 (border) - 50 (caption) = 150
        assert_eq!(bm.content_width(), 150.0);
    }

    #[test]
    fn outer_size_applies_constraints() {
        let bm = BoxModel {
            min_width: 100.0,
            min_height: 50.0,
            max_width: 500.0,
            max_height: 300.0,
            ..Default::default()
        };
        let s = bm.outer_size(Size {
            width: 10.0,
            height: 10.0,
        });
        assert_eq!(s.width, 100.0); // clamped to min
        assert_eq!(s.height, 50.0); // clamped to min
    }

    #[test]
    fn outer_size_fixed() {
        let bm = BoxModel {
            width: Some(200.0),
            height: Some(100.0),
            max_width: f64::MAX,
            max_height: f64::MAX,
            ..Default::default()
        };
        let s = bm.outer_size(Size {
            width: 50.0,
            height: 50.0,
        });
        assert_eq!(s.width, 200.0); // fixed
        assert_eq!(s.height, 100.0); // fixed
    }

    #[test]
    fn insets_helpers() {
        let i = Insets {
            top: 1.0,
            right: 2.0,
            bottom: 3.0,
            left: 4.0,
        };
        assert_eq!(i.horizontal(), 6.0);
        assert_eq!(i.vertical(), 4.0);
    }
}