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