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