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.
43pub struct FrameLayoutParams {
44    pub frame_id: usize,
45    pub position: FramePosition,
46    /// Frame width constraint (None = use available width).
47    pub width: Option<f32>,
48    /// Frame height constraint (None = auto from content).
49    pub height: Option<f32>,
50    pub margin_top: f32,
51    pub margin_bottom: f32,
52    pub margin_left: f32,
53    pub margin_right: f32,
54    pub padding: f32,
55    pub border_width: f32,
56    pub border_style: FrameBorderStyle,
57    /// Nested flow elements: blocks, tables, and frames within the frame.
58    /// Each element carries its `flow_index` (its position in the source
59    /// `FrameSnapshot.elements` vec) so `layout_frame` can interleave
60    /// blocks / tables / frames in document order. Without the index,
61    /// nested-frame content (e.g. a deeper blockquote between two
62    /// sibling blocks) would render in the wrong visual order.
63    pub blocks: Vec<(usize, BlockLayoutParams)>,
64    pub tables: Vec<(usize, TableLayoutParams)>,
65    pub frames: Vec<(usize, FrameLayoutParams)>,
66}
67
68/// One direct child of a frame, in document (flow) order.
69///
70/// `FrameLayout` stores its children in per-kind vecs (`blocks`, `tables`,
71/// `frames`); this enum records how those vecs interleave in the source
72/// flow. Incremental relayout uses it to reposition children in document
73/// order — without it, re-stacking would group children by kind and
74/// visually reorder e.g. a blockquote containing [block, table, block].
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum FrameChildRef {
77    /// A direct block, identified by `block_id`.
78    Block(usize),
79    /// A direct table, identified by `table_id`.
80    Table(usize),
81    /// A nested frame, identified by `frame_id`.
82    Frame(usize),
83}
84
85/// Computed layout for a frame.
86#[non_exhaustive]
87pub struct FrameLayout {
88    pub frame_id: usize,
89    pub y: f32,
90    pub x: f32,
91    pub total_width: f32,
92    pub total_height: f32,
93    pub content_x: f32,
94    pub content_y: f32,
95    pub content_width: f32,
96    pub content_height: f32,
97    pub blocks: Vec<BlockLayout>,
98    pub tables: Vec<TableLayout>,
99    pub frames: Vec<FrameLayout>,
100    /// Direct children in document (flow) order — see [`FrameChildRef`].
101    pub flow_order: Vec<FrameChildRef>,
102    pub border_width: f32,
103    pub border_style: FrameBorderStyle,
104}
105
106/// Lay out a frame: compute dimensions, lay out nested content.
107pub fn layout_frame(
108    registry: &FontRegistry,
109    params: &FrameLayoutParams,
110    available_width: f32,
111    scale_factor: f32,
112    font_scale: f32,
113) -> FrameLayout {
114    let border = params.border_width;
115    let pad = params.padding;
116    let frame_width = params.width.unwrap_or(available_width);
117    let content_width =
118        (frame_width - border * 2.0 - pad * 2.0 - params.margin_left - params.margin_right)
119            .max(0.0);
120
121    // Lay out nested elements (blocks, tables, frames) in document
122    // (flow) order — interleaved by `flow_index`. Y-coordinates and
123    // visual placement follow flow order; the output Vecs (blocks /
124    // tables / frames) are pushed in that same order, which is also
125    // the natural per-kind iteration order since `flow_index` is
126    // monotonic across the input streams.
127    enum FlowItem<'a> {
128        Block(&'a BlockLayoutParams),
129        Table(&'a TableLayoutParams),
130        Frame(&'a FrameLayoutParams),
131    }
132    let mut ordered: Vec<(usize, FlowItem)> =
133        Vec::with_capacity(params.blocks.len() + params.tables.len() + params.frames.len());
134    for (idx, b) in &params.blocks {
135        ordered.push((*idx, FlowItem::Block(b)));
136    }
137    for (idx, t) in &params.tables {
138        ordered.push((*idx, FlowItem::Table(t)));
139    }
140    for (idx, f) in &params.frames {
141        ordered.push((*idx, FlowItem::Frame(f)));
142    }
143    ordered.sort_by_key(|(idx, _)| *idx);
144
145    let mut blocks: Vec<BlockLayout> = Vec::with_capacity(params.blocks.len());
146    let mut tables: Vec<TableLayout> = Vec::with_capacity(params.tables.len());
147    let mut nested_frames: Vec<FrameLayout> = Vec::with_capacity(params.frames.len());
148    let mut flow_order: Vec<FrameChildRef> = Vec::with_capacity(ordered.len());
149    let mut content_y = 0.0f32;
150
151    for (_flow_idx, item) in &ordered {
152        match item {
153            FlowItem::Block(block_params) => {
154                let mut block = layout_block(
155                    registry,
156                    block_params,
157                    content_width,
158                    scale_factor,
159                    font_scale,
160                );
161                block.y = content_y + block.top_margin;
162                let block_content = block.height - block.top_margin - block.bottom_margin;
163                content_y = block.y + block_content + block.bottom_margin;
164                flow_order.push(FrameChildRef::Block(block.block_id));
165                blocks.push(block);
166            }
167            FlowItem::Table(table_params) => {
168                let mut table = layout_table(
169                    registry,
170                    table_params,
171                    content_width,
172                    scale_factor,
173                    font_scale,
174                );
175                table.y = content_y;
176                content_y += table.total_height;
177                flow_order.push(FrameChildRef::Table(table.table_id));
178                tables.push(table);
179            }
180            FlowItem::Frame(frame_params) => {
181                let mut nested = layout_frame(
182                    registry,
183                    frame_params,
184                    content_width,
185                    scale_factor,
186                    font_scale,
187                );
188                nested.y = content_y;
189                nested.x = 0.0;
190                content_y += nested.total_height;
191                flow_order.push(FrameChildRef::Frame(nested.frame_id));
192                nested_frames.push(nested);
193            }
194        }
195    }
196
197    let auto_content_height = content_y;
198    let content_height = params
199        .height
200        .map(|h| (h - border * 2.0 - pad * 2.0).max(0.0))
201        .unwrap_or(auto_content_height);
202
203    let total_height =
204        params.margin_top + border + pad + content_height + pad + border + params.margin_bottom;
205    let total_width =
206        params.margin_left + border + pad + content_width + pad + border + params.margin_right;
207
208    let content_x = params.margin_left + border + pad;
209    let content_y_offset = params.margin_top + border + pad;
210
211    FrameLayout {
212        frame_id: params.frame_id,
213        y: 0.0, // set by flow
214        x: 0.0,
215        total_width,
216        total_height,
217        content_x,
218        content_y: content_y_offset,
219        content_width,
220        content_height,
221        blocks,
222        tables,
223        frames: nested_frames,
224        flow_order,
225        border_width: border,
226        border_style: params.border_style,
227    }
228}