Skip to main content

text_typeset/
document_flow.rs

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