Skip to main content

text_typeset/
document_flow.rs

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