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