Skip to main content

text_typeset/layout/
frame.rs

1use crate::font::registry::FontRegistry;
2use crate::layout::block::layout_block;
3use crate::layout::block::{BlockLayout, BlockLayoutParams};
4use crate::layout::table::{TableLayout, TableLayoutParams, layout_table};
5
6/// Frame position type (from text-document's FramePosition).
7///
8/// **Note on floats**: `FloatLeft` and `FloatRight` currently place the frame
9/// at the correct x position but do not implement content wrapping (text does
10/// not flow beside the float). They advance `content_height` like `Inline`,
11/// so subsequent content appears below rather than beside the float.
12/// True float exclusion zones would require tracking available width per
13/// y-range during paragraph layout.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum FramePosition {
16    /// Inline: rendered in normal flow order, advances content_height.
17    #[default]
18    Inline,
19    /// Float left: placed at x=0, advances content_height.
20    /// Content wrapping is not yet implemented.
21    FloatLeft,
22    /// Float right: placed at x=available_width - frame_width, advances content_height.
23    /// Content wrapping is not yet implemented.
24    FloatRight,
25    /// Absolute: placed at (margin_left, margin_top) from document origin.
26    /// Does not affect flow or content_height.
27    Absolute,
28}
29
30/// How the frame border is drawn.
31#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
32pub enum FrameBorderStyle {
33    /// Draw border on all four sides (default).
34    #[default]
35    Full,
36    /// Draw only the left border (blockquote style).
37    LeftOnly,
38    /// No border.
39    None,
40}
41
42/// Parameters for a frame, extracted from text-document's FrameSnapshot.
43#[derive(Clone)]
44pub struct FrameLayoutParams {
45    pub frame_id: usize,
46    pub position: FramePosition,
47    /// Frame width constraint (None = use available width).
48    pub width: Option<f32>,
49    /// Frame height constraint (None = auto from content).
50    pub height: Option<f32>,
51    pub margin_top: f32,
52    pub margin_bottom: f32,
53    pub margin_left: f32,
54    pub margin_right: f32,
55    pub padding: f32,
56    pub border_width: f32,
57    pub border_style: FrameBorderStyle,
58    /// Nested flow elements: blocks, tables, and frames within the frame.
59    /// Each element carries its `flow_index` (its position in the source
60    /// `FrameSnapshot.elements` vec) so `layout_frame` can interleave
61    /// blocks / tables / frames in document order. Without the index,
62    /// nested-frame content (e.g. a deeper blockquote between two
63    /// sibling blocks) would render in the wrong visual order.
64    pub blocks: Vec<(usize, BlockLayoutParams)>,
65    pub tables: Vec<(usize, TableLayoutParams)>,
66    pub frames: Vec<(usize, FrameLayoutParams)>,
67}
68
69/// One direct child of a frame, in document (flow) order.
70///
71/// `FrameLayout` stores its children in per-kind vecs (`blocks`, `tables`,
72/// `frames`); this enum records how those vecs interleave in the source
73/// flow. Incremental relayout uses it to reposition children in document
74/// order — without it, re-stacking would group children by kind and
75/// visually reorder e.g. a blockquote containing [block, table, block].
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum FrameChildRef {
78    /// A direct block, identified by `block_id`.
79    Block(usize),
80    /// A direct table, identified by `table_id`.
81    Table(usize),
82    /// A nested frame, identified by `frame_id`.
83    Frame(usize),
84}
85
86/// Computed layout for a frame.
87#[non_exhaustive]
88pub struct FrameLayout {
89    pub frame_id: usize,
90    pub y: f32,
91    pub x: f32,
92    pub total_width: f32,
93    pub total_height: f32,
94    pub content_x: f32,
95    pub content_y: f32,
96    pub content_width: f32,
97    pub content_height: f32,
98    pub blocks: Vec<BlockLayout>,
99    pub tables: Vec<TableLayout>,
100    pub frames: Vec<FrameLayout>,
101    /// Direct children in document (flow) order — see [`FrameChildRef`].
102    pub flow_order: Vec<FrameChildRef>,
103    pub border_width: f32,
104    pub border_style: FrameBorderStyle,
105}
106
107/// Lay out a frame: compute dimensions, lay out nested content.
108pub fn layout_frame(
109    registry: &FontRegistry,
110    params: &FrameLayoutParams,
111    available_width: f32,
112    scale_factor: f32,
113    font_scale: f32,
114) -> FrameLayout {
115    let border = params.border_width;
116    let pad = params.padding;
117    let frame_width = params.width.unwrap_or(available_width);
118    let content_width =
119        (frame_width - border * 2.0 - pad * 2.0 - params.margin_left - params.margin_right)
120            .max(0.0);
121
122    // Lay out nested elements (blocks, tables, frames) in document
123    // (flow) order — interleaved by `flow_index`. Y-coordinates and
124    // visual placement follow flow order; the output Vecs (blocks /
125    // tables / frames) are pushed in that same order, which is also
126    // the natural per-kind iteration order since `flow_index` is
127    // monotonic across the input streams.
128    enum FlowItem<'a> {
129        Block(&'a BlockLayoutParams),
130        Table(&'a TableLayoutParams),
131        Frame(&'a FrameLayoutParams),
132    }
133    let mut ordered: Vec<(usize, FlowItem)> =
134        Vec::with_capacity(params.blocks.len() + params.tables.len() + params.frames.len());
135    for (idx, b) in &params.blocks {
136        ordered.push((*idx, FlowItem::Block(b)));
137    }
138    for (idx, t) in &params.tables {
139        ordered.push((*idx, FlowItem::Table(t)));
140    }
141    for (idx, f) in &params.frames {
142        ordered.push((*idx, FlowItem::Frame(f)));
143    }
144    ordered.sort_by_key(|(idx, _)| *idx);
145
146    let mut blocks: Vec<BlockLayout> = Vec::with_capacity(params.blocks.len());
147    let mut tables: Vec<TableLayout> = Vec::with_capacity(params.tables.len());
148    let mut nested_frames: Vec<FrameLayout> = Vec::with_capacity(params.frames.len());
149    let mut flow_order: Vec<FrameChildRef> = Vec::with_capacity(ordered.len());
150    let mut content_y = 0.0f32;
151
152    for (_flow_idx, item) in &ordered {
153        match item {
154            FlowItem::Block(block_params) => {
155                let mut block = layout_block(
156                    registry,
157                    block_params,
158                    content_width,
159                    scale_factor,
160                    font_scale,
161                );
162                block.y = content_y + block.top_margin;
163                let block_content = block.height - block.top_margin - block.bottom_margin;
164                content_y = block.y + block_content + block.bottom_margin;
165                flow_order.push(FrameChildRef::Block(block.block_id));
166                blocks.push(block);
167            }
168            FlowItem::Table(table_params) => {
169                let mut table = layout_table(
170                    registry,
171                    table_params,
172                    content_width,
173                    scale_factor,
174                    font_scale,
175                );
176                table.y = content_y;
177                content_y += table.total_height;
178                flow_order.push(FrameChildRef::Table(table.table_id));
179                tables.push(table);
180            }
181            FlowItem::Frame(frame_params) => {
182                let mut nested = layout_frame(
183                    registry,
184                    frame_params,
185                    content_width,
186                    scale_factor,
187                    font_scale,
188                );
189                nested.y = content_y;
190                nested.x = 0.0;
191                content_y += nested.total_height;
192                flow_order.push(FrameChildRef::Frame(nested.frame_id));
193                nested_frames.push(nested);
194            }
195        }
196    }
197
198    let auto_content_height = content_y;
199    let content_height = params
200        .height
201        .map(|h| (h - border * 2.0 - pad * 2.0).max(0.0))
202        .unwrap_or(auto_content_height);
203
204    let total_height =
205        params.margin_top + border + pad + content_height + pad + border + params.margin_bottom;
206    let total_width =
207        params.margin_left + border + pad + content_width + pad + border + params.margin_right;
208
209    let content_x = params.margin_left + border + pad;
210    let content_y_offset = params.margin_top + border + pad;
211
212    FrameLayout {
213        frame_id: params.frame_id,
214        y: 0.0, // set by flow
215        x: 0.0,
216        total_width,
217        total_height,
218        content_x,
219        content_y: content_y_offset,
220        content_width,
221        content_height,
222        blocks,
223        tables,
224        frames: nested_frames,
225        flow_order,
226        border_width: border,
227        border_style: params.border_style,
228    }
229}