Skip to main content

text_typeset/
types.rs

1/// Opaque handle to a registered font face.
2///
3/// Obtained from [`crate::TextFontService::register_font`] or [`crate::TextFontService::register_font_as`].
4/// Pass to [`crate::TextFontService::set_default_font`] to make it the default.
5#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
6pub struct FontFaceId(pub u32);
7
8// ── Render output ───────────────────────────────────────────────
9
10/// Everything needed to draw one frame.
11///
12/// Produced by [`crate::DocumentFlow::render`]. Contains glyph quads (textured rectangles
13/// from the atlas), inline image placeholders, and decoration rectangles
14/// (selections, cursor, underlines, table borders, etc.).
15///
16/// The adapter draws the frame in three passes:
17/// 1. Upload `atlas_pixels` as a GPU texture (only when `atlas_dirty` is true).
18/// 2. Draw each [`GlyphQuad`] as a textured rectangle from the atlas.
19/// 3. Draw each [`DecorationRect`] as a colored rectangle.
20pub struct RenderFrame {
21    /// True if the atlas texture changed since the last frame (needs re-upload).
22    pub atlas_dirty: bool,
23    /// Atlas texture width in pixels.
24    pub atlas_width: u32,
25    /// Atlas texture height in pixels.
26    pub atlas_height: u32,
27    /// RGBA pixel data, row-major. Length = `atlas_width * atlas_height * 4`.
28    pub atlas_pixels: Vec<u8>,
29    /// One textured rectangle per visible glyph.
30    pub glyphs: Vec<GlyphQuad>,
31    /// Inline image placeholders. The adapter loads the actual image data
32    /// (e.g., via `TextDocument::resource(name)`) and draws it at the given
33    /// screen position.
34    pub images: Vec<ImageQuad>,
35    /// Decoration rectangles: selections, cursor, underlines, strikeouts,
36    /// overlines, backgrounds, table borders, and cell backgrounds.
37    pub decorations: Vec<DecorationRect>,
38    /// Per-block glyph data for incremental updates. Keyed by block_id.
39    pub(crate) block_glyphs: Vec<(usize, Vec<GlyphQuad>)>,
40    /// Per-block decoration data (underlines, etc. — NOT cursor/selection).
41    pub(crate) block_decorations: Vec<(usize, Vec<DecorationRect>)>,
42    /// Per-block image data for incremental updates.
43    pub(crate) block_images: Vec<(usize, Vec<ImageQuad>)>,
44    /// Per-block height snapshot for detecting height changes in incremental render.
45    pub(crate) block_heights: std::collections::HashMap<usize, f32>,
46    /// Per-block glyph cache keys, parallel to [`Self::block_glyphs`]. Used by
47    /// [`crate::DocumentFlow::render_cursor_only`] and
48    /// [`crate::DocumentFlow::render_block_only`] to mark every cached
49    /// glyph as still-in-use in the shared `GlyphCache` — otherwise
50    /// glyphs reused via paint-cache hits (which never re-enter the
51    /// `cache.get()` path that refreshes timestamps) would age out and
52    /// their atlas slots could be reallocated for unrelated glyphs,
53    /// silently corrupting the cached `GlyphQuad`s' atlas references.
54    pub(crate) block_glyph_keys: Vec<(usize, Vec<crate::atlas::cache::GlyphCacheKey>)>,
55    /// Flat glyph cache keys, parallel to [`Self::glyphs`]. Rebuilt from
56    /// [`Self::block_glyph_keys`] by `rebuild_flat_frame`; passed to
57    /// [`crate::TextFontService::touch_glyphs`] on every cursor-only /
58    /// block-only paint so the shared atlas keeps visible glyphs alive.
59    pub(crate) glyph_keys: Vec<crate::atlas::cache::GlyphCacheKey>,
60    /// Snapshot of [`crate::TextFontService::eviction_epoch`] at the
61    /// moment this frame's atlas references were baked. Cursor-only
62    /// and block-only paths compare against the service's current
63    /// epoch and fall back to a full re-render if eviction has
64    /// happened since — defensive safety net behind the `touch_glyphs`
65    /// keep-alive mechanism.
66    pub(crate) atlas_eviction_epoch: u64,
67}
68
69/// A positioned glyph to draw as a textured quad from the atlas.
70///
71/// The adapter draws the rectangle at `screen` position, sampling from
72/// the `atlas` rectangle in the atlas texture, tinted with `color`.
73#[derive(Clone)]
74#[non_exhaustive]
75pub struct GlyphQuad {
76    /// Screen position and size: `[x, y, width, height]` in pixels.
77    pub screen: [f32; 4],
78    /// Atlas source rectangle: `[x, y, width, height]` in atlas pixel coordinates.
79    pub atlas: [f32; 4],
80    /// Glyph color: `[r, g, b, a]`, 0.0-1.0.
81    /// For normal text glyphs, this is the text color (default black).
82    /// For color emoji, this is `[1, 1, 1, 1]` (color is baked into the atlas).
83    pub color: [f32; 4],
84    /// `true` if the atlas region for this glyph holds a pre-multiplied
85    /// RGBA color bitmap (color emoji via COLR/CBDT/sbix). The renderer
86    /// must sample `texture.rgb` directly instead of using the texture
87    /// as an alpha mask tinted by [`color`](Self::color).
88    pub is_color: bool,
89}
90
91/// An inline image placeholder.
92///
93/// text-typeset computes the position and size but does NOT load or rasterize
94/// the image. The adapter retrieves the image data (e.g., from
95/// `TextDocument::resource(name)`) and draws it as a separate texture.
96#[derive(Clone)]
97#[non_exhaustive]
98pub struct ImageQuad {
99    /// Screen position and size: `[x, y, width, height]` in pixels.
100    ///
101    /// The size is the laid-out one: an image wider than its line's measure
102    /// is capped to that measure, its height scaled by the same factor, so
103    /// this can be smaller than the size the document stores. A host that
104    /// draws a resize grip or reports the size the writer sees takes it from
105    /// here, not from the document.
106    pub screen: [f32; 4],
107    /// Image resource name (matches `FragmentContent::Image::name` from text-document).
108    pub name: String,
109    /// Document-absolute character offset of this image's single `U+FFFC`.
110    ///
111    /// The name alone cannot say *which* placement this is — a document may
112    /// hold one picture in three places — so anything that has to answer "is
113    /// THIS image inside the selection" needs the offset. Same value, derived
114    /// the same way, as the offset `hit_test` reports for a click on it.
115    pub char_offset: usize,
116}
117
118impl ImageQuad {
119    /// An image placement: `screen` as `[x, y, width, height]`, the resource
120    /// `name`, and the `char_offset` of its `U+FFFC`. For a host that stands
121    /// in for the typesetter, a test for instance.
122    pub fn new(screen: [f32; 4], name: impl Into<String>, char_offset: usize) -> Self {
123        Self {
124            screen,
125            name: name.into(),
126            char_offset,
127        }
128    }
129}
130
131/// A colored rectangle for decorations (underlines, selections, borders, etc.).
132#[derive(Clone)]
133#[non_exhaustive]
134pub struct DecorationRect {
135    /// Screen position and size: `[x, y, width, height]` in pixels.
136    pub rect: [f32; 4],
137    /// Color: `[r, g, b, a]`, 0.0-1.0.
138    pub color: [f32; 4],
139    /// What kind of decoration this rectangle represents.
140    pub kind: DecorationKind,
141}
142
143/// The type of a [`DecorationRect`].
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum DecorationKind {
146    /// Selection highlight (translucent background behind selected text).
147    Selection,
148    /// Cursor caret (thin vertical line at the insertion point).
149    Cursor,
150    /// Underline (below baseline, from font metrics).
151    Underline,
152    /// Strikethrough (at x-height, from font metrics).
153    Strikeout,
154    /// Overline (at ascent line).
155    Overline,
156    /// Generic background (e.g., frame borders).
157    Background,
158    /// Block-level background color.
159    BlockBackground,
160    /// Table border line.
161    TableBorder,
162    /// Table cell background color.
163    TableCellBackground,
164    /// Text-level background highlight (behind individual text runs).
165    /// Adapters should draw these before glyph quads so text appears on top.
166    TextBackground,
167    /// Cell-level selection highlight (entire cell background when cells are
168    /// selected as a rectangular region, as opposed to text within cells).
169    CellSelection,
170}
171
172/// Underline style for text decorations.
173#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
174pub enum UnderlineStyle {
175    /// No underline.
176    #[default]
177    None,
178    /// Solid single underline.
179    Single,
180    /// Dashed underline.
181    Dash,
182    /// Dotted underline.
183    Dot,
184    /// Alternating dash-dot pattern.
185    DashDot,
186    /// Alternating dash-dot-dot pattern.
187    DashDotDot,
188    /// Wavy underline.
189    Wave,
190    /// Spell-check underline (wavy, typically red).
191    SpellCheck,
192}
193
194/// Vertical alignment for characters (superscript, subscript, etc.).
195#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
196pub enum VerticalAlignment {
197    /// Normal baseline alignment.
198    #[default]
199    Normal,
200    /// Superscript: smaller size, shifted up.
201    SuperScript,
202    /// Subscript: smaller size, shifted down.
203    SubScript,
204}
205
206// ── Hit testing ─────────────────────────────────────────────────
207
208/// Disambiguates the two visual placements a single character position
209/// can have at a soft-wrap boundary. A long paragraph that wraps across
210/// lines K and K+1 has one character position N that sits at both the
211/// END of line K and the START of line K+1; affinity picks which one
212/// the caret renders at and which line `Home`/`End`-style navigation
213/// considers "current".
214///
215/// Affinity is a display concern: it makes no sense without a layout
216/// engine and a wrap width. It is never persisted with the text model
217/// (cf. Cocoa `NSSelectionAffinity` on `NSTextView`, not on
218/// `NSTextStorage`; Chromium `PositionWithAffinity` at the editing
219/// layer, not on `Position`; same in Qt and CodeMirror).
220///
221/// At positions that are NOT wrap boundaries — the interior of a line,
222/// the start of the first wrap-line, the end of the last wrap-line of
223/// a paragraph — affinity is a no-op and the rendering is identical.
224#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
225pub enum CursorAffinity {
226    /// Place the caret at the END of the previous wrap line. This is
227    /// the visual "trailing" placement and the default for any
228    /// position not produced by an upstream-side interaction.
229    #[default]
230    Downstream,
231    /// Place the caret at the START of the next wrap line.
232    Upstream,
233}
234
235/// Result of [`crate::DocumentFlow::hit_test`] - maps a screen-space point to a
236/// document position.
237#[non_exhaustive]
238pub struct HitTestResult {
239    /// Absolute character position in the document.
240    pub position: usize,
241    /// Which side of a soft-wrap boundary the click landed on. When
242    /// the matched line's Y range contained the click and `position`
243    /// equals that line's `char_range.start` AND the preceding line in
244    /// the same block wraps at the same position, the click is on the
245    /// upstream side of the boundary → `Upstream`. Otherwise
246    /// `Downstream`. At non-wrap positions, the start of a line after a
247    /// hard break included, the value is `Downstream` (default) and does
248    /// not affect anything.
249    pub affinity: CursorAffinity,
250    /// Which block (paragraph) was hit, identified by stable block ID.
251    pub block_id: usize,
252    /// Character offset within the block (0 = start of block).
253    pub offset_in_block: usize,
254    /// What region of the layout was hit.
255    pub region: HitRegion,
256    /// Tooltip text if the hit position has a tooltip. None otherwise.
257    pub tooltip: Option<String>,
258    /// When non-None, the hit position is inside a table cell.
259    /// Identifies the table by its stable table ID.
260    /// None for hits on top-level blocks, frame blocks, or outside any table.
261    pub table_id: Option<usize>,
262}
263
264/// What region of the layout a hit test landed in.
265#[derive(Debug)]
266pub enum HitRegion {
267    /// Inside a text run (normal text content).
268    Text,
269    /// In the block's left margin area (before any text content).
270    LeftMargin,
271    /// In the block's indent area.
272    Indent,
273    /// On a table border line.
274    TableBorder,
275    /// Below all content in the document.
276    BelowContent,
277    /// Past the end of a line (to the right of the last character).
278    PastLineEnd,
279    /// On an inline image.
280    Image { name: String },
281    /// On a hyperlink.
282    Link { href: String },
283}
284
285// ── Cursor display ──────────────────────────────────────────────
286
287/// Cursor display state for rendering.
288///
289/// The adapter reads cursor position from text-document's `TextCursor`
290/// and creates this struct to feed to [`crate::DocumentFlow::set_cursor`].
291/// text-typeset uses it to generate caret and selection decorations
292/// in the next [`crate::DocumentFlow::render`] call.
293pub struct CursorDisplay {
294    /// Cursor position (character offset in the document).
295    pub position: usize,
296    /// Selection anchor. Equals `position` when there is no selection.
297    /// When different from `position`, the range `[min(anchor, position), max(anchor, position))`
298    /// is highlighted as a selection.
299    pub anchor: usize,
300    /// Which side of a soft-wrap boundary the caret renders on (see
301    /// [`CursorAffinity`]). At non-boundary positions this is a
302    /// no-op; default `Downstream` (current behavior before affinity
303    /// was introduced).
304    pub affinity: CursorAffinity,
305    /// Whether the caret is visible (false during the blink-off phase).
306    /// The adapter manages the blink timer; text-typeset just respects this flag.
307    pub visible: bool,
308    /// When non-empty, render cell-level selection highlights instead of
309    /// text-level selection. Each tuple is `(table_id, row, col)` identifying
310    /// a selected cell. The adapter fills this from `TextCursor::selected_cells()`.
311    pub selected_cells: Vec<(usize, usize, usize)>,
312}
313
314// ── Scrolling ───────────────────────────────────────────────────
315
316/// Visual position and size of a laid-out table, and of its rows and
317/// columns.
318///
319/// Returned by [`crate::DocumentFlow::table_visual_info`]. `x` / `y` are the
320/// document-space top-left of the whole table box; `column_xs` and `row_ys`
321/// are measured from that origin, so cell `(r, c)` occupies
322/// `(x + column_xs[c], y + row_ys[r], column_content_widths[c], row_heights[r])`.
323#[non_exhaustive]
324pub struct TableVisualInfo {
325    /// Table ID (matches `TableSnapshot::table_id`).
326    pub table_id: usize,
327    /// Document-space x of the table box's left edge, in pixels.
328    pub x: f32,
329    /// Document-space y of the table box's top edge, in pixels.
330    pub y: f32,
331    /// Total width of the table, in pixels.
332    pub width: f32,
333    /// Total height of the table including borders, in pixels.
334    pub height: f32,
335    /// Left edge of each column's content area, relative to `x`.
336    pub column_xs: Vec<f32>,
337    /// Width of each column's content area, in pixels.
338    pub column_content_widths: Vec<f32>,
339    /// Top edge of each row's content area, relative to `y`.
340    pub row_ys: Vec<f32>,
341    /// Height of each row's content area, in pixels.
342    pub row_heights: Vec<f32>,
343}
344
345/// Visual position and size of a laid-out block.
346///
347/// Returned by [`crate::DocumentFlow::block_visual_info`] and, with the
348/// block's lines, by [`crate::DocumentFlow::block_geometry`].
349///
350/// Three x positions matter, and they are not the same:
351///
352/// - [`x`](Self::x), the left edge of the column the block sits in;
353/// - [`content_x`](Self::content_x), where the block's text starts, after its
354///   left margin and any list or paragraph indent;
355/// - [`marker_x`](Self::marker_x), where its list or checkbox marker is drawn,
356///   in the indent area before the text.
357///
358/// Line rectangles returned by [`crate::DocumentFlow::block_geometry`] and
359/// [`crate::DocumentFlow::block_line_geometry`] are relative to
360/// [`content_x`](Self::content_x), not to [`x`](Self::x).
361#[non_exhaustive]
362pub struct BlockVisualInfo {
363    /// Block ID (matches `BlockSnapshot::block_id`).
364    pub block_id: usize,
365    /// X position of the left edge of the block's column, relative to the
366    /// document start, in pixels. It does **not** include the block's own left
367    /// margin or indent: a rectangle around the block's text starts at
368    /// [`content_x`](Self::content_x), and one that also covers the marker
369    /// starts here.
370    ///
371    /// Zero for a block in the document's own column. A block inside a table
372    /// cell or a frame has its own left origin: column 1 of a table does not
373    /// start at the document's left edge.
374    pub x: f32,
375    /// X position where the block's text starts, relative to the document
376    /// start, in pixels: [`x`](Self::x) plus the block's left margin and its
377    /// list or paragraph indent. This is the origin of the `x` of every line
378    /// rectangle and segment the line geometry reports for the block, and the
379    /// origin the renderer paints glyphs from.
380    ///
381    /// Equal to [`x`](Self::x) for a block with no margin and no indent.
382    pub content_x: f32,
383    /// X position of the block's list or checkbox marker box, relative to the
384    /// document start, in pixels, or `None` when the block has no marker.
385    ///
386    /// The marker is drawn in the indent area just before the text,
387    /// right-aligned with a small gap, and never left of the block's left
388    /// margin. When the indent is narrower than the marker, the marker starts
389    /// at the left margin (`x` plus the margin) and its box overlaps the text.
390    /// In a right-to-left block it is currently still drawn at the left.
391    pub marker_x: Option<f32>,
392    /// Advance width of the marker, in pixels; `0.0` when the block has no
393    /// marker. The marker box is `marker_x` to `marker_x + marker_width`,
394    /// on the block's first line.
395    pub marker_width: f32,
396    /// Y position of the block's top edge relative to the document start, in pixels.
397    pub y: f32,
398    /// Total height of the block including margins, in pixels.
399    pub height: f32,
400}
401
402// ── OpenType features ───────────────────────────────────────────
403
404/// An OpenType feature toggle applied during shaping.
405///
406/// `tag` is the 4-byte feature tag (e.g. `*b"liga"`, `*b"smcp"`,
407/// `*b"tnum"`, `*b"ss01"`); `value` is the feature value — `0` disables
408/// it, `1` enables it, and some features (e.g. `aalt`) take an index.
409///
410/// Script-mandated features (Arabic joining, Indic reordering, etc.)
411/// always apply regardless of this list; these toggles control the
412/// *discretionary* typographic features a caller wants on or off.
413#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
414pub struct FontFeature {
415    /// The 4-byte OpenType feature tag.
416    pub tag: [u8; 4],
417    /// Feature value: `0` = off, `1` = on, or a feature-specific index.
418    pub value: u32,
419}
420
421impl FontFeature {
422    /// A feature tag turned on (`value = 1`).
423    pub const fn on(tag: [u8; 4]) -> Self {
424        Self { tag, value: 1 }
425    }
426
427    /// A feature tag turned off (`value = 0`).
428    pub const fn off(tag: [u8; 4]) -> Self {
429        Self { tag, value: 0 }
430    }
431
432    /// A feature tag with an explicit value.
433    pub const fn new(tag: [u8; 4], value: u32) -> Self {
434        Self { tag, value }
435    }
436}
437
438/// Hyphenation settings for line wrapping.
439///
440/// Presence (`Some`) enables hyphenation; the `language` selects the
441/// Knuth-Liang dictionary. Soft hyphens (U+00AD) always break and render a
442/// hyphen when enabled, regardless of language; dictionary hyphenation
443/// applies only when the language's patterns are compiled in (otherwise it
444/// silently falls back to soft-hyphen-only).
445#[derive(Clone, Copy, Debug, PartialEq, Eq)]
446pub struct Hyphenation {
447    /// ISO 639-1 language code, e.g. `*b"en"`, `*b"fr"`, `*b"de"`.
448    pub language: [u8; 2],
449}
450
451impl Hyphenation {
452    /// Hyphenation in the given ISO 639-1 language.
453    pub const fn new(language: [u8; 2]) -> Self {
454        Self { language }
455    }
456
457    /// English hyphenation (`en`).
458    pub const ENGLISH: Self = Self { language: *b"en" };
459}
460
461impl Default for Hyphenation {
462    fn default() -> Self {
463        Self::ENGLISH
464    }
465}
466
467// ── Single-line API ────────────────────────────────────────────
468
469/// Text formatting parameters for the single-line layout API.
470///
471/// Controls font selection, size, and text color. All fields are optional
472/// and fall back to the typesetter's defaults (default font, default size,
473/// default text color).
474#[derive(Clone, Debug, Default)]
475pub struct TextFormat {
476    /// Font family name (e.g., "Noto Sans", "monospace").
477    /// None means use the default font.
478    pub font_family: Option<String>,
479    /// Font weight (100-900). Overrides `font_bold`.
480    pub font_weight: Option<u32>,
481    /// Shorthand for weight 700. Ignored if `font_weight` is set.
482    pub font_bold: Option<bool>,
483    /// Italic style.
484    pub font_italic: Option<bool>,
485    /// Font size in pixels. None means use the default size.
486    pub font_size: Option<f32>,
487    /// Text color (RGBA, 0.0-1.0). None means use the typesetter's text color.
488    pub color: Option<[f32; 4]>,
489    /// Discretionary OpenType features to toggle during shaping (ligatures,
490    /// small caps, tabular numerals, stylistic sets, …). Empty = font defaults.
491    pub features: Vec<FontFeature>,
492    /// Hyphenation (Knuth-Liang dictionary + soft-hyphen breaks) for line
493    /// wrapping. `None` = disabled (default); most useful for justified
494    /// prose. See [`Hyphenation`].
495    pub hyphenation: Option<Hyphenation>,
496}
497
498/// Result of [`crate::DocumentFlow::layout_single_line`].
499///
500/// Contains the measured dimensions and GPU-ready glyph quads for a
501/// single line of text. No flow layout, line breaking, or bidi analysis
502/// is performed.
503#[non_exhaustive]
504pub struct SingleLineResult {
505    /// Total advance width of the shaped text, in pixels.
506    pub width: f32,
507    /// Line height (ascent + descent + leading), in pixels.
508    pub height: f32,
509    /// Distance from the top of the line to the baseline, in pixels.
510    pub baseline: f32,
511    /// Distance from baseline to the top of the underline, in logical
512    /// pixels. Positive = below the baseline. Sourced from the primary
513    /// font's `post` table.
514    pub underline_offset: f32,
515    /// Underline line thickness in logical pixels. Sourced from the
516    /// primary font's stroke size.
517    pub underline_thickness: f32,
518    /// GPU-ready glyph quads, positioned at y=0 (no scroll offset).
519    pub glyphs: Vec<GlyphQuad>,
520    /// Per-glyph cache keys, parallel to `glyphs`. Callers that cache
521    /// glyph output externally should pass these back to
522    /// [`crate::TextFontService::touch_glyphs`] each frame to prevent the
523    /// atlas from evicting still-visible glyphs.
524    pub glyph_keys: Vec<crate::atlas::cache::GlyphCacheKey>,
525    /// Per-span bounding rectangles for markup-aware layout
526    /// ([`crate::DocumentFlow::layout_single_line_markup`]). Empty for
527    /// the plain-text layout path.
528    pub spans: Vec<LaidOutSpan>,
529}
530
531/// A single laid-out span produced by the markup-aware layout path.
532///
533/// When a link wraps across two paragraph lines, it produces two
534/// `LaidOutSpan` entries sharing the same URL and byte_range but with
535/// distinct `line_index` / `rect`.
536#[derive(Debug, Clone)]
537#[non_exhaustive]
538pub struct LaidOutSpan {
539    pub kind: LaidOutSpanKind,
540    /// Which wrapped line this span piece lives on (0 for single-line).
541    pub line_index: usize,
542    /// Local-space rect: `[x, y, width, height]`, same space as glyph quads.
543    pub rect: [f32; 4],
544    /// Byte range into the original markup source.
545    pub byte_range: std::ops::Range<usize>,
546}
547
548/// Kind discriminator for [`LaidOutSpan`].
549#[derive(Debug, Clone)]
550pub enum LaidOutSpanKind {
551    Text,
552    Link { url: String },
553}
554
555/// Result of [`crate::DocumentFlow::layout_paragraph`].
556///
557/// Contains the measured dimensions and GPU-ready glyph quads for a
558/// multi-line paragraph wrapped at a fixed width. Glyphs are positioned
559/// in paragraph-local coordinates: `x = 0` is the left edge of the
560/// paragraph, `y = 0` is the top of the first line's line box. The
561/// adapter should offset all glyph quads by the paragraph's screen
562/// position before drawing.
563#[non_exhaustive]
564pub struct ParagraphResult {
565    /// Width of the widest laid-out line, in pixels. May be less than the
566    /// `max_width` passed to `layout_paragraph` if the content is narrower.
567    pub width: f32,
568    /// Total stacked paragraph height in pixels — sum of line heights for
569    /// all emitted lines.
570    pub height: f32,
571    /// Distance from `y = 0` to the baseline of the first line, in pixels.
572    pub baseline_first: f32,
573    /// Number of lines actually emitted (respects `max_lines` when set).
574    pub line_count: usize,
575    /// Line height (single line's ascent + descent + leading), in pixels.
576    /// Useful for callers that need to reason about per-line geometry.
577    pub line_height: f32,
578    /// Distance from baseline to the top of the underline, in logical
579    /// pixels. Positive = below the baseline. Sourced from the primary
580    /// font's `post` table.
581    pub underline_offset: f32,
582    /// Underline line thickness in logical pixels. Sourced from the
583    /// primary font's stroke size.
584    pub underline_thickness: f32,
585    /// GPU-ready glyph quads in paragraph-local coordinates.
586    pub glyphs: Vec<GlyphQuad>,
587    /// Per-glyph cache keys, parallel to `glyphs`. See
588    /// [`SingleLineResult::glyph_keys`].
589    pub glyph_keys: Vec<crate::atlas::cache::GlyphCacheKey>,
590    /// Per-span bounding rectangles for markup-aware layout
591    /// ([`crate::DocumentFlow::layout_paragraph_markup`]). Empty for
592    /// the plain-text layout path.
593    pub spans: Vec<LaidOutSpan>,
594}
595
596impl RenderFrame {
597    pub(crate) fn new() -> Self {
598        Self {
599            atlas_dirty: false,
600            atlas_width: 0,
601            atlas_height: 0,
602            atlas_pixels: Vec::new(),
603            glyphs: Vec::new(),
604            images: Vec::new(),
605            decorations: Vec::new(),
606            block_glyphs: Vec::new(),
607            block_decorations: Vec::new(),
608            block_images: Vec::new(),
609            block_heights: std::collections::HashMap::new(),
610            block_glyph_keys: Vec::new(),
611            glyph_keys: Vec::new(),
612            atlas_eviction_epoch: 0,
613        }
614    }
615}
616
617// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
618// CharacterGeometry — accessibility per-character advance data
619// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
620
621/// Per-character advance geometry for a laid-out text run.
622///
623/// Consumed by accessibility layers that need to populate AccessKit's
624/// `character_positions` and `character_widths` on a `Role::TextRun`
625/// node so screen reader highlight cursors and screen magnifiers can
626/// track the caret at character granularity.
627///
628/// `position` is measured in run-local coordinates: the first
629/// character of the requested range sits at `position == 0.0`, and
630/// subsequent characters accumulate their advance widths. `width` is
631/// the advance width of each character, in the same units.
632#[derive(Debug, Clone, Copy, PartialEq)]
633#[non_exhaustive]
634pub struct CharacterGeometry {
635    pub position: f32,
636    pub width: f32,
637}
638
639// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
640// Line geometry — per-line, per-character layout output
641// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
642
643/// Reading direction of a [`LineSegment`], as the accessibility layer
644/// needs it.
645///
646/// Distinct from [`crate::TextDirection`], which carries an `Auto`
647/// variant meaning "not yet resolved". Geometry is produced *after*
648/// shaping, so every segment's direction is known.
649#[derive(Debug, Clone, Copy, PartialEq, Eq)]
650pub enum GeometryDirection {
651    LeftToRight,
652    RightToLeft,
653}
654
655/// How a laid-out line ends.
656///
657/// A screen reader distinguishes a paragraph break (which it announces
658/// and which occupies a character in the accessible text) from a soft
659/// wrap (which occupies nothing).
660#[derive(Debug, Clone, Copy, PartialEq, Eq)]
661pub enum LineEnd {
662    /// The line was broken to fit the wrap width. Nothing in the source
663    /// separates it from the next line.
664    SoftWrap,
665    /// The line ends with an explicit break in the source: a `\n`, a `\r\n`,
666    /// or any other hard line break of UAX #14 (a carriage return, next
667    /// line, vertical tab, form feed, paragraph separator, or the line
668    /// separator U+2028 a word processor inserts for Shift+Enter).
669    ///
670    /// `chars` is how many source *characters* the break occupies (1, or 2
671    /// for `\r\n`); `bytes` is how many source *bytes* it occupies (1 for
672    /// `\n`, 2 for `\r\n`, 3 for U+2028). AccessKit counts a `\r\n` as a
673    /// single character whose `character_lengths` entry is 2 — that is
674    /// `bytes`.
675    HardBreak { chars: u8, bytes: u8 },
676    /// The line ends because the source does.
677    EndOfText,
678}
679
680impl LineEnd {
681    /// The explicit break `text` ends with, if it ends with one.
682    pub(crate) fn hard_break_ending(text: &str) -> Option<Self> {
683        if text.ends_with("\r\n") {
684            return Some(LineEnd::HardBreak { chars: 2, bytes: 2 });
685        }
686        let last = text.chars().next_back()?;
687        is_hard_break(last).then(|| LineEnd::HardBreak {
688            chars: 1,
689            bytes: last.len_utf8() as u8,
690        })
691    }
692}
693
694/// Whether `c` is a hard line break, after which a line always ends (UAX #14
695/// classes BK, CR, LF and NL): line feed, carriage return, next line,
696/// vertical tab, form feed, line separator (U+2028) and paragraph separator
697/// (U+2029).
698///
699/// It is laid out as nothing: no glyph and no advance. A font that draws one
700/// (some draw U+2028 as a box) would otherwise put it at the end of the line,
701/// and its advance would push a right-aligned or centred line off its place.
702pub(crate) fn is_hard_break(c: char) -> bool {
703    matches!(
704        c,
705        '\n' | '\r' | '\u{0085}' | '\u{000B}' | '\u{000C}' | '\u{2028}' | '\u{2029}'
706    )
707}
708
709/// Where a line's trailing ellipsis was drawn, for a line the layout
710/// truncated.
711#[derive(Debug, Clone, Copy, PartialEq)]
712#[non_exhaustive]
713pub struct LineTruncation {
714    /// Leading edge of the ellipsis glyph, in layout-local coordinates.
715    pub ellipsis_x: f32,
716    /// Advance width of the ellipsis glyph.
717    pub ellipsis_width: f32,
718}
719
720/// One direction-uniform stretch of a laid-out line.
721///
722/// A pure LTR or pure RTL line has exactly one segment; a bidirectional
723/// line has one per direction change, in *logical* order.
724#[derive(Debug, Clone, PartialEq)]
725#[non_exhaustive]
726pub struct LineSegment {
727    /// Byte range of this segment in the source text (or, on the markup
728    /// paths, in [`LayoutGeometry::rendered_text`]).
729    pub byte_range: std::ops::Range<usize>,
730    /// Character range of this segment, in the same text.
731    pub char_range: std::ops::Range<usize>,
732    /// Reading direction of every character in this segment.
733    pub direction: GeometryDirection,
734    /// Bounding box `[x, y, width, height]` in layout-local coordinates, with
735    /// the same origin as [`LineGeometry::rect`].
736    pub rect: [f32; 4],
737    /// One entry per character of `char_range`, in **logical** order.
738    ///
739    /// `position` is measured from the segment's *leading* edge — its
740    /// left edge when [`direction`](Self::direction) is
741    /// [`GeometryDirection::LeftToRight`], its right edge when it is
742    /// [`GeometryDirection::RightToLeft`] — so positions are
743    /// non-decreasing and widths are never negative in both cases.
744    ///
745    /// A character with no advance of its own (a combining mark, the
746    /// interior of a ligature) reports its cluster's leading position and
747    /// a width of `0.0`.
748    pub characters: Vec<CharacterGeometry>,
749}
750
751/// One laid-out visual line.
752#[derive(Debug, Clone, PartialEq)]
753#[non_exhaustive]
754pub struct LineGeometry {
755    /// Zero-based index of this line within the layout.
756    pub index: usize,
757    /// Byte range of the line in the source text, including any trailing
758    /// hard break (see [`LineEnd`]).
759    pub byte_range: std::ops::Range<usize>,
760    /// Character range of the line, in the same text.
761    pub char_range: std::ops::Range<usize>,
762    /// Bounding box `[x, y, width, height]` in layout-local coordinates.
763    /// `y` is the top of the line box, `height` its full line height.
764    ///
765    /// For a line of a laid-out document block, `x` is measured from
766    /// [`BlockVisualInfo::content_x`], the start of the block's text, and `y`
767    /// from the block's top edge.
768    pub rect: [f32; 4],
769    /// Baseline y in layout-local coordinates.
770    pub baseline: f32,
771    /// Where a caret sits on a line with no glyphs of its own — the x the
772    /// first typed character would take, honouring indent, alignment and
773    /// base direction. Like `rect`, it is measured from
774    /// [`BlockVisualInfo::content_x`] for a laid-out document block.
775    pub caret_x: f32,
776    /// Direction-uniform stretches in logical order.
777    ///
778    /// **Empty means unmeasurable, never partial**: a consumer that finds
779    /// no segments must fall back to degenerate geometry for the whole
780    /// line rather than for part of it.
781    pub segments: Vec<LineSegment>,
782    /// How the line ends.
783    pub end: LineEnd,
784    /// Set when the line was cut short and an ellipsis drawn.
785    pub truncation: Option<LineTruncation>,
786}
787
788/// One hyperlink in a markup layout, reported against the rendered text.
789#[derive(Debug, Clone, PartialEq)]
790#[non_exhaustive]
791pub struct LinkGeometry {
792    /// Byte range of the link's label in
793    /// [`LayoutGeometry::rendered_text`] — *not* in the markup source.
794    pub rendered_byte_range: std::ops::Range<usize>,
795    /// The link target.
796    pub url: String,
797}
798
799/// Per-line, per-character geometry for one layout call.
800///
801/// Produced by the `*_with_geometry` layout methods on
802/// [`crate::DocumentFlow`]. Every range in it indexes
803/// [`rendered_text`](Self::rendered_text) when that is `Some` (the markup
804/// paths) and the caller's source text otherwise.
805#[derive(Debug, Clone, Default, PartialEq)]
806#[non_exhaustive]
807pub struct LayoutGeometry {
808    /// One entry per emitted line, in visual top-to-bottom order.
809    pub lines: Vec<LineGeometry>,
810    /// How many further lines the layout produced but did not emit,
811    /// because `max_lines` cut them.
812    pub dropped_lines: usize,
813    /// Byte length of the text every range indexes.
814    pub source_len: usize,
815    /// The text the ranges index, when it differs from the caller's input
816    /// — i.e. on the markup paths, where the syntax has been stripped.
817    /// `None` on the plain-text paths, where the input *is* that text.
818    pub rendered_text: Option<String>,
819    /// Hyperlinks found in the markup, against the rendered text.
820    pub links: Vec<LinkGeometry>,
821}