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, ParagraphResult, RenderFrame, SingleLineResult,
61    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        let empty = SingleLineResult {
1216            width: 0.0,
1217            height: 0.0,
1218            baseline: 0.0,
1219            underline_offset: 0.0,
1220            underline_thickness: 0.0,
1221            glyphs: Vec::new(),
1222            glyph_keys: Vec::new(),
1223            spans: Vec::new(),
1224        };
1225
1226        if text.is_empty() {
1227            return empty;
1228        }
1229
1230        let font_point_size = format.font_size.map(|s| s as u32);
1231        let resolved = match resolve_font(
1232            &service.font_registry,
1233            format.font_family.as_deref(),
1234            format.font_weight,
1235            format.font_bold,
1236            format.font_italic,
1237            font_point_size,
1238            service.scale_factor,
1239            1.0, // standalone shaper: caller's explicit size is already theme-scaled
1240        ) {
1241            Some(r) => r,
1242            None => return empty,
1243        };
1244
1245        let metrics = match font_metrics_px(&service.font_registry, &resolved) {
1246            Some(m) => m,
1247            None => return empty,
1248        };
1249        let line_height = metrics.ascent + metrics.descent + metrics.leading;
1250        let baseline = metrics.ascent;
1251
1252        let features = to_harfrust_features(&format.features);
1253        let runs: Vec<_> = bidi_runs(text)
1254            .into_iter()
1255            .filter_map(|br| {
1256                let slice = text.get(br.byte_range.clone())?;
1257                shape_text_with_fallback(
1258                    &service.font_registry,
1259                    &resolved,
1260                    slice,
1261                    br.byte_range.start,
1262                    br.direction,
1263                    &features,
1264                )
1265            })
1266            .collect();
1267
1268        if runs.is_empty() {
1269            return empty;
1270        }
1271
1272        let total_advance: f32 = runs.iter().map(|r| r.advance_width).sum();
1273
1274        let (truncate_at_visual_index, final_width, ellipsis_run) = if let Some(max_w) = max_width
1275            && total_advance > max_w
1276        {
1277            let ellipsis_run = shape_text(&service.font_registry, &resolved, "\u{2026}", 0);
1278            let ellipsis_width = ellipsis_run
1279                .as_ref()
1280                .map(|r| r.advance_width)
1281                .unwrap_or(0.0);
1282            let budget = (max_w - ellipsis_width).max(0.0);
1283
1284            let mut used = 0.0f32;
1285            let mut count = 0usize;
1286            'outer: for run in &runs {
1287                for g in &run.glyphs {
1288                    if used + g.x_advance > budget {
1289                        break 'outer;
1290                    }
1291                    used += g.x_advance;
1292                    count += 1;
1293                }
1294            }
1295
1296            (Some(count), used + ellipsis_width, ellipsis_run)
1297        } else {
1298            (None, total_advance, None)
1299        };
1300
1301        let text_color = format.color.unwrap_or(self.text_color);
1302        let glyph_capacity: usize = runs.iter().map(|r| r.glyphs.len()).sum();
1303        let mut quads = Vec::with_capacity(glyph_capacity + 1);
1304        let mut keys = Vec::with_capacity(glyph_capacity + 1);
1305        let mut pen_x = 0.0f32;
1306        let mut emitted = 0usize;
1307
1308        'emit: for run in &runs {
1309            for glyph in &run.glyphs {
1310                if let Some(limit) = truncate_at_visual_index
1311                    && emitted >= limit
1312                {
1313                    break 'emit;
1314                }
1315                rasterize_glyph_quad(
1316                    service,
1317                    glyph,
1318                    run,
1319                    pen_x,
1320                    baseline,
1321                    text_color,
1322                    raster_scale,
1323                    &mut quads,
1324                    &mut keys,
1325                );
1326                pen_x += glyph.x_advance;
1327                emitted += 1;
1328            }
1329        }
1330
1331        if let Some(ref e_run) = ellipsis_run {
1332            for glyph in &e_run.glyphs {
1333                rasterize_glyph_quad(
1334                    service,
1335                    glyph,
1336                    e_run,
1337                    pen_x,
1338                    baseline,
1339                    text_color,
1340                    raster_scale,
1341                    &mut quads,
1342                    &mut keys,
1343                );
1344                pen_x += glyph.x_advance;
1345            }
1346        }
1347
1348        SingleLineResult {
1349            width: final_width,
1350            height: line_height,
1351            baseline,
1352            underline_offset: metrics.underline_offset,
1353            underline_thickness: metrics.stroke_size,
1354            glyphs: quads,
1355            glyph_keys: keys,
1356            spans: Vec::new(),
1357        }
1358    }
1359
1360    /// Lay out a multi-line paragraph by wrapping text at `max_width`.
1361    ///
1362    /// Multi-line counterpart to
1363    /// [`layout_single_line`](Self::layout_single_line). Shapes the
1364    /// input, breaks it at Unicode line-break opportunities
1365    /// (greedy, left-aligned), and rasterizes each line's glyphs
1366    /// into paragraph-local coordinates starting at `(0, 0)`.
1367    ///
1368    /// If `max_lines` is `Some(n)`, at most `n` lines are emitted
1369    /// and any remainder is silently dropped.
1370    ///
1371    /// See [`layout_single_line`](Self::layout_single_line) for the
1372    /// `raster_scale` contract (pass `1.0` for unscaled UI).
1373    pub fn layout_paragraph(
1374        &mut self,
1375        service: &mut TextFontService,
1376        text: &str,
1377        format: &TextFormat,
1378        max_width: f32,
1379        max_lines: Option<usize>,
1380        raster_scale: f32,
1381    ) -> ParagraphResult {
1382        let empty = ParagraphResult {
1383            width: 0.0,
1384            height: 0.0,
1385            baseline_first: 0.0,
1386            line_count: 0,
1387            line_height: 0.0,
1388            underline_offset: 0.0,
1389            underline_thickness: 0.0,
1390            glyphs: Vec::new(),
1391            glyph_keys: Vec::new(),
1392            spans: Vec::new(),
1393        };
1394
1395        if text.is_empty() || max_width <= 0.0 {
1396            return empty;
1397        }
1398
1399        let font_point_size = format.font_size.map(|s| s as u32);
1400        let resolved = match resolve_font(
1401            &service.font_registry,
1402            format.font_family.as_deref(),
1403            format.font_weight,
1404            format.font_bold,
1405            format.font_italic,
1406            font_point_size,
1407            service.scale_factor,
1408            1.0, // standalone shaper: caller's explicit size is already theme-scaled
1409        ) {
1410            Some(r) => r,
1411            None => return empty,
1412        };
1413
1414        let metrics = match font_metrics_px(&service.font_registry, &resolved) {
1415            Some(m) => m,
1416            None => return empty,
1417        };
1418
1419        let features = to_harfrust_features(&format.features);
1420        let runs: Vec<_> = bidi_runs(text)
1421            .into_iter()
1422            .filter_map(|br| {
1423                let slice = text.get(br.byte_range.clone())?;
1424                shape_text_with_fallback(
1425                    &service.font_registry,
1426                    &resolved,
1427                    slice,
1428                    br.byte_range.start,
1429                    br.direction,
1430                    &features,
1431                )
1432            })
1433            .collect();
1434
1435        if runs.is_empty() {
1436            return empty;
1437        }
1438
1439        let hyphenator = format.hyphenation.and_then(|h| {
1440            shape_text(&service.font_registry, &resolved, "-", 0)
1441                .and_then(|r| r.glyphs.into_iter().next())
1442                .map(|glyph| Hyphenator {
1443                    glyph,
1444                    language: h.language,
1445                })
1446        });
1447        let lines = break_into_lines(
1448            runs,
1449            text,
1450            max_width,
1451            Alignment::Left,
1452            0.0,
1453            &metrics,
1454            hyphenator,
1455            // This path ran the bidi algorithm itself and shaped in
1456            // display order, so the runs must not be reordered again.
1457            RunOrder::AlreadyVisual,
1458        );
1459
1460        let line_count = match max_lines {
1461            Some(n) => lines.len().min(n),
1462            None => lines.len(),
1463        };
1464
1465        let text_color = format.color.unwrap_or(self.text_color);
1466        let mut quads: Vec<GlyphQuad> = Vec::new();
1467        let mut keys: Vec<crate::atlas::cache::GlyphCacheKey> = Vec::new();
1468        let mut y_top = 0.0f32;
1469        let mut max_line_width = 0.0f32;
1470        let baseline_first = metrics.ascent;
1471
1472        for line in lines.iter().take(line_count) {
1473            if line.width > max_line_width {
1474                max_line_width = line.width;
1475            }
1476            let baseline_y = y_top + metrics.ascent;
1477            for run in &line.runs {
1478                let mut pen_x = run.x;
1479                let run_copy = run.shaped_run.clone();
1480                for glyph in &run_copy.glyphs {
1481                    rasterize_glyph_quad(
1482                        service,
1483                        glyph,
1484                        &run_copy,
1485                        pen_x,
1486                        baseline_y,
1487                        text_color,
1488                        raster_scale,
1489                        &mut quads,
1490                        &mut keys,
1491                    );
1492                    pen_x += glyph.x_advance;
1493                }
1494            }
1495            y_top += metrics.ascent + metrics.descent + metrics.leading;
1496        }
1497
1498        let line_height = metrics.ascent + metrics.descent + metrics.leading;
1499        ParagraphResult {
1500            width: max_line_width,
1501            height: y_top,
1502            baseline_first,
1503            line_count,
1504            line_height,
1505            underline_offset: metrics.underline_offset,
1506            underline_thickness: metrics.stroke_size,
1507            glyphs: quads,
1508            glyph_keys: keys,
1509            spans: Vec::new(),
1510        }
1511    }
1512
1513    /// Single-line layout with inline markup. See
1514    /// [`layout_single_line`](Self::layout_single_line) for the plain
1515    /// variant. Accepts parsed `[label](url)`, `*italic*`, and
1516    /// `**bold**` spans and annotates the output with per-span
1517    /// bounding rectangles for hit-testing.
1518    pub fn layout_single_line_markup(
1519        &mut self,
1520        service: &mut TextFontService,
1521        markup: &InlineMarkup,
1522        format: &TextFormat,
1523        max_width: Option<f32>,
1524        raster_scale: f32,
1525    ) -> SingleLineResult {
1526        if markup.spans.is_empty() {
1527            return SingleLineResult {
1528                width: 0.0,
1529                height: 0.0,
1530                baseline: 0.0,
1531                underline_offset: 0.0,
1532                underline_thickness: 0.0,
1533                glyphs: Vec::new(),
1534                glyph_keys: Vec::new(),
1535                spans: Vec::new(),
1536            };
1537        }
1538
1539        let per_span: Vec<(SingleLineResult, &crate::layout::inline_markup::InlineSpan)> = markup
1540            .spans
1541            .iter()
1542            .map(|sp| {
1543                let fmt = merge_format(format, sp.attrs);
1544                let r = if sp.text.is_empty() {
1545                    SingleLineResult {
1546                        width: 0.0,
1547                        height: 0.0,
1548                        baseline: 0.0,
1549                        underline_offset: 0.0,
1550                        underline_thickness: 0.0,
1551                        glyphs: Vec::new(),
1552                        glyph_keys: Vec::new(),
1553                        spans: Vec::new(),
1554                    }
1555                } else {
1556                    self.layout_single_line(service, &sp.text, &fmt, None, raster_scale)
1557                };
1558                (r, sp)
1559            })
1560            .collect();
1561
1562        let total_width: f32 = per_span.iter().map(|(r, _)| r.width).sum();
1563        let line_height = per_span
1564            .iter()
1565            .map(|(r, _)| r.height)
1566            .fold(0.0f32, f32::max);
1567        let baseline = per_span
1568            .iter()
1569            .map(|(r, _)| r.baseline)
1570            .fold(0.0f32, f32::max);
1571        // Carry underline metrics from the first non-empty span. Spans may
1572        // use different fonts but a single line only has one underline, so
1573        // the first span wins.
1574        let (underline_offset, underline_thickness) = per_span
1575            .iter()
1576            .map(|(r, _)| (r.underline_offset, r.underline_thickness))
1577            .find(|(_, t)| *t > 0.0)
1578            .unwrap_or((0.0, 0.0));
1579
1580        let truncate = match max_width {
1581            Some(mw) if total_width > mw => Some(mw),
1582            _ => None,
1583        };
1584
1585        let mut glyphs: Vec<GlyphQuad> = Vec::new();
1586        let mut all_keys: Vec<crate::atlas::cache::GlyphCacheKey> = Vec::new();
1587        let mut spans_out: Vec<LaidOutSpan> = Vec::new();
1588        let mut pen_x: f32 = 0.0;
1589        let effective_width = truncate.unwrap_or(total_width);
1590
1591        for (r, sp) in &per_span {
1592            let remaining = (effective_width - pen_x).max(0.0);
1593            let span_visible_width = r.width.min(remaining);
1594            if span_visible_width <= 0.0 && r.width > 0.0 {
1595                spans_out.push(LaidOutSpan {
1596                    kind: if let Some(url) = sp.link_url.clone() {
1597                        LaidOutSpanKind::Link { url }
1598                    } else {
1599                        LaidOutSpanKind::Text
1600                    },
1601                    line_index: 0,
1602                    rect: [pen_x, 0.0, 0.0, line_height],
1603                    byte_range: sp.byte_range.clone(),
1604                });
1605                continue;
1606            }
1607
1608            for (gi, g) in r.glyphs.iter().enumerate() {
1609                let g_right = pen_x + g.screen[0] + g.screen[2];
1610                if g_right > effective_width + 0.5 {
1611                    break;
1612                }
1613                let mut gq = g.clone();
1614                gq.screen[0] += pen_x;
1615                glyphs.push(gq);
1616                if let Some(k) = r.glyph_keys.get(gi) {
1617                    all_keys.push(*k);
1618                }
1619            }
1620
1621            spans_out.push(LaidOutSpan {
1622                kind: if let Some(url) = sp.link_url.clone() {
1623                    LaidOutSpanKind::Link { url }
1624                } else {
1625                    LaidOutSpanKind::Text
1626                },
1627                line_index: 0,
1628                rect: [pen_x, 0.0, span_visible_width, line_height],
1629                byte_range: sp.byte_range.clone(),
1630            });
1631
1632            pen_x += r.width;
1633            if truncate.is_some() && pen_x >= effective_width {
1634                break;
1635            }
1636        }
1637
1638        SingleLineResult {
1639            width: effective_width,
1640            height: line_height,
1641            baseline,
1642            underline_offset,
1643            underline_thickness,
1644            glyphs,
1645            glyph_keys: all_keys,
1646            spans: spans_out,
1647        }
1648    }
1649
1650    /// Paragraph layout with inline markup. Multi-line counterpart
1651    /// to [`layout_single_line_markup`](Self::layout_single_line_markup).
1652    /// Emits a [`LaidOutSpan`] for every link segment so the caller
1653    /// can hit-test against wrapped links.
1654    pub fn layout_paragraph_markup(
1655        &mut self,
1656        service: &mut TextFontService,
1657        markup: &InlineMarkup,
1658        format: &TextFormat,
1659        max_width: f32,
1660        max_lines: Option<usize>,
1661        raster_scale: f32,
1662    ) -> ParagraphResult {
1663        let empty = ParagraphResult {
1664            width: 0.0,
1665            height: 0.0,
1666            baseline_first: 0.0,
1667            line_count: 0,
1668            line_height: 0.0,
1669            underline_offset: 0.0,
1670            underline_thickness: 0.0,
1671            glyphs: Vec::new(),
1672            glyph_keys: Vec::new(),
1673            spans: Vec::new(),
1674        };
1675
1676        if markup.spans.is_empty() || max_width <= 0.0 {
1677            return empty;
1678        }
1679
1680        let mut flat = String::new();
1681        let mut span_flat_offsets: Vec<usize> = Vec::with_capacity(markup.spans.len());
1682        for sp in &markup.spans {
1683            span_flat_offsets.push(flat.len());
1684            flat.push_str(&sp.text);
1685        }
1686        if flat.is_empty() {
1687            return empty;
1688        }
1689
1690        let base_point_size = format.font_size.map(|s| s as u32);
1691        let base_resolved = match resolve_font(
1692            &service.font_registry,
1693            format.font_family.as_deref(),
1694            format.font_weight,
1695            format.font_bold,
1696            format.font_italic,
1697            base_point_size,
1698            service.scale_factor,
1699            1.0, // standalone shaper: caller's explicit size is already theme-scaled
1700        ) {
1701            Some(r) => r,
1702            None => return empty,
1703        };
1704        let metrics = match font_metrics_px(&service.font_registry, &base_resolved) {
1705            Some(m) => m,
1706            None => return empty,
1707        };
1708
1709        let mut all_runs: Vec<ShapedRun> = Vec::new();
1710        for (span_idx, sp) in markup.spans.iter().enumerate() {
1711            if sp.text.is_empty() {
1712                continue;
1713            }
1714            let fmt = merge_format(format, sp.attrs);
1715            let span_point_size = fmt.font_size.map(|s| s as u32);
1716            let Some(resolved) = resolve_font(
1717                &service.font_registry,
1718                fmt.font_family.as_deref(),
1719                fmt.font_weight,
1720                fmt.font_bold,
1721                fmt.font_italic,
1722                span_point_size,
1723                service.scale_factor,
1724                1.0, // standalone shaper: caller's explicit size is already theme-scaled
1725            ) else {
1726                continue;
1727            };
1728
1729            let flat_start = span_flat_offsets[span_idx];
1730            let features = to_harfrust_features(&fmt.features);
1731            for br in bidi_runs(&sp.text) {
1732                let slice = match sp.text.get(br.byte_range.clone()) {
1733                    Some(s) => s,
1734                    None => continue,
1735                };
1736                let Some(mut run) = shape_text_with_fallback(
1737                    &service.font_registry,
1738                    &resolved,
1739                    slice,
1740                    flat_start + br.byte_range.start,
1741                    br.direction,
1742                    &features,
1743                ) else {
1744                    continue;
1745                };
1746                if let Some(url) = sp.link_url.as_ref() {
1747                    run.is_link = true;
1748                    run.anchor_href = Some(url.clone());
1749                }
1750                all_runs.push(run);
1751            }
1752        }
1753
1754        if all_runs.is_empty() {
1755            return empty;
1756        }
1757
1758        let hyphenator = format.hyphenation.and_then(|h| {
1759            shape_text(&service.font_registry, &base_resolved, "-", 0)
1760                .and_then(|r| r.glyphs.into_iter().next())
1761                .map(|glyph| Hyphenator {
1762                    glyph,
1763                    language: h.language,
1764                })
1765        });
1766        let lines = break_into_lines(
1767            all_runs,
1768            &flat,
1769            max_width,
1770            Alignment::Left,
1771            0.0,
1772            &metrics,
1773            hyphenator,
1774            // This path ran the bidi algorithm itself and shaped in
1775            // display order, so the runs must not be reordered again.
1776            RunOrder::AlreadyVisual,
1777        );
1778
1779        let line_count = match max_lines {
1780            Some(n) => lines.len().min(n),
1781            None => lines.len(),
1782        };
1783
1784        let text_color = format.color.unwrap_or(self.text_color);
1785        let mut glyphs_out: Vec<GlyphQuad> = Vec::new();
1786        let mut keys_out: Vec<crate::atlas::cache::GlyphCacheKey> = Vec::new();
1787        let mut spans_out: Vec<LaidOutSpan> = Vec::new();
1788        let line_height = metrics.ascent + metrics.descent + metrics.leading;
1789        let mut y_top: f32 = 0.0;
1790        let mut max_line_width: f32 = 0.0;
1791        let baseline_first = metrics.ascent;
1792
1793        for (line_idx, line) in lines.iter().take(line_count).enumerate() {
1794            if line.width > max_line_width {
1795                max_line_width = line.width;
1796            }
1797            let baseline_y = y_top + metrics.ascent;
1798
1799            for pr in &line.runs {
1800                let run_copy = pr.shaped_run.clone();
1801                let mut pen_x = pr.x;
1802                for glyph in &run_copy.glyphs {
1803                    rasterize_glyph_quad(
1804                        service,
1805                        glyph,
1806                        &run_copy,
1807                        pen_x,
1808                        baseline_y,
1809                        text_color,
1810                        raster_scale,
1811                        &mut glyphs_out,
1812                        &mut keys_out,
1813                    );
1814                    pen_x += glyph.x_advance;
1815                }
1816
1817                if pr.decorations.is_link
1818                    && let Some(url) = pr.decorations.anchor_href.clone()
1819                {
1820                    let width = pr.shaped_run.advance_width;
1821                    spans_out.push(LaidOutSpan {
1822                        kind: LaidOutSpanKind::Link { url },
1823                        line_index: line_idx,
1824                        rect: [pr.x, y_top, width, line_height],
1825                        byte_range: pr.shaped_run.text_range.clone(),
1826                    });
1827                }
1828            }
1829
1830            y_top += line_height;
1831        }
1832
1833        ParagraphResult {
1834            width: max_line_width,
1835            height: y_top,
1836            baseline_first,
1837            line_count,
1838            line_height,
1839            underline_offset: metrics.underline_offset,
1840            underline_thickness: metrics.stroke_size,
1841            glyphs: glyphs_out,
1842            glyph_keys: keys_out,
1843            spans: spans_out,
1844        }
1845    }
1846
1847    // ── Hit testing & character geometry ───────────────────────
1848
1849    /// Map a screen-space point to a document position. Coordinates
1850    /// are relative to the widget's top-left corner; the scroll
1851    /// offset is applied internally. Returns `None` when the flow
1852    /// has no content.
1853    pub fn hit_test(&self, x: f32, y: f32) -> Option<HitTestResult> {
1854        crate::render::hit_test::hit_test(
1855            &self.flow_layout,
1856            self.scroll_offset,
1857            x / self.zoom,
1858            y / self.zoom,
1859        )
1860    }
1861
1862    /// Per-character advance geometry within a laid-out block.
1863    ///
1864    /// Used by accessibility layers that need to expose character
1865    /// positions to screen readers (AccessKit's `character_positions`
1866    /// / `character_widths` on `Role::TextRun`). `char_start` and
1867    /// `char_end` are block-relative character offsets. Returns one
1868    /// entry per character in the range, with `position` measured
1869    /// in run-local coordinates (the first character sits at `0`).
1870    pub fn character_geometry(
1871        &self,
1872        block_id: usize,
1873        char_start: usize,
1874        char_end: usize,
1875    ) -> Vec<CharacterGeometry> {
1876        // x for `offset` against a sorted, offset-deduped stop list: exact match,
1877        // else the nearer of the two bracketing stops (lower offset wins a tie) —
1878        // the same rule `LayoutLine::x_for_offset` applies, but O(log n) against a
1879        // shared build instead of an O(n) rebuild-and-scan per character.
1880        fn x_in_sorted_stops(stops: &[(usize, f32)], offset: usize) -> f32 {
1881            if stops.is_empty() {
1882                return 0.0;
1883            }
1884            match stops.binary_search_by_key(&offset, |(o, _)| *o) {
1885                Ok(i) => stops[i].1,
1886                Err(i) => {
1887                    let left = i.checked_sub(1).map(|j| stops[j]);
1888                    let right = stops.get(i).copied();
1889                    match (left, right) {
1890                        (Some((lo, lx)), Some((ro, rx))) => {
1891                            if offset.abs_diff(lo) <= ro.abs_diff(offset) {
1892                                lx
1893                            } else {
1894                                rx
1895                            }
1896                        }
1897                        (Some((_, lx)), None) => lx,
1898                        (None, Some((_, rx))) => rx,
1899                        (None, None) => 0.0,
1900                    }
1901                }
1902            }
1903        }
1904
1905        if char_start >= char_end {
1906            return Vec::new();
1907        }
1908        let block = match self.flow_layout.blocks.get(&block_id) {
1909            Some(b) => b,
1910            None => return Vec::new(),
1911        };
1912
1913        let mut absolute: Vec<(usize, f32)> = Vec::with_capacity(char_end - char_start);
1914        for line in &block.lines {
1915            if line.char_range.end <= char_start || line.char_range.start >= char_end {
1916                continue;
1917            }
1918            let local_start = char_start.max(line.char_range.start);
1919            let local_end = char_end.min(line.char_range.end);
1920            // Build the line's caret stops ONCE and index into them, rather than
1921            // calling `x_for_offset` per character — which rebuilt the stop list
1922            // (O(runs+glyphs), one allocation) every call. The paint pass splits
1923            // a spell-checked line into a run per range, so `x_for_offset`-per-char
1924            // is O(chars × runs) per line and turns quadratic on a dense document
1925            // (this dominated the accessibility rebuild on a Lorem scene with tens
1926            // of thousands of ranges). Stable-sort by offset then dedup keeps
1927            // the first (leftmost) x per offset.
1928            //
1929            // At a direction boundary an offset has two stops at different x,
1930            // and this deliberately keeps the leftmost rather than following
1931            // affinity the way `x_for_offset` now does: these are character
1932            // *extents* for a screen reader, which has no caret and so no
1933            // affinity to consult. A stable choice matters more than which
1934            // side it lands on.
1935            let mut stops: Vec<(usize, f32)> =
1936                line.caret_stops().iter().map(|s| (s.offset, s.x)).collect();
1937            stops.sort_by_key(|(o, _)| *o);
1938            stops.dedup_by_key(|(o, _)| *o);
1939            for c in local_start..local_end {
1940                absolute.push((c, x_in_sorted_stops(&stops, c)));
1941            }
1942            if local_end == char_end {
1943                absolute.push((local_end, x_in_sorted_stops(&stops, local_end)));
1944            }
1945        }
1946
1947        if absolute.is_empty() {
1948            return Vec::new();
1949        }
1950
1951        absolute.sort_by_key(|(c, _)| *c);
1952
1953        let base_x = absolute.first().map(|(_, x)| *x).unwrap_or(0.0);
1954        let mut out: Vec<CharacterGeometry> = Vec::with_capacity(absolute.len());
1955        for window in absolute.windows(2) {
1956            let (c, x) = window[0];
1957            let (_, x_next) = window[1];
1958            if c >= char_end {
1959                break;
1960            }
1961            out.push(CharacterGeometry {
1962                position: x - base_x,
1963                width: (x_next - x).max(0.0),
1964            });
1965        }
1966        out
1967    }
1968
1969    /// Screen-space caret rectangle at a document position with the
1970    /// given affinity, as `[x, y, width, height]`. Feed this to the
1971    /// platform IME for composition window placement. For drawing the
1972    /// caret itself, use the `DecorationKind::Cursor` entry in
1973    /// [`RenderFrame::decorations`] instead.
1974    ///
1975    /// Affinity only changes the result at soft-wrap boundaries; at
1976    /// every other position the two affinities return the same rect.
1977    /// `CursorAffinity::Downstream` matches the pre-affinity behavior.
1978    pub fn caret_rect(&self, position: usize, affinity: crate::types::CursorAffinity) -> [f32; 4] {
1979        let mut rect = crate::render::hit_test::caret_rect(
1980            &self.flow_layout,
1981            self.scroll_offset,
1982            position,
1983            affinity,
1984        );
1985        rect[0] *= self.zoom;
1986        rect[1] *= self.zoom;
1987        rect[2] *= self.zoom;
1988        rect[3] *= self.zoom;
1989        rect
1990    }
1991
1992    // ── Cursor & colors ────────────────────────────────────────
1993
1994    /// Replace the cursor display with a single cursor.
1995    pub fn set_cursor(&mut self, cursor: &CursorDisplay) {
1996        self.cursors = vec![CursorDisplay {
1997            position: cursor.position,
1998            anchor: cursor.anchor,
1999            affinity: cursor.affinity,
2000            visible: cursor.visible,
2001            selected_cells: cursor.selected_cells.clone(),
2002        }];
2003    }
2004
2005    /// Replace the cursor display with multiple cursors (multi-caret
2006    /// editing). Each cursor independently generates a caret and
2007    /// optional selection highlight.
2008    pub fn set_cursors(&mut self, cursors: &[CursorDisplay]) {
2009        self.cursors = cursors
2010            .iter()
2011            .map(|c| CursorDisplay {
2012                position: c.position,
2013                anchor: c.anchor,
2014                affinity: c.affinity,
2015                visible: c.visible,
2016                selected_cells: c.selected_cells.clone(),
2017            })
2018            .collect();
2019    }
2020
2021    /// Set the selection highlight color `[r, g, b, a]` in 0..=1
2022    /// space. Default: `[0.26, 0.52, 0.96, 0.3]` (translucent blue).
2023    pub fn set_selection_color(&mut self, color: [f32; 4]) {
2024        self.selection_color = color;
2025    }
2026
2027    /// Set the caret color `[r, g, b, a]`. Default: black.
2028    pub fn set_cursor_color(&mut self, color: [f32; 4]) {
2029        self.cursor_color = color;
2030    }
2031
2032    /// Set the default text color `[r, g, b, a]`, used when a
2033    /// fragment has no explicit `foreground_color`. Default: black.
2034    pub fn set_text_color(&mut self, color: [f32; 4]) {
2035        self.text_color = color;
2036    }
2037
2038    /// Current default text color.
2039    pub fn text_color(&self) -> [f32; 4] {
2040        self.text_color
2041    }
2042
2043    /// Set the background painted behind fenced code blocks when the
2044    /// block carries no explicit `background_color`. Hosts wire this
2045    /// from the active theme so dark / light swaps reach the cards.
2046    /// Default `[0.95, 0.95, 0.95, 1.0]` (light grey). Affects future
2047    /// `layout_full` / `relayout_block` calls; existing layouts keep
2048    /// their already-converted background until they next re-shape.
2049    pub fn set_code_block_background(&mut self, color: [f32; 4]) {
2050        self.code_block_background = color;
2051    }
2052
2053    /// Current code-block background default.
2054    pub fn code_block_background(&self) -> [f32; 4] {
2055        self.code_block_background
2056    }
2057
2058    /// Auto-hyphenate justified blocks (that don't set `hyphenate`
2059    /// explicitly) on future `layout_full` / `relayout_block` calls.
2060    /// Enable on prose/rich-text surfaces; leave off for single-line or
2061    /// label widgets. Default `false`.
2062    pub fn set_hyphenate_justified(&mut self, enabled: bool) {
2063        self.hyphenate_justified = enabled;
2064    }
2065
2066    /// Whether justified blocks are auto-hyphenated.
2067    pub fn hyphenate_justified(&self) -> bool {
2068        self.hyphenate_justified
2069    }
2070
2071    /// Set the foreground used for monospaced runs (inline `code`,
2072    /// fenced code blocks) that carry no explicit `foreground_color`.
2073    /// `None` (default) keeps the engine's `text_color`. Hosts wire
2074    /// this from the active theme alongside `set_code_block_background`.
2075    pub fn set_code_block_foreground(&mut self, color: Option<[f32; 4]>) {
2076        self.code_block_foreground = color;
2077    }
2078
2079    /// Current code-block foreground override.
2080    pub fn code_block_foreground(&self) -> Option<[f32; 4]> {
2081        self.code_block_foreground
2082    }
2083
2084    /// Set the foreground used for hyperlink runs that carry no explicit
2085    /// `foreground_color`. `None` (default) keeps the engine's
2086    /// `text_color` — i.e. links that look like prose. Hosts wire this
2087    /// from the active theme, alongside `set_code_block_foreground`.
2088    ///
2089    /// Changing it needs a full relayout: the colour is baked into the
2090    /// shaped runs at layout time, not resolved at paint.
2091    pub fn set_link_foreground(&mut self, color: Option<[f32; 4]>) {
2092        self.link_foreground = color;
2093    }
2094
2095    /// Current link foreground override.
2096    pub fn link_foreground(&self) -> Option<[f32; 4]> {
2097        self.link_foreground
2098    }
2099
2100    /// Set the echo / masking character for secure (password) fields.
2101    ///
2102    /// When `Some(c)`, every character laid out by future `layout_full`
2103    /// calls is replaced with `c` before shaping, so the real text never
2104    /// reaches the shaper or the glyph atlas. `None` (default) lays text
2105    /// out verbatim. One echo char is emitted per source `char`,
2106    /// preserving char counts so caret / selection / hit-test (all
2107    /// char-indexed) stay aligned with the host document's positions.
2108    ///
2109    /// Affects future `layout_full` calls; existing layouts keep their
2110    /// already-converted glyphs until they next re-shape. The incremental
2111    /// `relayout_block` path takes pre-converted [`BlockLayoutParams`], so
2112    /// hosts driving that path must thread the same echo char through
2113    /// their own [`crate::bridge::BridgeOptions`].
2114    pub fn set_echo_char(&mut self, echo: Option<char>) {
2115        self.echo_char = echo;
2116    }
2117
2118    /// Current echo / masking character, if any.
2119    pub fn echo_char(&self) -> Option<char> {
2120        self.echo_char
2121    }
2122
2123    // ── Scrolling helpers ──────────────────────────────────────
2124
2125    /// Visual position and height of a laid-out block. Returns
2126    /// `None` if `block_id` is not in the current layout.
2127    /// The document-character offset the layout believes `block_id` starts at.
2128    ///
2129    /// The layout keeps its own copy of each block's position and shifts it on
2130    /// every incremental relayout; this is that copy, which is what `hit_test`
2131    /// and `caret_rect` resolve against. Exposed so a caller — or a test — can
2132    /// check it against the document's own idea, since the two silently drifting
2133    /// apart is invisible until a click lands on the wrong character.
2134    pub fn block_position(&self, block_id: usize) -> Option<usize> {
2135        crate::layout::flow::find_block_ref(&self.flow_layout, block_id).map(|b| b.position)
2136    }
2137
2138    pub fn block_visual_info(&self, block_id: usize) -> Option<BlockVisualInfo> {
2139        let block = self.flow_layout.blocks.get(&block_id)?;
2140        Some(BlockVisualInfo {
2141            block_id,
2142            y: block.y,
2143            height: block.height,
2144        })
2145    }
2146
2147    /// The reading direction of the text *at* `position`.
2148    ///
2149    /// This is the direction of the bidi run the caret sits in, not the
2150    /// paragraph's — inside an English quotation in an Arabic paragraph
2151    /// it reports left-to-right. That is what an arrow key needs: which
2152    /// way the caret travels visually when it steps one character
2153    /// forward logically.
2154    ///
2155    /// Falls back to the paragraph direction at a position no run
2156    /// covers (an empty block, or the very end of the text), and to
2157    /// `LeftToRight` when there is no layout at all.
2158    pub fn direction_at(&self, position: usize) -> TextDirection {
2159        let Some(block) = self.block_containing(position) else {
2160            return TextDirection::LeftToRight;
2161        };
2162        let offset = position.saturating_sub(block.position);
2163
2164        for line in &block.lines {
2165            if offset < line.char_range.start || offset > line.char_range.end {
2166                continue;
2167            }
2168            // Compare against each run's own cluster span rather than
2169            // asking `cluster_end` per glyph: that scans every glyph on
2170            // the line, which made this quadratic in line length on a
2171            // path every arrow keypress runs.
2172            for run in &line.runs {
2173                let mut lo = usize::MAX;
2174                let mut hi = 0usize;
2175                for g in &run.shaped_run.glyphs {
2176                    let c = g.cluster as usize;
2177                    lo = lo.min(c);
2178                    hi = hi.max(c);
2179                }
2180                if lo == usize::MAX {
2181                    continue;
2182                }
2183                // `hi` is the last cluster's *start*; the run reaches at
2184                // least one character past it.
2185                if offset >= lo && offset <= hi.max(lo) {
2186                    return run.shaped_run.direction;
2187                }
2188            }
2189        }
2190        block.base_direction
2191    }
2192
2193    /// The base direction of the paragraph containing `position`.
2194    ///
2195    /// Home and End want this one rather than [`Self::direction_at`]: they move
2196    /// to the logical ends of the line, and which visual edge those land
2197    /// on is a property of the paragraph, not of whatever run the caret
2198    /// happens to be sitting in.
2199    pub fn paragraph_direction_at(&self, position: usize) -> TextDirection {
2200        self.block_containing(position)
2201            .map(|b| b.base_direction)
2202            .unwrap_or(TextDirection::LeftToRight)
2203    }
2204
2205    /// The document positions of the start and end of the *visual* line
2206    /// containing `position` — i.e. what Home and End should move to.
2207    ///
2208    /// These are logical ends: the start is the lowest character offset
2209    /// on the line whichever screen edge that sits on. Asking the
2210    /// question this way rather than hit-testing a far-off-screen x
2211    /// keeps Home and End correct in right-to-left paragraphs, where the
2212    /// logical start is drawn on the right, and avoids depending on how
2213    /// a hit-test clamps coordinates outside the text.
2214    ///
2215    /// `affinity` picks the line at a soft-wrap boundary, where one
2216    /// position belongs to both the end of one line and the start of the
2217    /// next. Returns `None` if there is no layout for `position`.
2218    pub fn visual_line_range_at(
2219        &self,
2220        position: usize,
2221        affinity: crate::types::CursorAffinity,
2222    ) -> Option<(usize, usize)> {
2223        let block = self.block_containing(position)?;
2224        let offset = position.saturating_sub(block.position);
2225
2226        let mut candidates = block
2227            .lines
2228            .iter()
2229            .filter(|l| offset >= l.char_range.start && offset <= l.char_range.end);
2230        let first = candidates.next()?;
2231
2232        // Two lines can claim a boundary offset. Per `CursorAffinity`:
2233        // Downstream renders at the END of the previous wrap line,
2234        // Upstream at the START of the next one.
2235        let line = match candidates.next() {
2236            Some(second) if affinity == crate::types::CursorAffinity::Upstream => second,
2237            Some(_) => first,
2238            None => first,
2239        };
2240
2241        Some((
2242            block.position + line.char_range.start,
2243            block.position + line.char_range.end,
2244        ))
2245    }
2246
2247    /// The laid-out block whose character range covers `position`.
2248    ///
2249    /// Searches top-level blocks, table cells and frames, so a caret
2250    /// inside a table or a blockquote resolves like any other.
2251    fn block_containing(&self, position: usize) -> Option<&crate::layout::block::BlockLayout> {
2252        // `end` is inclusive so a caret at the very end of a block still
2253        // resolves, but that makes a block boundary match *two* blocks.
2254        // `blocks` is a HashMap, so picking whichever `find` reached
2255        // first made the answer depend on hash order — Home/End and the
2256        // arrow keys behaved differently from run to run at every
2257        // paragraph start. Prefer a block that strictly contains the
2258        // position, and fall back to a boundary match only if none does.
2259        let strictly_inside = |b: &crate::layout::block::BlockLayout| {
2260            let end = block_end(b);
2261            position >= b.position && position < end
2262        };
2263        let covers = |b: &crate::layout::block::BlockLayout| {
2264            position >= b.position && position <= block_end(b)
2265        };
2266
2267        fn block_end(b: &crate::layout::block::BlockLayout) -> usize {
2268            b.lines
2269                .last()
2270                .map(|l| b.position + l.char_range.end)
2271                .unwrap_or(b.position)
2272        }
2273
2274        // Deterministic tie-break among boundary matches: the latest
2275        // block that starts at or before the position.
2276        fn best<'b>(
2277            acc: Option<&'b crate::layout::block::BlockLayout>,
2278            b: &'b crate::layout::block::BlockLayout,
2279        ) -> Option<&'b crate::layout::block::BlockLayout> {
2280            match acc {
2281                Some(prev) if prev.position >= b.position => Some(prev),
2282                _ => Some(b),
2283            }
2284        }
2285
2286        if let Some(b) = self
2287            .flow_layout
2288            .blocks
2289            .values()
2290            .filter(|b| strictly_inside(b))
2291            .fold(None, best)
2292        {
2293            return Some(b);
2294        }
2295        if let Some(b) = self
2296            .flow_layout
2297            .blocks
2298            .values()
2299            .filter(|b| covers(b))
2300            .fold(None, best)
2301        {
2302            return Some(b);
2303        }
2304        for table in self.flow_layout.tables.values() {
2305            for cell in &table.cell_layouts {
2306                if let Some(b) = cell.blocks.iter().find(|b| covers(b)) {
2307                    return Some(b);
2308                }
2309            }
2310        }
2311        for frame in self.flow_layout.frames.values() {
2312            if let Some(b) = frame.blocks.iter().find(|b| covers(b)) {
2313                return Some(b);
2314            }
2315        }
2316        None
2317    }
2318
2319    /// Whether `position` sits on a direction boundary — a place where
2320    /// an LTR run meets an RTL one and the caret has two possible x on
2321    /// the same line.
2322    ///
2323    /// The widget layer uses this to decide whether moving the caret
2324    /// here has to choose a side: at an ordinary position affinity makes
2325    /// no difference and can be left alone, but at a seam the caret
2326    /// jumps across the line if it carries the wrong one.
2327    pub fn is_direction_boundary_at(&self, position: usize) -> bool {
2328        let Some(block) = self.block_containing(position) else {
2329            return false;
2330        };
2331        let offset = position.saturating_sub(block.position);
2332        block
2333            .lines
2334            .iter()
2335            .filter(|l| offset >= l.char_range.start && offset <= l.char_range.end)
2336            .any(|l| l.is_direction_boundary(offset))
2337    }
2338
2339    /// Whether a block lives inside any table cell.
2340    pub fn is_block_in_table(&self, block_id: usize) -> bool {
2341        self.flow_layout.tables.values().any(|table| {
2342            table
2343                .cell_layouts
2344                .iter()
2345                .any(|cell| cell.blocks.iter().any(|b| b.block_id == block_id))
2346        })
2347    }
2348
2349    /// Scroll so that `position` is visible, placing it roughly one
2350    /// third from the top of the viewport. Returns the new offset.
2351    /// Affinity defaults to `Downstream` since scroll targeting picks
2352    /// any acceptable line for the position.
2353    pub fn scroll_to_position(&mut self, position: usize) -> f32 {
2354        let rect = crate::render::hit_test::caret_rect(
2355            &self.flow_layout,
2356            self.scroll_offset,
2357            position,
2358            crate::types::CursorAffinity::Downstream,
2359        );
2360        let target_y = rect[1] + self.scroll_offset - self.viewport_height / (3.0 * self.zoom);
2361        self.scroll_offset = target_y.max(0.0);
2362        self.scroll_offset
2363    }
2364
2365    /// Scroll the minimum amount needed to make the current caret
2366    /// visible. Call after arrow-key / click / typing. Returns
2367    /// `Some(new_offset)` if the scroll moved, `None` otherwise.
2368    ///
2369    /// The caret this reads is the one last handed to [`set_cursor`](Self::set_cursor),
2370    /// which an editor typically refreshes once per frame — so calling this
2371    /// from inside a key handler corrects for wherever the caret was on the
2372    /// *previous* frame, not where the keystroke just put it. Editors that move
2373    /// a cursor and reveal it in the same breath want
2374    /// [`ensure_position_visible`](Self::ensure_position_visible), which takes
2375    /// the position outright.
2376    pub fn ensure_caret_visible(&mut self) -> Option<f32> {
2377        if self.cursors.is_empty() {
2378            return None;
2379        }
2380        let pos = self.cursors[0].position;
2381        let affinity = self.cursors[0].affinity;
2382        self.ensure_position_visible(pos, affinity)
2383    }
2384
2385    /// Scroll the minimum amount needed to make `position` visible. Returns
2386    /// `Some(new_offset)` if the scroll moved, `None` otherwise.
2387    ///
2388    /// The explicit-position form of [`ensure_caret_visible`](Self::ensure_caret_visible),
2389    /// for the common editor shape where a key handler moves its own cursor and
2390    /// then reveals it: the flow's cached cursor is a frame behind at that
2391    /// moment, and correcting against it leaves the caret the keystroke just
2392    /// moved sitting outside the viewport until the *next* keystroke.
2393    pub fn ensure_position_visible(
2394        &mut self,
2395        position: usize,
2396        affinity: crate::types::CursorAffinity,
2397    ) -> Option<f32> {
2398        let rect = crate::render::hit_test::caret_rect(
2399            &self.flow_layout,
2400            self.scroll_offset,
2401            position,
2402            affinity,
2403        );
2404        let caret_screen_y = rect[1];
2405        let caret_screen_bottom = caret_screen_y + rect[3];
2406        let effective_vh = self.viewport_height / self.zoom;
2407        let margin = 10.0 / self.zoom;
2408        let old_offset = self.scroll_offset;
2409
2410        if caret_screen_y < 0.0 {
2411            self.scroll_offset += caret_screen_y - margin;
2412            self.scroll_offset = self.scroll_offset.max(0.0);
2413        } else if caret_screen_bottom > effective_vh {
2414            self.scroll_offset += caret_screen_bottom - effective_vh + margin;
2415        }
2416
2417        if (self.scroll_offset - old_offset).abs() > 0.001 {
2418            Some(self.scroll_offset)
2419        } else {
2420            None
2421        }
2422    }
2423}
2424
2425impl Default for DocumentFlow {
2426    fn default() -> Self {
2427        Self::new()
2428    }
2429}
2430
2431#[cfg(feature = "text-document")]
2432enum FlowItemKind {
2433    Block(BlockLayoutParams),
2434    Table(TableLayoutParams),
2435    Frame(FrameLayoutParams),
2436}
2437
2438/// Rasterize a single glyph into the service's atlas and append a
2439/// `GlyphQuad` to the output vec. Shared between
2440/// [`DocumentFlow::layout_single_line`] and
2441/// [`DocumentFlow::layout_paragraph`] (plus the markup variants).
2442///
2443/// `raster_scale` densifies the bitmap without touching layout: the
2444/// glyph is rasterized at `size × scale_factor × raster_scale`
2445/// physical pixels while the emitted `screen` rect stays in logical
2446/// pixels (divided by the *total* scale), so content drawn under a
2447/// scale transform (scene zoom) samples a matching-resolution bitmap
2448/// instead of stretching a 1× raster. Scaled rasters are unhinted —
2449/// glyph positions come from shaping at the logical ppem.
2450#[allow(clippy::too_many_arguments)]
2451fn rasterize_glyph_quad(
2452    service: &mut TextFontService,
2453    glyph: &ShapedGlyph,
2454    run: &ShapedRun,
2455    pen_x: f32,
2456    baseline: f32,
2457    text_color: [f32; 4],
2458    raster_scale: f32,
2459    quads: &mut Vec<GlyphQuad>,
2460    glyph_keys: &mut Vec<crate::atlas::cache::GlyphCacheKey>,
2461) {
2462    use crate::atlas::cache::GlyphCacheKey;
2463    use crate::atlas::rasterizer::rasterize_glyph;
2464
2465    if glyph.glyph_id == 0 {
2466        return;
2467    }
2468
2469    let entry = match service.font_registry.get(glyph.font_face_id) {
2470        Some(e) => e,
2471        None => return,
2472    };
2473
2474    let raster_scale = if raster_scale > 0.0 {
2475        raster_scale
2476    } else {
2477        1.0
2478    };
2479    let hinted = raster_scale == 1.0;
2480    let sf = service.scale_factor.max(f32::MIN_POSITIVE);
2481    let inv_total = 1.0 / (sf * raster_scale);
2482    let physical_size_px = run.size_px * sf * raster_scale;
2483    let cache_key = GlyphCacheKey::with_weight(
2484        glyph.font_face_id,
2485        glyph.glyph_id,
2486        physical_size_px,
2487        run.weight as u32,
2488        hinted,
2489    );
2490
2491    if service.glyph_cache.peek(&cache_key).is_none()
2492        && let Some(image) = rasterize_glyph(
2493            &mut service.scale_context,
2494            entry.bytes(),
2495            entry.face_index,
2496            entry.swash_cache_key,
2497            glyph.glyph_id,
2498            physical_size_px,
2499            run.weight as u32,
2500            hinted,
2501        )
2502        && image.width > 0
2503        && image.height > 0
2504    {
2505        let (alloc, evicted) = crate::atlas::allocate_or_evict(
2506            &mut service.atlas,
2507            &mut service.glyph_cache,
2508            image.width,
2509            image.height,
2510        );
2511        if evicted {
2512            service.eviction_epoch = service.eviction_epoch.wrapping_add(1);
2513        }
2514        if let Some(alloc) = alloc {
2515            let rect = alloc.rectangle;
2516            let atlas_x = rect.min.x as u32;
2517            let atlas_y = rect.min.y as u32;
2518            if image.is_color {
2519                service
2520                    .atlas
2521                    .blit_rgba(atlas_x, atlas_y, image.width, image.height, &image.data);
2522            } else {
2523                service
2524                    .atlas
2525                    .blit_mask(atlas_x, atlas_y, image.width, image.height, &image.data);
2526            }
2527            service.glyph_cache.insert(
2528                cache_key,
2529                crate::atlas::cache::CachedGlyph {
2530                    alloc_id: alloc.id,
2531                    atlas_x,
2532                    atlas_y,
2533                    width: image.width,
2534                    height: image.height,
2535                    placement_left: image.placement_left,
2536                    placement_top: image.placement_top,
2537                    is_color: image.is_color,
2538                    last_used: 0,
2539                },
2540            );
2541        }
2542    }
2543
2544    if let Some(cached) = service.glyph_cache.get(&cache_key) {
2545        let logical_w = cached.width as f32 * inv_total;
2546        let logical_h = cached.height as f32 * inv_total;
2547        let logical_left = cached.placement_left as f32 * inv_total;
2548        let logical_top = cached.placement_top as f32 * inv_total;
2549        let screen_x = pen_x + glyph.x_offset + logical_left;
2550        let screen_y = baseline - glyph.y_offset - logical_top;
2551        let color = if cached.is_color {
2552            [1.0, 1.0, 1.0, 1.0]
2553        } else {
2554            text_color
2555        };
2556        quads.push(GlyphQuad {
2557            screen: [screen_x, screen_y, logical_w, logical_h],
2558            atlas: [
2559                cached.atlas_x as f32,
2560                cached.atlas_y as f32,
2561                cached.width as f32,
2562                cached.height as f32,
2563            ],
2564            color,
2565            is_color: cached.is_color,
2566        });
2567        glyph_keys.push(cache_key);
2568    }
2569}
2570
2571/// Quantize an accumulated densification scale onto a geometric ladder of
2572/// 1.25ⁿ steps, `n ∈ [0, 6]` (so the value lands in `[1.0, ~3.81]`), for
2573/// glyph raster densification under zoom / external scale transforms.
2574///
2575/// The ladder bounds the number of distinct atlas entries a continuous
2576/// zoom gesture can create (7 buckets). The bucket value is derived from
2577/// an integer index, so the same input always yields the bit-identical
2578/// f32 — cache keys stay stable across frames — and the function is
2579/// idempotent (a bucket value maps to itself). Between buckets the
2580/// residual GPU scaling is at most ~12%, invisible under the glyph
2581/// atlas's linear filtering. Scales below 1 clamp to 1: zoomed-out text
2582/// relies on linear minification rather than rasterizing below logical
2583/// size.
2584///
2585/// Kept in lockstep with `teksilo_canvas::quantize_raster_scale` (scene
2586/// transform densification uses the same ladder).
2587pub fn quantize_raster_scale(scale: f32) -> f32 {
2588    if !scale.is_finite() || scale <= 1.0 {
2589        return 1.0;
2590    }
2591    const STEP: f32 = 1.25;
2592    /// 1.25⁶ ≈ 3.81 — the densest raster bucket. Deep zoom beyond it
2593    /// rides linear magnification; an unbounded ladder would explode
2594    /// atlas area quadratically.
2595    const MAX_BUCKET: i32 = 6;
2596    let bucket = ((scale.ln() / STEP.ln()).round() as i32).clamp(0, MAX_BUCKET);
2597    STEP.powi(bucket)
2598}
2599
2600/// Scale all screen-space coordinates in a RenderFrame by `zoom`.
2601fn apply_zoom(frame: &mut RenderFrame, zoom: f32) {
2602    if (zoom - 1.0).abs() <= f32::EPSILON {
2603        return;
2604    }
2605    for q in &mut frame.glyphs {
2606        q.screen[0] *= zoom;
2607        q.screen[1] *= zoom;
2608        q.screen[2] *= zoom;
2609        q.screen[3] *= zoom;
2610    }
2611    for q in &mut frame.images {
2612        q.screen[0] *= zoom;
2613        q.screen[1] *= zoom;
2614        q.screen[2] *= zoom;
2615        q.screen[3] *= zoom;
2616    }
2617    apply_zoom_decorations(&mut frame.decorations, zoom);
2618}
2619
2620/// Scale all screen-space coordinates in decoration rects by `zoom`.
2621fn apply_zoom_decorations(decorations: &mut [DecorationRect], zoom: f32) {
2622    if (zoom - 1.0).abs() <= f32::EPSILON {
2623        return;
2624    }
2625    for d in decorations.iter_mut() {
2626        d.rect[0] *= zoom;
2627        d.rect[1] *= zoom;
2628        d.rect[2] *= zoom;
2629        d.rect[3] *= zoom;
2630    }
2631}
2632
2633/// Derive a per-span [`TextFormat`] from a base format and inline
2634/// markup attributes (bold / italic).
2635fn merge_format(base: &TextFormat, attrs: InlineAttrs) -> TextFormat {
2636    let mut fmt = base.clone();
2637    if attrs.is_bold() {
2638        fmt.font_bold = Some(true);
2639        if let Some(w) = fmt.font_weight
2640            && w < 600
2641        {
2642            fmt.font_weight = Some(700);
2643        } else if fmt.font_weight.is_none() {
2644            fmt.font_weight = Some(700);
2645        }
2646    }
2647    if attrs.is_italic() {
2648        fmt.font_italic = Some(true);
2649    }
2650    fmt
2651}
2652
2653#[cfg(test)]
2654mod tests {
2655    use super::*;
2656    use crate::layout::block::{BlockLayoutParams, FragmentParams};
2657    use crate::layout::paragraph::Alignment;
2658    use crate::types::{UnderlineStyle, VerticalAlignment};
2659
2660    const NOTO_SANS: &[u8] = include_bytes!("../test-fonts/NotoSans-Variable.ttf");
2661
2662    fn service() -> TextFontService {
2663        // Hermetic: don't pull in the host machine's fonts.
2664        let mut s = TextFontService::new_without_system_fonts();
2665        let face = s.register_font(NOTO_SANS);
2666        s.set_default_font(face, 16.0);
2667        s
2668    }
2669
2670    fn block(id: usize, text: &str) -> BlockLayoutParams {
2671        BlockLayoutParams {
2672            base_direction: Default::default(),
2673            block_id: id,
2674            position: 0,
2675            text: text.to_string(),
2676            fragments: vec![FragmentParams {
2677                text: text.to_string(),
2678                offset: 0,
2679                length: text.len(),
2680                font_family: None,
2681                font_weight: None,
2682                font_bold: None,
2683                font_italic: None,
2684                font_point_size: None,
2685                underline_style: UnderlineStyle::None,
2686                overline: false,
2687                strikeout: false,
2688                is_link: false,
2689                letter_spacing: 0.0,
2690                word_spacing: 0.0,
2691                foreground_color: None,
2692                underline_color: None,
2693                background_color: None,
2694                anchor_href: None,
2695                tooltip: None,
2696                vertical_alignment: VerticalAlignment::Normal,
2697                image_name: None,
2698                image_width: 0.0,
2699                image_height: 0.0,
2700                footnote_marker: None,
2701                features: Vec::new(),
2702            }],
2703            alignment: Alignment::Left,
2704            top_margin: 0.0,
2705            bottom_margin: 0.0,
2706            left_margin: 0.0,
2707            right_margin: 0.0,
2708            text_indent: 0.0,
2709            list_marker: String::new(),
2710            list_indent: 0.0,
2711            tab_positions: vec![],
2712            line_height_multiplier: None,
2713            non_breakable_lines: false,
2714            hyphenation: None,
2715            checkbox: None,
2716            background_color: None,
2717        }
2718    }
2719
2720    #[test]
2721    fn relayout_block_returns_no_layout_when_never_laid_out() {
2722        let svc = service();
2723        let mut flow = DocumentFlow::new();
2724        flow.set_viewport(400.0, 200.0);
2725        let err = flow.relayout_block(&svc, &block(1, "Hello")).unwrap_err();
2726        assert_eq!(err, RelayoutError::NoLayout);
2727    }
2728
2729    #[test]
2730    fn relayout_block_returns_scale_dirty_after_scale_factor_change() {
2731        let mut svc = service();
2732        let mut flow = DocumentFlow::new();
2733        flow.set_viewport(400.0, 200.0);
2734        flow.layout_blocks(&svc, vec![block(1, "Hello")]);
2735        assert!(flow.has_layout());
2736
2737        // Simulate a HiDPI transition on the shared service.
2738        svc.set_scale_factor(2.0);
2739        assert!(flow.layout_dirty_for_scale(&svc));
2740
2741        let err = flow
2742            .relayout_block(&svc, &block(1, "Hello world"))
2743            .unwrap_err();
2744        assert_eq!(err, RelayoutError::ScaleDirty);
2745    }
2746
2747    #[test]
2748    fn relayout_block_succeeds_after_fresh_layout_post_scale_change() {
2749        let mut svc = service();
2750        let mut flow = DocumentFlow::new();
2751        flow.set_viewport(400.0, 200.0);
2752        flow.layout_blocks(&svc, vec![block(1, "Hello")]);
2753
2754        svc.set_scale_factor(2.0);
2755        // Caller is expected to re-run a full layout at the new
2756        // scale before issuing incremental updates.
2757        flow.layout_blocks(&svc, vec![block(1, "Hello")]);
2758        assert!(!flow.layout_dirty_for_scale(&svc));
2759
2760        // Now the incremental path succeeds.
2761        flow.relayout_block(&svc, &block(1, "Hello world"))
2762            .expect("relayout_block must succeed after a fresh post-scale layout");
2763    }
2764
2765    /// `block_params_for` converts a document block snapshot into layout params
2766    /// — the per-block seam the windowed streaming path is built on. The text
2767    /// must round-trip so the shaped row matches the document.
2768    #[test]
2769    fn block_params_for_converts_a_document_snapshot() {
2770        let flow = DocumentFlow::new();
2771        let doc = text_document::TextDocument::new();
2772        doc.set_plain_text("alpha\nbeta").unwrap();
2773
2774        // Second block ("beta") starts after "alpha\n" — position 6.
2775        let snap = doc.snapshot_block_at_position(6).expect("block snapshot");
2776        let params = flow.block_params_for(&snap);
2777
2778        assert_eq!(params.text, "beta", "the block text must round-trip");
2779        assert!(
2780            !params.fragments.is_empty(),
2781            "a non-empty block must convert to at least one fragment"
2782        );
2783    }
2784
2785    /// It must use *this flow's* bridge options, not defaults — otherwise the
2786    /// windowed path would shape a block differently from `layout_full`. The
2787    /// echo char is the cheapest observable: with it set, the conversion masks
2788    /// the text.
2789    #[test]
2790    fn block_params_for_honours_the_flow_echo_char() {
2791        let mut flow = DocumentFlow::new();
2792        flow.set_echo_char(Some('•'));
2793        let doc = text_document::TextDocument::new();
2794        doc.set_plain_text("secret").unwrap();
2795
2796        let snap = doc.snapshot_block_at_position(0).expect("block snapshot");
2797        let params = flow.block_params_for(&snap);
2798
2799        assert!(
2800            params.fragments.iter().all(|f| !f.text.contains("secret")),
2801            "the flow's echo char must mask the plaintext, proving its own \
2802             bridge options are used"
2803        );
2804    }
2805}