1use 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#[derive(Clone)]
22pub struct TextFrame {
23 pub(crate) doc: Arc<Mutex<TextDocumentInner>>,
24 pub(crate) frame_id: usize,
25}
26
27impl TextFrame {
28 pub fn id(&self) -> usize {
30 self.frame_id
31 }
32
33 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 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 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
79pub(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
117pub(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
141fn 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 elements.push(FlowElement::Block(TextBlock {
153 doc: Arc::clone(doc_arc),
154 block_id: entry as usize,
155 }));
156 } else if entry < 0 {
157 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 elements.push(FlowElement::Table(TextTable {
166 doc: Arc::clone(doc_arc),
167 table_id: table_id as usize,
168 }));
169 } else {
170 elements.push(FlowElement::Frame(TextFrame {
172 doc: Arc::clone(doc_arc),
173 frame_id: sub_frame_id as usize,
174 }));
175 }
176 }
177 }
178 }
180
181 elements
182}
183
184fn flow_fallback(
186 inner: &TextDocumentInner,
187 doc_arc: &Arc<Mutex<TextDocumentInner>>,
188 frame_dto: &frontend::frame::dtos::FrameDto,
189) -> Vec<FlowElement> {
190 let cell_frame_ids = build_cell_frame_ids(inner);
192
193 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 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; }
226 if cell_frame_ids.contains(&(f.id as EntityId)) {
227 continue; }
229 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
248fn 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
260pub(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
277fn 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
301fn 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; 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
429pub(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
478fn 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 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
547pub(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}