Skip to main content

text_document/
text_frame.rs

1//! Read-only frame handle and shared flow traversal logic.
2
3use std::collections::HashSet;
4use std::sync::Arc;
5
6use parking_lot::Mutex;
7
8use frontend::commands::{block_commands, frame_commands, table_cell_commands, table_commands};
9use frontend::common::types::EntityId;
10
11use crate::FrameFormat;
12use crate::convert::to_usize;
13use crate::flow::{CellSnapshot, FlowElement, FlowElementSnapshot, FrameSnapshot, TableSnapshot};
14use crate::inner::TextDocumentInner;
15use crate::text_block::{SnapshotLookups, TextBlock};
16use crate::text_table::TextTable;
17
18/// A read-only handle to a frame in the document.
19///
20/// Obtained from [`FlowElement::Frame`] or [`TextBlock::frame()`].
21#[derive(Clone)]
22pub struct TextFrame {
23    pub(crate) doc: Arc<Mutex<TextDocumentInner>>,
24    pub(crate) frame_id: usize,
25}
26
27impl TextFrame {
28    /// Stable entity ID.
29    pub fn id(&self) -> usize {
30        self.frame_id
31    }
32
33    /// Frame formatting (height, width, margins, padding, border, position).
34    pub fn format(&self) -> FrameFormat {
35        let inner = self.doc.lock();
36        let frame_dto = frame_commands::get_frame(&inner.ctx, &(self.frame_id as EntityId))
37            .ok()
38            .flatten();
39        match frame_dto {
40            Some(f) => frame_dto_to_format(&f),
41            None => FrameFormat::default(),
42        }
43    }
44
45    /// Nested flow within this frame. Same `child_order` traversal as
46    /// [`TextDocument::flow()`](crate::TextDocument::flow).
47    pub fn flow(&self) -> Vec<FlowElement> {
48        let inner = self.doc.lock();
49        build_flow_elements(&inner, &self.doc, self.frame_id as EntityId)
50    }
51
52    /// Snapshot of this frame and all its contents, captured in a single
53    /// lock acquisition. Thread-safe — the returned [`FrameSnapshot`]
54    /// contains only plain data.
55    pub fn snapshot(&self) -> FrameSnapshot {
56        let inner = self.doc.lock();
57        let format = frame_commands::get_frame(&inner.ctx, &(self.frame_id as EntityId))
58            .ok()
59            .flatten()
60            .map(|f| frame_dto_to_format(&f))
61            .unwrap_or_default();
62        let elements = build_flow_snapshot(
63            &inner,
64            self.frame_id as EntityId,
65            crate::highlight::SnapshotHighlights {
66                kind: inner.highlight_kind,
67                mask: &crate::highlight::HighlightMask::ALL,
68                suppress_paint: false,
69            },
70        );
71        FrameSnapshot {
72            frame_id: self.frame_id,
73            format,
74            elements,
75        }
76    }
77}
78
79// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
80// Shared flow traversal (used by TextDocument and TextFrame)
81// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
82
83/// The blocks and tables under `frame_id` in reading order, each quotation's own flow in its
84/// place rather than as a [`FlowElement::Frame`]: the text a caret or a selection runs
85/// through, however deep the quotations nest. A table's cells are its own and are not
86/// listed.
87///
88/// Read only at the top of the main frame, a table standing in a quotation was not found:
89/// a selection of all of a text opening or ending with a quoted table copied nothing, and
90/// cutting it put nothing on the clipboard. Walked with a stack of its own, so a quotation
91/// nested past any depth costs no recursion, and a frame met twice is read once.
92pub(crate) fn flow_in_reading_order(
93    inner: &TextDocumentInner,
94    doc_arc: &Arc<Mutex<TextDocumentInner>>,
95    frame_id: EntityId,
96) -> Vec<FlowElement> {
97    let mut out = Vec::new();
98    let mut seen: HashSet<EntityId> = HashSet::from([frame_id]);
99    let mut stack = vec![build_flow_elements(inner, doc_arc, frame_id).into_iter()];
100    while let Some(frame) = stack.last_mut() {
101        match frame.next() {
102            None => {
103                stack.pop();
104            }
105            Some(FlowElement::Frame(sub_frame)) => {
106                let sub_frame_id = sub_frame.frame_id as EntityId;
107                if seen.insert(sub_frame_id) {
108                    stack.push(build_flow_elements(inner, doc_arc, sub_frame_id).into_iter());
109                }
110            }
111            Some(element) => out.push(element),
112        }
113    }
114    out
115}
116
117/// Build flow elements for a frame, returning FlowElement variants.
118///
119/// This is the main entry point. `doc_arc` is the shared document handle
120/// that will be cloned into each returned handle.
121pub(crate) fn build_flow_elements(
122    inner: &TextDocumentInner,
123    doc_arc: &Arc<Mutex<TextDocumentInner>>,
124    frame_id: EntityId,
125) -> Vec<FlowElement> {
126    let frame_dto = match frame_commands::get_frame(&inner.ctx, &frame_id)
127        .ok()
128        .flatten()
129    {
130        Some(f) => f,
131        None => return Vec::new(),
132    };
133
134    if !frame_dto.child_order.is_empty() {
135        flow_from_child_order(inner, doc_arc, &frame_dto.child_order)
136    } else {
137        flow_fallback(inner, doc_arc, &frame_dto)
138    }
139}
140
141/// Build flow from populated `child_order`.
142fn flow_from_child_order(
143    inner: &TextDocumentInner,
144    doc_arc: &Arc<Mutex<TextDocumentInner>>,
145    child_order: &[i64],
146) -> Vec<FlowElement> {
147    let mut elements = Vec::with_capacity(child_order.len());
148
149    for &entry in child_order {
150        if entry > 0 {
151            // Positive: block ID
152            elements.push(FlowElement::Block(TextBlock {
153                doc: Arc::clone(doc_arc),
154                block_id: entry as usize,
155            }));
156        } else if entry < 0 {
157            // Negative: frame ID (negated)
158            let sub_frame_id = (-entry) as EntityId;
159            if let Some(sub_frame) = frame_commands::get_frame(&inner.ctx, &sub_frame_id)
160                .ok()
161                .flatten()
162            {
163                if let Some(table_id) = sub_frame.table {
164                    // Anchor frame for a table
165                    elements.push(FlowElement::Table(TextTable {
166                        doc: Arc::clone(doc_arc),
167                        table_id: table_id as usize,
168                    }));
169                } else {
170                    // Non-table sub-frame
171                    elements.push(FlowElement::Frame(TextFrame {
172                        doc: Arc::clone(doc_arc),
173                        frame_id: sub_frame_id as usize,
174                    }));
175                }
176            }
177        }
178        // entry == 0 is ignored (shouldn't happen)
179    }
180
181    elements
182}
183
184/// Fallback flow: iterate blocks sorted by document_position, skip cell frames.
185fn flow_fallback(
186    inner: &TextDocumentInner,
187    doc_arc: &Arc<Mutex<TextDocumentInner>>,
188    frame_dto: &frontend::frame::dtos::FrameDto,
189) -> Vec<FlowElement> {
190    // Build set of cell frame IDs to skip
191    let cell_frame_ids = build_cell_frame_ids(inner);
192
193    // Get blocks in this frame, sorted by document_position
194    let block_ids = &frame_dto.blocks;
195    let mut block_dtos: Vec<_> = block_ids
196        .iter()
197        .filter_map(|&id| {
198            block_commands::get_block(&inner.ctx, &{ id })
199                .ok()
200                .flatten()
201        })
202        .collect();
203    let store = inner.ctx.db_context.get_store();
204    crate::inner::refresh_block_positions(&mut block_dtos, store);
205    block_dtos.sort_by_key(|b| b.document_position);
206
207    let mut elements: Vec<FlowElement> = block_dtos
208        .iter()
209        .map(|b| {
210            FlowElement::Block(TextBlock {
211                doc: Arc::clone(doc_arc),
212                block_id: b.id as usize,
213            })
214        })
215        .collect();
216
217    // Also check for sub-frames that are children of this frame's document
218    // but not cell frames. In fallback mode, we can't interleave perfectly,
219    // so we append sub-frames after blocks.
220    // For the main frame, get all document frames and check parentage.
221    let all_frames = frame_commands::get_all_frame(&inner.ctx).unwrap_or_default();
222    for f in &all_frames {
223        if f.id == frame_dto.id {
224            continue; // skip self
225        }
226        if cell_frame_ids.contains(&(f.id as EntityId)) {
227            continue; // skip cell frames
228        }
229        // Check if this frame's parent is the current frame
230        if f.parent_frame == Some(frame_dto.id) {
231            if let Some(table_id) = f.table {
232                elements.push(FlowElement::Table(TextTable {
233                    doc: Arc::clone(doc_arc),
234                    table_id: table_id as usize,
235                }));
236            } else {
237                elements.push(FlowElement::Frame(TextFrame {
238                    doc: Arc::clone(doc_arc),
239                    frame_id: f.id as usize,
240                }));
241            }
242        }
243    }
244
245    elements
246}
247
248/// Build a set of all frame IDs that are table cell frames.
249fn build_cell_frame_ids(inner: &TextDocumentInner) -> HashSet<EntityId> {
250    let mut ids = HashSet::new();
251    let all_cells = table_cell_commands::get_all_table_cell(&inner.ctx).unwrap_or_default();
252    for cell in &all_cells {
253        if let Some(frame_id) = cell.cell_frame {
254            ids.insert(frame_id);
255        }
256    }
257    ids
258}
259
260// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
261// Snapshot helpers (called while lock is held)
262// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
263
264/// Build a FlowSnapshot for the given frame. Called while lock is held.
265///
266/// Block positions are computed on-the-fly from child_order + text_length
267/// rather than using stored `document_position` values (which may be stale
268/// after insert_text defers position updates for performance).
269pub(crate) fn build_flow_snapshot(
270    inner: &TextDocumentInner,
271    frame_id: EntityId,
272    hl: crate::highlight::SnapshotHighlights,
273) -> Vec<FlowElementSnapshot> {
274    build_flow_snapshot_with(inner, frame_id, hl, &SnapshotLookups::default())
275}
276
277/// [`build_flow_snapshot`] as part of a larger snapshot, sharing its `lookups`.
278fn build_flow_snapshot_with(
279    inner: &TextDocumentInner,
280    frame_id: EntityId,
281    hl: crate::highlight::SnapshotHighlights,
282    lookups: &SnapshotLookups,
283) -> Vec<FlowElementSnapshot> {
284    let frame_dto = match frame_commands::get_frame(&inner.ctx, &frame_id)
285        .ok()
286        .flatten()
287    {
288        Some(f) => f,
289        None => return Vec::new(),
290    };
291
292    if !frame_dto.child_order.is_empty() {
293        let (elements, _) =
294            snapshot_from_child_order(inner, &frame_dto.child_order, 0, frame_id, hl, lookups);
295        elements
296    } else {
297        snapshot_fallback(inner, &frame_dto, hl, lookups)
298    }
299}
300
301/// Walk child_order, building snapshots with on-the-fly position computation.
302/// `parent_frame_id` is passed down so per-block snapshots skip the
303/// expensive `find_parent_frame` walk over every frame in the store —
304/// a major contributor to per-keystroke editor lag.
305/// Returns (elements, running_position_after_last_block).
306fn snapshot_from_child_order(
307    inner: &TextDocumentInner,
308    child_order: &[i64],
309    start_pos: usize,
310    parent_frame_id: EntityId,
311    hl: crate::highlight::SnapshotHighlights,
312    lookups: &SnapshotLookups,
313) -> (Vec<FlowElementSnapshot>, usize) {
314    let mut elements = Vec::with_capacity(child_order.len());
315    let mut running_pos = start_pos;
316
317    for &entry in child_order {
318        if entry > 0 {
319            let block_id = entry as u64;
320            if let Some(snap) = crate::text_block::build_block_snapshot_with_position_and_parent(
321                inner,
322                block_id,
323                Some(running_pos),
324                Some(parent_frame_id),
325                hl,
326                lookups,
327            ) {
328                running_pos += snap.length + 1; // +1 for block separator
329                elements.push(FlowElementSnapshot::Block(snap));
330            }
331        } else if entry < 0 {
332            let sub_frame_id = (-entry) as EntityId;
333            if let Some(sub_frame) = frame_commands::get_frame(&inner.ctx, &sub_frame_id)
334                .ok()
335                .flatten()
336            {
337                if let Some(table_id) = sub_frame.table {
338                    if let Some((snap, new_pos)) = build_table_snapshot_with_positions(
339                        inner,
340                        table_id,
341                        running_pos,
342                        hl,
343                        lookups,
344                    ) {
345                        running_pos = new_pos;
346                        elements.push(FlowElementSnapshot::Table(snap));
347                    }
348                } else {
349                    let (nested, new_pos) = snapshot_from_child_order(
350                        inner,
351                        &sub_frame.child_order,
352                        running_pos,
353                        sub_frame_id,
354                        hl,
355                        lookups,
356                    );
357                    running_pos = new_pos;
358                    elements.push(FlowElementSnapshot::Frame(FrameSnapshot {
359                        frame_id: sub_frame_id as usize,
360                        format: frame_dto_to_format(&sub_frame),
361                        elements: nested,
362                    }));
363                }
364            }
365        }
366    }
367
368    (elements, running_pos)
369}
370
371fn snapshot_fallback(
372    inner: &TextDocumentInner,
373    frame_dto: &frontend::frame::dtos::FrameDto,
374    hl: crate::highlight::SnapshotHighlights,
375    lookups: &SnapshotLookups,
376) -> Vec<FlowElementSnapshot> {
377    let cell_frame_ids = build_cell_frame_ids(inner);
378
379    let block_ids = &frame_dto.blocks;
380    let mut block_dtos: Vec<_> = block_ids
381        .iter()
382        .filter_map(|&id| {
383            block_commands::get_block(&inner.ctx, &{ id })
384                .ok()
385                .flatten()
386        })
387        .collect();
388    let store = inner.ctx.db_context.get_store();
389    crate::inner::refresh_block_positions(&mut block_dtos, store);
390    block_dtos.sort_by_key(|b| b.document_position);
391
392    let mut elements: Vec<FlowElementSnapshot> = block_dtos
393        .iter()
394        .filter_map(|b| {
395            crate::text_block::build_block_snapshot_with_position_and_parent(
396                inner, b.id, None, None, hl, lookups,
397            )
398        })
399        .map(FlowElementSnapshot::Block)
400        .collect();
401
402    let all_frames = frame_commands::get_all_frame(&inner.ctx).unwrap_or_default();
403    for f in &all_frames {
404        if f.id == frame_dto.id {
405            continue;
406        }
407        if cell_frame_ids.contains(&(f.id as EntityId)) {
408            continue;
409        }
410        if f.parent_frame == Some(frame_dto.id) {
411            if let Some(table_id) = f.table {
412                if let Some(snap) = build_table_snapshot(inner, table_id, hl, lookups) {
413                    elements.push(FlowElementSnapshot::Table(snap));
414                }
415            } else {
416                let nested = build_flow_snapshot_with(inner, f.id as EntityId, hl, lookups);
417                elements.push(FlowElementSnapshot::Frame(FrameSnapshot {
418                    frame_id: f.id as usize,
419                    format: frame_dto_to_format(f),
420                    elements: nested,
421                }));
422            }
423        }
424    }
425
426    elements
427}
428
429/// Build a TableSnapshot for the given table ID. Called while lock is held.
430/// `lookups` is shared with the rest of the snapshot this table belongs to, if any.
431pub(crate) fn build_table_snapshot(
432    inner: &TextDocumentInner,
433    table_id: u64,
434    hl: crate::highlight::SnapshotHighlights,
435    lookups: &SnapshotLookups,
436) -> Option<TableSnapshot> {
437    let table_dto = table_commands::get_table(&inner.ctx, &table_id)
438        .ok()
439        .flatten()?;
440
441    let mut cells = Vec::new();
442    for &cell_id in &table_dto.cells {
443        if let Some(cell_dto) = table_cell_commands::get_table_cell(&inner.ctx, &{ cell_id })
444            .ok()
445            .flatten()
446        {
447            let blocks = if let Some(cell_frame_id) = cell_dto.cell_frame {
448                crate::text_block::build_blocks_snapshot_for_frame(
449                    inner,
450                    cell_frame_id,
451                    hl,
452                    lookups,
453                )
454            } else {
455                Vec::new()
456            };
457            cells.push(CellSnapshot {
458                row: to_usize(cell_dto.row),
459                column: to_usize(cell_dto.column),
460                row_span: to_usize(cell_dto.row_span),
461                column_span: to_usize(cell_dto.column_span),
462                format: cell_dto_to_format(&cell_dto),
463                blocks,
464            });
465        }
466    }
467
468    Some(TableSnapshot {
469        table_id: table_id as usize,
470        rows: to_usize(table_dto.rows),
471        columns: to_usize(table_dto.columns),
472        column_widths: table_dto.column_widths.iter().map(|&v| v as i32).collect(),
473        format: table_dto_to_format(&table_dto),
474        cells,
475    })
476}
477
478/// Build a TableSnapshot with computed positions for cell blocks, starting from
479/// `start_pos`. Returns `(snapshot, running_pos_after_last_cell_block)`.
480///
481/// Cells are processed in row-major order, and block positions within each cell
482/// are computed sequentially — matching `find_block_at_position_sequential` in
483/// the editing use cases.
484fn build_table_snapshot_with_positions(
485    inner: &TextDocumentInner,
486    table_id: u64,
487    start_pos: usize,
488    hl: crate::highlight::SnapshotHighlights,
489    lookups: &SnapshotLookups,
490) -> Option<(TableSnapshot, usize)> {
491    let table_dto = table_commands::get_table(&inner.ctx, &table_id)
492        .ok()
493        .flatten()?;
494
495    // Collect and sort cell DTOs in row-major order
496    let mut cell_dtos: Vec<_> = table_dto
497        .cells
498        .iter()
499        .filter_map(|&cell_id| {
500            table_cell_commands::get_table_cell(&inner.ctx, &{ cell_id })
501                .ok()
502                .flatten()
503        })
504        .collect();
505    cell_dtos.sort_by(|a, b| a.row.cmp(&b.row).then(a.column.cmp(&b.column)));
506
507    let mut running_pos = start_pos;
508    let mut cells = Vec::with_capacity(cell_dtos.len());
509    for cell_dto in &cell_dtos {
510        let blocks = if let Some(cell_frame_id) = cell_dto.cell_frame {
511            let (snaps, new_pos) =
512                crate::text_block::build_blocks_snapshot_for_frame_with_positions(
513                    inner,
514                    cell_frame_id,
515                    running_pos,
516                    hl,
517                    lookups,
518                );
519            running_pos = new_pos;
520            snaps
521        } else {
522            Vec::new()
523        };
524        cells.push(CellSnapshot {
525            row: to_usize(cell_dto.row),
526            column: to_usize(cell_dto.column),
527            row_span: to_usize(cell_dto.row_span),
528            column_span: to_usize(cell_dto.column_span),
529            format: cell_dto_to_format(cell_dto),
530            blocks,
531        });
532    }
533
534    Some((
535        TableSnapshot {
536            table_id: table_id as usize,
537            rows: to_usize(table_dto.rows),
538            columns: to_usize(table_dto.columns),
539            column_widths: table_dto.column_widths.iter().map(|&v| v as i32).collect(),
540            format: table_dto_to_format(&table_dto),
541            cells,
542        },
543        running_pos,
544    ))
545}
546
547// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
548// DTO → public format conversions
549// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
550
551pub(crate) fn frame_dto_to_format(f: &frontend::frame::dtos::FrameDto) -> FrameFormat {
552    FrameFormat {
553        height: f.fmt_height.map(|v| v as i32),
554        width: f.fmt_width.map(|v| v as i32),
555        top_margin: f.fmt_top_margin.map(|v| v as i32),
556        bottom_margin: f.fmt_bottom_margin.map(|v| v as i32),
557        left_margin: f.fmt_left_margin.map(|v| v as i32),
558        right_margin: f.fmt_right_margin.map(|v| v as i32),
559        padding: f.fmt_padding.map(|v| v as i32),
560        border: f.fmt_border.map(|v| v as i32),
561        position: f.fmt_position.clone(),
562        is_blockquote: f.fmt_is_blockquote,
563    }
564}
565
566pub(crate) fn table_dto_to_format(t: &frontend::table::dtos::TableDto) -> crate::flow::TableFormat {
567    crate::flow::TableFormat {
568        border: t.fmt_border.map(|v| v as i32),
569        cell_spacing: t.fmt_cell_spacing.map(|v| v as i32),
570        cell_padding: t.fmt_cell_padding.map(|v| v as i32),
571        width: t.fmt_width.map(|v| v as i32),
572        alignment: t.fmt_alignment.clone(),
573    }
574}
575
576pub(crate) fn cell_dto_to_format(
577    c: &frontend::table_cell::dtos::TableCellDto,
578) -> crate::flow::CellFormat {
579    use frontend::common::entities::CellVerticalAlignment as BackendCVA;
580    crate::flow::CellFormat {
581        padding: c.fmt_padding.map(|v| v as i32),
582        border: c.fmt_border.map(|v| v as i32),
583        vertical_alignment: c.fmt_vertical_alignment.as_ref().map(|v| match v {
584            BackendCVA::Top => crate::flow::CellVerticalAlignment::Top,
585            BackendCVA::Middle => crate::flow::CellVerticalAlignment::Middle,
586            BackendCVA::Bottom => crate::flow::CellVerticalAlignment::Bottom,
587        }),
588        background_color: c.fmt_background_color.clone(),
589    }
590}