Skip to main content

text_document/
flow.rs

1//! Flow types for document traversal and layout engine support.
2//!
3//! The layout engine processes [`FlowElement`]s in order to build its layout
4//! tree. Snapshot types capture consistent views for thread-safe reads.
5
6use crate::text_block::TextBlock;
7use crate::text_frame::TextFrame;
8use crate::text_table::TextTable;
9use crate::{Alignment, BlockFormat, FrameFormat, ListStyle, TextFormat};
10
11// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
12// FlowElement
13// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
14
15/// An element in the document's visual flow.
16///
17/// The layout engine processes these in order to build its layout tree.
18/// Obtained from [`TextDocument::flow()`](crate::TextDocument::flow) or
19/// [`TextFrame::flow()`].
20#[derive(Clone)]
21pub enum FlowElement {
22    /// A paragraph or heading. Layout as a text block.
23    Block(TextBlock),
24
25    /// A table at this position in the flow. Layout as a grid.
26    /// The anchor frame's `table` field identifies the table entity.
27    Table(TextTable),
28
29    /// A non-table sub-frame (float, sidebar, blockquote).
30    /// Contains its own nested flow, accessible via
31    /// [`TextFrame::flow()`].
32    Frame(TextFrame),
33}
34
35impl FlowElement {
36    /// Snapshot this element into a thread-safe, plain-data representation.
37    ///
38    /// Dispatches to [`TextBlock::snapshot()`], [`TextTable::snapshot()`],
39    /// or [`TextFrame::snapshot()`] as appropriate.
40    pub fn snapshot(&self) -> FlowElementSnapshot {
41        match self {
42            FlowElement::Block(b) => FlowElementSnapshot::Block(b.snapshot()),
43            FlowElement::Table(t) => FlowElementSnapshot::Table(t.snapshot()),
44            FlowElement::Frame(f) => FlowElementSnapshot::Frame(f.snapshot()),
45        }
46    }
47}
48
49// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
50// FragmentContent
51// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
52
53/// A contiguous run of content with uniform formatting within a block.
54///
55/// Offsets are **block-relative**: `offset` is the character position
56/// within the block where this fragment starts (0 = block start).
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum FragmentContent {
59    /// A text run. The layout engine shapes these into glyphs.
60    Text {
61        text: String,
62        format: TextFormat,
63        /// Character offset within the block (block-relative).
64        offset: usize,
65        /// Character count.
66        length: usize,
67        /// Stable synthesized id for the underlying format run
68        /// (see [`synth_element_id`](common::format_runs::synth_element_id)).
69        /// Survives edits that don't delete the run (character insertions
70        /// inside the run keep the same id). Used by accessibility layers
71        /// to build stable `NodeId`s for AccessKit `TextRun` children.
72        element_id: u64,
73        /// Unicode word starts within `text`, expressed as character
74        /// indices (not byte offsets). Computed per UAX #29 via
75        /// `unicode-segmentation`. Fed directly into AccessKit's
76        /// `set_word_starts` on the corresponding `Role::TextRun`.
77        word_starts: Vec<u8>,
78    },
79    /// An inline image. The layout engine reserves space for it.
80    ///
81    /// To retrieve the image pixel data, use the existing
82    /// [`TextDocument::resource(name)`](crate::TextDocument::resource) method.
83    Image {
84        name: String,
85        width: u32,
86        height: u32,
87        quality: u32,
88        format: TextFormat,
89        /// Character offset within the block (block-relative).
90        offset: usize,
91        /// Stable synthesized id for the underlying image anchor
92        /// (see [`synth_element_id`](common::format_runs::synth_element_id)).
93        element_id: u64,
94    },
95}
96
97// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
98// BlockSnapshot
99// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
100
101/// All layout-relevant data for one block, captured atomically.
102#[derive(Debug, Clone, PartialEq)]
103pub struct BlockSnapshot {
104    pub block_id: usize,
105    pub position: usize,
106    pub length: usize,
107    pub text: String,
108    pub fragments: Vec<FragmentContent>,
109    pub block_format: BlockFormat,
110    pub list_info: Option<ListInfo>,
111    /// Parent frame ID. Needed to know where this block lives in the
112    /// frame tree (e.g. main frame vs. a sub-frame or table cell frame).
113    pub parent_frame_id: Option<usize>,
114    /// If this block is inside a table cell, the cell coordinates.
115    /// Needed so the typesetter can propagate height changes to the
116    /// enclosing table row.
117    pub table_cell: Option<TableCellContext>,
118}
119
120/// Snapshot-friendly reference to a table cell (plain IDs, no live handles).
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct TableCellContext {
123    pub table_id: usize,
124    pub row: usize,
125    pub column: usize,
126}
127
128// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
129// ListInfo
130// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
131
132/// List membership and marker information for a block.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct ListInfo {
135    pub list_id: usize,
136    /// The list style (Disc, Decimal, LowerAlpha, etc.).
137    pub style: ListStyle,
138    /// Indentation level.
139    pub indent: u8,
140    /// Pre-formatted marker text: "•", "3.", "(c)", "IV.", etc.
141    pub marker: String,
142    /// 0-based index of this item within its list.
143    pub item_index: usize,
144}
145
146// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
147// TableCellRef
148// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
149
150/// Reference to a table cell that contains a block.
151#[derive(Clone)]
152pub struct TableCellRef {
153    pub table: TextTable,
154    pub row: usize,
155    pub column: usize,
156}
157
158// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
159// CellRange / SelectionKind
160// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
161
162/// A rectangular range of cells within a single table (inclusive bounds).
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct CellRange {
165    pub table_id: usize,
166    pub start_row: usize,
167    pub start_col: usize,
168    pub end_row: usize,
169    pub end_col: usize,
170}
171
172impl CellRange {
173    /// Expand the range so that every merged cell whose span overlaps the
174    /// rectangle is fully included. `cells` is a slice of
175    /// `(row, col, row_span, col_span)` for every cell in the table.
176    ///
177    /// Uses fixed-point iteration (converges in 1-2 rounds for typical tables).
178    pub fn expand_for_spans(mut self, cells: &[(usize, usize, usize, usize)]) -> Self {
179        loop {
180            let mut expanded = false;
181            for &(row, col, rs, cs) in cells {
182                let cell_bottom = row + rs - 1;
183                let cell_right = col + cs - 1;
184                // Check overlap with current range
185                if row <= self.end_row
186                    && cell_bottom >= self.start_row
187                    && col <= self.end_col
188                    && cell_right >= self.start_col
189                {
190                    if row < self.start_row {
191                        self.start_row = row;
192                        expanded = true;
193                    }
194                    if cell_bottom > self.end_row {
195                        self.end_row = cell_bottom;
196                        expanded = true;
197                    }
198                    if col < self.start_col {
199                        self.start_col = col;
200                        expanded = true;
201                    }
202                    if cell_right > self.end_col {
203                        self.end_col = cell_right;
204                        expanded = true;
205                    }
206                }
207            }
208            if !expanded {
209                break;
210            }
211        }
212        self
213    }
214}
215
216/// Describes what kind of selection the cursor currently has.
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub enum SelectionKind {
219    /// No selection (position == anchor).
220    None,
221    /// Normal text selection within a single cell or outside any table.
222    Text,
223    /// Rectangular cell selection within a table.
224    Cells(CellRange),
225    /// Selection crosses a table boundary (starts/ends outside the table).
226    /// The table portion is a rectangular cell range; `text_before` /
227    /// `text_after` indicate whether text outside the table is also selected.
228    Mixed {
229        cell_range: CellRange,
230        text_before: bool,
231        text_after: bool,
232    },
233}
234
235// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
236// Table format types
237// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
238
239/// Table-level formatting.
240#[derive(Debug, Clone, Default, PartialEq, Eq)]
241pub struct TableFormat {
242    pub border: Option<i32>,
243    pub cell_spacing: Option<i32>,
244    pub cell_padding: Option<i32>,
245    pub width: Option<i32>,
246    pub alignment: Option<Alignment>,
247}
248
249/// Cell-level formatting.
250#[derive(Debug, Clone, Default, PartialEq, Eq)]
251pub struct CellFormat {
252    pub padding: Option<i32>,
253    pub border: Option<i32>,
254    pub vertical_alignment: Option<CellVerticalAlignment>,
255    pub background_color: Option<String>,
256}
257
258/// Vertical alignment within a table cell.
259#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
260pub enum CellVerticalAlignment {
261    #[default]
262    Top,
263    Middle,
264    Bottom,
265}
266
267// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
268// Table and Cell Snapshots
269// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
270
271/// Consistent snapshot of a table's structure and all cell content.
272#[derive(Debug, Clone, PartialEq)]
273pub struct TableSnapshot {
274    pub table_id: usize,
275    pub rows: usize,
276    pub columns: usize,
277    pub column_widths: Vec<i32>,
278    pub format: TableFormat,
279    pub cells: Vec<CellSnapshot>,
280}
281
282/// Snapshot of one table cell including its block content.
283#[derive(Debug, Clone, PartialEq)]
284pub struct CellSnapshot {
285    pub row: usize,
286    pub column: usize,
287    pub row_span: usize,
288    pub column_span: usize,
289    pub format: CellFormat,
290    pub blocks: Vec<BlockSnapshot>,
291}
292
293// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
294// Flow Snapshots
295// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
296
297/// Consistent snapshot of the entire document flow, captured in a
298/// single lock acquisition.
299#[derive(Debug, Clone, PartialEq)]
300pub struct FlowSnapshot {
301    pub elements: Vec<FlowElementSnapshot>,
302}
303
304/// Snapshot of one flow element.
305#[derive(Debug, Clone, PartialEq)]
306pub enum FlowElementSnapshot {
307    Block(BlockSnapshot),
308    Table(TableSnapshot),
309    Frame(FrameSnapshot),
310}
311
312/// Snapshot of a sub-frame and its contents.
313#[derive(Debug, Clone, PartialEq)]
314pub struct FrameSnapshot {
315    pub frame_id: usize,
316    pub format: FrameFormat,
317    pub elements: Vec<FlowElementSnapshot>,
318}
319
320// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
321// FormatChangeKind
322// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
323
324/// What kind of formatting changed.
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub enum FormatChangeKind {
327    /// Block-level: alignment, margins, indent, heading level.
328    /// Requires paragraph relayout.
329    Block,
330    /// Character-level: font, bold, italic, underline, color.
331    /// Requires reshaping but not necessarily reflow.
332    Character,
333    /// List-level: style, indent, prefix, suffix.
334    /// Requires marker relayout for list items.
335    List,
336}