Skip to main content

text_typeset/
document_flow.rs

1//! Per-widget document flow state.
2//!
3//! A [`DocumentFlow`] is everything that describes **what a specific
4//! widget is showing** — viewport, zoom, scroll offset, wrap mode,
5//! the laid-out flow (blocks / tables / frames), the rendered frame
6//! cache, the cursor(s), and the selection / caret / text colors.
7//!
8//! Flows do not own font data. Every layout and render call takes a
9//! [`TextFontService`] by reference and reads the font registry,
10//! glyph atlas, and glyph cache through it. This split lets many
11//! widgets in the same window share one atlas (and one GPU upload
12//! per frame) while each owns an independent view onto its own
13//! document.
14//!
15//! # Lifecycle
16//!
17//! ```rust,no_run
18//! use text_typeset::{DocumentFlow, TextFontService};
19//!
20//! let mut service = TextFontService::new();
21//! let face = service.register_font(include_bytes!("../test-fonts/NotoSans-Variable.ttf"));
22//! service.set_default_font(face, 16.0);
23//!
24//! let mut flow = DocumentFlow::new();
25//! flow.set_viewport(800.0, 600.0);
26//!
27//! # #[cfg(feature = "text-document")]
28//! # {
29//! let doc = text_document::TextDocument::new();
30//! doc.set_plain_text("Hello, world!").unwrap();
31//! flow.layout_full(&service, &doc.snapshot_flow());
32//! # }
33//!
34//! let frame = flow.render(&mut service);
35//! // frame.glyphs     -> glyph quads (textured rects from the shared atlas)
36//! // frame.decorations -> cursor, selection, underlines, borders
37//! ```
38//!
39//! The caller's pattern for a multi-widget UI is the same, plus one
40//! rule: each widget owns its own `DocumentFlow` and must re-push
41//! its view state (viewport, zoom, scroll, cursor, colors) before
42//! its own `layout_*` / `render` call, because those fields live on
43//! the flow itself, not on the shared service.
44
45use crate::TextFontService;
46use crate::font::resolve::resolve_font;
47use crate::font::script_fallback::ScriptContext;
48use crate::layout::block::BlockLayoutParams;
49use crate::layout::flow::{FlowItem, FlowLayout};
50use crate::layout::frame::FrameLayoutParams;
51use crate::layout::inline_markup::{InlineAttrs, InlineMarkup};
52use crate::layout::paragraph::{Alignment, Hyphenator, RunOrder, break_into_lines};
53use crate::layout::table::TableLayoutParams;
54use crate::shaping::run::{ShapedGlyph, ShapedRun};
55use crate::shaping::shaper::{
56    TextDirection, bidi_runs, font_metrics_px, shape_text, shape_text_in_paragraph,
57    to_harfrust_features,
58};
59use crate::types::{
60    BlockVisualInfo, CharacterGeometry, CursorDisplay, DecorationKind, DecorationRect, GlyphQuad,
61    HitTestResult, LaidOutSpan, LaidOutSpanKind, LayoutGeometry, LineGeometry, LineTruncation,
62    ParagraphResult, RenderFrame, SingleLineResult, TableVisualInfo, TextFormat,
63};
64
65/// Reasons [`DocumentFlow::relayout_block`] may refuse an
66/// incremental update.
67///
68/// Both variants describe invariant violations the caller can
69/// detect structurally ahead of time by asking
70/// [`DocumentFlow::has_layout`] and
71/// [`DocumentFlow::layout_dirty_for_scale`]. Returned as a
72/// `Result` rather than panicking so a misbehaving caller
73/// produces a recoverable error at the exact call site instead
74/// of corrupting the flow with a partial relayout.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum RelayoutError {
77    /// No `layout_*` method has been called on this flow yet.
78    /// The caller must run [`DocumentFlow::layout_full`] or
79    /// [`DocumentFlow::layout_blocks`] first to establish a
80    /// baseline layout before incremental updates make sense.
81    NoLayout,
82    /// The backing [`TextFontService`] has had its HiDPI scale
83    /// factor changed since this flow was last laid out, so the
84    /// existing block layouts hold advances at the old ppem.
85    /// Re-shaping a single block would leave it at the new ppem
86    /// while neighbors stay at the old, producing an inconsistent
87    /// flow. The caller must re-run `layout_full` /
88    /// `layout_blocks` to rebuild everything at the new scale.
89    ScaleDirty,
90    /// `params.block_id` is not in this flow's layout — not a top-level block,
91    /// not in any table cell, not in any frame.
92    ///
93    /// Reported rather than ignored because ignoring it is worse than it looks:
94    /// the incremental path exists to relayout the block AND shift the
95    /// document-character positions of everything after it, so doing nothing
96    /// leaves the flow holding pre-edit text and pre-edit positions while the
97    /// document has moved on. Hit-testing and selection painting then disagree
98    /// with the document by the edit's length, for every block after it, until
99    /// something forces a full layout. The caller's recovery is to run
100    /// [`DocumentFlow::layout_full`].
101    UnknownBlock(usize),
102}
103
104impl std::fmt::Display for RelayoutError {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        match self {
107            RelayoutError::NoLayout => {
108                f.write_str("relayout_block called before any layout_* method")
109            }
110            RelayoutError::ScaleDirty => f.write_str(
111                "relayout_block called after a scale-factor change without a fresh layout_*",
112            ),
113            RelayoutError::UnknownBlock(id) => {
114                write!(f, "relayout_block: block {id} is not in this layout")
115            }
116        }
117    }
118}
119
120impl std::error::Error for RelayoutError {}
121
122/// How the content (layout) width is determined.
123///
124/// Controls whether text reflows when the viewport resizes (web or
125/// editor style) or wraps at a fixed width (page / WYSIWYG style).
126#[derive(Debug, Clone, Copy, Default)]
127pub enum ContentWidthMode {
128    /// Content width equals viewport width (divided by zoom). Text
129    /// reflows on window resize — the default, typical for editors
130    /// and web layout.
131    #[default]
132    Auto,
133    /// Content width is fixed at a specific value, independent of
134    /// the viewport. Useful for page-like WYSIWYG layout, print
135    /// preview, or side panels with their own column width.
136    Fixed(f32),
137}
138
139/// Per-widget document flow state.
140///
141/// See the module-level docs for the shape of the split and for
142/// lifecycle examples. Every layout/render method here takes a
143/// [`TextFontService`] reference so flows can share one atlas across
144/// an entire window.
145/// Whether the render window changed enough since the last full render that the
146/// incremental paths — which reuse the culled cache — must fall back to a full
147/// re-render. A `None`↔`Some` transition always drifts; two `Some`s drift on a
148/// >0.001px change in either endpoint (so a scroll re-renders, a still view does not).
149fn render_window_drifted(now: Option<(f32, f32)>, then: Option<(f32, f32)>) -> bool {
150    match (now, then) {
151        (None, None) => false,
152        (Some((t0, h0)), Some((t1, h1))) => (t0 - t1).abs() > 0.001 || (h0 - h1).abs() > 0.001,
153        _ => true,
154    }
155}
156
157pub struct DocumentFlow {
158    flow_layout: FlowLayout,
159    render_frame: RenderFrame,
160    scroll_offset: f32,
161    rendered_scroll_offset: f32,
162    /// When `Some((top, height))`, render culling uses this content-space band
163    /// instead of `[scroll_offset, scroll_offset + viewport_height]`. Positioning
164    /// (glyph screen y, hit-testing) is unaffected. See
165    /// [`DocumentFlow::set_render_window`].
166    render_window: Option<(f32, f32)>,
167    /// The `render_window` in effect at the last full `render()`, so the
168    /// incremental paths can fall back when the visible band scrolls.
169    rendered_window: Option<(f32, f32)>,
170    viewport_width: f32,
171    viewport_height: f32,
172    content_width_mode: ContentWidthMode,
173    selection_color: [f32; 4],
174    cursor_color: [f32; 4],
175    text_color: [f32; 4],
176    /// Background used by the text-document bridge when a code block
177    /// carries no explicit `background_color`. Overrides the bridge's
178    /// historical light-grey default. Threaded into every
179    /// `convert_flow_with` / `convert_block_with` call kicked off
180    /// from `layout_full`. See [`Self::set_code_block_background`].
181    code_block_background: [f32; 4],
182    /// Foreground used by the text-document bridge for monospaced runs
183    /// (markdown inline `code`, fenced code blocks) that carry no
184    /// explicit `foreground_color`. `None` keeps the engine's default
185    /// `text_color`. See [`Self::set_code_block_foreground`].
186    code_block_foreground: Option<[f32; 4]>,
187    /// Foreground used by the text-document bridge for runs carrying a
188    /// hyperlink that set no explicit `foreground_color`. `None` keeps
189    /// the engine's default `text_color`, which leaves links looking
190    /// exactly like prose. See [`Self::set_link_foreground`].
191    link_foreground: Option<[f32; 4]>,
192    /// Echo / masking character for secure (password) fields. When
193    /// `Some(c)`, every character laid out by `layout_full` is replaced
194    /// with `c` before shaping, so the real text never reaches the
195    /// shaper or the glyph atlas. `None` (default) lays text out
196    /// verbatim. Threaded into the bridge via [`crate::bridge::BridgeOptions::echo_char`]
197    /// from `layout_full`. See [`set_echo_char`](Self::set_echo_char).
198    echo_char: Option<char>,
199    /// Auto-hyphenate justified blocks that don't set `hyphenate`
200    /// explicitly. Threaded into the bridge via
201    /// [`crate::bridge::BridgeOptions::hyphenate_justified`] from
202    /// `layout_full`. Enable on prose surfaces only. `false` by default.
203    /// See [`set_hyphenate_justified`](Self::set_hyphenate_justified).
204    hyphenate_justified: bool,
205    cursors: Vec<CursorDisplay>,
206    zoom: f32,
207    rendered_zoom: f32,
208    /// Per-document logical text-magnification factor (`1.0` = none). Unlike
209    /// `zoom` (a post-layout *display* transform that leaves font metrics
210    /// untouched) and `raster_scale`/`scale_factor` (raster density only),
211    /// `font_scale` multiplies the resolved logical font size *before* shaping,
212    /// so glyph advances, line heights, and `content_height` all grow and text
213    /// re-wraps. This is the accessibility "grow all text" knob. Set via
214    /// [`set_font_scale`](Self::set_font_scale); pushed into `flow_layout` at
215    /// every `layout_*` call alongside `scale_factor`.
216    font_scale: f32,
217    /// Raster densification for content drawn under a scale transform.
218    /// `1.0` = unscaled UI. Rasterization happens at
219    /// `size × scale_factor × raster_scale` physical pixels while layout
220    /// and glyph `screen` rects stay in logical pixels. Unlike `zoom`
221    /// (a post-layout coordinate transform) this changes which bitmaps
222    /// the quads sample, so the incremental `render_block_only` path
223    /// falls back to a full render when it changed. See
224    /// [`set_raster_scale`](Self::set_raster_scale).
225    raster_scale: f32,
226    rendered_raster_scale: f32,
227    /// `TextFontService::scale_generation` at the time of the last
228    /// `layout_*` call. Used by
229    /// [`layout_dirty_for_scale`](DocumentFlow::layout_dirty_for_scale)
230    /// so the framework can detect HiDPI transitions and re-run
231    /// layout without having to track them itself.
232    layout_scale_generation: u64,
233    /// Whether any `layout_*` call has been made at least once.
234    has_layout: bool,
235}
236
237/// The visual geometry of one resolved block.
238///
239/// The one place a [`BlockVisualInfo`] is built, so `block_visual_info` and
240/// `block_geometry` cannot answer differently. `BlockLayout::left_margin`
241/// already holds the effective margin (the block's left margin plus its list
242/// or paragraph indent), so `content_x` adds nothing else to it. The marker is
243/// positioned relative to the column edge, as the renderer paints it.
244fn block_visual_info_of(
245    block_id: usize,
246    resolved: &crate::layout::flow::ResolvedBlock<'_>,
247) -> BlockVisualInfo {
248    let marker = resolved.block.list_marker.as_ref();
249    BlockVisualInfo {
250        block_id,
251        x: resolved.origin_x,
252        content_x: resolved.origin_x + resolved.block.left_margin,
253        marker_x: marker.map(|m| resolved.origin_x + m.x),
254        marker_width: marker.map_or(0.0, |m| m.run.advance_width),
255        y: resolved.origin_y + resolved.block.y,
256        height: resolved.block.height,
257    }
258}
259
260impl DocumentFlow {
261    /// Create an empty flow with no content.
262    ///
263    /// After construction the caller typically calls
264    /// [`set_viewport`](Self::set_viewport) and one of the
265    /// `layout_*` methods before the first render.
266    pub fn new() -> Self {
267        Self {
268            flow_layout: FlowLayout::new(),
269            render_frame: RenderFrame::new(),
270            scroll_offset: 0.0,
271            rendered_scroll_offset: f32::NAN,
272            render_window: None,
273            rendered_window: None,
274            viewport_width: 0.0,
275            viewport_height: 0.0,
276            content_width_mode: ContentWidthMode::Auto,
277            selection_color: [0.26, 0.52, 0.96, 0.3],
278            cursor_color: [0.0, 0.0, 0.0, 1.0],
279            text_color: [0.0, 0.0, 0.0, 1.0],
280            code_block_background: [0.95, 0.95, 0.95, 1.0],
281            code_block_foreground: None,
282            link_foreground: None,
283            echo_char: None,
284            hyphenate_justified: false,
285            cursors: Vec::new(),
286            zoom: 1.0,
287            rendered_zoom: f32::NAN,
288            font_scale: 1.0,
289            raster_scale: 1.0,
290            rendered_raster_scale: f32::NAN,
291            layout_scale_generation: 0,
292            has_layout: false,
293        }
294    }
295
296    // ── Viewport & content width ───────────────────────────────
297
298    /// Set the visible area dimensions in logical pixels.
299    ///
300    /// The viewport controls:
301    ///
302    /// - **Culling**: only blocks within the viewport are rendered.
303    /// - **Selection highlight**: multi-line selection extends to
304    ///   the viewport width.
305    /// - **Layout width** (in [`ContentWidthMode::Auto`]): text
306    ///   wraps at `viewport_width / zoom`.
307    ///
308    /// Call this when the widget's container resizes. A resize by
309    /// itself does not relayout — re-run `layout_full` /
310    /// `layout_blocks` if the wrap width changed.
311    pub fn set_viewport(&mut self, width: f32, height: f32) {
312        self.viewport_width = width;
313        self.viewport_height = height;
314        self.flow_layout.viewport_width = width;
315        self.flow_layout.viewport_height = height;
316    }
317
318    /// Current viewport width in logical pixels.
319    pub fn viewport_width(&self) -> f32 {
320        self.viewport_width
321    }
322
323    /// Current viewport height in logical pixels.
324    pub fn viewport_height(&self) -> f32 {
325        self.viewport_height
326    }
327
328    /// Pin content width at a fixed value, independent of viewport.
329    ///
330    /// Text wraps at this width regardless of how wide the viewport
331    /// is. Use for page-like (WYSIWYG) layout or documents with an
332    /// explicit column width. Pass `f32::INFINITY` for no-wrap mode.
333    pub fn set_content_width(&mut self, width: f32) {
334        self.content_width_mode = ContentWidthMode::Fixed(width);
335    }
336
337    /// Reflow content width to follow the viewport (the default).
338    ///
339    /// Text re-wraps on every viewport resize. Standard editor and
340    /// web-style layout.
341    pub fn set_content_width_auto(&mut self) {
342        self.content_width_mode = ContentWidthMode::Auto;
343    }
344
345    /// The effective width used for text layout (line wrapping,
346    /// table columns, etc.).
347    ///
348    /// In [`ContentWidthMode::Auto`], equals `viewport_width / zoom`
349    /// so that text reflows to fit the zoomed viewport. In
350    /// [`ContentWidthMode::Fixed`], equals the set value (zoom only
351    /// magnifies the rendered output).
352    pub fn layout_width(&self) -> f32 {
353        match self.content_width_mode {
354            ContentWidthMode::Auto => self.viewport_width / self.zoom,
355            ContentWidthMode::Fixed(w) => w,
356        }
357    }
358
359    /// The currently configured content-width mode.
360    pub fn content_width_mode(&self) -> ContentWidthMode {
361        self.content_width_mode
362    }
363
364    /// Set the vertical scroll offset in logical pixels from the
365    /// top of the document. Affects culling and screen-space `y`
366    /// coordinates in the rendered frame.
367    pub fn set_scroll_offset(&mut self, offset: f32) {
368        self.scroll_offset = offset;
369    }
370
371    /// Current vertical scroll offset.
372    pub fn scroll_offset(&self) -> f32 {
373        self.scroll_offset
374    }
375
376    /// Restrict render **culling** to the content-space band `[top, top + height]`
377    /// instead of the default `[scroll_offset, scroll_offset + viewport_height]`.
378    ///
379    /// This affects *only* which blocks / lines / decorations are emitted into the
380    /// frame — glyph screen positions, hit-testing and caret geometry all still key
381    /// off `scroll_offset` and are unchanged. It exists for an editor laid out at its
382    /// full document height inside an outer `ScrollArea` ("bastard mode"): its own
383    /// viewport spans the whole document (so the viewport-derived window culls
384    /// nothing) and `scroll_offset` stays `0` (the ancestor scrolls it by
385    /// translation), so the true visible band must be supplied from the ancestor
386    /// clip. Pass `None` (the default) to restore the viewport-derived window.
387    pub fn set_render_window(&mut self, window: Option<(f32, f32)>) {
388        self.render_window = window;
389    }
390
391    /// The active render window, if any. See [`set_render_window`](Self::set_render_window).
392    pub fn render_window(&self) -> Option<(f32, f32)> {
393        self.render_window
394    }
395
396    /// Total content height after layout, in logical pixels.
397    pub fn content_height(&self) -> f32 {
398        self.flow_layout.content_height
399    }
400
401    /// Maximum content width across all laid-out lines, in logical
402    /// pixels. Used for horizontal scrollbar range when wrapping
403    /// is disabled.
404    pub fn max_content_width(&self) -> f32 {
405        self.flow_layout.cached_max_content_width
406    }
407
408    // ── Zoom ────────────────────────────────────────────────────
409
410    /// Set the display zoom level (`1.0` = 100 %).
411    ///
412    /// Zoom scales screen-space output (glyph quads, decorations, caret
413    /// rects) after layout. Font metrics at layout stay at base size;
414    /// hit-test inputs are inversely scaled.
415    ///
416    /// **Wrap / reflow.** In [`ContentWidthMode::Auto`] (the editor
417    /// default) layout width is `viewport_width / zoom`, so text
418    /// re-wraps when zoom changes — browser-style zoom. In
419    /// [`ContentWidthMode::Fixed`], wrap width is independent of zoom
420    /// (page magnify without reflow).
421    ///
422    /// **Sharpness.** Glyph bitmaps densify under zoom: the next
423    /// [`render`](Self::render) rasterizes at
424    /// `ambient_raster_scale × quantize(zoom)` physical density so
425    /// magnified text stays crisp instead of stretching a 1× atlas
426    /// entry. Zoom-out (`< 1`) keeps density ≥ 1 and relies on linear
427    /// minification. Continuous zoom is quantized onto a short ladder
428    /// (same contract as scene transform densification) so the atlas
429    /// does not grow a new size per frame.
430    ///
431    /// Clamped to `0.1..=10.0`. Default is `1.0`.
432    pub fn set_zoom(&mut self, zoom: f32) {
433        self.zoom = zoom.clamp(0.1, 10.0);
434    }
435
436    /// Current display zoom level.
437    pub fn zoom(&self) -> f32 {
438        self.zoom
439    }
440
441    /// Raster densification used on the next paint: ambient
442    /// [`raster_scale`](Self::raster_scale) × zoom, quantized onto the
443    /// densify ladder (see [`quantize_raster_scale`]). Layout and
444    /// pre-zoom `screen` rects stay logical; only the atlas bitmap
445    /// density changes.
446    fn densify_raster_scale(&self) -> f32 {
447        quantize_raster_scale(self.raster_scale * self.zoom)
448    }
449
450    // ── Font scale (logical text magnification) ──────────────────
451
452    /// Set the per-document logical font-scale factor (`1.0` = none).
453    ///
454    /// Unlike [`set_zoom`](Self::set_zoom) (a post-layout display transform
455    /// that does **not** change font metrics), `font_scale` multiplies the
456    /// resolved logical font size *before* shaping. Glyph advances, line
457    /// heights, and `content_height` all grow, and text re-wraps — true text
458    /// magnification, the mechanism behind an app-wide "grow all text"
459    /// accessibility setting. Takes effect on the next `layout_*` call.
460    /// Clamped to `0.1..=10.0`.
461    pub fn set_font_scale(&mut self, font_scale: f32) {
462        self.font_scale = font_scale.clamp(0.1, 10.0);
463    }
464
465    /// Current logical font-scale factor.
466    pub fn font_scale(&self) -> f32 {
467        self.font_scale
468    }
469
470    /// Set the ambient raster densification scale for content drawn
471    /// under an *external* scale transform (a zoomed scene viewport).
472    ///
473    /// Combined with [`set_zoom`](Self::set_zoom) at paint time: glyphs
474    /// densify at `quantize(raster_scale × zoom)`. Layout, metrics, and
475    /// pre-zoom `screen` rects stay logical, so no relayout is needed
476    /// after changing ambient densification alone. The next
477    /// [`render`](Self::render) rasterizes missing glyphs at the new
478    /// density; old-density entries age out of the atlas via the normal
479    /// LRU. Scaled rasters (`!= 1.0`) are unhinted.
480    ///
481    /// Clamped to `0.1..=16.0`. Default is `1.0`.
482    pub fn set_raster_scale(&mut self, raster_scale: f32) {
483        self.raster_scale = raster_scale.clamp(0.1, 16.0);
484    }
485
486    /// Current raster densification scale.
487    pub fn raster_scale(&self) -> f32 {
488        self.raster_scale
489    }
490
491    // ── Scale factor sync ───────────────────────────────────────
492
493    /// Whether any `layout_*` method has run on this flow at least
494    /// once. Callers that need to distinguish "never laid out"
495    /// from "laid out against a stale scale factor" read this
496    /// alongside [`layout_dirty_for_scale`](Self::layout_dirty_for_scale).
497    pub fn has_layout(&self) -> bool {
498        self.has_layout
499    }
500
501    /// Returns `true` when the backing [`TextFontService`] has had
502    /// its HiDPI scale factor changed since this flow was last laid
503    /// out, meaning stored shaped advances and cached ppem values
504    /// are stale.
505    ///
506    /// Call after every `service.set_scale_factor(...)` to decide
507    /// whether to re-run `layout_full` / `layout_blocks` before the
508    /// next render. Returns `false` for flows that have never been
509    /// laid out at all (nothing to invalidate).
510    pub fn layout_dirty_for_scale(&self, service: &TextFontService) -> bool {
511        self.has_layout && self.layout_scale_generation != service.scale_generation()
512    }
513
514    // ── Layout ──────────────────────────────────────────────────
515
516    /// Full layout from a text-document `FlowSnapshot`.
517    ///
518    /// Clears any existing flow state and lays out every element
519    /// (blocks, tables, frames) from the snapshot in flow order.
520    /// Call on document load or `DocumentReset`. For single-block
521    /// edits prefer [`relayout_block`](Self::relayout_block).
522    #[cfg(feature = "text-document")]
523    pub fn layout_full(&mut self, service: &TextFontService, flow: &text_document::FlowSnapshot) {
524        use crate::bridge::{BridgeOptions, convert_flow_with};
525
526        let opts = BridgeOptions {
527            code_block_background: self.code_block_background,
528            code_block_foreground: self.code_block_foreground,
529            link_foreground: self.link_foreground,
530            echo_char: self.echo_char,
531            hyphenate_justified: self.hyphenate_justified,
532        };
533        let converted = convert_flow_with(flow, &opts);
534
535        // Merge all elements by flow index and process in order.
536        let mut all_items: Vec<(usize, FlowItemKind)> = Vec::new();
537        for (idx, params) in converted.blocks {
538            all_items.push((idx, FlowItemKind::Block(params)));
539        }
540        for (idx, params) in converted.tables {
541            all_items.push((idx, FlowItemKind::Table(params)));
542        }
543        for (idx, params) in converted.frames {
544            all_items.push((idx, FlowItemKind::Frame(params)));
545        }
546        all_items.sort_by_key(|(idx, _)| *idx);
547
548        let lw = self.layout_width();
549        self.flow_layout.clear();
550        self.flow_layout.viewport_width = self.viewport_width;
551        self.flow_layout.viewport_height = self.viewport_height;
552        self.flow_layout.scale_factor = service.scale_factor;
553        self.flow_layout.font_scale = self.font_scale;
554
555        for (_idx, kind) in all_items {
556            match kind {
557                FlowItemKind::Block(params) => {
558                    self.flow_layout
559                        .add_block(&service.font_registry, &params, lw);
560                }
561                FlowItemKind::Table(params) => {
562                    self.flow_layout
563                        .add_table(&service.font_registry, &params, lw);
564                }
565                FlowItemKind::Frame(params) => {
566                    self.flow_layout
567                        .add_frame(&service.font_registry, &params, lw);
568                }
569            }
570        }
571
572        // A full layout leaves the live blocks as their own paint base, so this
573        // only has to drop whatever the previous layout had captured. The engine
574        // applies paint spans afterward (recolor without reshape) and captures a
575        // base per block as it does.
576        self.flow_layout.reset_paint_base();
577
578        self.note_layout_done(service);
579    }
580
581    /// Lay out a list of blocks from scratch.
582    ///
583    /// Framework-agnostic entry point — the caller assembles
584    /// [`BlockLayoutParams`] directly without going through
585    /// text-document. Replaces any existing flow state.
586    pub fn layout_blocks(
587        &mut self,
588        service: &TextFontService,
589        block_params: Vec<BlockLayoutParams>,
590    ) {
591        self.flow_layout.scale_factor = service.scale_factor;
592        self.flow_layout.font_scale = self.font_scale;
593        self.flow_layout
594            .layout_blocks(&service.font_registry, block_params, self.layout_width());
595        self.note_layout_done(service);
596    }
597
598    /// Append a block to the current flow, in O(1).
599    ///
600    /// The block counterpart of [`add_frame`](Self::add_frame) /
601    /// [`add_table`](Self::add_table), and the incremental alternative to
602    /// re-running [`layout_blocks`](Self::layout_blocks) after content grows.
603    ///
604    /// Streaming consumers (a log/console view tailing output) need this: a
605    /// full re-layout is O(N) in the whole document, so appending one line to
606    /// a 100 000-line buffer costs over a second, while this stays flat at the
607    /// cost of shaping the one new line, whatever the buffer already holds.
608    /// See `docs/streaming-baseline.md` for the measurements.
609    ///
610    /// Appends at the tail: the new block takes the current `content_height`
611    /// as its `y` (margin-collapsed against the previous block, exactly as a
612    /// bulk layout would place it), so an append-only sequence produces a flow
613    /// identical to laying the same blocks out in one call.
614    ///
615    /// # Invariants
616    ///
617    /// Like [`relayout_block`](Self::relayout_block), this is an incremental
618    /// operation, so it must not run against a layout shaped at a different
619    /// HiDPI scale: appending at the current scale while every existing block
620    /// sits at the old one would leave the flow permanently mixed-scale — and
621    /// worse, stamping the flow as freshly laid out would clear the very
622    /// staleness flag ([`layout_dirty_for_scale`](Self::layout_dirty_for_scale))
623    /// the caller relies on to know it must re-layout. Returns
624    /// [`RelayoutError::ScaleDirty`] instead; the caller re-runs
625    /// [`layout_full`](Self::layout_full) / [`layout_blocks`](Self::layout_blocks).
626    ///
627    /// Unlike `relayout_block` there is no `NoLayout` error: appending to an
628    /// empty flow is how an append-only buffer legitimately starts.
629    pub fn add_block(
630        &mut self,
631        service: &TextFontService,
632        params: &BlockLayoutParams,
633    ) -> Result<(), RelayoutError> {
634        // Only meaningful once a layout exists; an empty flow has no
635        // established scale to conflict with.
636        if self.has_layout && self.layout_scale_generation != service.scale_generation() {
637            return Err(RelayoutError::ScaleDirty);
638        }
639        self.flow_layout.scale_factor = service.scale_factor;
640        self.flow_layout.font_scale = self.font_scale;
641        self.flow_layout
642            .append_block(&service.font_registry, params, self.layout_width());
643        self.note_layout_done(service);
644        Ok(())
645    }
646
647    /// Drop the first `n` blocks of the flow, returning how many were removed.
648    ///
649    /// The eviction half of a bounded streaming buffer: pair it with
650    /// [`add_block`](Self::add_block) to hold a scrollback cap. Usually O(n)
651    /// plus one `Vec` memmove of the survivors — nothing is reshaped. The
652    /// return value is the count actually evicted, which is less than `n` when
653    /// the flow holds fewer leading blocks than that, or a table/frame stops
654    /// the walk.
655    ///
656    /// Survivors keep their absolute `y`, so the vacated band at the top
657    /// becomes empty and `content_height` does not change: content below never
658    /// moves, and the viewport stays where the user put it. Callers that want
659    /// the freed space reclaimed re-run a full [`layout_blocks`](Self::layout_blocks).
660    ///
661    /// Only leading top-level blocks are evicted; a leading table or frame
662    /// stops the walk. Evicting the widest block re-derives
663    /// [`max_content_width`](Self::max_content_width) from the survivors, so
664    /// the horizontal scroll range stops describing content that is gone.
665    pub fn remove_leading(&mut self, n: usize) -> usize {
666        self.flow_layout.remove_leading(n)
667    }
668
669    /// Shape only `window` — a slice of a much larger uniform-row-height
670    /// document — placing each row at `y = index * row_height`.
671    ///
672    /// The memory counterpart of [`add_block`](Self::add_block): `add_block`
673    /// makes *growing* a buffer cheap, this makes *holding* a large one cheap.
674    /// A resident shaped line costs ~6.5 KB, so a fully laid-out 100 000-line
675    /// buffer costs ~623 MB, against ~1 MB for a viewport-sized window; render
676    /// already culls to the viewport, so shaping the rest buys nothing. See
677    /// `docs/streaming-baseline.md`.
678    ///
679    /// `content_height` is derived from `total_rows`, so the scrollbar spans
680    /// the whole document even though almost none of it is shaped. Re-call this
681    /// when the visible range moves; append at the tail with
682    /// [`add_block`](Self::add_block) and trim the front with
683    /// [`remove_leading`](Self::remove_leading) while following output, which
684    /// avoids re-shaping the window on every line.
685    ///
686    /// # Invariants
687    ///
688    /// Correct only for genuinely uniform rows: **one row = one visual line of
689    /// exactly `row_height`** — no wrapping, no embedded newlines, no per-row
690    /// margins, one font size throughout (log/console output, monospaced
691    /// code). Variable-height or wrapped content must use
692    /// [`layout_blocks`](Self::layout_blocks) / [`layout_full`](Self::layout_full).
693    /// `window` must be sorted ascending by index. Both are checked in debug
694    /// builds.
695    ///
696    /// Rows outside the window are not laid out, so
697    /// [`block_visual_info`](Self::block_visual_info) and hit-testing answer
698    /// only for resident rows; derive off-window geometry arithmetically from
699    /// `row_height`.
700    ///
701    /// # Behaviour worth knowing
702    ///
703    /// Like [`layout_blocks`](Self::layout_blocks), this drops any paint
704    /// overlay — re-apply spans after re-windowing or the rows render in base
705    /// colours. Since re-windowing happens on every visible-range change, that
706    /// re-apply belongs on the scroll path, not in one-off setup.
707    ///
708    /// [`max_content_width`](Self::max_content_width) reports the widest row
709    /// *seen so far* in this session: not the document's widest (unknowable
710    /// without shaping all of it), and deliberately not the window's widest,
711    /// which would make the horizontal scrollbar jump on every vertical scroll.
712    ///
713    /// `f32` places rows exactly only to 2^24, so past ~840 000 rows at a 20 px
714    /// row height positions begin quantizing — far beyond the target sizes, but
715    /// not unbounded.
716    pub fn layout_window(
717        &mut self,
718        service: &TextFontService,
719        window: &[(usize, BlockLayoutParams)],
720        total_rows: usize,
721        row_height: f32,
722    ) {
723        self.flow_layout.scale_factor = service.scale_factor;
724        self.flow_layout.font_scale = self.font_scale;
725        self.flow_layout.layout_window(
726            &service.font_registry,
727            window,
728            total_rows,
729            row_height,
730            self.layout_width(),
731        );
732        self.note_layout_done(service);
733    }
734
735    /// Declare the total extent of a uniform-row-height document without
736    /// shaping anything.
737    ///
738    /// Keeps the scrollbar honest when the row count changes outside the shaped
739    /// window — a line appended while the user is scrolled away from the tail,
740    /// where [`add_block`](Self::add_block) would wrongly shape a row nowhere
741    /// near the window. Leaves the shaped window untouched.
742    ///
743    /// Only meaningful for a flow driven by [`layout_window`](Self::layout_window).
744    /// On a normally laid-out flow this overwrites the accumulated
745    /// `content_height` with a fabricated `total_rows * row_height` that bears
746    /// no relation to the real content, so the scroll range goes wrong; nothing
747    /// in the type distinguishes the two, so this is the caller's contract.
748    pub fn set_uniform_extent(&mut self, total_rows: usize, row_height: f32) {
749        self.flow_layout.set_uniform_extent(total_rows, row_height);
750    }
751
752    /// Convert one document block snapshot into layout params using this flow's
753    /// own bridge options — the per-block half of [`layout_full`](Self::layout_full)'s
754    /// conversion, exposed for the windowed streaming path.
755    ///
756    /// [`layout_window`](Self::layout_window) takes already-built
757    /// [`BlockLayoutParams`], but only
758    /// this flow knows the code-block colours, echo char, and
759    /// justified-hyphenation policy that `layout_full` folds in through
760    /// [`BridgeOptions`](crate::bridge::BridgeOptions). A streaming consumer
761    /// building a window of rows from document snapshots calls this per row, so
762    /// the windowed and full paths shape a given block identically. The result
763    /// is a plain value the caller may tint (set a fragment's
764    /// `foreground_color`) before handing the window to `layout_window`.
765    #[cfg(feature = "text-document")]
766    pub fn block_params_for(
767        &self,
768        block: &text_document::BlockSnapshot,
769    ) -> crate::layout::block::BlockLayoutParams {
770        let opts = crate::bridge::BridgeOptions {
771            code_block_background: self.code_block_background,
772            code_block_foreground: self.code_block_foreground,
773            link_foreground: self.link_foreground,
774            echo_char: self.echo_char,
775            hyphenate_justified: self.hyphenate_justified,
776        };
777        crate::bridge::convert_block_with(block, &opts)
778    }
779
780    /// Append a frame to the current flow. The frame's position
781    /// (inline, float, absolute) is carried in `params`.
782    pub fn add_frame(&mut self, service: &TextFontService, params: &FrameLayoutParams) {
783        self.flow_layout.scale_factor = service.scale_factor;
784        self.flow_layout.font_scale = self.font_scale;
785        self.flow_layout
786            .add_frame(&service.font_registry, params, self.layout_width());
787        self.note_layout_done(service);
788    }
789
790    /// Append a table to the current flow.
791    pub fn add_table(&mut self, service: &TextFontService, params: &TableLayoutParams) {
792        self.flow_layout.scale_factor = service.scale_factor;
793        self.flow_layout.font_scale = self.font_scale;
794        self.flow_layout
795            .add_table(&service.font_registry, params, self.layout_width());
796        self.note_layout_done(service);
797    }
798
799    /// Relayout a single block after its content or formatting
800    /// changed.
801    ///
802    /// Re-shapes and re-wraps just that block, then shifts
803    /// subsequent items if the height changed. Much cheaper than a
804    /// full layout for single-block edits (typing, format toggles).
805    /// If the block lives inside a table cell, the row height is
806    /// re-measured and content below the table shifts.
807    ///
808    /// # Invariants
809    ///
810    /// This is an incremental operation and only makes sense when
811    /// a valid layout is already installed on this flow, laid out
812    /// against the same HiDPI scale factor the service currently
813    /// reports. Violations produce a [`RelayoutError`]:
814    ///
815    /// - [`RelayoutError::NoLayout`] if no `layout_*` method has
816    ///   run on this flow yet — there is nothing to update.
817    /// - [`RelayoutError::ScaleDirty`] if the service's scale
818    ///   factor has changed since the last layout — reshaping a
819    ///   single block would leave neighbors at the old ppem and
820    ///   produce an inconsistent flow. The caller must re-run
821    ///   [`layout_full`](Self::layout_full) / [`layout_blocks`](Self::layout_blocks)
822    ///   first.
823    ///
824    /// Both conditions are detected structurally from
825    /// [`has_layout`](Self::has_layout) and
826    /// [`layout_dirty_for_scale`](Self::layout_dirty_for_scale),
827    /// so callers that already guard those don't need to handle
828    /// the error.
829    pub fn relayout_block(
830        &mut self,
831        service: &TextFontService,
832        params: &BlockLayoutParams,
833    ) -> Result<(), RelayoutError> {
834        if !self.has_layout {
835            return Err(RelayoutError::NoLayout);
836        }
837        if self.layout_scale_generation != service.scale_generation() {
838            return Err(RelayoutError::ScaleDirty);
839        }
840        self.flow_layout.scale_factor = service.scale_factor;
841        self.flow_layout.font_scale = self.font_scale;
842        if !self
843            .flow_layout
844            .relayout_block(&service.font_registry, params, self.layout_width())
845        {
846            return Err(RelayoutError::UnknownBlock(params.block_id));
847        }
848        self.note_layout_done(service);
849        Ok(())
850    }
851
852    /// Replace the paint-only color overlay for the whole flow, re-derived from
853    /// the captured base layout. Recolors without reshaping or reflowing — the
854    /// fast path for search / spell / paint-only syntax highlights. Call
855    /// `render` afterward to refresh the GPU frame.
856    pub fn apply_paint_spans_for(
857        &mut self,
858        spans_by_block: std::collections::HashMap<usize, Vec<crate::layout::block::PaintSpan>>,
859    ) {
860        self.flow_layout.apply_paint_spans_for(spans_by_block);
861    }
862
863    /// How many blocks currently hold a captured paint base. See
864    /// [`FlowLayout::captured_paint_bases`].
865    pub fn captured_paint_bases(&self) -> usize {
866        self.flow_layout.captured_paint_bases()
867    }
868
869    /// Apply (or clear) the paint overlay for a single block. Returns `false`
870    /// when nothing was recoloured: either the block is not in this layout, or
871    /// it is being cleared while it never carried an overlay and so already
872    /// shows its base colours.
873    pub fn apply_block_paint_spans(
874        &mut self,
875        block_id: usize,
876        spans: &[crate::layout::block::PaintSpan],
877    ) -> bool {
878        self.flow_layout.apply_block_paint_spans(block_id, spans)
879    }
880
881    fn note_layout_done(&mut self, service: &TextFontService) {
882        self.has_layout = true;
883        self.layout_scale_generation = service.scale_generation();
884    }
885
886    // ── Rendering ──────────────────────────────────────────────
887
888    /// Render the visible viewport and return the produced frame.
889    ///
890    /// Performs viewport culling, rasterizes any glyphs missing
891    /// from the atlas into it, and emits glyph quads, image quads,
892    /// and decoration rectangles. The returned reference borrows
893    /// both `self` and `service`; drop it before the next mutation.
894    ///
895    /// On every call, stale glyphs (unused for ~120 frames) are
896    /// evicted from the atlas to reclaim slot space.
897    pub fn render(&mut self, service: &mut TextFontService) -> &RenderFrame {
898        let effective_vw = self.viewport_width / self.zoom;
899        let effective_vh = self.viewport_height / self.zoom;
900        let densify = self.densify_raster_scale();
901        crate::render::frame::build_render_frame(
902            &self.flow_layout,
903            &service.font_registry,
904            &mut service.atlas,
905            &mut service.glyph_cache,
906            &mut service.scale_context,
907            self.scroll_offset,
908            effective_vw,
909            effective_vh,
910            self.render_window,
911            &self.cursors,
912            self.cursor_color,
913            self.selection_color,
914            self.text_color,
915            densify,
916            &mut self.render_frame,
917            &mut service.eviction_epoch,
918        );
919        self.rendered_scroll_offset = self.scroll_offset;
920        self.rendered_window = self.render_window;
921        self.rendered_zoom = self.zoom;
922        self.rendered_raster_scale = self.raster_scale;
923        apply_zoom(&mut self.render_frame, self.zoom);
924        &self.render_frame
925    }
926
927    /// Incremental render that only re-renders one block's glyphs.
928    ///
929    /// Reuses cached glyph / decoration data for all other blocks
930    /// from the last full `render()`. Call after
931    /// [`relayout_block`](Self::relayout_block) when only one block's
932    /// text changed.
933    ///
934    /// Falls back to a full [`render`](Self::render) if the block's
935    /// height changed (subsequent glyph positions would be stale),
936    /// if scroll offset or zoom changed since the last full render,
937    /// or if the block lives inside a table / frame (those are
938    /// cached with a different key).
939    pub fn render_block_only(
940        &mut self,
941        service: &mut TextFontService,
942        block_id: usize,
943    ) -> &RenderFrame {
944        if (self.scroll_offset - self.rendered_scroll_offset).abs() > 0.001
945            || render_window_drifted(self.render_window, self.rendered_window)
946            || (self.zoom - self.rendered_zoom).abs() > 0.001
947            || (self.raster_scale - self.rendered_raster_scale).abs() > 0.001
948        {
949            return self.render(service);
950        }
951
952        // Defensive: if the atlas has dropped any entry since the last
953        // full render, our cached per-block glyph quads may now point
954        // at slots owned by unrelated glyphs. Fall back to a full
955        // re-render — `touch_glyphs` in `rebuild_flat_frame` is the
956        // primary keep-alive mechanism, this is the safety net.
957        if service.eviction_epoch != self.render_frame.atlas_eviction_epoch {
958            return self.render(service);
959        }
960
961        if !self.flow_layout.blocks.contains_key(&block_id) {
962            let in_table = self.flow_layout.tables.values().any(|table| {
963                table
964                    .cell_layouts
965                    .iter()
966                    .any(|c| c.blocks.iter().any(|b| b.block_id == block_id))
967            });
968            if in_table {
969                return self.render(service);
970            }
971            let in_frame = self
972                .flow_layout
973                .frames
974                .values()
975                .any(|frame| crate::layout::flow::frame_contains_block(frame, block_id));
976            if in_frame {
977                return self.render(service);
978            }
979        }
980
981        if let Some(block) = self.flow_layout.blocks.get(&block_id) {
982            let old_height = self
983                .render_frame
984                .block_heights
985                .get(&block_id)
986                .copied()
987                .unwrap_or(block.height);
988            if (block.height - old_height).abs() > 0.001 {
989                return self.render(service);
990            }
991        }
992
993        let effective_vw = self.viewport_width / self.zoom;
994        let effective_vh = self.viewport_height / self.zoom;
995        let densify = self.densify_raster_scale();
996        let scale_factor = service.scale_factor;
997        let mut new_glyphs = Vec::new();
998        let mut new_images = Vec::new();
999        let mut new_keys: Vec<crate::atlas::cache::GlyphCacheKey> = Vec::new();
1000        if let Some(block) = self.flow_layout.blocks.get(&block_id) {
1001            let mut tmp = RenderFrame::new();
1002            crate::render::frame::render_block_at_offset(
1003                block,
1004                0.0,
1005                0.0,
1006                &service.font_registry,
1007                &mut service.atlas,
1008                &mut service.glyph_cache,
1009                &mut service.scale_context,
1010                self.scroll_offset,
1011                effective_vh,
1012                self.render_window,
1013                self.text_color,
1014                scale_factor,
1015                densify,
1016                &mut tmp,
1017                &mut new_keys,
1018                &mut service.eviction_epoch,
1019            );
1020            new_glyphs = tmp.glyphs;
1021            new_images = tmp.images;
1022        }
1023
1024        let new_decos = if let Some(block) = self.flow_layout.blocks.get(&block_id) {
1025            crate::render::decoration::generate_block_decorations(
1026                block,
1027                &service.font_registry,
1028                self.scroll_offset,
1029                effective_vh,
1030                self.render_window,
1031                0.0,
1032                0.0,
1033                effective_vw,
1034                self.text_color,
1035                scale_factor,
1036            )
1037        } else {
1038            Vec::new()
1039        };
1040
1041        if let Some(entry) = self
1042            .render_frame
1043            .block_glyphs
1044            .iter_mut()
1045            .find(|(id, _)| *id == block_id)
1046        {
1047            entry.1 = new_glyphs;
1048        }
1049        if let Some(entry) = self
1050            .render_frame
1051            .block_images
1052            .iter_mut()
1053            .find(|(id, _)| *id == block_id)
1054        {
1055            entry.1 = new_images;
1056        }
1057        if let Some(entry) = self
1058            .render_frame
1059            .block_decorations
1060            .iter_mut()
1061            .find(|(id, _)| *id == block_id)
1062        {
1063            entry.1 = new_decos;
1064        }
1065        if let Some(entry) = self
1066            .render_frame
1067            .block_glyph_keys
1068            .iter_mut()
1069            .find(|(id, _)| *id == block_id)
1070        {
1071            entry.1 = new_keys;
1072        }
1073
1074        self.rebuild_flat_frame(service);
1075        apply_zoom(&mut self.render_frame, self.zoom);
1076        &self.render_frame
1077    }
1078
1079    /// Lightweight render that only updates cursor/selection
1080    /// decorations.
1081    ///
1082    /// Reuses the existing glyph quads and images from the last
1083    /// full `render()`. Use when only the cursor blinked or the
1084    /// selection changed. Falls back to a full [`render`](Self::render)
1085    /// if the scroll offset or zoom changed in the meantime.
1086    pub fn render_cursor_only(&mut self, service: &mut TextFontService) -> &RenderFrame {
1087        if (self.scroll_offset - self.rendered_scroll_offset).abs() > 0.001
1088            || render_window_drifted(self.render_window, self.rendered_window)
1089            || (self.zoom - self.rendered_zoom).abs() > 0.001
1090        {
1091            return self.render(service);
1092        }
1093
1094        // Defensive: if any atlas eviction has happened since the last
1095        // full render, our cached glyph quads' atlas coordinates may
1096        // refer to slots reallocated for unrelated glyphs. Fall back
1097        // to a fresh render rather than painting garbled text.
1098        if service.eviction_epoch != self.render_frame.atlas_eviction_epoch {
1099            return self.render(service);
1100        }
1101
1102        // Keep cached glyphs alive in the shared atlas. Cursor blinks
1103        // and selection-only changes paint the cached `render_frame.glyphs`
1104        // without ever calling `cache.get`, so the LRU sees those
1105        // glyphs as idle and ages them out under sustained activity
1106        // in *other* widgets sharing the atlas. Touching here closes
1107        // that gap so the eviction fallback above stays a safety net
1108        // rather than a hot path.
1109        service.touch_glyphs(&self.render_frame.glyph_keys);
1110
1111        self.render_frame.decorations.retain(|d| {
1112            !matches!(
1113                d.kind,
1114                DecorationKind::Cursor | DecorationKind::Selection | DecorationKind::CellSelection
1115            )
1116        });
1117
1118        let effective_vw = self.viewport_width / self.zoom;
1119        let effective_vh = self.viewport_height / self.zoom;
1120        let mut cursor_decos = crate::render::cursor::generate_cursor_decorations(
1121            &self.flow_layout,
1122            &self.cursors,
1123            self.scroll_offset,
1124            self.cursor_color,
1125            self.selection_color,
1126            effective_vw,
1127            effective_vh,
1128        );
1129        apply_zoom_decorations(&mut cursor_decos, self.zoom);
1130        self.render_frame.decorations.extend(cursor_decos);
1131
1132        &self.render_frame
1133    }
1134
1135    fn rebuild_flat_frame(&mut self, service: &mut TextFontService) {
1136        self.render_frame.glyphs.clear();
1137        self.render_frame.images.clear();
1138        self.render_frame.decorations.clear();
1139        self.render_frame.glyph_keys.clear();
1140        for (_, glyphs) in &self.render_frame.block_glyphs {
1141            self.render_frame.glyphs.extend_from_slice(glyphs);
1142        }
1143        for (_, images) in &self.render_frame.block_images {
1144            self.render_frame.images.extend_from_slice(images);
1145        }
1146        for (_, decos) in &self.render_frame.block_decorations {
1147            self.render_frame.decorations.extend_from_slice(decos);
1148        }
1149        for (_, keys) in &self.render_frame.block_glyph_keys {
1150            self.render_frame.glyph_keys.extend_from_slice(keys);
1151        }
1152        // Keep the cached glyphs alive in the shared atlas. Without
1153        // this, blocks that are still visible through cached quads
1154        // but never re-rasterized this frame would age out under the
1155        // 120-generation LRU and have their atlas slots reallocated
1156        // to unrelated glyphs — corrupting every paint that reuses
1157        // these quads (the editor-and-viewer-mangled-together bug).
1158        service.touch_glyphs(&self.render_frame.glyph_keys);
1159
1160        for item in &self.flow_layout.flow_order {
1161            match item {
1162                FlowItem::Table { table_id, .. } => {
1163                    if let Some(table) = self.flow_layout.tables.get(table_id) {
1164                        let decos = crate::layout::table::generate_table_decorations(
1165                            table,
1166                            self.scroll_offset,
1167                        );
1168                        self.render_frame.decorations.extend(decos);
1169                    }
1170                }
1171                FlowItem::Frame { frame_id, .. } => {
1172                    if let Some(frame) = self.flow_layout.frames.get(frame_id) {
1173                        crate::render::frame::append_frame_table_decorations(
1174                            frame,
1175                            0.0,
1176                            0.0,
1177                            self.scroll_offset,
1178                            &mut self.render_frame.decorations,
1179                        );
1180                        crate::render::frame::append_frame_border_decorations(
1181                            frame,
1182                            self.scroll_offset,
1183                            &mut self.render_frame.decorations,
1184                        );
1185                    }
1186                }
1187                FlowItem::Block { .. } => {}
1188            }
1189        }
1190
1191        let effective_vw = self.viewport_width / self.zoom;
1192        let effective_vh = self.viewport_height / self.zoom;
1193        let cursor_decos = crate::render::cursor::generate_cursor_decorations(
1194            &self.flow_layout,
1195            &self.cursors,
1196            self.scroll_offset,
1197            self.cursor_color,
1198            self.selection_color,
1199            effective_vw,
1200            effective_vh,
1201        );
1202        self.render_frame.decorations.extend(cursor_decos);
1203
1204        self.render_frame.atlas_dirty = service.atlas.dirty;
1205        self.render_frame.atlas_width = service.atlas.width;
1206        self.render_frame.atlas_height = service.atlas.height;
1207        if service.atlas.dirty {
1208            let pixels = &service.atlas.pixels;
1209            let needed = (service.atlas.width * service.atlas.height * 4) as usize;
1210            self.render_frame.atlas_pixels.resize(needed, 0);
1211            let copy_len = needed.min(pixels.len());
1212            self.render_frame.atlas_pixels[..copy_len].copy_from_slice(&pixels[..copy_len]);
1213            service.atlas.dirty = false;
1214        }
1215    }
1216
1217    // ── Single-line layout ──────────────────────────────────────
1218
1219    /// Lay out a single line of text and return GPU-ready glyph
1220    /// quads. Fast path for labels, tooltips, overlays — anything
1221    /// that doesn't need the full document pipeline.
1222    ///
1223    /// If `max_width` is set and the shaped text exceeds it, the
1224    /// output is truncated with an ellipsis character. Glyph quads
1225    /// are positioned with the top-left at `(0, 0)`.
1226    ///
1227    /// `raster_scale` densifies glyph bitmaps for content drawn under
1228    /// a scale transform (pass `1.0` for unscaled UI): rasterization
1229    /// happens at `size × scale_factor × raster_scale` physical pixels
1230    /// while every returned metric and `screen` rect stays in logical
1231    /// pixels — layout is identical at every raster scale.
1232    pub fn layout_single_line(
1233        &mut self,
1234        service: &mut TextFontService,
1235        text: &str,
1236        format: &TextFormat,
1237        max_width: Option<f32>,
1238        raster_scale: f32,
1239    ) -> SingleLineResult {
1240        self.layout_single_line_inner(service, text, format, max_width, raster_scale, false)
1241            .0
1242    }
1243
1244    /// [`layout_single_line`](Self::layout_single_line) plus per-line,
1245    /// per-character geometry.
1246    ///
1247    /// The extra pass measures each character's leading edge and advance
1248    /// so an accessibility layer can populate AccessKit's
1249    /// `character_positions` / `character_widths`. Callers that do not
1250    /// need it should use the plain method, which skips the pass.
1251    pub fn layout_single_line_with_geometry(
1252        &mut self,
1253        service: &mut TextFontService,
1254        text: &str,
1255        format: &TextFormat,
1256        max_width: Option<f32>,
1257        raster_scale: f32,
1258    ) -> (SingleLineResult, LayoutGeometry) {
1259        self.layout_single_line_inner(service, text, format, max_width, raster_scale, true)
1260    }
1261
1262    fn layout_single_line_inner(
1263        &mut self,
1264        service: &mut TextFontService,
1265        text: &str,
1266        format: &TextFormat,
1267        max_width: Option<f32>,
1268        raster_scale: f32,
1269        want_geometry: bool,
1270    ) -> (SingleLineResult, LayoutGeometry) {
1271        let no_geometry = LayoutGeometry {
1272            source_len: text.len(),
1273            ..LayoutGeometry::default()
1274        };
1275        let empty = SingleLineResult {
1276            width: 0.0,
1277            height: 0.0,
1278            baseline: 0.0,
1279            underline_offset: 0.0,
1280            underline_thickness: 0.0,
1281            glyphs: Vec::new(),
1282            glyph_keys: Vec::new(),
1283            spans: Vec::new(),
1284        };
1285
1286        if text.is_empty() {
1287            return (empty, no_geometry);
1288        }
1289
1290        let font_point_size = format.font_size.map(|s| s as u32);
1291        let resolved = match resolve_font(
1292            &service.font_registry,
1293            format.font_family.as_deref(),
1294            format.font_weight,
1295            format.font_bold,
1296            format.font_italic,
1297            font_point_size,
1298            service.scale_factor,
1299            1.0, // standalone shaper: caller's explicit size is already theme-scaled
1300        ) {
1301            Some(r) => r,
1302            None => return (empty, no_geometry),
1303        };
1304
1305        let metrics = match font_metrics_px(&service.font_registry, &resolved) {
1306            Some(m) => m,
1307            None => return (empty, no_geometry),
1308        };
1309        let line_height = metrics.ascent + metrics.descent + metrics.leading;
1310        let baseline = metrics.ascent;
1311
1312        let features = to_harfrust_features(&format.features);
1313        let runs: Vec<_> = bidi_runs(text)
1314            .into_iter()
1315            .filter_map(|br| {
1316                let slice = text.get(br.byte_range.clone())?;
1317                shape_text_in_paragraph(
1318                    &service.font_registry,
1319                    &resolved,
1320                    slice,
1321                    br.byte_range.start,
1322                    br.direction,
1323                    &features,
1324                    &ScriptContext::new(text, None),
1325                    br.byte_range.start,
1326                )
1327            })
1328            .collect();
1329
1330        if runs.is_empty() {
1331            return (empty, no_geometry);
1332        }
1333
1334        let total_advance: f32 = runs.iter().map(|r| r.advance_width).sum();
1335
1336        let (truncate_at_visual_index, final_width, ellipsis_run, truncation) = if let Some(max_w) =
1337            max_width
1338            && total_advance > max_w
1339        {
1340            let ellipsis_run = shape_text(&service.font_registry, &resolved, "\u{2026}", 0);
1341            let ellipsis_width = ellipsis_run
1342                .as_ref()
1343                .map(|r| r.advance_width)
1344                .unwrap_or(0.0);
1345            let budget = (max_w - ellipsis_width).max(0.0);
1346
1347            let mut used = 0.0f32;
1348            let mut count = 0usize;
1349            'outer: for run in &runs {
1350                for g in &run.glyphs {
1351                    if used + g.x_advance > budget {
1352                        break 'outer;
1353                    }
1354                    used += g.x_advance;
1355                    count += 1;
1356                }
1357            }
1358
1359            (
1360                Some(count),
1361                used + ellipsis_width,
1362                ellipsis_run,
1363                Some(LineTruncation {
1364                    ellipsis_x: used,
1365                    ellipsis_width,
1366                }),
1367            )
1368        } else {
1369            (None, total_advance, None, None)
1370        };
1371
1372        let text_color = format.color.unwrap_or(self.text_color);
1373        let glyph_capacity: usize = runs.iter().map(|r| r.glyphs.len()).sum();
1374        let mut quads = Vec::with_capacity(glyph_capacity + 1);
1375        let mut keys = Vec::with_capacity(glyph_capacity + 1);
1376        let mut pen_x = 0.0f32;
1377        let mut emitted = 0usize;
1378
1379        'emit: for run in &runs {
1380            for glyph in &run.glyphs {
1381                if let Some(limit) = truncate_at_visual_index
1382                    && emitted >= limit
1383                {
1384                    break 'emit;
1385                }
1386                rasterize_glyph_quad(
1387                    service,
1388                    glyph,
1389                    run,
1390                    pen_x,
1391                    baseline,
1392                    text_color,
1393                    raster_scale,
1394                    &mut quads,
1395                    &mut keys,
1396                );
1397                pen_x += glyph.x_advance;
1398                emitted += 1;
1399            }
1400        }
1401
1402        if let Some(ref e_run) = ellipsis_run {
1403            for glyph in &e_run.glyphs {
1404                rasterize_glyph_quad(
1405                    service,
1406                    glyph,
1407                    e_run,
1408                    pen_x,
1409                    baseline,
1410                    text_color,
1411                    raster_scale,
1412                    &mut quads,
1413                    &mut keys,
1414                );
1415                pen_x += glyph.x_advance;
1416            }
1417        }
1418
1419        let geometry = if want_geometry {
1420            crate::layout::geometry::single_line_geometry(
1421                text,
1422                &runs,
1423                truncate_at_visual_index,
1424                truncation,
1425                metrics.ascent,
1426                metrics.descent,
1427                metrics.leading,
1428            )
1429        } else {
1430            no_geometry
1431        };
1432
1433        (
1434            SingleLineResult {
1435                width: final_width,
1436                height: line_height,
1437                baseline,
1438                underline_offset: metrics.underline_offset,
1439                underline_thickness: metrics.stroke_size,
1440                glyphs: quads,
1441                glyph_keys: keys,
1442                spans: Vec::new(),
1443            },
1444            geometry,
1445        )
1446    }
1447
1448    /// Lay out a multi-line paragraph by wrapping text at `max_width`.
1449    ///
1450    /// Multi-line counterpart to
1451    /// [`layout_single_line`](Self::layout_single_line). Shapes the
1452    /// input, breaks it at Unicode line-break opportunities
1453    /// (greedy, left-aligned), and rasterizes each line's glyphs
1454    /// into paragraph-local coordinates starting at `(0, 0)`.
1455    ///
1456    /// If `max_lines` is `Some(n)`, at most `n` lines are emitted
1457    /// and any remainder is silently dropped.
1458    ///
1459    /// See [`layout_single_line`](Self::layout_single_line) for the
1460    /// `raster_scale` contract (pass `1.0` for unscaled UI).
1461    pub fn layout_paragraph(
1462        &mut self,
1463        service: &mut TextFontService,
1464        text: &str,
1465        format: &TextFormat,
1466        max_width: f32,
1467        max_lines: Option<usize>,
1468        raster_scale: f32,
1469    ) -> ParagraphResult {
1470        self.layout_paragraph_inner(
1471            service,
1472            text,
1473            format,
1474            max_width,
1475            max_lines,
1476            raster_scale,
1477            false,
1478        )
1479        .0
1480    }
1481
1482    /// [`layout_paragraph`](Self::layout_paragraph) plus per-line,
1483    /// per-character geometry. See
1484    /// [`layout_single_line_with_geometry`](Self::layout_single_line_with_geometry).
1485    pub fn layout_paragraph_with_geometry(
1486        &mut self,
1487        service: &mut TextFontService,
1488        text: &str,
1489        format: &TextFormat,
1490        max_width: f32,
1491        max_lines: Option<usize>,
1492        raster_scale: f32,
1493    ) -> (ParagraphResult, LayoutGeometry) {
1494        self.layout_paragraph_inner(
1495            service,
1496            text,
1497            format,
1498            max_width,
1499            max_lines,
1500            raster_scale,
1501            true,
1502        )
1503    }
1504
1505    #[allow(clippy::too_many_arguments)]
1506    fn layout_paragraph_inner(
1507        &mut self,
1508        service: &mut TextFontService,
1509        text: &str,
1510        format: &TextFormat,
1511        max_width: f32,
1512        max_lines: Option<usize>,
1513        raster_scale: f32,
1514        want_geometry: bool,
1515    ) -> (ParagraphResult, LayoutGeometry) {
1516        let no_geometry = LayoutGeometry {
1517            source_len: text.len(),
1518            ..LayoutGeometry::default()
1519        };
1520        let empty = ParagraphResult {
1521            width: 0.0,
1522            height: 0.0,
1523            baseline_first: 0.0,
1524            line_count: 0,
1525            line_height: 0.0,
1526            underline_offset: 0.0,
1527            underline_thickness: 0.0,
1528            glyphs: Vec::new(),
1529            glyph_keys: Vec::new(),
1530            spans: Vec::new(),
1531        };
1532
1533        if text.is_empty() || max_width <= 0.0 {
1534            return (empty, no_geometry);
1535        }
1536
1537        let font_point_size = format.font_size.map(|s| s as u32);
1538        let resolved = match resolve_font(
1539            &service.font_registry,
1540            format.font_family.as_deref(),
1541            format.font_weight,
1542            format.font_bold,
1543            format.font_italic,
1544            font_point_size,
1545            service.scale_factor,
1546            1.0, // standalone shaper: caller's explicit size is already theme-scaled
1547        ) {
1548            Some(r) => r,
1549            None => return (empty, no_geometry),
1550        };
1551
1552        let metrics = match font_metrics_px(&service.font_registry, &resolved) {
1553            Some(m) => m,
1554            None => return (empty, no_geometry),
1555        };
1556
1557        let features = to_harfrust_features(&format.features);
1558        let runs: Vec<_> = bidi_runs(text)
1559            .into_iter()
1560            .filter_map(|br| {
1561                let slice = text.get(br.byte_range.clone())?;
1562                shape_text_in_paragraph(
1563                    &service.font_registry,
1564                    &resolved,
1565                    slice,
1566                    br.byte_range.start,
1567                    br.direction,
1568                    &features,
1569                    &ScriptContext::new(text, None),
1570                    br.byte_range.start,
1571                )
1572            })
1573            .collect();
1574
1575        if runs.is_empty() {
1576            return (empty, no_geometry);
1577        }
1578
1579        let hyphenator = format.hyphenation.and_then(|h| {
1580            shape_text(&service.font_registry, &resolved, "-", 0)
1581                .and_then(|r| r.glyphs.into_iter().next())
1582                .map(|glyph| Hyphenator {
1583                    glyph,
1584                    language: h.language,
1585                })
1586        });
1587        let lines = break_into_lines(
1588            runs,
1589            text,
1590            max_width,
1591            Alignment::Left,
1592            0.0,
1593            &metrics,
1594            hyphenator,
1595            // This path ran the bidi algorithm itself and shaped in
1596            // display order, so the runs must not be reordered again.
1597            RunOrder::AlreadyVisual,
1598        );
1599
1600        let line_count = match max_lines {
1601            Some(n) => lines.len().min(n),
1602            None => lines.len(),
1603        };
1604
1605        let text_color = format.color.unwrap_or(self.text_color);
1606        let mut quads: Vec<GlyphQuad> = Vec::new();
1607        let mut keys: Vec<crate::atlas::cache::GlyphCacheKey> = Vec::new();
1608        let mut y_top = 0.0f32;
1609        let mut max_line_width = 0.0f32;
1610        let baseline_first = metrics.ascent;
1611
1612        for line in lines.iter().take(line_count) {
1613            if line.width > max_line_width {
1614                max_line_width = line.width;
1615            }
1616            let baseline_y = y_top + metrics.ascent;
1617            for run in &line.runs {
1618                let mut pen_x = run.x;
1619                let run_copy = run.shaped_run.clone();
1620                for glyph in &run_copy.glyphs {
1621                    rasterize_glyph_quad(
1622                        service,
1623                        glyph,
1624                        &run_copy,
1625                        pen_x,
1626                        baseline_y,
1627                        text_color,
1628                        raster_scale,
1629                        &mut quads,
1630                        &mut keys,
1631                    );
1632                    pen_x += glyph.x_advance;
1633                }
1634            }
1635            y_top += metrics.ascent + metrics.descent + metrics.leading;
1636        }
1637
1638        let line_height = metrics.ascent + metrics.descent + metrics.leading;
1639        let geometry = if want_geometry {
1640            crate::layout::geometry::paragraph_geometry(
1641                &lines[..line_count],
1642                text,
1643                line_height,
1644                lines.len() - line_count,
1645                None,
1646                Vec::new(),
1647            )
1648        } else {
1649            no_geometry
1650        };
1651
1652        (
1653            ParagraphResult {
1654                width: max_line_width,
1655                height: y_top,
1656                baseline_first,
1657                line_count,
1658                line_height,
1659                underline_offset: metrics.underline_offset,
1660                underline_thickness: metrics.stroke_size,
1661                glyphs: quads,
1662                glyph_keys: keys,
1663                spans: Vec::new(),
1664            },
1665            geometry,
1666        )
1667    }
1668
1669    /// Single-line layout with inline markup. See
1670    /// [`layout_single_line`](Self::layout_single_line) for the plain
1671    /// variant. Accepts parsed `[label](url)`, `*italic*`, and
1672    /// `**bold**` spans and annotates the output with per-span
1673    /// bounding rectangles for hit-testing.
1674    pub fn layout_single_line_markup(
1675        &mut self,
1676        service: &mut TextFontService,
1677        markup: &InlineMarkup,
1678        format: &TextFormat,
1679        max_width: Option<f32>,
1680        raster_scale: f32,
1681    ) -> SingleLineResult {
1682        self.layout_single_line_markup_inner(
1683            service,
1684            markup,
1685            format,
1686            max_width,
1687            raster_scale,
1688            false,
1689        )
1690        .0
1691    }
1692
1693    /// [`layout_single_line_markup`](Self::layout_single_line_markup) plus
1694    /// per-line, per-character geometry.
1695    ///
1696    /// Every range in the returned geometry indexes
1697    /// [`LayoutGeometry::rendered_text`] — the markup with its syntax
1698    /// stripped — and [`LayoutGeometry::links`] reports each link's label
1699    /// against that same text.
1700    pub fn layout_single_line_markup_with_geometry(
1701        &mut self,
1702        service: &mut TextFontService,
1703        markup: &InlineMarkup,
1704        format: &TextFormat,
1705        max_width: Option<f32>,
1706        raster_scale: f32,
1707    ) -> (SingleLineResult, LayoutGeometry) {
1708        self.layout_single_line_markup_inner(service, markup, format, max_width, raster_scale, true)
1709    }
1710
1711    fn layout_single_line_markup_inner(
1712        &mut self,
1713        service: &mut TextFontService,
1714        markup: &InlineMarkup,
1715        format: &TextFormat,
1716        max_width: Option<f32>,
1717        raster_scale: f32,
1718        want_geometry: bool,
1719    ) -> (SingleLineResult, LayoutGeometry) {
1720        if markup.spans.is_empty() {
1721            return (
1722                SingleLineResult {
1723                    width: 0.0,
1724                    height: 0.0,
1725                    baseline: 0.0,
1726                    underline_offset: 0.0,
1727                    underline_thickness: 0.0,
1728                    glyphs: Vec::new(),
1729                    glyph_keys: Vec::new(),
1730                    spans: Vec::new(),
1731                },
1732                LayoutGeometry::default(),
1733            );
1734        }
1735
1736        let per_span: Vec<(
1737            SingleLineResult,
1738            LayoutGeometry,
1739            &crate::layout::inline_markup::InlineSpan,
1740        )> = markup
1741            .spans
1742            .iter()
1743            .map(|sp| {
1744                let fmt = merge_format(format, sp.attrs);
1745                let (r, g) = if sp.text.is_empty() {
1746                    (
1747                        SingleLineResult {
1748                            width: 0.0,
1749                            height: 0.0,
1750                            baseline: 0.0,
1751                            underline_offset: 0.0,
1752                            underline_thickness: 0.0,
1753                            glyphs: Vec::new(),
1754                            glyph_keys: Vec::new(),
1755                            spans: Vec::new(),
1756                        },
1757                        LayoutGeometry::default(),
1758                    )
1759                } else {
1760                    self.layout_single_line_inner(
1761                        service,
1762                        &sp.text,
1763                        &fmt,
1764                        None,
1765                        raster_scale,
1766                        want_geometry,
1767                    )
1768                };
1769                (r, g, sp)
1770            })
1771            .collect();
1772
1773        let total_width: f32 = per_span.iter().map(|(r, _, _)| r.width).sum();
1774        let line_height = per_span
1775            .iter()
1776            .map(|(r, _, _)| r.height)
1777            .fold(0.0f32, f32::max);
1778        let baseline = per_span
1779            .iter()
1780            .map(|(r, _, _)| r.baseline)
1781            .fold(0.0f32, f32::max);
1782        // Carry underline metrics from the first non-empty span. Spans may
1783        // use different fonts but a single line only has one underline, so
1784        // the first span wins.
1785        let (underline_offset, underline_thickness) = per_span
1786            .iter()
1787            .map(|(r, _, _)| (r.underline_offset, r.underline_thickness))
1788            .find(|(_, t)| *t > 0.0)
1789            .unwrap_or((0.0, 0.0));
1790
1791        let truncate = match max_width {
1792            Some(mw) if total_width > mw => Some(mw),
1793            _ => None,
1794        };
1795
1796        let mut glyphs: Vec<GlyphQuad> = Vec::new();
1797        let mut all_keys: Vec<crate::atlas::cache::GlyphCacheKey> = Vec::new();
1798        let mut spans_out: Vec<LaidOutSpan> = Vec::new();
1799        let mut pen_x: f32 = 0.0;
1800        let effective_width = truncate.unwrap_or(total_width);
1801        // The rendered text and its links cover every span, including any
1802        // the emit loop below stops short of.
1803        let mut rendered = String::new();
1804        let mut links: Vec<crate::types::LinkGeometry> = Vec::new();
1805        let mut flat_offsets: Vec<(usize, usize)> = Vec::with_capacity(per_span.len());
1806        if want_geometry {
1807            let mut flat_char = 0usize;
1808            for (_, _, sp) in &per_span {
1809                flat_offsets.push((rendered.len(), flat_char));
1810                if let Some(url) = sp.link_url.as_ref() {
1811                    links.push(crate::types::LinkGeometry {
1812                        rendered_byte_range: rendered.len()..rendered.len() + sp.text.len(),
1813                        url: url.clone(),
1814                    });
1815                }
1816                rendered.push_str(&sp.text);
1817                flat_char += sp.text.chars().count();
1818            }
1819        }
1820        let mut segments: Vec<crate::types::LineSegment> = Vec::new();
1821        let mut clip_x: Option<f32> = None;
1822
1823        for (span_idx, (r, g, sp)) in per_span.iter().enumerate() {
1824            if want_geometry {
1825                let (flat_byte, flat_char) = flat_offsets[span_idx];
1826                // A span the clip cut short contributes no geometry: the
1827                // caller anchors everything past `clip_x` there instead.
1828                if clip_x.is_none() && pen_x + r.width <= effective_width + 0.5 {
1829                    for line in &g.lines {
1830                        for seg in &line.segments {
1831                            let mut seg = seg.clone();
1832                            seg.rect[0] += pen_x;
1833                            seg.byte_range =
1834                                seg.byte_range.start + flat_byte..seg.byte_range.end + flat_byte;
1835                            seg.char_range =
1836                                seg.char_range.start + flat_char..seg.char_range.end + flat_char;
1837                            segments.push(seg);
1838                        }
1839                    }
1840                } else if clip_x.is_none() {
1841                    clip_x = Some(pen_x.min(effective_width));
1842                }
1843            }
1844
1845            let remaining = (effective_width - pen_x).max(0.0);
1846            let span_visible_width = r.width.min(remaining);
1847            if span_visible_width <= 0.0 && r.width > 0.0 {
1848                spans_out.push(LaidOutSpan {
1849                    kind: if let Some(url) = sp.link_url.clone() {
1850                        LaidOutSpanKind::Link { url }
1851                    } else {
1852                        LaidOutSpanKind::Text
1853                    },
1854                    line_index: 0,
1855                    rect: [pen_x, 0.0, 0.0, line_height],
1856                    byte_range: sp.byte_range.clone(),
1857                });
1858                continue;
1859            }
1860
1861            for (gi, g) in r.glyphs.iter().enumerate() {
1862                let g_right = pen_x + g.screen[0] + g.screen[2];
1863                if g_right > effective_width + 0.5 {
1864                    break;
1865                }
1866                let mut gq = g.clone();
1867                gq.screen[0] += pen_x;
1868                glyphs.push(gq);
1869                if let Some(k) = r.glyph_keys.get(gi) {
1870                    all_keys.push(*k);
1871                }
1872            }
1873
1874            spans_out.push(LaidOutSpan {
1875                kind: if let Some(url) = sp.link_url.clone() {
1876                    LaidOutSpanKind::Link { url }
1877                } else {
1878                    LaidOutSpanKind::Text
1879                },
1880                line_index: 0,
1881                rect: [pen_x, 0.0, span_visible_width, line_height],
1882                byte_range: sp.byte_range.clone(),
1883            });
1884
1885            pen_x += r.width;
1886            if truncate.is_some() && pen_x >= effective_width {
1887                break;
1888            }
1889        }
1890
1891        let geometry = if want_geometry {
1892            let total_chars = rendered.chars().count();
1893            let end = crate::types::LineEnd::hard_break_ending(&rendered)
1894                .unwrap_or(crate::types::LineEnd::EndOfText);
1895            LayoutGeometry {
1896                lines: vec![crate::types::LineGeometry {
1897                    index: 0,
1898                    byte_range: 0..rendered.len(),
1899                    char_range: 0..total_chars,
1900                    rect: [0.0, 0.0, effective_width, line_height],
1901                    baseline,
1902                    caret_x: 0.0,
1903                    segments,
1904                    end,
1905                    // The markup path clips rather than ellipsizing, so the
1906                    // "ellipsis" is a zero-width mark at the clip point.
1907                    truncation: clip_x.map(|x| LineTruncation {
1908                        ellipsis_x: x,
1909                        ellipsis_width: 0.0,
1910                    }),
1911                }],
1912                dropped_lines: 0,
1913                source_len: rendered.len(),
1914                rendered_text: Some(rendered),
1915                links,
1916            }
1917        } else {
1918            LayoutGeometry::default()
1919        };
1920
1921        (
1922            SingleLineResult {
1923                width: effective_width,
1924                height: line_height,
1925                baseline,
1926                underline_offset,
1927                underline_thickness,
1928                glyphs,
1929                glyph_keys: all_keys,
1930                spans: spans_out,
1931            },
1932            geometry,
1933        )
1934    }
1935
1936    /// Paragraph layout with inline markup. Multi-line counterpart
1937    /// to [`layout_single_line_markup`](Self::layout_single_line_markup).
1938    /// Emits a [`LaidOutSpan`] for every link segment so the caller
1939    /// can hit-test against wrapped links.
1940    pub fn layout_paragraph_markup(
1941        &mut self,
1942        service: &mut TextFontService,
1943        markup: &InlineMarkup,
1944        format: &TextFormat,
1945        max_width: f32,
1946        max_lines: Option<usize>,
1947        raster_scale: f32,
1948    ) -> ParagraphResult {
1949        self.layout_paragraph_markup_inner(
1950            service,
1951            markup,
1952            format,
1953            max_width,
1954            max_lines,
1955            raster_scale,
1956            false,
1957        )
1958        .0
1959    }
1960
1961    /// [`layout_paragraph_markup`](Self::layout_paragraph_markup) plus
1962    /// per-line, per-character geometry. See
1963    /// [`layout_single_line_markup_with_geometry`](Self::layout_single_line_markup_with_geometry)
1964    /// for how the ranges relate to the markup source.
1965    pub fn layout_paragraph_markup_with_geometry(
1966        &mut self,
1967        service: &mut TextFontService,
1968        markup: &InlineMarkup,
1969        format: &TextFormat,
1970        max_width: f32,
1971        max_lines: Option<usize>,
1972        raster_scale: f32,
1973    ) -> (ParagraphResult, LayoutGeometry) {
1974        self.layout_paragraph_markup_inner(
1975            service,
1976            markup,
1977            format,
1978            max_width,
1979            max_lines,
1980            raster_scale,
1981            true,
1982        )
1983    }
1984
1985    #[allow(clippy::too_many_arguments)]
1986    fn layout_paragraph_markup_inner(
1987        &mut self,
1988        service: &mut TextFontService,
1989        markup: &InlineMarkup,
1990        format: &TextFormat,
1991        max_width: f32,
1992        max_lines: Option<usize>,
1993        raster_scale: f32,
1994        want_geometry: bool,
1995    ) -> (ParagraphResult, LayoutGeometry) {
1996        let empty = ParagraphResult {
1997            width: 0.0,
1998            height: 0.0,
1999            baseline_first: 0.0,
2000            line_count: 0,
2001            line_height: 0.0,
2002            underline_offset: 0.0,
2003            underline_thickness: 0.0,
2004            glyphs: Vec::new(),
2005            glyph_keys: Vec::new(),
2006            spans: Vec::new(),
2007        };
2008
2009        if markup.spans.is_empty() || max_width <= 0.0 {
2010            return (empty, LayoutGeometry::default());
2011        }
2012
2013        let mut flat = String::new();
2014        let mut span_flat_offsets: Vec<usize> = Vec::with_capacity(markup.spans.len());
2015        for sp in &markup.spans {
2016            span_flat_offsets.push(flat.len());
2017            flat.push_str(&sp.text);
2018        }
2019        if flat.is_empty() {
2020            return (empty, LayoutGeometry::default());
2021        }
2022        let links: Vec<crate::types::LinkGeometry> = markup
2023            .spans
2024            .iter()
2025            .enumerate()
2026            .filter_map(|(i, sp)| {
2027                let url = sp.link_url.clone()?;
2028                let start = span_flat_offsets[i];
2029                Some(crate::types::LinkGeometry {
2030                    rendered_byte_range: start..start + sp.text.len(),
2031                    url,
2032                })
2033            })
2034            .collect();
2035
2036        let base_point_size = format.font_size.map(|s| s as u32);
2037        let base_resolved = match resolve_font(
2038            &service.font_registry,
2039            format.font_family.as_deref(),
2040            format.font_weight,
2041            format.font_bold,
2042            format.font_italic,
2043            base_point_size,
2044            service.scale_factor,
2045            1.0, // standalone shaper: caller's explicit size is already theme-scaled
2046        ) {
2047            Some(r) => r,
2048            None => return (empty, LayoutGeometry::default()),
2049        };
2050        let metrics = match font_metrics_px(&service.font_registry, &base_resolved) {
2051            Some(m) => m,
2052            None => return (empty, LayoutGeometry::default()),
2053        };
2054
2055        let mut all_runs: Vec<ShapedRun> = Vec::new();
2056        for (span_idx, sp) in markup.spans.iter().enumerate() {
2057            if sp.text.is_empty() {
2058                continue;
2059            }
2060            let fmt = merge_format(format, sp.attrs);
2061            let span_point_size = fmt.font_size.map(|s| s as u32);
2062            let Some(resolved) = resolve_font(
2063                &service.font_registry,
2064                fmt.font_family.as_deref(),
2065                fmt.font_weight,
2066                fmt.font_bold,
2067                fmt.font_italic,
2068                span_point_size,
2069                service.scale_factor,
2070                1.0, // standalone shaper: caller's explicit size is already theme-scaled
2071            ) else {
2072                continue;
2073            };
2074
2075            let flat_start = span_flat_offsets[span_idx];
2076            let features = to_harfrust_features(&fmt.features);
2077            for br in bidi_runs(&sp.text) {
2078                let slice = match sp.text.get(br.byte_range.clone()) {
2079                    Some(s) => s,
2080                    None => continue,
2081                };
2082                let Some(mut run) = shape_text_in_paragraph(
2083                    &service.font_registry,
2084                    &resolved,
2085                    slice,
2086                    flat_start + br.byte_range.start,
2087                    br.direction,
2088                    &features,
2089                    &ScriptContext::new(&flat, None),
2090                    flat_start + br.byte_range.start,
2091                ) else {
2092                    continue;
2093                };
2094                if let Some(url) = sp.link_url.as_ref() {
2095                    run.is_link = true;
2096                    run.anchor_href = Some(url.clone());
2097                }
2098                all_runs.push(run);
2099            }
2100        }
2101
2102        if all_runs.is_empty() {
2103            return (empty, LayoutGeometry::default());
2104        }
2105
2106        let hyphenator = format.hyphenation.and_then(|h| {
2107            shape_text(&service.font_registry, &base_resolved, "-", 0)
2108                .and_then(|r| r.glyphs.into_iter().next())
2109                .map(|glyph| Hyphenator {
2110                    glyph,
2111                    language: h.language,
2112                })
2113        });
2114        let lines = break_into_lines(
2115            all_runs,
2116            &flat,
2117            max_width,
2118            Alignment::Left,
2119            0.0,
2120            &metrics,
2121            hyphenator,
2122            // This path ran the bidi algorithm itself and shaped in
2123            // display order, so the runs must not be reordered again.
2124            RunOrder::AlreadyVisual,
2125        );
2126
2127        let line_count = match max_lines {
2128            Some(n) => lines.len().min(n),
2129            None => lines.len(),
2130        };
2131
2132        let text_color = format.color.unwrap_or(self.text_color);
2133        let mut glyphs_out: Vec<GlyphQuad> = Vec::new();
2134        let mut keys_out: Vec<crate::atlas::cache::GlyphCacheKey> = Vec::new();
2135        let mut spans_out: Vec<LaidOutSpan> = Vec::new();
2136        let line_height = metrics.ascent + metrics.descent + metrics.leading;
2137        let mut y_top: f32 = 0.0;
2138        let mut max_line_width: f32 = 0.0;
2139        let baseline_first = metrics.ascent;
2140
2141        for (line_idx, line) in lines.iter().take(line_count).enumerate() {
2142            if line.width > max_line_width {
2143                max_line_width = line.width;
2144            }
2145            let baseline_y = y_top + metrics.ascent;
2146
2147            for pr in &line.runs {
2148                let run_copy = pr.shaped_run.clone();
2149                let mut pen_x = pr.x;
2150                for glyph in &run_copy.glyphs {
2151                    rasterize_glyph_quad(
2152                        service,
2153                        glyph,
2154                        &run_copy,
2155                        pen_x,
2156                        baseline_y,
2157                        text_color,
2158                        raster_scale,
2159                        &mut glyphs_out,
2160                        &mut keys_out,
2161                    );
2162                    pen_x += glyph.x_advance;
2163                }
2164
2165                if pr.decorations.is_link
2166                    && let Some(url) = pr.decorations.anchor_href.clone()
2167                {
2168                    let width = pr.shaped_run.advance_width;
2169                    spans_out.push(LaidOutSpan {
2170                        kind: LaidOutSpanKind::Link { url },
2171                        line_index: line_idx,
2172                        rect: [pr.x, y_top, width, line_height],
2173                        byte_range: pr.shaped_run.text_range.clone(),
2174                    });
2175                }
2176            }
2177
2178            y_top += line_height;
2179        }
2180
2181        let geometry = if want_geometry {
2182            crate::layout::geometry::paragraph_geometry(
2183                &lines[..line_count],
2184                &flat,
2185                line_height,
2186                lines.len() - line_count,
2187                Some(flat.clone()),
2188                links,
2189            )
2190        } else {
2191            LayoutGeometry::default()
2192        };
2193
2194        (
2195            ParagraphResult {
2196                width: max_line_width,
2197                height: y_top,
2198                baseline_first,
2199                line_count,
2200                line_height,
2201                underline_offset: metrics.underline_offset,
2202                underline_thickness: metrics.stroke_size,
2203                glyphs: glyphs_out,
2204                glyph_keys: keys_out,
2205                spans: spans_out,
2206            },
2207            geometry,
2208        )
2209    }
2210
2211    // ── Hit testing & character geometry ───────────────────────
2212
2213    /// Map a screen-space point to a document position. Coordinates
2214    /// are relative to the widget's top-left corner; the scroll
2215    /// offset is applied internally. Returns `None` when the flow
2216    /// has no content.
2217    pub fn hit_test(&self, x: f32, y: f32) -> Option<HitTestResult> {
2218        crate::render::hit_test::hit_test(
2219            &self.flow_layout,
2220            self.scroll_offset,
2221            x / self.zoom,
2222            y / self.zoom,
2223        )
2224    }
2225
2226    /// Per-character advance geometry within a laid-out block.
2227    ///
2228    /// Used by accessibility layers that need to expose character
2229    /// positions to screen readers (AccessKit's `character_positions`
2230    /// / `character_widths` on `Role::TextRun`). `char_start` and
2231    /// `char_end` are block-relative character offsets. Returns one
2232    /// entry per character in the range, with `position` measured
2233    /// in run-local coordinates (the first character sits at `0`).
2234    ///
2235    /// Widths come from each character's own advance, so a
2236    /// right-to-left character reports a positive width. Deriving them
2237    /// from the left-to-right delta between caret stops — as this used
2238    /// to — collapsed every RTL character to zero.
2239    pub fn character_geometry(
2240        &self,
2241        block_id: usize,
2242        char_start: usize,
2243        char_end: usize,
2244    ) -> Vec<CharacterGeometry> {
2245        let Some(resolved) = self.flow_layout.resolve_block(block_id) else {
2246            return Vec::new();
2247        };
2248        crate::layout::geometry::character_geometry_over_lines(
2249            &resolved.block.lines,
2250            char_start,
2251            char_end,
2252        )
2253    }
2254
2255    /// Per-line, per-character geometry for one laid-out block.
2256    ///
2257    /// `text` is the block's own text — the layout stores char offsets,
2258    /// not the string they index, so the caller supplies it and every
2259    /// byte range in the result indexes it. Line boxes, `caret_x` and
2260    /// segments are relative to the block's top edge and, horizontally, to
2261    /// [`BlockVisualInfo::content_x`] (the start of the block's text, after
2262    /// its margin and indent), not to the column edge.
2263    pub fn block_line_geometry(&self, block_id: usize, text: &str) -> Vec<LineGeometry> {
2264        let Some(resolved) = self.flow_layout.resolve_block(block_id) else {
2265            return Vec::new();
2266        };
2267        crate::layout::geometry::stacked_lines_geometry(&resolved.block.lines, text, |_, line| {
2268            line.y - line.ascent
2269        })
2270    }
2271
2272    /// Screen-space caret rectangle at a document position with the
2273    /// given affinity, as `[x, y, width, height]`. Feed this to the
2274    /// platform IME for composition window placement. For drawing the
2275    /// caret itself, use the `DecorationKind::Cursor` entry in
2276    /// [`RenderFrame::decorations`] instead.
2277    ///
2278    /// Affinity only changes the result at soft-wrap boundaries; at
2279    /// every other position the two affinities return the same rect.
2280    /// `CursorAffinity::Downstream` matches the pre-affinity behavior.
2281    pub fn caret_rect(&self, position: usize, affinity: crate::types::CursorAffinity) -> [f32; 4] {
2282        let mut rect = crate::render::hit_test::caret_rect(
2283            &self.flow_layout,
2284            self.scroll_offset,
2285            position,
2286            affinity,
2287        );
2288        rect[0] *= self.zoom;
2289        rect[1] *= self.zoom;
2290        rect[2] *= self.zoom;
2291        rect[3] *= self.zoom;
2292        rect
2293    }
2294
2295    // ── Cursor & colors ────────────────────────────────────────
2296
2297    /// Replace the cursor display with a single cursor.
2298    pub fn set_cursor(&mut self, cursor: &CursorDisplay) {
2299        self.cursors = vec![CursorDisplay {
2300            position: cursor.position,
2301            anchor: cursor.anchor,
2302            affinity: cursor.affinity,
2303            visible: cursor.visible,
2304            selected_cells: cursor.selected_cells.clone(),
2305        }];
2306    }
2307
2308    /// Replace the cursor display with multiple cursors (multi-caret
2309    /// editing). Each cursor independently generates a caret and
2310    /// optional selection highlight.
2311    pub fn set_cursors(&mut self, cursors: &[CursorDisplay]) {
2312        self.cursors = cursors
2313            .iter()
2314            .map(|c| CursorDisplay {
2315                position: c.position,
2316                anchor: c.anchor,
2317                affinity: c.affinity,
2318                visible: c.visible,
2319                selected_cells: c.selected_cells.clone(),
2320            })
2321            .collect();
2322    }
2323
2324    /// Set the selection highlight color `[r, g, b, a]` in 0..=1
2325    /// space. Default: `[0.26, 0.52, 0.96, 0.3]` (translucent blue).
2326    pub fn set_selection_color(&mut self, color: [f32; 4]) {
2327        self.selection_color = color;
2328    }
2329
2330    /// Set the caret color `[r, g, b, a]`. Default: black.
2331    pub fn set_cursor_color(&mut self, color: [f32; 4]) {
2332        self.cursor_color = color;
2333    }
2334
2335    /// Set the default text color `[r, g, b, a]`, used when a
2336    /// fragment has no explicit `foreground_color`. Default: black.
2337    pub fn set_text_color(&mut self, color: [f32; 4]) {
2338        self.text_color = color;
2339    }
2340
2341    /// Current default text color.
2342    pub fn text_color(&self) -> [f32; 4] {
2343        self.text_color
2344    }
2345
2346    /// Set the background painted behind fenced code blocks when the
2347    /// block carries no explicit `background_color`. Hosts wire this
2348    /// from the active theme so dark / light swaps reach the cards.
2349    /// Default `[0.95, 0.95, 0.95, 1.0]` (light grey). Affects future
2350    /// `layout_full` / `relayout_block` calls; existing layouts keep
2351    /// their already-converted background until they next re-shape.
2352    pub fn set_code_block_background(&mut self, color: [f32; 4]) {
2353        self.code_block_background = color;
2354    }
2355
2356    /// Current code-block background default.
2357    pub fn code_block_background(&self) -> [f32; 4] {
2358        self.code_block_background
2359    }
2360
2361    /// Auto-hyphenate justified blocks (that don't set `hyphenate`
2362    /// explicitly) on future `layout_full` / `relayout_block` calls.
2363    /// Enable on prose/rich-text surfaces; leave off for single-line or
2364    /// label widgets. Default `false`.
2365    pub fn set_hyphenate_justified(&mut self, enabled: bool) {
2366        self.hyphenate_justified = enabled;
2367    }
2368
2369    /// Whether justified blocks are auto-hyphenated.
2370    pub fn hyphenate_justified(&self) -> bool {
2371        self.hyphenate_justified
2372    }
2373
2374    /// Set the foreground used for monospaced runs (inline `code`,
2375    /// fenced code blocks) that carry no explicit `foreground_color`.
2376    /// `None` (default) keeps the engine's `text_color`. Hosts wire
2377    /// this from the active theme alongside `set_code_block_background`.
2378    pub fn set_code_block_foreground(&mut self, color: Option<[f32; 4]>) {
2379        self.code_block_foreground = color;
2380    }
2381
2382    /// Current code-block foreground override.
2383    pub fn code_block_foreground(&self) -> Option<[f32; 4]> {
2384        self.code_block_foreground
2385    }
2386
2387    /// Set the foreground used for hyperlink runs that carry no explicit
2388    /// `foreground_color`. `None` (default) keeps the engine's
2389    /// `text_color` — i.e. links that look like prose. Hosts wire this
2390    /// from the active theme, alongside `set_code_block_foreground`.
2391    ///
2392    /// Changing it needs a full relayout: the colour is baked into the
2393    /// shaped runs at layout time, not resolved at paint.
2394    pub fn set_link_foreground(&mut self, color: Option<[f32; 4]>) {
2395        self.link_foreground = color;
2396    }
2397
2398    /// Current link foreground override.
2399    pub fn link_foreground(&self) -> Option<[f32; 4]> {
2400        self.link_foreground
2401    }
2402
2403    /// Set the echo / masking character for secure (password) fields.
2404    ///
2405    /// When `Some(c)`, every character laid out by future `layout_full`
2406    /// calls is replaced with `c` before shaping, so the real text never
2407    /// reaches the shaper or the glyph atlas. `None` (default) lays text
2408    /// out verbatim. One echo char is emitted per source `char`,
2409    /// preserving char counts so caret / selection / hit-test (all
2410    /// char-indexed) stay aligned with the host document's positions.
2411    ///
2412    /// Affects future `layout_full` calls; existing layouts keep their
2413    /// already-converted glyphs until they next re-shape. The incremental
2414    /// `relayout_block` path takes pre-converted [`BlockLayoutParams`], so
2415    /// hosts driving that path must thread the same echo char through
2416    /// their own [`crate::bridge::BridgeOptions`].
2417    pub fn set_echo_char(&mut self, echo: Option<char>) {
2418        self.echo_char = echo;
2419    }
2420
2421    /// Current echo / masking character, if any.
2422    pub fn echo_char(&self) -> Option<char> {
2423        self.echo_char
2424    }
2425
2426    // ── Scrolling helpers ──────────────────────────────────────
2427
2428    /// The document-character offset the layout believes `block_id` starts at.
2429    ///
2430    /// The layout keeps its own copy of each block's position and shifts it on
2431    /// every incremental relayout; this is that copy, which is what `hit_test`
2432    /// and `caret_rect` resolve against. Exposed so a caller — or a test — can
2433    /// check it against the document's own idea, since the two silently drifting
2434    /// apart is invisible until a click lands on the wrong character.
2435    pub fn block_position(&self, block_id: usize) -> Option<usize> {
2436        crate::layout::flow::find_block_ref(&self.flow_layout, block_id).map(|b| b.position)
2437    }
2438
2439    /// Visual position and height of a laid-out block. Returns
2440    /// `None` if `block_id` is not in the current layout.
2441    ///
2442    /// See [`BlockVisualInfo`] for the three x positions (`x`, `content_x`,
2443    /// `marker_x`).
2444    pub fn block_visual_info(&self, block_id: usize) -> Option<BlockVisualInfo> {
2445        let resolved = self.flow_layout.resolve_block(block_id)?;
2446        Some(block_visual_info_of(block_id, &resolved))
2447    }
2448
2449    /// The reading direction of the text *at* `position`.
2450    ///
2451    /// This is the direction of the bidi run the caret sits in, not the
2452    /// paragraph's — inside an English quotation in an Arabic paragraph
2453    /// it reports left-to-right. That is what an arrow key needs: which
2454    /// way the caret travels visually when it steps one character
2455    /// forward logically.
2456    ///
2457    /// Falls back to the paragraph direction at a position no run
2458    /// covers (an empty block, or the very end of the text), and to
2459    /// `LeftToRight` when there is no layout at all.
2460    pub fn direction_at(&self, position: usize) -> TextDirection {
2461        let Some(block) = self.block_containing(position) else {
2462            return TextDirection::LeftToRight;
2463        };
2464        let offset = position.saturating_sub(block.position);
2465
2466        for line in &block.lines {
2467            if !line.holds_caret_at(offset) {
2468                continue;
2469            }
2470            // Compare against each run's own cluster span rather than
2471            // asking `cluster_end` per glyph: that scans every glyph on
2472            // the line, which made this quadratic in line length on a
2473            // path every arrow keypress runs.
2474            for run in &line.runs {
2475                let mut lo = usize::MAX;
2476                let mut hi = 0usize;
2477                for g in &run.shaped_run.glyphs {
2478                    let c = g.cluster as usize;
2479                    lo = lo.min(c);
2480                    hi = hi.max(c);
2481                }
2482                if lo == usize::MAX {
2483                    continue;
2484                }
2485                // `hi` is the last cluster's *start*; the run reaches at
2486                // least one character past it.
2487                if offset >= lo && offset <= hi.max(lo) {
2488                    return run.shaped_run.direction;
2489                }
2490            }
2491        }
2492        block.base_direction
2493    }
2494
2495    /// The base direction of the paragraph containing `position`.
2496    ///
2497    /// Home and End want this one rather than [`Self::direction_at`]: they move
2498    /// to the logical ends of the line, and which visual edge those land
2499    /// on is a property of the paragraph, not of whatever run the caret
2500    /// happens to be sitting in.
2501    pub fn paragraph_direction_at(&self, position: usize) -> TextDirection {
2502        self.block_containing(position)
2503            .map(|b| b.base_direction)
2504            .unwrap_or(TextDirection::LeftToRight)
2505    }
2506
2507    /// The document positions of the start and end of the *visual* line
2508    /// containing `position` — i.e. what Home and End should move to.
2509    ///
2510    /// These are logical ends: the start is the lowest character offset
2511    /// on the line whichever screen edge that sits on. Asking the
2512    /// question this way rather than hit-testing a far-off-screen x
2513    /// keeps Home and End correct in right-to-left paragraphs, where the
2514    /// logical start is drawn on the right, and avoids depending on how
2515    /// a hit-test clamps coordinates outside the text.
2516    ///
2517    /// `affinity` picks the line at a soft-wrap boundary, where one
2518    /// position belongs to both the end of one line and the start of the
2519    /// next. Returns `None` if there is no layout for `position`.
2520    pub fn visual_line_range_at(
2521        &self,
2522        position: usize,
2523        affinity: crate::types::CursorAffinity,
2524    ) -> Option<(usize, usize)> {
2525        let block = self.block_containing(position)?;
2526        let offset = position.saturating_sub(block.position);
2527
2528        let mut candidates = block.lines.iter().filter(|l| l.holds_caret_at(offset));
2529        let first = candidates.next()?;
2530
2531        // Two lines can claim a boundary offset. Per `CursorAffinity`:
2532        // Downstream renders at the END of the previous wrap line,
2533        // Upstream at the START of the next one.
2534        let line = match candidates.next() {
2535            Some(second) if affinity == crate::types::CursorAffinity::Upstream => second,
2536            Some(_) => first,
2537            None => first,
2538        };
2539
2540        // End stops before the hard break a line ends with: after it is the
2541        // next line.
2542        Some((
2543            block.position + line.char_range.start,
2544            block.position + line.caret_end(),
2545        ))
2546    }
2547
2548    /// The laid-out block whose character range covers `position`.
2549    ///
2550    /// Searches top-level blocks, table cells and frames, so a caret
2551    /// inside a table or a blockquote resolves like any other.
2552    fn block_containing(&self, position: usize) -> Option<&crate::layout::block::BlockLayout> {
2553        // `end` is inclusive so a caret at the very end of a block still
2554        // resolves, but that makes a block boundary match *two* blocks.
2555        // `blocks` is a HashMap, so picking whichever `find` reached
2556        // first made the answer depend on hash order — Home/End and the
2557        // arrow keys behaved differently from run to run at every
2558        // paragraph start. Prefer a block that strictly contains the
2559        // position, and fall back to a boundary match only if none does.
2560        let strictly_inside = |b: &crate::layout::block::BlockLayout| {
2561            let end = block_end(b);
2562            position >= b.position && position < end
2563        };
2564        let covers = |b: &crate::layout::block::BlockLayout| {
2565            position >= b.position && position <= block_end(b)
2566        };
2567
2568        fn block_end(b: &crate::layout::block::BlockLayout) -> usize {
2569            b.lines
2570                .last()
2571                .map(|l| b.position + l.char_range.end)
2572                .unwrap_or(b.position)
2573        }
2574
2575        // Deterministic tie-break among boundary matches: the latest
2576        // block that starts at or before the position.
2577        fn best<'b>(
2578            acc: Option<&'b crate::layout::block::BlockLayout>,
2579            b: &'b crate::layout::block::BlockLayout,
2580        ) -> Option<&'b crate::layout::block::BlockLayout> {
2581            match acc {
2582                Some(prev) if prev.position >= b.position => Some(prev),
2583                _ => Some(b),
2584            }
2585        }
2586
2587        if let Some(b) = self
2588            .flow_layout
2589            .blocks
2590            .values()
2591            .filter(|b| strictly_inside(b))
2592            .fold(None, best)
2593        {
2594            return Some(b);
2595        }
2596        if let Some(b) = self
2597            .flow_layout
2598            .blocks
2599            .values()
2600            .filter(|b| covers(b))
2601            .fold(None, best)
2602        {
2603            return Some(b);
2604        }
2605        for table in self.flow_layout.tables.values() {
2606            for cell in &table.cell_layouts {
2607                if let Some(b) = cell.blocks.iter().find(|b| covers(b)) {
2608                    return Some(b);
2609                }
2610            }
2611        }
2612        for frame in self.flow_layout.frames.values() {
2613            if let Some(b) = frame.blocks.iter().find(|b| covers(b)) {
2614                return Some(b);
2615            }
2616        }
2617        None
2618    }
2619
2620    /// Whether `position` sits on a direction boundary — a place where
2621    /// an LTR run meets an RTL one and the caret has two possible x on
2622    /// the same line.
2623    ///
2624    /// The widget layer uses this to decide whether moving the caret
2625    /// here has to choose a side: at an ordinary position affinity makes
2626    /// no difference and can be left alone, but at a seam the caret
2627    /// jumps across the line if it carries the wrong one.
2628    pub fn is_direction_boundary_at(&self, position: usize) -> bool {
2629        let Some(block) = self.block_containing(position) else {
2630            return false;
2631        };
2632        let offset = position.saturating_sub(block.position);
2633        block
2634            .lines
2635            .iter()
2636            .filter(|l| l.holds_caret_at(offset))
2637            .any(|l| l.is_direction_boundary(offset))
2638    }
2639
2640    /// Visual geometry of a laid-out table — the table box plus its row and
2641    /// column tracks — in document space.
2642    ///
2643    /// Answers for a table at the top level or inside a frame at any depth.
2644    /// `None` when no table with that id is laid out, which is also what an
2645    /// unlaid-out document returns.
2646    pub fn table_visual_info(&self, table_id: usize) -> Option<TableVisualInfo> {
2647        let resolved = self.flow_layout.resolve_table(table_id)?;
2648        Some(TableVisualInfo {
2649            table_id,
2650            x: resolved.origin_x,
2651            y: resolved.origin_y,
2652            width: resolved.table.total_width,
2653            height: resolved.table.total_height,
2654            column_xs: resolved.table.column_xs.clone(),
2655            column_content_widths: resolved.table.column_content_widths.clone(),
2656            row_ys: resolved.table.row_ys.clone(),
2657            row_heights: resolved.table.row_heights.clone(),
2658        })
2659    }
2660
2661    /// A block's visual geometry and its per-line geometry in one lookup.
2662    ///
2663    /// [`block_visual_info`](Self::block_visual_info) and
2664    /// [`block_line_geometry`](Self::block_line_geometry) each have to find
2665    /// the block first, and for a block nested in a table cell or a frame that
2666    /// search is a walk rather than a hash lookup. A caller that wants both —
2667    /// the accessibility walk wants both for every block it emits — should ask
2668    /// once.
2669    ///
2670    /// The line rectangles, `caret_x` and segments are relative to the
2671    /// returned [`BlockVisualInfo::content_x`] horizontally and to the
2672    /// block's top edge vertically. They are not relative to
2673    /// [`BlockVisualInfo::x`]: a list item or an indented paragraph starts its
2674    /// text `content_x - x` to the right of it.
2675    pub fn block_geometry(
2676        &self,
2677        block_id: usize,
2678        text: &str,
2679    ) -> Option<(BlockVisualInfo, Vec<LineGeometry>)> {
2680        let resolved = self.flow_layout.resolve_block(block_id)?;
2681        let info = block_visual_info_of(block_id, &resolved);
2682        let lines = crate::layout::geometry::stacked_lines_geometry(
2683            &resolved.block.lines,
2684            text,
2685            |_, line| line.y - line.ascent,
2686        );
2687        Some((info, lines))
2688    }
2689
2690    /// Whether `block_id` is laid out in the document's own column, rather
2691    /// than nested inside a table cell or a frame.
2692    ///
2693    /// The nested cases have their own left origin and their own coordinate
2694    /// base, so a caller drawing in document space — or one probing which
2695    /// kind of block a hit landed in — needs to ask rather than infer it
2696    /// from a geometry query coming back empty.
2697    pub fn is_top_level_block(&self, block_id: usize) -> bool {
2698        self.flow_layout.blocks.contains_key(&block_id)
2699    }
2700
2701    /// Whether a block lives inside any table cell.
2702    pub fn is_block_in_table(&self, block_id: usize) -> bool {
2703        self.flow_layout.tables.values().any(|table| {
2704            table
2705                .cell_layouts
2706                .iter()
2707                .any(|cell| cell.blocks.iter().any(|b| b.block_id == block_id))
2708        })
2709    }
2710
2711    /// Scroll so that `position` is visible, placing it roughly one
2712    /// third from the top of the viewport. Returns the new offset.
2713    /// Affinity defaults to `Downstream` since scroll targeting picks
2714    /// any acceptable line for the position.
2715    pub fn scroll_to_position(&mut self, position: usize) -> f32 {
2716        let rect = crate::render::hit_test::caret_rect(
2717            &self.flow_layout,
2718            self.scroll_offset,
2719            position,
2720            crate::types::CursorAffinity::Downstream,
2721        );
2722        let target_y = rect[1] + self.scroll_offset - self.viewport_height / (3.0 * self.zoom);
2723        self.scroll_offset = target_y.max(0.0);
2724        self.scroll_offset
2725    }
2726
2727    /// Scroll the minimum amount needed to make the current caret
2728    /// visible. Call after arrow-key / click / typing. Returns
2729    /// `Some(new_offset)` if the scroll moved, `None` otherwise.
2730    ///
2731    /// The caret this reads is the one last handed to [`set_cursor`](Self::set_cursor),
2732    /// which an editor typically refreshes once per frame — so calling this
2733    /// from inside a key handler corrects for wherever the caret was on the
2734    /// *previous* frame, not where the keystroke just put it. Editors that move
2735    /// a cursor and reveal it in the same breath want
2736    /// [`ensure_position_visible`](Self::ensure_position_visible), which takes
2737    /// the position outright.
2738    pub fn ensure_caret_visible(&mut self) -> Option<f32> {
2739        if self.cursors.is_empty() {
2740            return None;
2741        }
2742        let pos = self.cursors[0].position;
2743        let affinity = self.cursors[0].affinity;
2744        self.ensure_position_visible(pos, affinity)
2745    }
2746
2747    /// Scroll the minimum amount needed to make `position` visible. Returns
2748    /// `Some(new_offset)` if the scroll moved, `None` otherwise.
2749    ///
2750    /// The explicit-position form of [`ensure_caret_visible`](Self::ensure_caret_visible),
2751    /// for the common editor shape where a key handler moves its own cursor and
2752    /// then reveals it: the flow's cached cursor is a frame behind at that
2753    /// moment, and correcting against it leaves the caret the keystroke just
2754    /// moved sitting outside the viewport until the *next* keystroke.
2755    pub fn ensure_position_visible(
2756        &mut self,
2757        position: usize,
2758        affinity: crate::types::CursorAffinity,
2759    ) -> Option<f32> {
2760        let rect = crate::render::hit_test::caret_rect(
2761            &self.flow_layout,
2762            self.scroll_offset,
2763            position,
2764            affinity,
2765        );
2766        let caret_screen_y = rect[1];
2767        let caret_screen_bottom = caret_screen_y + rect[3];
2768        let effective_vh = self.viewport_height / self.zoom;
2769        let margin = 10.0 / self.zoom;
2770        let old_offset = self.scroll_offset;
2771
2772        if caret_screen_y < 0.0 {
2773            self.scroll_offset += caret_screen_y - margin;
2774            self.scroll_offset = self.scroll_offset.max(0.0);
2775        } else if caret_screen_bottom > effective_vh {
2776            self.scroll_offset += caret_screen_bottom - effective_vh + margin;
2777        }
2778
2779        if (self.scroll_offset - old_offset).abs() > 0.001 {
2780            Some(self.scroll_offset)
2781        } else {
2782            None
2783        }
2784    }
2785}
2786
2787impl Default for DocumentFlow {
2788    fn default() -> Self {
2789        Self::new()
2790    }
2791}
2792
2793#[cfg(feature = "text-document")]
2794enum FlowItemKind {
2795    Block(BlockLayoutParams),
2796    Table(TableLayoutParams),
2797    Frame(FrameLayoutParams),
2798}
2799
2800/// Rasterize a single glyph into the service's atlas and append a
2801/// `GlyphQuad` to the output vec. Shared between
2802/// [`DocumentFlow::layout_single_line`] and
2803/// [`DocumentFlow::layout_paragraph`] (plus the markup variants).
2804///
2805/// `raster_scale` densifies the bitmap without touching layout: the
2806/// glyph is rasterized at `size × scale_factor × raster_scale`
2807/// physical pixels while the emitted `screen` rect stays in logical
2808/// pixels (divided by the *total* scale), so content drawn under a
2809/// scale transform (scene zoom) samples a matching-resolution bitmap
2810/// instead of stretching a 1× raster. Scaled rasters are unhinted —
2811/// glyph positions come from shaping at the logical ppem.
2812#[allow(clippy::too_many_arguments)]
2813fn rasterize_glyph_quad(
2814    service: &mut TextFontService,
2815    glyph: &ShapedGlyph,
2816    run: &ShapedRun,
2817    pen_x: f32,
2818    baseline: f32,
2819    text_color: [f32; 4],
2820    raster_scale: f32,
2821    quads: &mut Vec<GlyphQuad>,
2822    glyph_keys: &mut Vec<crate::atlas::cache::GlyphCacheKey>,
2823) {
2824    use crate::atlas::cache::GlyphCacheKey;
2825    use crate::atlas::rasterizer::rasterize_glyph_styled;
2826
2827    if glyph.glyph_id == 0 {
2828        return;
2829    }
2830
2831    let entry = match service.font_registry.get(glyph.font_face_id) {
2832        Some(e) => e,
2833        None => return,
2834    };
2835
2836    let raster_scale = if raster_scale > 0.0 {
2837        raster_scale
2838    } else {
2839        1.0
2840    };
2841    let hinted = raster_scale == 1.0;
2842    let sf = service.scale_factor.max(f32::MIN_POSITIVE);
2843    let inv_total = 1.0 / (sf * raster_scale);
2844    let physical_size_px = run.size_px * sf * raster_scale;
2845    let cache_key = GlyphCacheKey::with_style(
2846        glyph.font_face_id,
2847        glyph.glyph_id,
2848        physical_size_px,
2849        run.weight as u32,
2850        hinted,
2851        run.italic,
2852    );
2853
2854    if service.glyph_cache.peek(&cache_key).is_none()
2855        && let Some(image) = rasterize_glyph_styled(
2856            &mut service.scale_context,
2857            entry.bytes(),
2858            entry.face_index,
2859            entry.swash_cache_key,
2860            glyph.glyph_id,
2861            physical_size_px,
2862            run.weight as u32,
2863            hinted,
2864            run.italic,
2865        )
2866        && image.width > 0
2867        && image.height > 0
2868    {
2869        let (alloc, evicted) = crate::atlas::allocate_or_evict(
2870            &mut service.atlas,
2871            &mut service.glyph_cache,
2872            image.width,
2873            image.height,
2874        );
2875        if evicted {
2876            service.eviction_epoch = service.eviction_epoch.wrapping_add(1);
2877        }
2878        if let Some(alloc) = alloc {
2879            let rect = alloc.rectangle;
2880            let atlas_x = rect.min.x as u32;
2881            let atlas_y = rect.min.y as u32;
2882            if image.is_color {
2883                service
2884                    .atlas
2885                    .blit_rgba(atlas_x, atlas_y, image.width, image.height, &image.data);
2886            } else {
2887                service
2888                    .atlas
2889                    .blit_mask(atlas_x, atlas_y, image.width, image.height, &image.data);
2890            }
2891            service.glyph_cache.insert(
2892                cache_key,
2893                crate::atlas::cache::CachedGlyph {
2894                    alloc_id: alloc.id,
2895                    atlas_x,
2896                    atlas_y,
2897                    width: image.width,
2898                    height: image.height,
2899                    placement_left: image.placement_left,
2900                    placement_top: image.placement_top,
2901                    is_color: image.is_color,
2902                    last_used: 0,
2903                },
2904            );
2905        }
2906    }
2907
2908    if let Some(cached) = service.glyph_cache.get(&cache_key) {
2909        let logical_w = cached.width as f32 * inv_total;
2910        let logical_h = cached.height as f32 * inv_total;
2911        let logical_left = cached.placement_left as f32 * inv_total;
2912        let logical_top = cached.placement_top as f32 * inv_total;
2913        let screen_x = pen_x + glyph.x_offset + logical_left;
2914        let screen_y = baseline - glyph.y_offset - logical_top;
2915        let color = if cached.is_color {
2916            [1.0, 1.0, 1.0, 1.0]
2917        } else {
2918            text_color
2919        };
2920        quads.push(GlyphQuad {
2921            screen: [screen_x, screen_y, logical_w, logical_h],
2922            atlas: [
2923                cached.atlas_x as f32,
2924                cached.atlas_y as f32,
2925                cached.width as f32,
2926                cached.height as f32,
2927            ],
2928            color,
2929            is_color: cached.is_color,
2930        });
2931        glyph_keys.push(cache_key);
2932    }
2933}
2934
2935/// Quantize an accumulated densification scale onto a geometric ladder of
2936/// 1.25ⁿ steps, `n ∈ [0, 6]` (so the value lands in `[1.0, ~3.81]`), for
2937/// glyph raster densification under zoom / external scale transforms.
2938///
2939/// The ladder bounds the number of distinct atlas entries a continuous
2940/// zoom gesture can create (7 buckets). The bucket value is derived from
2941/// an integer index, so the same input always yields the bit-identical
2942/// f32 — cache keys stay stable across frames — and the function is
2943/// idempotent (a bucket value maps to itself). Between buckets the
2944/// residual GPU scaling is at most ~12%, invisible under the glyph
2945/// atlas's linear filtering. Scales below 1 clamp to 1: zoomed-out text
2946/// relies on linear minification rather than rasterizing below logical
2947/// size.
2948///
2949/// Kept in lockstep with `teksilo_canvas::quantize_raster_scale` (scene
2950/// transform densification uses the same ladder).
2951pub fn quantize_raster_scale(scale: f32) -> f32 {
2952    if !scale.is_finite() || scale <= 1.0 {
2953        return 1.0;
2954    }
2955    const STEP: f32 = 1.25;
2956    /// 1.25⁶ ≈ 3.81 — the densest raster bucket. Deep zoom beyond it
2957    /// rides linear magnification; an unbounded ladder would explode
2958    /// atlas area quadratically.
2959    const MAX_BUCKET: i32 = 6;
2960    let bucket = ((scale.ln() / STEP.ln()).round() as i32).clamp(0, MAX_BUCKET);
2961    STEP.powi(bucket)
2962}
2963
2964/// Scale all screen-space coordinates in a RenderFrame by `zoom`.
2965fn apply_zoom(frame: &mut RenderFrame, zoom: f32) {
2966    if (zoom - 1.0).abs() <= f32::EPSILON {
2967        return;
2968    }
2969    for q in &mut frame.glyphs {
2970        q.screen[0] *= zoom;
2971        q.screen[1] *= zoom;
2972        q.screen[2] *= zoom;
2973        q.screen[3] *= zoom;
2974    }
2975    for q in &mut frame.images {
2976        q.screen[0] *= zoom;
2977        q.screen[1] *= zoom;
2978        q.screen[2] *= zoom;
2979        q.screen[3] *= zoom;
2980    }
2981    apply_zoom_decorations(&mut frame.decorations, zoom);
2982}
2983
2984/// Scale all screen-space coordinates in decoration rects by `zoom`.
2985fn apply_zoom_decorations(decorations: &mut [DecorationRect], zoom: f32) {
2986    if (zoom - 1.0).abs() <= f32::EPSILON {
2987        return;
2988    }
2989    for d in decorations.iter_mut() {
2990        d.rect[0] *= zoom;
2991        d.rect[1] *= zoom;
2992        d.rect[2] *= zoom;
2993        d.rect[3] *= zoom;
2994    }
2995}
2996
2997/// Derive a per-span [`TextFormat`] from a base format and inline
2998/// markup attributes (bold / italic).
2999fn merge_format(base: &TextFormat, attrs: InlineAttrs) -> TextFormat {
3000    let mut fmt = base.clone();
3001    if attrs.is_bold() {
3002        fmt.font_bold = Some(true);
3003        if let Some(w) = fmt.font_weight
3004            && w < 600
3005        {
3006            fmt.font_weight = Some(700);
3007        } else if fmt.font_weight.is_none() {
3008            fmt.font_weight = Some(700);
3009        }
3010    }
3011    if attrs.is_italic() {
3012        fmt.font_italic = Some(true);
3013    }
3014    fmt
3015}
3016
3017#[cfg(test)]
3018mod tests {
3019    use super::*;
3020    use crate::layout::block::{BlockLayoutParams, FragmentParams};
3021    use crate::layout::paragraph::Alignment;
3022    use crate::types::{UnderlineStyle, VerticalAlignment};
3023
3024    const NOTO_SANS: &[u8] = include_bytes!("../test-fonts/NotoSans-Variable.ttf");
3025
3026    fn service() -> TextFontService {
3027        // Hermetic: don't pull in the host machine's fonts.
3028        let mut s = TextFontService::new_without_system_fonts();
3029        let face = s.register_font(NOTO_SANS);
3030        s.set_default_font(face, 16.0);
3031        s
3032    }
3033
3034    fn block(id: usize, text: &str) -> BlockLayoutParams {
3035        BlockLayoutParams {
3036            base_direction: Default::default(),
3037            block_id: id,
3038            position: 0,
3039            text: text.to_string(),
3040            fragments: vec![FragmentParams {
3041                text: text.to_string(),
3042                offset: 0,
3043                length: text.len(),
3044                font_family: None,
3045                font_weight: None,
3046                font_bold: None,
3047                font_italic: None,
3048                font_point_size: None,
3049                size_scale: 1.0,
3050                underline_style: UnderlineStyle::None,
3051                overline: false,
3052                strikeout: false,
3053                is_link: false,
3054                letter_spacing: 0.0,
3055                word_spacing: 0.0,
3056                foreground_color: None,
3057                underline_color: None,
3058                background_color: None,
3059                anchor_href: None,
3060                tooltip: None,
3061                vertical_alignment: VerticalAlignment::Normal,
3062                image_name: None,
3063                image_width: 0.0,
3064                image_height: 0.0,
3065                footnote_marker: None,
3066                features: Vec::new(),
3067            }],
3068            alignment: Alignment::Left,
3069            top_margin: 0.0,
3070            bottom_margin: 0.0,
3071            left_margin: 0.0,
3072            right_margin: 0.0,
3073            text_indent: 0.0,
3074            list_marker: String::new(),
3075            list_indent: 0.0,
3076            tab_positions: vec![],
3077            line_height_multiplier: None,
3078            non_breakable_lines: false,
3079            hyphenation: None,
3080            checkbox: None,
3081            background_color: None,
3082        }
3083    }
3084
3085    #[test]
3086    fn relayout_block_returns_no_layout_when_never_laid_out() {
3087        let svc = service();
3088        let mut flow = DocumentFlow::new();
3089        flow.set_viewport(400.0, 200.0);
3090        let err = flow.relayout_block(&svc, &block(1, "Hello")).unwrap_err();
3091        assert_eq!(err, RelayoutError::NoLayout);
3092    }
3093
3094    #[test]
3095    fn relayout_block_returns_scale_dirty_after_scale_factor_change() {
3096        let mut svc = service();
3097        let mut flow = DocumentFlow::new();
3098        flow.set_viewport(400.0, 200.0);
3099        flow.layout_blocks(&svc, vec![block(1, "Hello")]);
3100        assert!(flow.has_layout());
3101
3102        // Simulate a HiDPI transition on the shared service.
3103        svc.set_scale_factor(2.0);
3104        assert!(flow.layout_dirty_for_scale(&svc));
3105
3106        let err = flow
3107            .relayout_block(&svc, &block(1, "Hello world"))
3108            .unwrap_err();
3109        assert_eq!(err, RelayoutError::ScaleDirty);
3110    }
3111
3112    #[test]
3113    fn a_change_of_default_language_marks_the_flow_stale() {
3114        let mut svc = service();
3115        let mut flow = DocumentFlow::new();
3116        flow.set_viewport(400.0, 200.0);
3117        flow.layout_blocks(&svc, vec![block(1, "Hello")]);
3118
3119        // A language that names no CJK language sets none: no change.
3120        svc.set_default_language(Some("fr-FR"));
3121        assert!(!flow.layout_dirty_for_scale(&svc));
3122
3123        svc.set_default_language(Some("ja-JP"));
3124        assert!(flow.layout_dirty_for_scale(&svc));
3125        flow.layout_blocks(&svc, vec![block(1, "Hello")]);
3126
3127        // The language it already has changes nothing.
3128        svc.set_default_language(Some("ja"));
3129        assert!(!flow.layout_dirty_for_scale(&svc));
3130    }
3131
3132    #[test]
3133    fn relayout_block_succeeds_after_fresh_layout_post_scale_change() {
3134        let mut svc = service();
3135        let mut flow = DocumentFlow::new();
3136        flow.set_viewport(400.0, 200.0);
3137        flow.layout_blocks(&svc, vec![block(1, "Hello")]);
3138
3139        svc.set_scale_factor(2.0);
3140        // Caller is expected to re-run a full layout at the new
3141        // scale before issuing incremental updates.
3142        flow.layout_blocks(&svc, vec![block(1, "Hello")]);
3143        assert!(!flow.layout_dirty_for_scale(&svc));
3144
3145        // Now the incremental path succeeds.
3146        flow.relayout_block(&svc, &block(1, "Hello world"))
3147            .expect("relayout_block must succeed after a fresh post-scale layout");
3148    }
3149
3150    /// `block_params_for` converts a document block snapshot into layout params
3151    /// — the per-block seam the windowed streaming path is built on. The text
3152    /// must round-trip so the shaped row matches the document.
3153    #[test]
3154    #[cfg(feature = "text-document")]
3155    fn block_params_for_converts_a_document_snapshot() {
3156        let flow = DocumentFlow::new();
3157        let doc = text_document::TextDocument::new();
3158        doc.set_plain_text("alpha\nbeta").unwrap();
3159
3160        // Second block ("beta") starts after "alpha\n" — position 6.
3161        let snap = doc.snapshot_block_at_position(6).expect("block snapshot");
3162        let params = flow.block_params_for(&snap);
3163
3164        assert_eq!(params.text, "beta", "the block text must round-trip");
3165        assert!(
3166            !params.fragments.is_empty(),
3167            "a non-empty block must convert to at least one fragment"
3168        );
3169    }
3170
3171    /// It must use *this flow's* bridge options, not defaults — otherwise the
3172    /// windowed path would shape a block differently from `layout_full`. The
3173    /// echo char is the cheapest observable: with it set, the conversion masks
3174    /// the text.
3175    #[test]
3176    #[cfg(feature = "text-document")]
3177    fn block_params_for_honours_the_flow_echo_char() {
3178        let mut flow = DocumentFlow::new();
3179        flow.set_echo_char(Some('•'));
3180        let doc = text_document::TextDocument::new();
3181        doc.set_plain_text("secret").unwrap();
3182
3183        let snap = doc.snapshot_block_at_position(0).expect("block snapshot");
3184        let params = flow.block_params_for(&snap);
3185
3186        assert!(
3187            params.fragments.iter().all(|f| !f.text.contains("secret")),
3188            "the flow's echo char must mask the plaintext, proving its own \
3189             bridge options are used"
3190        );
3191    }
3192}