Skip to main content

text_typeset/layout/
flow.rs

1use std::collections::HashMap;
2
3use crate::font::registry::FontRegistry;
4use crate::layout::block::{
5    BlockLayout, BlockLayoutParams, PaintSpan, apply_paint_spans, layout_block,
6};
7use crate::layout::frame::{FrameLayout, FrameLayoutParams, layout_frame};
8use crate::layout::table::{TableLayout, TableLayoutParams, layout_table};
9
10pub enum FlowItem {
11    Block {
12        block_id: usize,
13        y: f32,
14        height: f32,
15    },
16    Table {
17        table_id: usize,
18        y: f32,
19        height: f32,
20    },
21    Frame {
22        frame_id: usize,
23        y: f32,
24        height: f32,
25    },
26}
27
28pub struct FlowLayout {
29    pub blocks: HashMap<usize, BlockLayout>,
30    pub tables: HashMap<usize, TableLayout>,
31    pub frames: HashMap<usize, FrameLayout>,
32    pub flow_order: Vec<FlowItem>,
33    pub content_height: f32,
34    pub viewport_width: f32,
35    pub viewport_height: f32,
36    pub cached_max_content_width: f32,
37    /// Device pixel ratio passed to shapers and rasterizers.
38    /// Layout is always stored in logical pixels; this only affects
39    /// precision (physical ppem) and glyph bitmap resolution.
40    pub scale_factor: f32,
41    /// Per-document logical text-magnification factor (`1.0` = none). Set from
42    /// `DocumentFlow::font_scale` at layout time and threaded into block layout
43    /// alongside `scale_factor`; multiplies the resolved font size so all text
44    /// grows logically (advances, line heights, content height) and reflows.
45    pub font_scale: f32,
46    /// Un-overlaid (shaped) copy of each block that currently carries a paint
47    /// overlay, keyed by block_id. The paint-overlay fast path re-derives the
48    /// live block from this so repeated highlight changes never compound run
49    /// splits.
50    ///
51    /// **Captured on write, not at layout.** Straight out of a full layout the
52    /// live blocks already ARE their own base, so a block enters this map only
53    /// when an overlay is first applied to it, and leaves when its overlay is
54    /// cleared. A document nothing highlights therefore keeps this map empty.
55    /// Capturing every block up front instead cost a second deep copy of the
56    /// whole shaped layout: on a book-length manuscript, 17 MB that only a
57    /// handful of blocks would ever have used.
58    ///
59    /// Absent means "identical to the live block", never "missing".
60    base_blocks: HashMap<usize, BlockLayout>,
61    /// Current paint-only highlight overlay per block_id. Empty for a block
62    /// means "no overlay" (base colors). Kept so an incrementally relaid block
63    /// re-applies its overlay.
64    pending_paint_spans: HashMap<usize, Vec<PaintSpan>>,
65}
66
67impl Default for FlowLayout {
68    fn default() -> Self {
69        Self::new()
70    }
71}
72
73impl FlowLayout {
74    pub fn new() -> Self {
75        Self {
76            blocks: HashMap::new(),
77            tables: HashMap::new(),
78            frames: HashMap::new(),
79            flow_order: Vec::new(),
80            content_height: 0.0,
81            viewport_width: 0.0,
82            viewport_height: 0.0,
83            cached_max_content_width: 0.0,
84            scale_factor: 1.0,
85            font_scale: 1.0,
86            base_blocks: HashMap::new(),
87            pending_paint_spans: HashMap::new(),
88        }
89    }
90
91    /// Add a table to the flow at the current y position.
92    pub fn add_table(
93        &mut self,
94        registry: &FontRegistry,
95        params: &TableLayoutParams,
96        available_width: f32,
97    ) {
98        let mut table = layout_table(
99            registry,
100            params,
101            available_width,
102            self.scale_factor,
103            self.font_scale,
104        );
105
106        let mut y = self.content_height;
107        table.y = y;
108        y += table.total_height;
109
110        self.flow_order.push(FlowItem::Table {
111            table_id: table.table_id,
112            y: table.y,
113            height: table.total_height,
114        });
115        if table.total_width > self.cached_max_content_width {
116            self.cached_max_content_width = table.total_width;
117        }
118        self.tables.insert(table.table_id, table);
119        self.content_height = y;
120    }
121
122    /// Add a frame to the flow.
123    ///
124    /// - **Inline**: placed in normal flow, advances content_height.
125    /// - **FloatLeft**: placed at current y, x=0. Does not advance content_height
126    ///   (surrounding content wraps around it).
127    /// - **FloatRight**: placed at current y, x=available_width - frame_width.
128    /// - **Absolute**: placed at (margin_left, margin_top) from document origin.
129    ///   Does not affect flow at all.
130    pub fn add_frame(
131        &mut self,
132        registry: &FontRegistry,
133        params: &FrameLayoutParams,
134        available_width: f32,
135    ) {
136        use crate::layout::frame::FramePosition;
137
138        let mut frame = layout_frame(
139            registry,
140            params,
141            available_width,
142            self.scale_factor,
143            self.font_scale,
144        );
145
146        match params.position {
147            FramePosition::Inline => {
148                frame.y = self.content_height;
149                frame.x = 0.0;
150                self.content_height += frame.total_height;
151            }
152            FramePosition::FloatLeft => {
153                frame.y = self.content_height;
154                frame.x = 0.0;
155                // Float doesn't advance content_height -content wraps beside it.
156                // For simplicity, we still advance so subsequent blocks appear below.
157                // True float wrapping would require a "float exclusion zone" tracked
158                // during paragraph layout, which is significantly more complex.
159                self.content_height += frame.total_height;
160            }
161            FramePosition::FloatRight => {
162                frame.y = self.content_height;
163                frame.x = (available_width - frame.total_width).max(0.0);
164                self.content_height += frame.total_height;
165            }
166            FramePosition::Absolute => {
167                // Absolute frames are positioned relative to the document origin
168                // using their margin values as coordinates. They don't affect flow.
169                frame.y = params.margin_top;
170                frame.x = params.margin_left;
171                // Don't advance content_height
172            }
173        }
174
175        self.flow_order.push(FlowItem::Frame {
176            frame_id: frame.frame_id,
177            y: frame.y,
178            height: frame.total_height,
179        });
180        if frame.total_width > self.cached_max_content_width {
181            self.cached_max_content_width = frame.total_width;
182        }
183        self.frames.insert(frame.frame_id, frame);
184    }
185
186    /// Clear all layout state. Call before rebuilding from a new FlowSnapshot.
187    pub fn clear(&mut self) {
188        self.blocks.clear();
189        self.tables.clear();
190        self.frames.clear();
191        self.flow_order.clear();
192        self.content_height = 0.0;
193        self.cached_max_content_width = 0.0;
194        self.base_blocks.clear();
195        self.pending_paint_spans.clear();
196    }
197
198    /// Drop every captured paint base. Called after a full layout, where the
199    /// freshly-shaped blocks are their own base and any prior overlay is gone.
200    ///
201    /// This used to deep-copy every laid-out block into `base_blocks` here. The
202    /// copy was correct and almost entirely unused: only a block that actually
203    /// receives an overlay is ever re-derived from its base, and
204    /// [`ensure_base`](Self::ensure_base) takes that copy at the moment it is
205    /// needed instead.
206    pub(crate) fn reset_paint_base(&mut self) {
207        self.base_blocks.clear();
208    }
209
210    /// How many blocks currently hold a captured paint base.
211    ///
212    /// The memory characteristic this layout makes a promise about: a block
213    /// enters the set when an overlay is applied to it and leaves when that
214    /// overlay is cleared, so a document nothing highlights answers `0`. Read by
215    /// the paint-overlay tests, and useful in a debugger when a highlight looks
216    /// stuck.
217    pub fn captured_paint_bases(&self) -> usize {
218        self.base_blocks.len()
219    }
220
221    /// Capture `block_id`'s live (base-coloured) shaped output, if it has not
222    /// been captured already. Returns whether the block exists at all.
223    ///
224    /// Called immediately before an overlay is applied, which is the only moment
225    /// a base is needed and the only moment the live block is still guaranteed
226    /// to be un-overlaid.
227    fn ensure_base(&mut self, block_id: usize) -> bool {
228        if self.base_blocks.contains_key(&block_id) {
229            return true;
230        }
231        let Some(fresh) = find_block_ref(self, block_id).cloned() else {
232            return false;
233        };
234        self.base_blocks.insert(block_id, fresh);
235        true
236    }
237
238    /// Forget the captured base of every block that no longer carries an
239    /// overlay, so toggling a highlight on and off does not accumulate copies.
240    ///
241    /// Safe only after the overlay walk has restored those blocks from their
242    /// bases: dropping a base a block still needs would freeze its colours.
243    fn drop_unused_bases(&mut self) {
244        if self.pending_paint_spans.is_empty() {
245            self.base_blocks.clear();
246            return;
247        }
248        self.base_blocks
249            .retain(|id, _| self.pending_paint_spans.contains_key(id));
250    }
251
252    /// Replace the paint-only color overlay for the whole flow.
253    ///
254    /// `spans_by_block` maps block_id → its disjoint paint spans (from
255    /// `text_document`'s `extract_paint_spans`). Every block is re-derived from
256    /// its captured base, so colors/decorations change but glyph positions,
257    /// advances, line breaks, and heights do NOT — no reshape, no reflow.
258    /// Blocks absent from the map reset to base colors.
259    pub fn apply_paint_spans_for(&mut self, spans_by_block: HashMap<usize, Vec<PaintSpan>>) {
260        // An empty span list means "no overlay", exactly as it does in
261        // `apply_block_paint_spans`. Keeping such an entry would pin a base copy
262        // for a block that carries nothing, which is the cost this capture-on-
263        // write layout exists to avoid.
264        let mut spans_by_block = spans_by_block;
265        spans_by_block.retain(|_, spans| !spans.is_empty());
266        // Capture a base for every block about to be overlaid. A block that is
267        // only being cleared keeps the base it was given when it was overlaid,
268        // which is what the walk below restores it from.
269        for &block_id in spans_by_block.keys() {
270            self.ensure_base(block_id);
271        }
272        self.pending_paint_spans = spans_by_block;
273        let base = &self.base_blocks;
274        let pending = &self.pending_paint_spans;
275        for b in self.blocks.values_mut() {
276            overlay_block_in_place(b, base, pending);
277        }
278        for t in self.tables.values_mut() {
279            for c in &mut t.cell_layouts {
280                for b in &mut c.blocks {
281                    overlay_block_in_place(b, base, pending);
282                }
283            }
284        }
285        for f in self.frames.values_mut() {
286            overlay_frame_in_place(f, base, pending);
287        }
288        self.drop_unused_bases();
289    }
290
291    /// Apply (or clear, when `spans` is empty) the paint overlay for a single
292    /// block, re-derived from its base.
293    ///
294    /// Returns `false` when there is nothing to do: either the block is not in
295    /// this layout at all, or it is being cleared while it never carried an
296    /// overlay, in which case it already shows its base colours. Callers read
297    /// the answer as "did anything change here", and repaint on `true`.
298    pub fn apply_block_paint_spans(&mut self, block_id: usize, spans: &[PaintSpan]) -> bool {
299        if spans.is_empty() {
300            if !self.base_blocks.contains_key(&block_id) {
301                return false;
302            }
303            self.pending_paint_spans.remove(&block_id);
304        } else {
305            if !self.ensure_base(block_id) {
306                return false;
307            }
308            self.pending_paint_spans.insert(block_id, spans.to_vec());
309        }
310        let base = &self.base_blocks;
311        let pending = &self.pending_paint_spans;
312        if let Some(b) = self.blocks.get_mut(&block_id) {
313            overlay_block_in_place(b, base, pending);
314            self.drop_unused_bases();
315            return true;
316        }
317        let mut overlaid = false;
318        for t in self.tables.values_mut() {
319            for c in &mut t.cell_layouts {
320                for b in &mut c.blocks {
321                    if b.block_id == block_id {
322                        overlay_block_in_place(b, base, pending);
323                        overlaid = true;
324                    }
325                }
326            }
327        }
328        if overlaid {
329            self.drop_unused_bases();
330            return true;
331        }
332        for f in self.frames.values_mut() {
333            if overlay_one_in_frame(f, block_id, base, pending) {
334                self.drop_unused_bases();
335                return true;
336            }
337        }
338        // The block is in none of the three places a block can live, so nothing
339        // was recoloured and the caller has nothing to repaint.
340        self.drop_unused_bases();
341        false
342    }
343
344    /// After an incremental relayout of `block_id`, make its freshly-shaped
345    /// output the new base and re-apply its pending overlay in place.
346    ///
347    /// The stale capture is **dropped** rather than refreshed. The fresh shaped
348    /// output IS the new base, so a later `apply_block_paint_spans` (the engine
349    /// re-applying syntax, search or spell highlights after an edit) captures it
350    /// on demand. Keeping the pre-edit copy instead would have that overlay
351    /// re-derive the block from text the writer has already changed, silently
352    /// clobbering the just-typed characters (visible only in highlights-on
353    /// views; a full re-layout from a resize would restore it).
354    fn refresh_base_and_overlay_block(&mut self, block_id: usize) {
355        self.base_blocks.remove(&block_id);
356        // Nothing to overlay unless this block itself carries pending spans: the
357        // freshly-reshaped block already holds the correct base-colored output,
358        // and every other block keeps whatever base it was captured with.
359        if !self.pending_paint_spans.contains_key(&block_id) {
360            return;
361        }
362        self.ensure_base(block_id);
363        let base = &self.base_blocks;
364        let pending = &self.pending_paint_spans;
365        if let Some(b) = self.blocks.get_mut(&block_id) {
366            overlay_block_in_place(b, base, pending);
367            return;
368        }
369        for t in self.tables.values_mut() {
370            for c in &mut t.cell_layouts {
371                for b in &mut c.blocks {
372                    if b.block_id == block_id {
373                        overlay_block_in_place(b, base, pending);
374                        return;
375                    }
376                }
377            }
378        }
379        for f in self.frames.values_mut() {
380            if overlay_one_in_frame(f, block_id, base, pending) {
381                return;
382            }
383        }
384    }
385
386    /// Add a single block to the flow at the current y position.
387    ///
388    /// **Bulk-path primitive.** This touches no paint-overlay bookkeeping at
389    /// all, which is what a full layout wants: it runs after `clear`, so no
390    /// stale base or pending overlay can be left over, and a base is captured
391    /// on demand when an overlay is first applied.
392    ///
393    /// Appending to an *existing* layout is different, because that layout may
394    /// already hold a base or a pending overlay under the same block_id — from
395    /// a previous block that carried it. Use
396    /// [`append_block`](Self::append_block) there. Reaching for this one is
397    /// silent when wrong: the block lays out and renders fine, but a stale base
398    /// re-derives it from the *previous* block's shaped output the next time
399    /// anything recolours it.
400    pub fn add_block(
401        &mut self,
402        registry: &FontRegistry,
403        params: &BlockLayoutParams,
404        available_width: f32,
405    ) {
406        let mut block = layout_block(
407            registry,
408            params,
409            available_width,
410            self.scale_factor,
411            self.font_scale,
412        );
413
414        // Margin collapsing with previous block
415        let mut y = self.content_height;
416        if let Some(FlowItem::Block {
417            block_id: prev_id, ..
418        }) = self.flow_order.last()
419        {
420            if let Some(prev_block) = self.blocks.get(prev_id) {
421                let collapsed = prev_block.bottom_margin.max(block.top_margin);
422                y -= prev_block.bottom_margin;
423                y += collapsed;
424            } else {
425                y += block.top_margin;
426            }
427        } else {
428            y += block.top_margin;
429        }
430
431        block.y = y;
432        let block_content = block.height - block.top_margin - block.bottom_margin;
433        y += block_content + block.bottom_margin;
434
435        self.flow_order.push(FlowItem::Block {
436            block_id: block.block_id,
437            y: block.y,
438            height: block.height,
439        });
440        self.update_max_width_for_block(&block);
441        self.blocks.insert(block.block_id, block);
442        self.content_height = y;
443    }
444
445    /// Append one block to the tail of an *existing* layout, in O(1).
446    ///
447    /// This is [`add_block`](Self::add_block) plus the paint-overlay
448    /// bookkeeping that only a tail append needs. A full layout runs after
449    /// `clear`, so nothing can be stale there; appending into a live layout can
450    /// land on a block_id that still carries the base and pending overlay of the
451    /// block that held it before, and re-deriving the new block from that base
452    /// would paint the *old* block's shaped output.
453    ///
454    /// So it drops any stale base for the appended id and re-applies whatever
455    /// overlay is still pending for it, in O(1)
456    /// (`refresh_base_and_overlay_block`, the same call
457    /// [`relayout_block`](Self::relayout_block) already relies on).
458    pub fn append_block(
459        &mut self,
460        registry: &FontRegistry,
461        params: &BlockLayoutParams,
462        available_width: f32,
463    ) {
464        self.add_block(registry, params, available_width);
465        self.refresh_base_and_overlay_block(params.block_id);
466    }
467
468    /// Drop the first `n` top-level blocks, returning how many were removed.
469    ///
470    /// The eviction half of a bounded streaming buffer (a log viewer's
471    /// scrollback cap). Usually O(n) map removals plus one `Vec` memmove of the
472    /// surviving `flow_order` entries — no reshaping. The return value is the
473    /// count actually evicted, which is less than `n` when the run of leading
474    /// blocks is shorter than `n` or a table/frame stops the walk.
475    ///
476    /// Surviving blocks deliberately **keep their absolute `y`**. The vacated
477    /// band at the top simply becomes empty, and `content_height` is unchanged,
478    /// so nothing below moves and no scroll position shifts under the user.
479    /// Rewriting every survivor's `y` would make eviction O(remaining) and
480    /// would yank the viewport; leaving them is both cheaper and correct.
481    /// `flow_order`'s ascending-`y` ordering — which `hit_test`'s binary search
482    /// relies on — is preserved, since removing a prefix of a sorted run leaves
483    /// it sorted.
484    ///
485    /// Only top-level blocks are considered; a leading table or frame stops the
486    /// eviction (a streaming buffer is a flat run of blocks by construction).
487    ///
488    /// If the widest block in the flow is among those evicted,
489    /// `max_content_width` is recomputed from the survivors — O(remaining) for
490    /// that call only. Evicting narrower blocks (the overwhelmingly common
491    /// case) cannot lower the maximum and skips the recompute.
492    pub fn remove_leading(&mut self, n: usize) -> usize {
493        let mut removed = 0;
494        let mut evicted_widest = false;
495
496        for item in self.flow_order.iter().take(n) {
497            let FlowItem::Block { block_id, .. } = item else {
498                break;
499            };
500            if let Some(block) = self.blocks.remove(block_id) {
501                // `cached_max_content_width` only ever grows, so it goes stale
502                // exactly when the block that set it leaves. Comparing against
503                // it here keeps the common case O(n).
504                if block_max_width(&block) >= self.cached_max_content_width {
505                    evicted_widest = true;
506                }
507            }
508            self.base_blocks.remove(block_id);
509            self.pending_paint_spans.remove(block_id);
510            removed += 1;
511        }
512
513        self.flow_order.drain(..removed);
514        if evicted_widest {
515            self.recompute_max_content_width();
516        }
517        removed
518    }
519
520    /// Re-derive `cached_max_content_width` from everything currently laid out.
521    ///
522    /// The cache is a running maximum that only grows, which is fine while a
523    /// flow only ever gains content. Anything that *removes* content has to
524    /// re-derive it, or the horizontal scroll range keeps describing content
525    /// that is no longer there.
526    pub(crate) fn recompute_max_content_width(&mut self) {
527        let mut max: f32 = 0.0;
528        for block in self.blocks.values() {
529            max = max.max(block_max_width(block));
530        }
531        for table in self.tables.values() {
532            max = max.max(table.total_width);
533        }
534        for frame in self.frames.values() {
535            max = max.max(frame.total_width);
536        }
537        self.cached_max_content_width = max;
538    }
539
540    /// Declare the total extent of a uniform-row-height document without
541    /// shaping anything.
542    ///
543    /// In windowed mode `content_height` describes the whole document, not the
544    /// shaped window, so it cannot come from the usual accumulator. Use this to
545    /// keep the scrollbar honest when the row count changes outside the shaped
546    /// window (a line appended while the user is scrolled away from the tail).
547    ///
548    /// Leaves the shaped window untouched.
549    pub fn set_uniform_extent(&mut self, total_rows: usize, row_height: f32) {
550        self.content_height = total_rows as f32 * row_height;
551    }
552
553    /// Shape only `window` — a slice of a much larger uniform-row-height
554    /// document — placing each row at an arithmetic `y = index * row_height`.
555    ///
556    /// Shaping every line is what makes a large document expensive: a resident
557    /// shaped line costs ~6.5 KB, so a 100 000-line buffer costs ~623 MB fully
558    /// laid out, against ~1 MB for a viewport-sized window
559    /// (`docs/streaming-baseline.md`). Rendering already culls to the viewport,
560    /// so shaping the off-screen remainder buys nothing.
561    ///
562    /// `y` is arithmetic rather than accumulated precisely so that a row can be
563    /// placed without having laid out — or even having in memory — any of the
564    /// rows above it, which is what lets the window start at an arbitrary
565    /// scroll position. `content_height` is likewise derived from
566    /// `total_rows`, so the scrollbar reflects the whole document rather than
567    /// the shaped window.
568    ///
569    /// # Invariants
570    ///
571    /// The arithmetic placement is only correct for a document whose rows are
572    /// genuinely uniform: **one row = one visual line of exactly `row_height`**
573    /// — no wrapping (`non_breakable_lines`), no embedded newlines, no
574    /// per-row margins, one font size throughout. That suits log/console
575    /// output and monospaced code; it does not suit prose. Callers with
576    /// variable-height content must use [`layout_blocks`](Self::layout_blocks).
577    /// `window` must be sorted ascending by index, which keeps `flow_order`
578    /// ascending by `y` as `hit_test`'s binary search requires. Both are
579    /// checked in debug builds.
580    ///
581    /// After this call, appending at the tail with
582    /// [`append_block`](Self::append_block) stays correct: `content_height` is
583    /// exactly `total_rows * row_height`, which is where row `total_rows`
584    /// belongs. Trim the window's front with
585    /// [`remove_leading`](Self::remove_leading).
586    ///
587    /// # Behaviour worth knowing
588    ///
589    /// Like [`layout_blocks`](Self::layout_blocks), this drops any paint
590    /// overlay: re-apply spans after re-windowing, or the new rows render in
591    /// base colours. Because this runs on every visible-range change, that
592    /// re-apply is part of the scroll path, not a one-off.
593    ///
594    /// `max_content_width` accumulates across windows rather than being
595    /// re-derived per window: it reports the widest row *seen so far*, not the
596    /// widest row in the document (unknowable without shaping all of it) and
597    /// not the widest row on screen (which would make the horizontal scrollbar
598    /// jump on every vertical scroll). It therefore only grows during a
599    /// windowed session.
600    ///
601    /// `y` is `index * row_height` in `f32`, which represents consecutive
602    /// integers exactly only to 2^24: past ~840 000 rows at a 20 px row height,
603    /// row positions begin quantizing and neighbouring rows drift out of
604    /// alignment. Well beyond the sizes this targets, but not infinite.
605    pub fn layout_window(
606        &mut self,
607        registry: &FontRegistry,
608        window: &[(usize, BlockLayoutParams)],
609        total_rows: usize,
610        row_height: f32,
611        available_width: f32,
612    ) {
613        debug_assert!(
614            window.windows(2).all(|w| w[0].0 < w[1].0),
615            "layout_window: window must be sorted ascending by row index, else \
616             flow_order stops being ascending by y and hit_test's binary search \
617             silently misreports rows"
618        );
619        debug_assert!(
620            window.last().is_none_or(|(last, _)| *last < total_rows),
621            "layout_window: window reaches row {:?} but the document declares \
622             only {total_rows} rows — those rows would sit below content_height \
623             and be unreachable by scrolling",
624            window.last().map(|(i, _)| *i)
625        );
626
627        // The widest row seen so far must survive the rebuild: re-deriving it
628        // from the window alone would make the horizontal scroll range track
629        // whatever happens to be on screen, so it would jump on every vertical
630        // scroll.
631        let max_width_seen = self.cached_max_content_width;
632        self.clear();
633        self.cached_max_content_width = max_width_seen;
634
635        for (index, params) in window {
636            let mut block = layout_block(
637                registry,
638                params,
639                available_width,
640                self.scale_factor,
641                self.font_scale,
642            );
643            debug_assert!(
644                (block.height - row_height).abs() < 0.5,
645                "layout_window: row {index} laid out {:.2}px tall against a \
646                 declared row_height of {row_height:.2}px — the row is not a \
647                 single unwrapped line, so arithmetic y placement would drift",
648                block.height
649            );
650
651            let y = *index as f32 * row_height;
652            block.y = y;
653            self.flow_order.push(FlowItem::Block {
654                block_id: block.block_id,
655                y,
656                height: block.height,
657            });
658            self.update_max_width_for_block(&block);
659            self.blocks.insert(block.block_id, block);
660        }
661
662        // Describes the whole document, not the shaped window — so the
663        // scrollbar spans everything even though almost none of it is shaped.
664        self.set_uniform_extent(total_rows, row_height);
665        // O(1): a full layout leaves the live blocks as their own base.
666        self.reset_paint_base();
667    }
668
669    /// Lay out a sequence of blocks vertically.
670    pub fn layout_blocks(
671        &mut self,
672        registry: &FontRegistry,
673        block_params: Vec<BlockLayoutParams>,
674        available_width: f32,
675    ) {
676        self.clear();
677        // Note: viewport_width is NOT set here. It's a display property
678        // set by Typesetter::set_viewport(), not a layout property.
679        // available_width is the layout width which may differ from viewport
680        // when using ContentWidthMode::Fixed.
681        for params in &block_params {
682            self.add_block(registry, params, available_width);
683        }
684        // A full layout clears any prior overlay (see `clear`), so the live
685        // blocks ARE the base at this point. The engine applies paint spans
686        // afterward via `apply_paint_spans_for`, which captures what it needs.
687        self.reset_paint_base();
688    }
689
690    /// Update a single block's layout and shift subsequent items if height changed.
691    ///
692    /// Finds the block in top-level blocks, table cells, or frames, re-layouts
693    /// it, and propagates any height delta to subsequent flow items.
694    /// Relayout the one block `params` names, wherever it lives, and shift the
695    /// document-character positions of everything after it.
696    ///
697    /// Returns `false` when the block is in none of the three places a block can
698    /// be — top level, a table cell, a frame. The caller must treat that as a
699    /// failed relayout and fall back to a full one: the shift is half of this
700    /// method's job, so skipping it silently leaves every later block's
701    /// `position` describing the document as it was before the edit.
702    #[must_use]
703    pub fn relayout_block(
704        &mut self,
705        registry: &FontRegistry,
706        params: &BlockLayoutParams,
707        available_width: f32,
708    ) -> bool {
709        let block_id = params.block_id;
710
711        // Top-level block
712        if self.blocks.contains_key(&block_id) {
713            self.relayout_top_level_block(registry, params, available_width);
714            self.refresh_base_and_overlay_block(block_id);
715            return true;
716        }
717
718        // Table cell block: scan tables for the block_id
719        let table_match = self.tables.iter().find_map(|(&tid, table)| {
720            for cell in &table.cell_layouts {
721                if cell.blocks.iter().any(|b| b.block_id == block_id) {
722                    return Some((tid, cell.row, cell.column));
723                }
724            }
725            None
726        });
727        if let Some((table_id, row, col)) = table_match {
728            let old_char_len = block_char_len(find_block_ref(self, block_id));
729            self.relayout_table_block(registry, params, table_id, row, col);
730            let new_char_len = block_char_len(find_block_ref(self, block_id));
731            let char_delta = new_char_len as isize - old_char_len as isize;
732            self.shift_block_positions_after_table_block(table_id, block_id, char_delta);
733            self.refresh_base_and_overlay_block(block_id);
734            return true;
735        }
736
737        // Frame block: scan frames (including nested frames) for the block_id
738        let frame_match = self.frames.iter().find_map(|(&fid, frame)| {
739            if frame_contains_block(frame, block_id) {
740                return Some(fid);
741            }
742            None
743        });
744        if let Some(frame_id) = frame_match {
745            let old_char_len = block_char_len(find_block_ref(self, block_id));
746            self.relayout_frame_block(registry, params, frame_id);
747            let new_char_len = block_char_len(find_block_ref(self, block_id));
748            let char_delta = new_char_len as isize - old_char_len as isize;
749            self.shift_block_positions_after_frame_block(frame_id, block_id, char_delta);
750            self.refresh_base_and_overlay_block(block_id);
751            return true;
752        }
753
754        false
755    }
756
757    /// Relayout a top-level block (existing logic).
758    fn relayout_top_level_block(
759        &mut self,
760        registry: &FontRegistry,
761        params: &BlockLayoutParams,
762        available_width: f32,
763    ) {
764        let block_id = params.block_id;
765        let old_y = self.blocks.get(&block_id).map(|b| b.y).unwrap_or(0.0);
766        let old_height = self.blocks.get(&block_id).map(|b| b.height).unwrap_or(0.0);
767        let old_top_margin = self
768            .blocks
769            .get(&block_id)
770            .map(|b| b.top_margin)
771            .unwrap_or(0.0);
772        let old_bottom_margin = self
773            .blocks
774            .get(&block_id)
775            .map(|b| b.bottom_margin)
776            .unwrap_or(0.0);
777        let old_content = old_height - old_top_margin - old_bottom_margin;
778        let old_end = old_y + old_content + old_bottom_margin;
779        let old_char_len = block_char_len(self.blocks.get(&block_id));
780
781        let mut block = layout_block(
782            registry,
783            params,
784            available_width,
785            self.scale_factor,
786            self.font_scale,
787        );
788        block.y = old_y;
789
790        if (block.top_margin - old_top_margin).abs() > 0.001 {
791            let prev_bm = self.prev_block_bottom_margin(block_id).unwrap_or(0.0);
792            let old_collapsed = prev_bm.max(old_top_margin);
793            let new_collapsed = prev_bm.max(block.top_margin);
794            block.y = old_y + (new_collapsed - old_collapsed);
795        }
796
797        let new_content = block.height - block.top_margin - block.bottom_margin;
798        let new_end = block.y + new_content + block.bottom_margin;
799        let delta = new_end - old_end;
800        let new_char_len = block_char_len(Some(&block));
801        let char_delta = new_char_len as isize - old_char_len as isize;
802
803        let new_y = block.y;
804        let new_height = block.height;
805        self.update_max_width_for_block(&block);
806        self.blocks.insert(block_id, block);
807
808        // Update flow_order entry
809        for item in &mut self.flow_order {
810            if let FlowItem::Block {
811                block_id: id,
812                y,
813                height,
814            } = item
815                && *id == block_id
816            {
817                *y = new_y;
818                *height = new_height;
819                break;
820            }
821        }
822
823        self.shift_items_after_block(block_id, delta);
824        self.shift_block_positions_after_block(block_id, char_delta);
825    }
826
827    /// Relayout a block inside a table cell. Recomputes the row height
828    /// and propagates any table height delta to subsequent flow items.
829    fn relayout_table_block(
830        &mut self,
831        registry: &FontRegistry,
832        params: &BlockLayoutParams,
833        table_id: usize,
834        row: usize,
835        col: usize,
836    ) {
837        let table = match self.tables.get_mut(&table_id) {
838            Some(t) => t,
839            None => return,
840        };
841
842        let old_table_height = table.total_height;
843        recompute_table_cell(
844            table,
845            registry,
846            params,
847            row,
848            col,
849            self.scale_factor,
850            self.font_scale,
851        );
852        let delta = table.total_height - old_table_height;
853
854        // Update flow_order entry for this table
855        for item in &mut self.flow_order {
856            if let FlowItem::Table {
857                table_id: id,
858                height,
859                ..
860            } = item
861                && *id == table_id
862            {
863                *height = table.total_height;
864                break;
865            }
866        }
867
868        self.shift_items_after_table(table_id, delta);
869    }
870
871    /// Relayout a block inside a frame. Handles direct blocks, blocks in
872    /// cells of frame-nested tables, and blocks in nested frames (any
873    /// depth). Recomputes frame content height and propagates any height
874    /// delta to subsequent flow items.
875    fn relayout_frame_block(
876        &mut self,
877        registry: &FontRegistry,
878        params: &BlockLayoutParams,
879        frame_id: usize,
880    ) {
881        let old_total_height = match self.frames.get(&frame_id) {
882            Some(f) => f.total_height,
883            None => return,
884        };
885
886        {
887            let frame = self.frames.get_mut(&frame_id).unwrap();
888            relayout_block_deep_in_frame(
889                frame,
890                registry,
891                params,
892                self.scale_factor,
893                self.font_scale,
894            );
895        }
896
897        let new_total_height = self.frames[&frame_id].total_height;
898        let delta = new_total_height - old_total_height;
899
900        for item in &mut self.flow_order {
901            if let FlowItem::Frame {
902                frame_id: id,
903                height,
904                ..
905            } = item
906                && *id == frame_id
907            {
908                *height = new_total_height;
909                break;
910            }
911        }
912
913        self.shift_items_after_frame(frame_id, delta);
914    }
915
916    /// Shift the document-character `position` of every block that appears
917    /// after the given target block in flow order by `char_delta` characters.
918    ///
919    /// `shift_items_after_block` only propagates the vertical pixel delta.
920    /// This method propagates the character delta so hit_test and caret_rect
921    /// keep returning correct document positions after an incremental
922    /// relayout that changed the target block's char length (e.g. a cut or
923    /// paste inside a non-last paragraph).
924    fn shift_block_positions_after_block(&mut self, block_id: usize, char_delta: isize) {
925        self.shift_block_positions_after_flow_item(FlowItemRef::Block(block_id), char_delta);
926    }
927
928    /// Shift the document-character `position` of every block belonging to
929    /// a flow item that appears after `target` in flow order.
930    fn shift_block_positions_after_flow_item(&mut self, target: FlowItemRef, char_delta: isize) {
931        if char_delta == 0 {
932            return;
933        }
934        // Snapshot the order of items so we can mutate the containing
935        // HashMaps inside the loop.
936        let refs: Vec<FlowItemRef> = self
937            .flow_order
938            .iter()
939            .map(|item| match item {
940                FlowItem::Block { block_id, .. } => FlowItemRef::Block(*block_id),
941                FlowItem::Table { table_id, .. } => FlowItemRef::Table(*table_id),
942                FlowItem::Frame { frame_id, .. } => FlowItemRef::Frame(*frame_id),
943            })
944            .collect();
945        let mut found = false;
946        for r in refs {
947            if found {
948                match r {
949                    FlowItemRef::Block(id) => {
950                        if let Some(b) = self.blocks.get_mut(&id) {
951                            b.position = apply_char_delta(b.position, char_delta);
952                        }
953                    }
954                    FlowItemRef::Table(id) => {
955                        if let Some(t) = self.tables.get_mut(&id) {
956                            shift_block_positions_in_table(t, char_delta);
957                        }
958                    }
959                    FlowItemRef::Frame(id) => {
960                        if let Some(f) = self.frames.get_mut(&id) {
961                            shift_block_positions_in_frame(f, char_delta);
962                        }
963                    }
964                }
965            } else if r == target {
966                found = true;
967            }
968        }
969    }
970
971    /// Shift document positions after an edit inside a top-level table's
972    /// cell: cell blocks after the edited block within the table, then
973    /// every flow item after the table.
974    fn shift_block_positions_after_table_block(
975        &mut self,
976        table_id: usize,
977        block_id: usize,
978        char_delta: isize,
979    ) {
980        if char_delta == 0 {
981            return;
982        }
983        if let Some(table) = self.tables.get_mut(&table_id) {
984            shift_table_positions_after_block(table, block_id, char_delta);
985        }
986        self.shift_block_positions_after_flow_item(FlowItemRef::Table(table_id), char_delta);
987    }
988
989    /// Shift document positions after an edit inside a frame (any depth):
990    /// frame content after the edited block, then every flow item after
991    /// the frame.
992    fn shift_block_positions_after_frame_block(
993        &mut self,
994        frame_id: usize,
995        block_id: usize,
996        char_delta: isize,
997    ) {
998        if char_delta == 0 {
999            return;
1000        }
1001        if let Some(frame) = self.frames.get_mut(&frame_id) {
1002            shift_frame_positions_after_block(frame, block_id, char_delta);
1003        }
1004        self.shift_block_positions_after_flow_item(FlowItemRef::Frame(frame_id), char_delta);
1005    }
1006
1007    /// Shift all flow items after the given block by `delta` pixels.
1008    fn shift_items_after_block(&mut self, block_id: usize, delta: f32) {
1009        if delta.abs() <= 0.001 {
1010            return;
1011        }
1012        let mut found = false;
1013        for item in &mut self.flow_order {
1014            match item {
1015                FlowItem::Block {
1016                    block_id: id, y, ..
1017                } => {
1018                    if found {
1019                        *y += delta;
1020                        if let Some(b) = self.blocks.get_mut(id) {
1021                            b.y += delta;
1022                        }
1023                    }
1024                    if *id == block_id {
1025                        found = true;
1026                    }
1027                }
1028                FlowItem::Table {
1029                    table_id: id, y, ..
1030                } => {
1031                    if found {
1032                        *y += delta;
1033                        if let Some(t) = self.tables.get_mut(id) {
1034                            t.y += delta;
1035                        }
1036                    }
1037                }
1038                FlowItem::Frame {
1039                    frame_id: id, y, ..
1040                } => {
1041                    if found {
1042                        *y += delta;
1043                        if let Some(f) = self.frames.get_mut(id) {
1044                            f.y += delta;
1045                        }
1046                    }
1047                }
1048            }
1049        }
1050        self.content_height += delta;
1051    }
1052
1053    /// Shift all flow items after the given table by `delta` pixels.
1054    fn shift_items_after_table(&mut self, table_id: usize, delta: f32) {
1055        if delta.abs() <= 0.001 {
1056            return;
1057        }
1058        let mut found = false;
1059        for item in &mut self.flow_order {
1060            match item {
1061                FlowItem::Table {
1062                    table_id: id, y, ..
1063                } => {
1064                    if *id == table_id {
1065                        found = true;
1066                        continue;
1067                    }
1068                    if found {
1069                        *y += delta;
1070                        if let Some(t) = self.tables.get_mut(id) {
1071                            t.y += delta;
1072                        }
1073                    }
1074                }
1075                FlowItem::Block {
1076                    block_id: id, y, ..
1077                } => {
1078                    if found {
1079                        *y += delta;
1080                        if let Some(b) = self.blocks.get_mut(id) {
1081                            b.y += delta;
1082                        }
1083                    }
1084                }
1085                FlowItem::Frame {
1086                    frame_id: id, y, ..
1087                } => {
1088                    if found {
1089                        *y += delta;
1090                        if let Some(f) = self.frames.get_mut(id) {
1091                            f.y += delta;
1092                        }
1093                    }
1094                }
1095            }
1096        }
1097        self.content_height += delta;
1098    }
1099
1100    /// Shift all flow items after the given frame by `delta` pixels.
1101    fn shift_items_after_frame(&mut self, frame_id: usize, delta: f32) {
1102        if delta.abs() <= 0.001 {
1103            return;
1104        }
1105        let mut found = false;
1106        for item in &mut self.flow_order {
1107            match item {
1108                FlowItem::Frame {
1109                    frame_id: id, y, ..
1110                } => {
1111                    if *id == frame_id {
1112                        found = true;
1113                        continue;
1114                    }
1115                    if found {
1116                        *y += delta;
1117                        if let Some(f) = self.frames.get_mut(id) {
1118                            f.y += delta;
1119                        }
1120                    }
1121                }
1122                FlowItem::Block {
1123                    block_id: id, y, ..
1124                } => {
1125                    if found {
1126                        *y += delta;
1127                        if let Some(b) = self.blocks.get_mut(id) {
1128                            b.y += delta;
1129                        }
1130                    }
1131                }
1132                FlowItem::Table {
1133                    table_id: id, y, ..
1134                } => {
1135                    if found {
1136                        *y += delta;
1137                        if let Some(t) = self.tables.get_mut(id) {
1138                            t.y += delta;
1139                        }
1140                    }
1141                }
1142            }
1143        }
1144        self.content_height += delta;
1145    }
1146
1147    /// Update the cached max content width considering a single block's lines.
1148    fn update_max_width_for_block(&mut self, block: &BlockLayout) {
1149        let w = block_max_width(block);
1150        if w > self.cached_max_content_width {
1151            self.cached_max_content_width = w;
1152        }
1153    }
1154
1155    /// Find the bottom margin of the block immediately before `block_id` in flow order.
1156    fn prev_block_bottom_margin(&self, block_id: usize) -> Option<f32> {
1157        let mut prev_bm = None;
1158        for item in &self.flow_order {
1159            match item {
1160                FlowItem::Block { block_id: id, .. } => {
1161                    if *id == block_id {
1162                        return prev_bm;
1163                    }
1164                    if let Some(b) = self.blocks.get(id) {
1165                        prev_bm = Some(b.bottom_margin);
1166                    }
1167                }
1168                _ => {
1169                    // Non-block items reset margin collapsing
1170                    prev_bm = None;
1171                }
1172            }
1173        }
1174        None
1175    }
1176}
1177
1178#[derive(Clone, Copy, PartialEq, Eq)]
1179enum FlowItemRef {
1180    Block(usize),
1181    Table(usize),
1182    Frame(usize),
1183}
1184
1185fn block_char_len(block: Option<&BlockLayout>) -> usize {
1186    block
1187        .and_then(|b| b.lines.last().map(|l| l.char_range.end))
1188        .unwrap_or(0)
1189}
1190
1191fn apply_char_delta(position: usize, delta: isize) -> usize {
1192    if delta >= 0 {
1193        position + delta as usize
1194    } else {
1195        position.saturating_sub((-delta) as usize)
1196    }
1197}
1198
1199fn shift_block_positions_in_slice(blocks: &mut [BlockLayout], delta: isize) {
1200    for block in blocks {
1201        block.position = apply_char_delta(block.position, delta);
1202    }
1203}
1204
1205fn shift_block_positions_in_table(table: &mut TableLayout, delta: isize) {
1206    for cell in &mut table.cell_layouts {
1207        shift_block_positions_in_slice(&mut cell.blocks, delta);
1208    }
1209}
1210
1211fn shift_block_positions_in_frame(frame: &mut FrameLayout, delta: isize) {
1212    shift_block_positions_in_slice(&mut frame.blocks, delta);
1213    for table in &mut frame.tables {
1214        shift_block_positions_in_table(table, delta);
1215    }
1216    for nested in &mut frame.frames {
1217        shift_block_positions_in_frame(nested, delta);
1218    }
1219}
1220
1221/// Shift the `position` of every cell block that comes after `block_id`
1222/// within `table` (cells iterate in document/row-major order). Returns
1223/// `true` when the edited block was found in this table.
1224fn shift_table_positions_after_block(
1225    table: &mut TableLayout,
1226    block_id: usize,
1227    delta: isize,
1228) -> bool {
1229    let mut found = false;
1230    for cell in &mut table.cell_layouts {
1231        for b in &mut cell.blocks {
1232            if found {
1233                b.position = apply_char_delta(b.position, delta);
1234            } else if b.block_id == block_id {
1235                found = true;
1236            }
1237        }
1238    }
1239    found
1240}
1241
1242/// Shift the `position` of every block that comes after `block_id` in
1243/// `frame`'s document order — walking `flow_order` so interleaved blocks,
1244/// tables, and nested frames shift correctly. Returns `true` when the
1245/// edited block was found in this frame tree.
1246fn shift_frame_positions_after_block(
1247    frame: &mut FrameLayout,
1248    block_id: usize,
1249    delta: isize,
1250) -> bool {
1251    let order = frame.flow_order.clone();
1252    let mut found = false;
1253    for child in &order {
1254        match child {
1255            crate::layout::frame::FrameChildRef::Block(bid) => {
1256                if found {
1257                    if let Some(b) = frame.blocks.iter_mut().find(|b| b.block_id == *bid) {
1258                        b.position = apply_char_delta(b.position, delta);
1259                    }
1260                } else if *bid == block_id {
1261                    found = true;
1262                }
1263            }
1264            crate::layout::frame::FrameChildRef::Table(tid) => {
1265                if let Some(t) = frame.tables.iter_mut().find(|t| t.table_id == *tid) {
1266                    if found {
1267                        shift_block_positions_in_table(t, delta);
1268                    } else {
1269                        found = shift_table_positions_after_block(t, block_id, delta);
1270                    }
1271                }
1272            }
1273            crate::layout::frame::FrameChildRef::Frame(fid) => {
1274                if let Some(nested) = frame.frames.iter_mut().find(|f| f.frame_id == *fid) {
1275                    if found {
1276                        shift_block_positions_in_frame(nested, delta);
1277                    } else {
1278                        found = shift_frame_positions_after_block(nested, block_id, delta);
1279                    }
1280                }
1281            }
1282        }
1283    }
1284    found
1285}
1286
1287// ── Paint-overlay helpers (recolor without reshape/reflow) ──────────────────
1288
1289/// Re-derive `b` in place from its base + pending overlay. No-op if no base
1290/// was captured for it.
1291///
1292/// The base supplies the *shaped* output — runs, glyphs, line breaks — which is
1293/// what a recolor re-derives. It does **not** supply where the block sits.
1294///
1295/// Those are two different lifetimes. A base is captured when its own block is
1296/// laid out, but a block's placement changes without it being laid out at all:
1297/// an edit anywhere above shifts every later block's document-character
1298/// `position` and its `y`, live, through `shift_block_positions_after_block` and
1299/// `shift_items_after_block` — neither of which re-captures the bases they
1300/// invalidate. `apply_paint_spans` opens with `base.clone()`, so overlaying
1301/// without care puts a block back where it was before an edit it was never part
1302/// of. `hit_test` and `caret_rect` read `position` straight, so from then on a
1303/// click near that block landed N characters early and its selection highlights
1304/// painted N characters off — N being however many characters had been typed
1305/// above it. Only a full relayout recovered.
1306///
1307/// Carrying the live placement across is the whole fix: it is exactly the two
1308/// fields the shift functions own, and the live block is never the staler of the
1309/// two — a relayout of this block refreshes its base from it.
1310fn overlay_block_in_place(
1311    b: &mut BlockLayout,
1312    base: &HashMap<usize, BlockLayout>,
1313    pending: &HashMap<usize, Vec<PaintSpan>>,
1314) {
1315    if let Some(base_b) = base.get(&b.block_id) {
1316        let empty: Vec<PaintSpan> = Vec::new();
1317        let spans = pending.get(&b.block_id).unwrap_or(&empty);
1318        let (position, y) = (b.position, b.y);
1319        *b = apply_paint_spans(base_b, spans);
1320        b.position = position;
1321        b.y = y;
1322    }
1323}
1324
1325/// Re-derive every block in a frame (recursively) from base + pending.
1326fn overlay_frame_in_place(
1327    frame: &mut FrameLayout,
1328    base: &HashMap<usize, BlockLayout>,
1329    pending: &HashMap<usize, Vec<PaintSpan>>,
1330) {
1331    for b in &mut frame.blocks {
1332        overlay_block_in_place(b, base, pending);
1333    }
1334    for t in &mut frame.tables {
1335        for c in &mut t.cell_layouts {
1336            for b in &mut c.blocks {
1337                overlay_block_in_place(b, base, pending);
1338            }
1339        }
1340    }
1341    for nested in &mut frame.frames {
1342        overlay_frame_in_place(nested, base, pending);
1343    }
1344}
1345
1346/// Re-derive a single block (by id) inside a frame (recursively). Returns true
1347/// if found.
1348fn overlay_one_in_frame(
1349    frame: &mut FrameLayout,
1350    block_id: usize,
1351    base: &HashMap<usize, BlockLayout>,
1352    pending: &HashMap<usize, Vec<PaintSpan>>,
1353) -> bool {
1354    for b in &mut frame.blocks {
1355        if b.block_id == block_id {
1356            overlay_block_in_place(b, base, pending);
1357            return true;
1358        }
1359    }
1360    for t in &mut frame.tables {
1361        for c in &mut t.cell_layouts {
1362            for b in &mut c.blocks {
1363                if b.block_id == block_id {
1364                    overlay_block_in_place(b, base, pending);
1365                    return true;
1366                }
1367            }
1368        }
1369    }
1370    for nested in &mut frame.frames {
1371        if overlay_one_in_frame(nested, block_id, base, pending) {
1372            return true;
1373        }
1374    }
1375    false
1376}
1377
1378/// Find a block by id across top-level / table cells / frames.
1379/// Widest laid-out line of `block`, margins included.
1380///
1381/// The single definition of "how wide is this block", shared by the running
1382/// maximum (`update_max_width_for_block`) and the re-derivation eviction needs
1383/// (`recompute_max_content_width`), so the two cannot drift apart and disagree
1384/// about the horizontal scroll range.
1385fn block_max_width(block: &BlockLayout) -> f32 {
1386    block
1387        .lines
1388        .iter()
1389        .map(|line| line.width + block.left_margin + block.right_margin)
1390        .fold(0.0_f32, f32::max)
1391}
1392
1393pub(crate) fn find_block_ref(flow: &FlowLayout, block_id: usize) -> Option<&BlockLayout> {
1394    if let Some(b) = flow.blocks.get(&block_id) {
1395        return Some(b);
1396    }
1397    for t in flow.tables.values() {
1398        for c in &t.cell_layouts {
1399            for b in &c.blocks {
1400                if b.block_id == block_id {
1401                    return Some(b);
1402                }
1403            }
1404        }
1405    }
1406    for f in flow.frames.values() {
1407        if let Some(b) = find_block_in_frame(f, block_id) {
1408            return Some(b);
1409        }
1410    }
1411    None
1412}
1413
1414fn find_block_in_frame(frame: &FrameLayout, block_id: usize) -> Option<&BlockLayout> {
1415    for b in &frame.blocks {
1416        if b.block_id == block_id {
1417            return Some(b);
1418        }
1419    }
1420    for t in &frame.tables {
1421        for c in &t.cell_layouts {
1422            for b in &c.blocks {
1423                if b.block_id == block_id {
1424                    return Some(b);
1425                }
1426            }
1427        }
1428    }
1429    for nested in &frame.frames {
1430        if let Some(b) = find_block_in_frame(nested, block_id) {
1431            return Some(b);
1432        }
1433    }
1434    None
1435}
1436
1437/// Check whether a frame (or any of its nested frames) contains a block
1438/// with the given id — including blocks inside cells of tables that are
1439/// direct children of the frame.
1440pub(crate) fn frame_contains_block(frame: &FrameLayout, block_id: usize) -> bool {
1441    if frame.blocks.iter().any(|b| b.block_id == block_id) {
1442        return true;
1443    }
1444    for table in &frame.tables {
1445        for cell in &table.cell_layouts {
1446            if cell.blocks.iter().any(|b| b.block_id == block_id) {
1447                return true;
1448            }
1449        }
1450    }
1451    frame
1452        .frames
1453        .iter()
1454        .any(|nested| frame_contains_block(nested, block_id))
1455}
1456
1457/// Where inside a frame a given block lives (one level deep — nested
1458/// frames are reported as `NestedFrame` and must be descended into).
1459pub(crate) enum FrameBlockLocation {
1460    /// A direct child block of the frame.
1461    DirectBlock,
1462    /// A block inside a cell of a table that is a direct child of the
1463    /// frame. Carries `(table_id, row, column)`.
1464    TableCell(usize, usize, usize),
1465    /// A block somewhere inside a nested frame (carries the nested
1466    /// frame's id).
1467    NestedFrame(usize),
1468}
1469
1470/// Locate `block_id` among the direct children of `frame`.
1471pub(crate) fn find_block_location_in_frame(
1472    frame: &FrameLayout,
1473    block_id: usize,
1474) -> Option<FrameBlockLocation> {
1475    if frame.blocks.iter().any(|b| b.block_id == block_id) {
1476        return Some(FrameBlockLocation::DirectBlock);
1477    }
1478    for table in &frame.tables {
1479        for cell in &table.cell_layouts {
1480            if cell.blocks.iter().any(|b| b.block_id == block_id) {
1481                return Some(FrameBlockLocation::TableCell(
1482                    table.table_id,
1483                    cell.row,
1484                    cell.column,
1485                ));
1486            }
1487        }
1488    }
1489    for nested in &frame.frames {
1490        if frame_contains_block(nested, block_id) {
1491            return Some(FrameBlockLocation::NestedFrame(nested.frame_id));
1492        }
1493    }
1494    None
1495}
1496
1497/// Replace a direct child block of `frame` and re-stack the frame's
1498/// children. The caller is responsible for routing blocks that live in
1499/// nested frames or table cells (see `relayout_block_deep_in_frame`) —
1500/// the block must have been laid out at this frame's `content_width`.
1501fn relayout_block_in_frame(frame: &mut FrameLayout, block_id: usize, new_block: BlockLayout) {
1502    if let Some(old) = frame.blocks.iter_mut().find(|b| b.block_id == block_id) {
1503        *old = new_block;
1504    }
1505    reposition_frame_children(frame);
1506}
1507
1508/// Relayout the block identified by `params.block_id` wherever it lives
1509/// inside `frame`: as a direct block, inside a cell of a frame-nested
1510/// table, or anywhere within a nested frame (recursing to any depth).
1511/// Each level re-stacks its children in flow order on the way back up,
1512/// so height changes propagate to the outermost frame's `total_height`.
1513fn relayout_block_deep_in_frame(
1514    frame: &mut FrameLayout,
1515    registry: &FontRegistry,
1516    params: &BlockLayoutParams,
1517    scale_factor: f32,
1518    font_scale: f32,
1519) {
1520    match find_block_location_in_frame(frame, params.block_id) {
1521        None => {}
1522        Some(FrameBlockLocation::DirectBlock) => {
1523            let new_block = layout_block(
1524                registry,
1525                params,
1526                frame.content_width,
1527                scale_factor,
1528                font_scale,
1529            );
1530            relayout_block_in_frame(frame, params.block_id, new_block);
1531        }
1532        Some(FrameBlockLocation::TableCell(table_id, row, col)) => {
1533            if let Some(table) = frame.tables.iter_mut().find(|t| t.table_id == table_id) {
1534                recompute_table_cell(table, registry, params, row, col, scale_factor, font_scale);
1535            }
1536            reposition_frame_children(frame);
1537        }
1538        Some(FrameBlockLocation::NestedFrame(nested_frame_id)) => {
1539            if let Some(nested) = frame
1540                .frames
1541                .iter_mut()
1542                .find(|f| f.frame_id == nested_frame_id)
1543            {
1544                relayout_block_deep_in_frame(nested, registry, params, scale_factor, font_scale);
1545            }
1546            reposition_frame_children(frame);
1547        }
1548    }
1549}
1550
1551/// Re-layout the block identified by `params.block_id` inside the cell at
1552/// `(row, col)`, then recompute the row height, row y positions, and the
1553/// table's `total_height`. Shared by the top-level table relayout path and
1554/// the frame-nested one; the caller propagates the height delta into its
1555/// own container.
1556fn recompute_table_cell(
1557    table: &mut crate::layout::table::TableLayout,
1558    registry: &FontRegistry,
1559    params: &BlockLayoutParams,
1560    row: usize,
1561    col: usize,
1562    scale_factor: f32,
1563    font_scale: f32,
1564) {
1565    let cell_width = table
1566        .column_content_widths
1567        .get(col)
1568        .copied()
1569        .unwrap_or(200.0);
1570
1571    // Find the cell and replace the block
1572    let cell = match table
1573        .cell_layouts
1574        .iter_mut()
1575        .find(|c| c.row == row && c.column == col)
1576    {
1577        Some(c) => c,
1578        None => return,
1579    };
1580
1581    let new_block = layout_block(registry, params, cell_width, scale_factor, font_scale);
1582    if let Some(old) = cell
1583        .blocks
1584        .iter_mut()
1585        .find(|b| b.block_id == params.block_id)
1586    {
1587        *old = new_block;
1588    }
1589
1590    // Reposition blocks within the cell and recompute cell height
1591    let mut block_y = 0.0f32;
1592    for block in &mut cell.blocks {
1593        block.y = block_y;
1594        block_y += block.height;
1595    }
1596    let cell_height = block_y;
1597
1598    // Recompute row height by scanning all cells in this row
1599    if row < table.row_heights.len() {
1600        let mut max_h = 0.0f32;
1601        for c in &table.cell_layouts {
1602            if c.row == row {
1603                let h: f32 = c.blocks.iter().map(|b| b.height).sum();
1604                max_h = max_h.max(h);
1605            }
1606        }
1607        // Also consider the cell we just updated
1608        max_h = max_h.max(cell_height);
1609        table.row_heights[row] = max_h;
1610    }
1611
1612    // Recompute row y positions and total height
1613    let border = table.border_width;
1614    let padding = table.cell_padding;
1615    let spacing = if table.row_ys.len() > 1 {
1616        // Infer spacing from existing layout
1617        if table.row_ys.len() >= 2 && !table.row_heights.is_empty() {
1618            let expected = table.row_ys[0] + padding + table.row_heights[0] + padding;
1619            (table.row_ys.get(1).copied().unwrap_or(expected) - expected).max(0.0)
1620        } else {
1621            0.0
1622        }
1623    } else {
1624        0.0
1625    };
1626    let mut y = border;
1627    for (r, &row_h) in table.row_heights.iter().enumerate() {
1628        if r < table.row_ys.len() {
1629            table.row_ys[r] = y + padding;
1630        }
1631        y += padding * 2.0 + row_h;
1632        if r < table.row_heights.len() - 1 {
1633            y += spacing;
1634        }
1635    }
1636    table.total_height = y + border;
1637}
1638
1639/// Recompute the y position of every direct child of `frame` in document
1640/// (flow) order, then update `content_height` / `total_height`.
1641///
1642/// Walks `frame.flow_order` so interleaved children keep their document
1643/// order — stacking the per-kind vecs one after another would visually
1644/// reorder a frame containing e.g. [block, table, block]. Placement
1645/// mirrors `layout_frame` exactly: blocks at `content_y + top_margin`
1646/// (no collapsing between frame children), tables and nested frames at
1647/// `content_y` advancing by `total_height`.
1648pub(crate) fn reposition_frame_children(frame: &mut FrameLayout) {
1649    let old_content_height = frame.content_height;
1650    let order = frame.flow_order.clone();
1651    let mut content_y = 0.0f32;
1652
1653    for child in &order {
1654        match child {
1655            crate::layout::frame::FrameChildRef::Block(bid) => {
1656                if let Some(block) = frame.blocks.iter_mut().find(|b| b.block_id == *bid) {
1657                    block.y = content_y + block.top_margin;
1658                    let block_content = block.height - block.top_margin - block.bottom_margin;
1659                    content_y = block.y + block_content + block.bottom_margin;
1660                }
1661            }
1662            crate::layout::frame::FrameChildRef::Table(tid) => {
1663                if let Some(table) = frame.tables.iter_mut().find(|t| t.table_id == *tid) {
1664                    table.y = content_y;
1665                    content_y += table.total_height;
1666                }
1667            }
1668            crate::layout::frame::FrameChildRef::Frame(fid) => {
1669                if let Some(nested) = frame.frames.iter_mut().find(|f| f.frame_id == *fid) {
1670                    nested.y = content_y;
1671                    content_y += nested.total_height;
1672                }
1673            }
1674        }
1675    }
1676
1677    frame.content_height = content_y;
1678    frame.total_height += content_y - old_content_height;
1679}