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