Skip to main content

lightweight_pdf_layout/
render_node.rs

1use crate::geometry::Rect;
2use lightweight_pdf_core::{Align, Border, Color, ImageFormat, TextStyle};
3use std::sync::Arc;
4
5/// Positioned, resolved layout output ready for the facade to translate
6/// into `lightweight-pdf-writer` content-stream operations. Never seen by
7/// `lightweight-pdf-writer` directly (`plan/00a-contracts-and-artifacts.md` point 3).
8#[derive(Clone, Debug)]
9pub enum RenderNode {
10    Empty,
11    /// Already-wrapped lines, one per output line, top-aligned within `area`.
12    TextLines {
13        area: Rect,
14        style: TextStyle,
15        lines: Vec<String>,
16        line_height_pt: f32,
17    },
18    Rect {
19        area: Rect,
20        background: Option<Color>,
21        border: Option<Border>,
22    },
23    Line {
24        x1: f32,
25        y1: f32,
26        x2: f32,
27        y2: f32,
28        thickness: f32,
29        color: Color,
30    },
31    /// A validated JPEG/PNG placed at its final, Contain-fit size. `bytes`
32    /// are the original file bytes (facade decides how to embed them —
33    /// JPEG passes through as `DCTDecode`, PNG gets decoded once here to
34    /// split out the alpha channel as a `SMask`).
35    Image {
36        area: Rect,
37        bytes: Arc<[u8]>,
38        format: ImageFormat,
39        width_px: u32,
40        height_px: u32,
41        components: u8,
42    },
43    /// A container's own box: clipped (Grundprinzip 4), optionally painted
44    /// with a background/border, holding its children.
45    Group {
46        area: Rect,
47        clip: bool,
48        background: Option<Color>,
49        border: Option<Border>,
50        children: Vec<RenderNode>,
51    },
52}
53
54impl RenderNode {
55    /// Wraps `self` in a clipping group bound to `area` — the render-pass
56    /// safety net required from every element, not only containers
57    /// (Grundprinzip 4/6).
58    pub fn clipped(area: Rect, inner: RenderNode) -> RenderNode {
59        RenderNode::Group {
60            area,
61            clip: true,
62            background: None,
63            border: None,
64            children: vec![inner],
65        }
66    }
67
68    pub fn height(&self) -> f32 {
69        match self {
70            RenderNode::Empty => 0.0,
71            RenderNode::TextLines { area, .. }
72            | RenderNode::Rect { area, .. }
73            | RenderNode::Group { area, .. }
74            | RenderNode::Image { area, .. } => area.height,
75            RenderNode::Line { .. } => 0.0,
76        }
77    }
78}
79
80/// Just used inside `Row`/`Column` cross-axis alignment.
81pub fn align_offset(align: Align, available: f32, used: f32) -> f32 {
82    match align {
83        Align::Start => 0.0,
84        Align::Center => ((available - used) / 2.0).max(0.0),
85        Align::End => (available - used).max(0.0),
86    }
87}