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