Skip to main content

text_typeset/
document_flow.rs

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