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    /// How many characters at the end of `char_range` are the hard line
69    /// break the line ends with: 0 when it wraps or ends the text, 1 for a
70    /// `\n` or a line separator (U+2028, Shift+Enter in a word processor),
71    /// 2 for `\r\n`.
72    ///
73    /// The caret never sits after them on this line (see
74    /// [`caret_end`](Self::caret_end)).
75    pub hard_break_chars: usize,
76}
77
78impl LayoutLine {
79    /// The last offset the caret takes on this line: the end of its text,
80    /// before the hard break it ends with.
81    ///
82    /// At a soft wrap the offset where one line ends and the next starts
83    /// belongs to both, and affinity picks one. After a hard break it is the
84    /// next line's start and nothing else: drawn at the end of this line, a
85    /// caret there typed onto the next one, and End put it after the break.
86    pub fn caret_end(&self) -> usize {
87        self.char_range.end
88            - self
89                .hard_break_chars
90                .min(self.char_range.end - self.char_range.start)
91    }
92
93    /// Whether the caret at `offset` (in the block's text) can sit on this
94    /// line: from its start to its end, short of the offset after the hard
95    /// break it ends with, which is the next line's. The offset inside a
96    /// `\r\n` is this line's, drawn at its end.
97    pub(crate) fn holds_caret_at(&self, offset: usize) -> bool {
98        offset >= self.char_range.start
99            && if self.hard_break_chars > 0 && self.char_range.end > self.char_range.start {
100                offset < self.char_range.end
101            } else {
102                offset <= self.char_range.end
103            }
104    }
105
106    /// End (exclusive) of the cluster starting at char offset `cluster`:
107    /// the smallest distinct glyph cluster in the line strictly greater
108    /// than `cluster`, or the line's `char_range.end` if none is larger.
109    ///
110    /// Clusters across the whole line are the complete set of logical
111    /// char-offset boundaries, so the next-larger one is exactly where
112    /// `cluster`'s char span ends — true for LTR, RTL, and multi-char
113    /// (ligature) clusters alike.
114    pub(crate) fn cluster_end(&self, cluster: usize) -> usize {
115        let mut best: Option<usize> = None;
116        for run in &self.runs {
117            for g in &run.shaped_run.glyphs {
118                let c = g.cluster as usize;
119                if c > cluster {
120                    best = Some(best.map_or(c, |b| b.min(c)));
121                }
122            }
123        }
124        best.unwrap_or(self.char_range.end)
125    }
126
127    /// Find the x coordinate for a char offset within this line.
128    ///
129    /// Equivalent to [`Self::x_for_offset_with_affinity`] with the
130    /// default (downstream) affinity — the caret attaches to the text
131    /// *before* the offset.
132    pub fn x_for_offset(&self, offset: usize) -> f32 {
133        self.x_for_offset_with_affinity(offset, CursorAffinity::default())
134    }
135
136    /// Find the x coordinate for a char offset, disambiguating a
137    /// direction boundary with `affinity`.
138    ///
139    /// Builds the line's caret stops in visual order — direction-aware,
140    /// so an RTL run's caret for its lowest offset sits at its rightmost
141    /// edge — then returns the x of the stop matching `offset`.
142    ///
143    /// One offset can produce **two** stops. Where an LTR run meets an
144    /// RTL one, the boundary offset is both the trailing edge of the run
145    /// before it and the leading edge of the run after it, and those sit
146    /// at completely different x — often at opposite ends of the line.
147    /// Neither is "the" answer: which one the writer means depends on
148    /// which side they arrived from, so it is the caller's to say.
149    /// Picking the leftmost, as this used to, put the caret at the far
150    /// end of the line whenever the seam ran the other way.
151    ///
152    /// `Downstream` attaches the caret to the text before the offset (the
153    /// trailing stop), `Upstream` to the text after it (the leading
154    /// stop) — the same "before or after" question affinity already
155    /// answers at a soft-wrap boundary.
156    pub fn x_for_offset_with_affinity(&self, offset: usize, affinity: CursorAffinity) -> f32 {
157        let stops = self.caret_stops();
158        if stops.is_empty() {
159            // An empty line has no glyph to anchor to; use the position the
160            // first typed character would lay out at, so the caret does not
161            // jump on the first keystroke of an indented / aligned paragraph.
162            return self.empty_caret_x;
163        }
164
165        let exact: Vec<&CaretStop> = stops.iter().filter(|s| s.offset == offset).collect();
166        if let Some(stop) = pick_by_affinity(&exact, affinity) {
167            return stop.x;
168        }
169
170        // No exact stop (e.g. offset inside a multi-char cluster): snap to
171        // the nearest stop by logical distance.
172        stops
173            .iter()
174            .min_by_key(|s| s.offset.abs_diff(offset))
175            .map(|s| s.x)
176            .unwrap_or(0.0)
177    }
178
179    /// Whether `offset` sits on a direction boundary within this line —
180    /// i.e. whether [`Self::x_for_offset_with_affinity`] would return
181    /// different x for the two affinities.
182    ///
183    /// The widget layer needs this to know when moving the caret across
184    /// a seam has to flip affinity rather than leave it alone.
185    pub fn is_direction_boundary(&self, offset: usize) -> bool {
186        let stops = self.caret_stops();
187        let mut xs = stops.iter().filter(|s| s.offset == offset).map(|s| s.x);
188        let Some(first) = xs.next() else {
189            return false;
190        };
191        xs.any(|x| x != first)
192    }
193
194    /// Caret stops across the line in visual (left-to-right) order. For
195    /// an LTR run each glyph contributes a stop at its left edge (the
196    /// glyph's own cluster) plus a trailing stop at the run's right edge;
197    /// for an RTL run the leftmost edge is the trailing (highest) offset
198    /// and each glyph's right edge is its own (leading) offset.
199    pub(crate) fn caret_stops(&self) -> Vec<CaretStop> {
200        let mut stops: Vec<CaretStop> = Vec::new();
201        for run in &self.runs {
202            let glyphs = &run.shaped_run.glyphs;
203            if glyphs.is_empty() {
204                continue;
205            }
206            let mut gx = run.x;
207            if run.shaped_run.direction == TextDirection::RightToLeft {
208                // Leftmost edge: caret after the last logical char in the run.
209                stops.push(CaretStop {
210                    offset: self.cluster_end(glyphs[0].cluster as usize),
211                    x: gx,
212                    trailing: true,
213                });
214                for g in glyphs {
215                    gx += g.x_advance;
216                    stops.push(CaretStop {
217                        offset: g.cluster as usize,
218                        x: gx,
219                        trailing: false,
220                    });
221                }
222            } else {
223                for g in glyphs {
224                    stops.push(CaretStop {
225                        offset: g.cluster as usize,
226                        x: gx,
227                        trailing: false,
228                    });
229                    gx += g.x_advance;
230                }
231                // Rightmost edge: caret after the last logical char in the run.
232                let last = glyphs.last().map(|g| g.cluster as usize).unwrap_or(0);
233                stops.push(CaretStop {
234                    offset: self.cluster_end(last),
235                    x: gx,
236                    trailing: true,
237                });
238            }
239        }
240        stops
241    }
242}
243
244#[derive(Clone)]
245pub struct PositionedRun {
246    pub shaped_run: ShapedRun,
247    /// X offset from the left edge of the content area.
248    pub x: f32,
249    /// Decoration flags for this run.
250    pub decorations: RunDecorations,
251}
252
253/// Text decoration flags and metadata carried from the source TextFormat.
254#[derive(Clone, Debug, Default)]
255pub struct RunDecorations {
256    pub underline_style: crate::types::UnderlineStyle,
257    pub overline: bool,
258    pub strikeout: bool,
259    pub is_link: bool,
260    /// Text foreground color (RGBA). None means default (black).
261    pub foreground_color: Option<[f32; 4]>,
262    /// Underline color (RGBA). None means use foreground_color.
263    pub underline_color: Option<[f32; 4]>,
264    /// Text-level background highlight color (RGBA). None means transparent.
265    pub background_color: Option<[f32; 4]>,
266    /// Hyperlink destination URL.
267    pub anchor_href: Option<String>,
268    /// Tooltip text.
269    pub tooltip: Option<String>,
270    /// Vertical alignment (normal, superscript, subscript).
271    pub vertical_alignment: crate::types::VerticalAlignment,
272}