Skip to main content

text_typeset/layout/
line.rs

1use std::ops::Range;
2
3use crate::shaping::run::ShapedRun;
4use crate::shaping::shaper::TextDirection;
5use crate::types::CursorAffinity;
6
7/// One place the caret can sit on a line: a logical offset, the x it
8/// renders at, and which side of its run produced it.
9///
10/// `trailing` is what makes a direction boundary resolvable. A boundary
11/// offset appears twice — once as the trailing edge of the run before it
12/// and once as the leading edge of the run after — and the two sit at
13/// different x. Recording which is which lets the caller pick by
14/// affinity instead of by whichever happened to be leftmost.
15#[derive(Clone, Copy, Debug)]
16pub(crate) struct CaretStop {
17    pub offset: usize,
18    pub x: f32,
19    /// This stop is the *end* of its run's logical extent.
20    pub trailing: bool,
21}
22
23/// Choose among the stops that share one offset.
24///
25/// With a single candidate there is nothing to disambiguate. With two —
26/// a direction boundary — `Downstream` attaches the caret to the text
27/// before the offset (the trailing stop) and `Upstream` to the text
28/// after it (the leading stop). Falls back to the first candidate if the
29/// expected side is absent, so a malformed line still yields a caret.
30fn pick_by_affinity<'a>(
31    stops: &[&'a CaretStop],
32    affinity: CursorAffinity,
33) -> Option<&'a CaretStop> {
34    if stops.len() < 2 {
35        return stops.first().copied();
36    }
37    let want_trailing = affinity == CursorAffinity::Downstream;
38    stops
39        .iter()
40        .find(|s| s.trailing == want_trailing)
41        .or_else(|| stops.first())
42        .copied()
43}
44
45#[derive(Clone)]
46pub struct LayoutLine {
47    pub runs: Vec<PositionedRun>,
48    /// Baseline y relative to block top (set by block layout).
49    pub y: f32,
50    pub ascent: f32,
51    pub descent: f32,
52    pub leading: f32,
53    /// Total line height: ascent + descent + leading.
54    pub line_height: f32,
55    /// Actual content width (sum of run advances).
56    pub width: f32,
57    /// Character range in the block's text.
58    pub char_range: Range<usize>,
59    /// Where the caret sits when this line has no glyphs to derive a
60    /// position from — the x the first typed character's glyph would take,
61    /// honouring first-line indent, alignment and base direction (see
62    /// `empty_line_caret_x` in paragraph.rs). Without it an empty
63    /// paragraph's caret fell back to 0.0, flush left, and jumped to the
64    /// indent on the first keystroke. Only meaningful when `runs` yield no
65    /// caret stops; `build_line` records the line's start x for the
66    /// degenerate run-without-glyphs case.
67    pub empty_caret_x: f32,
68}
69
70impl LayoutLine {
71    /// End (exclusive) of the cluster starting at char offset `cluster`:
72    /// the smallest distinct glyph cluster in the line strictly greater
73    /// than `cluster`, or the line's `char_range.end` if none is larger.
74    ///
75    /// Clusters across the whole line are the complete set of logical
76    /// char-offset boundaries, so the next-larger one is exactly where
77    /// `cluster`'s char span ends — true for LTR, RTL, and multi-char
78    /// (ligature) clusters alike.
79    pub(crate) fn cluster_end(&self, cluster: usize) -> usize {
80        let mut best: Option<usize> = None;
81        for run in &self.runs {
82            for g in &run.shaped_run.glyphs {
83                let c = g.cluster as usize;
84                if c > cluster {
85                    best = Some(best.map_or(c, |b| b.min(c)));
86                }
87            }
88        }
89        best.unwrap_or(self.char_range.end)
90    }
91
92    /// Find the x coordinate for a char offset within this line.
93    ///
94    /// Equivalent to [`Self::x_for_offset_with_affinity`] with the
95    /// default (downstream) affinity — the caret attaches to the text
96    /// *before* the offset.
97    pub fn x_for_offset(&self, offset: usize) -> f32 {
98        self.x_for_offset_with_affinity(offset, CursorAffinity::default())
99    }
100
101    /// Find the x coordinate for a char offset, disambiguating a
102    /// direction boundary with `affinity`.
103    ///
104    /// Builds the line's caret stops in visual order — direction-aware,
105    /// so an RTL run's caret for its lowest offset sits at its rightmost
106    /// edge — then returns the x of the stop matching `offset`.
107    ///
108    /// One offset can produce **two** stops. Where an LTR run meets an
109    /// RTL one, the boundary offset is both the trailing edge of the run
110    /// before it and the leading edge of the run after it, and those sit
111    /// at completely different x — often at opposite ends of the line.
112    /// Neither is "the" answer: which one the writer means depends on
113    /// which side they arrived from, so it is the caller's to say.
114    /// Picking the leftmost, as this used to, put the caret at the far
115    /// end of the line whenever the seam ran the other way.
116    ///
117    /// `Downstream` attaches the caret to the text before the offset (the
118    /// trailing stop), `Upstream` to the text after it (the leading
119    /// stop) — the same "before or after" question affinity already
120    /// answers at a soft-wrap boundary.
121    pub fn x_for_offset_with_affinity(&self, offset: usize, affinity: CursorAffinity) -> f32 {
122        let stops = self.caret_stops();
123        if stops.is_empty() {
124            // An empty line has no glyph to anchor to; use the position the
125            // first typed character would lay out at, so the caret does not
126            // jump on the first keystroke of an indented / aligned paragraph.
127            return self.empty_caret_x;
128        }
129
130        let exact: Vec<&CaretStop> = stops.iter().filter(|s| s.offset == offset).collect();
131        if let Some(stop) = pick_by_affinity(&exact, affinity) {
132            return stop.x;
133        }
134
135        // No exact stop (e.g. offset inside a multi-char cluster): snap to
136        // the nearest stop by logical distance.
137        stops
138            .iter()
139            .min_by_key(|s| s.offset.abs_diff(offset))
140            .map(|s| s.x)
141            .unwrap_or(0.0)
142    }
143
144    /// Whether `offset` sits on a direction boundary within this line —
145    /// i.e. whether [`Self::x_for_offset_with_affinity`] would return
146    /// different x for the two affinities.
147    ///
148    /// The widget layer needs this to know when moving the caret across
149    /// a seam has to flip affinity rather than leave it alone.
150    pub fn is_direction_boundary(&self, offset: usize) -> bool {
151        let stops = self.caret_stops();
152        let mut xs = stops.iter().filter(|s| s.offset == offset).map(|s| s.x);
153        let Some(first) = xs.next() else {
154            return false;
155        };
156        xs.any(|x| x != first)
157    }
158
159    /// Caret stops across the line in visual (left-to-right) order. For
160    /// an LTR run each glyph contributes a stop at its left edge (the
161    /// glyph's own cluster) plus a trailing stop at the run's right edge;
162    /// for an RTL run the leftmost edge is the trailing (highest) offset
163    /// and each glyph's right edge is its own (leading) offset.
164    pub(crate) fn caret_stops(&self) -> Vec<CaretStop> {
165        let mut stops: Vec<CaretStop> = Vec::new();
166        for run in &self.runs {
167            let glyphs = &run.shaped_run.glyphs;
168            if glyphs.is_empty() {
169                continue;
170            }
171            let mut gx = run.x;
172            if run.shaped_run.direction == TextDirection::RightToLeft {
173                // Leftmost edge: caret after the last logical char in the run.
174                stops.push(CaretStop {
175                    offset: self.cluster_end(glyphs[0].cluster as usize),
176                    x: gx,
177                    trailing: true,
178                });
179                for g in glyphs {
180                    gx += g.x_advance;
181                    stops.push(CaretStop {
182                        offset: g.cluster as usize,
183                        x: gx,
184                        trailing: false,
185                    });
186                }
187            } else {
188                for g in glyphs {
189                    stops.push(CaretStop {
190                        offset: g.cluster as usize,
191                        x: gx,
192                        trailing: false,
193                    });
194                    gx += g.x_advance;
195                }
196                // Rightmost edge: caret after the last logical char in the run.
197                let last = glyphs.last().map(|g| g.cluster as usize).unwrap_or(0);
198                stops.push(CaretStop {
199                    offset: self.cluster_end(last),
200                    x: gx,
201                    trailing: true,
202                });
203            }
204        }
205        stops
206    }
207}
208
209#[derive(Clone)]
210pub struct PositionedRun {
211    pub shaped_run: ShapedRun,
212    /// X offset from the left edge of the content area.
213    pub x: f32,
214    /// Decoration flags for this run.
215    pub decorations: RunDecorations,
216}
217
218/// Text decoration flags and metadata carried from the source TextFormat.
219#[derive(Clone, Debug, Default)]
220pub struct RunDecorations {
221    pub underline_style: crate::types::UnderlineStyle,
222    pub overline: bool,
223    pub strikeout: bool,
224    pub is_link: bool,
225    /// Text foreground color (RGBA). None means default (black).
226    pub foreground_color: Option<[f32; 4]>,
227    /// Underline color (RGBA). None means use foreground_color.
228    pub underline_color: Option<[f32; 4]>,
229    /// Text-level background highlight color (RGBA). None means transparent.
230    pub background_color: Option<[f32; 4]>,
231    /// Hyperlink destination URL.
232    pub anchor_href: Option<String>,
233    /// Tooltip text.
234    pub tooltip: Option<String>,
235    /// Vertical alignment (normal, superscript, subscript).
236    pub vertical_alignment: crate::types::VerticalAlignment,
237}