1use crate::{TextPosition, edit::word_ranges, text_area::grapheme_boundaries};
2use std::{collections::BTreeMap, ops::Range};
3use unicode_bidi::BidiInfo;
4
5#[derive(Clone, Debug, PartialEq)]
7pub struct VisualGrapheme {
8 pub bytes: Range<usize>,
9 pub leading: f32,
10 pub trailing: f32,
11 pub rtl: bool,
12}
13
14impl VisualGrapheme {
15 pub fn span(&self) -> Range<f32> {
16 self.leading.min(self.trailing)..self.leading.max(self.trailing)
17 }
18
19 fn edge(&self, right: bool) -> TextPosition {
20 let trailing = right != self.rtl;
21 TextPosition {
22 offset: if trailing {
23 self.bytes.end
24 } else {
25 self.bytes.start
26 },
27 trailing,
28 }
29 }
30}
31
32#[derive(Clone, Debug, PartialEq)]
34pub struct VisualTextLine {
35 cells: Vec<VisualGrapheme>,
36 visual: Vec<usize>,
37 width: f32,
38 rtl: bool,
39}
40
41impl VisualTextLine {
42 pub fn new(text: &str, glyphs: impl IntoIterator<Item = (usize, f32)>) -> Self {
44 let bidi = BidiInfo::new(text, None);
45 let paragraph = bidi.paragraphs.first();
46 let rtl = paragraph.is_some_and(|paragraph| paragraph.level.is_rtl());
47 let levels = paragraph
48 .filter(|_| bidi.has_rtl())
49 .map(|paragraph| bidi.reordered_levels(paragraph, paragraph.range.clone()));
50 let boundaries = grapheme_boundaries(text);
51 let mut cells: Vec<_> = boundaries
52 .windows(2)
53 .map(|pair| VisualGrapheme {
54 bytes: pair[0]..pair[1],
55 leading: 0.0,
56 trailing: 0.0,
57 rtl: levels
58 .as_ref()
59 .and_then(|levels| levels.get(pair[0]))
60 .is_some_and(|level| level.is_rtl()),
61 })
62 .collect();
63
64 let mut clusters: BTreeMap<usize, Range<f32>> = BTreeMap::new();
65 let mut pen = 0.0_f32;
66 for (byte, advance) in glyphs {
67 if byte >= text.len() || !advance.is_finite() {
68 continue;
69 }
70 let next = pen + advance;
71 let first = boundaries.partition_point(|&boundary| boundary <= byte) - 1;
72 let start = pen.min(next);
73 let end = pen.max(next);
74 clusters
75 .entry(first)
76 .and_modify(|span| {
77 span.start = span.start.min(start);
78 span.end = span.end.max(end);
79 })
80 .or_insert(start..end);
81 pen = next;
82 }
83
84 if let Some((&first, span)) = clusters.first_key_value() {
85 let x = if cells[first].rtl {
86 span.end
87 } else {
88 span.start
89 };
90 for cell in &mut cells[..first] {
91 cell.leading = x;
92 cell.trailing = x;
93 }
94 }
95 let mut clusters = clusters.into_iter().peekable();
96 let cell_count = cells.len();
97 while let Some((start, span)) = clusters.next() {
98 let end = clusters.peek().map_or(cell_count, |(start, _)| *start);
99 let count = (end - start) as f32;
100 let rtl = cells[start].rtl;
101 let (first, last) = if rtl {
102 (span.end, span.start)
103 } else {
104 (span.start, span.end)
105 };
106 let x = |index: usize| first + (last - first) * (index as f32 / count);
109 for (index, cell) in cells[start..end].iter_mut().enumerate() {
110 cell.leading = x(index);
111 cell.trailing = x(index + 1);
112 cell.rtl = rtl;
113 }
114 }
115 let mut visual: Vec<_> = cells
116 .iter()
117 .enumerate()
118 .filter_map(|(index, cell)| (cell.leading != cell.trailing).then_some(index))
119 .collect();
120 visual.sort_by(|&left, &right| {
121 cells[left]
122 .span()
123 .start
124 .total_cmp(&cells[right].span().start)
125 });
126 Self {
127 cells,
128 visual,
129 width: pen.max(0.0),
130 rtl,
131 }
132 }
133
134 pub fn width(&self) -> f32 {
135 self.width
136 }
137 pub fn is_rtl(&self) -> bool {
138 self.rtl
139 }
140 pub fn graphemes(&self) -> &[VisualGrapheme] {
141 &self.cells
142 }
143
144 pub fn caret_x(&self, position: TextPosition) -> f32 {
145 let index = self
146 .cells
147 .partition_point(|cell| cell.bytes.start < position.offset);
148 if let Some(cell) = index
149 .checked_sub(1)
150 .and_then(|previous| self.cells.get(previous))
151 && (position.trailing || index == self.cells.len() || position.offset < cell.bytes.end)
152 {
153 cell.trailing
154 } else {
155 self.cells.get(index).map_or(0.0, |cell| cell.leading)
156 }
157 }
158
159 pub fn hit(&self, x: f32) -> TextPosition {
160 let index = self
161 .visual
162 .partition_point(|&index| self.cells[index].span().end <= x);
163 let Some(&index) = self.visual.get(index).or_else(|| self.visual.last()) else {
164 return TextPosition::default();
165 };
166 let cell = &self.cells[index];
167 cell.edge(x > cell.leading.midpoint(cell.trailing))
168 }
169
170 pub fn edge(&self, right: bool) -> TextPosition {
171 self.hit(if right {
172 f32::INFINITY
173 } else {
174 f32::NEG_INFINITY
175 })
176 }
177
178 fn step_index(&self, position: TextPosition, right: bool) -> Option<usize> {
179 let x = self.caret_x(position);
180 let index = if right {
181 self.visual
182 .partition_point(|&index| self.cells[index].span().end <= x + 0.001)
183 } else {
184 self.visual
185 .partition_point(|&index| self.cells[index].span().start < x - 0.001)
186 .checked_sub(1)?
187 };
188 (index < self.visual.len()).then_some(index)
189 }
190
191 pub fn step(&self, position: TextPosition, right: bool) -> Option<TextPosition> {
192 self.step_index(position, right)
193 .map(|index| self.cells[self.visual[index]].edge(right))
194 }
195
196 pub fn word_step(
198 &self,
199 text: &str,
200 position: TextPosition,
201 right: bool,
202 ) -> Option<TextPosition> {
203 let start = self.step_index(position, right)?;
204 let words: Vec<_> = word_ranges(text).collect();
205 let mut chosen = None;
206 let mut end = None;
207 let indices = std::iter::successors(Some(start), |&index| {
208 if right {
209 (index + 1 < self.visual.len()).then_some(index + 1)
210 } else {
211 index.checked_sub(1)
212 }
213 });
214 for index in indices {
215 let cell = &self.cells[self.visual[index]];
216 let slot = words.partition_point(|word| word.end <= cell.bytes.start);
217 let word = words.get(slot).filter(|word| word.start < cell.bytes.end);
218 if chosen.is_some() && word.map(|_| slot) != chosen {
219 break;
220 }
221 chosen = word.map(|_| slot);
222 end = Some(cell.edge(right));
223 }
224 end
225 }
226
227 fn selected(&self, bytes: Range<usize>) -> impl DoubleEndedIterator<Item = &VisualGrapheme> {
228 self.visual
229 .iter()
230 .map(|&index| &self.cells[index])
231 .filter(move |cell| {
232 !bytes.is_empty() && bytes.start < cell.bytes.end && cell.bytes.start < bytes.end
233 })
234 }
235
236 pub fn selection_edge(&self, bytes: Range<usize>, right: bool) -> Option<TextPosition> {
237 if bytes.is_empty() {
238 return None;
239 }
240 let mut selected = self.selected(bytes);
241 let cell = if right {
242 selected.next_back()
243 } else {
244 selected.next()
245 }?;
246 Some(cell.edge(right))
247 }
248
249 pub fn selection_spans(&self, bytes: Range<usize>) -> Vec<Range<f32>> {
250 let mut spans: Vec<Range<f32>> = Vec::new();
251 if bytes.is_empty() {
252 return spans;
253 }
254 for cell in self.selected(bytes) {
255 let span = cell.span();
256 if let Some(last) = spans.last_mut()
257 && span.start <= last.end + 0.001
258 {
259 last.end = last.end.max(span.end);
260 } else {
261 spans.push(span);
262 }
263 }
264 spans
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271
272 #[test]
273 fn words_follow_shaped_order_across_a_bidirectional_run() {
274 let text = "foo אבג baz";
275 let line = VisualTextLine::new(
276 text,
277 [0, 1, 2, 3, 8, 6, 4, 10, 11, 12, 13].map(|index| (index, 10.0)),
278 );
279 let start = TextPosition {
280 offset: 3,
281 trailing: true,
282 };
283 let position = line.word_step(text, start, true).unwrap();
284 assert_eq!(
285 position,
286 TextPosition {
287 offset: 4,
288 trailing: false
289 }
290 );
291 assert_eq!(line.caret_x(position), 70.0);
292 let position = line.word_step(text, position, true).unwrap();
293 assert_eq!(position.offset, text.len());
294 let position = line.word_step(text, position, false).unwrap();
295 assert_eq!(position.offset, 11);
296 let position = line.word_step(text, position, false).unwrap();
297 assert_eq!(
298 position,
299 TextPosition {
300 offset: 10,
301 trailing: true
302 }
303 );
304 assert_eq!(line.caret_x(position), 40.0);
305 }
306
307 #[test]
308 fn mixed_runs_keep_distinct_caret_edges_and_split_logical_selections() {
309 let line = VisualTextLine::new("aאבb", [0, 3, 1, 5].map(|index| (index, 10.0)));
310 let before = TextPosition {
311 offset: 1,
312 trailing: true,
313 };
314 let after = TextPosition {
315 offset: 1,
316 trailing: false,
317 };
318 assert_eq!(line.caret_x(before), 10.0);
319 assert_eq!(line.caret_x(after), 30.0);
320 assert_eq!(
321 line.hit(22.0),
322 TextPosition {
323 offset: 3,
324 trailing: true
325 }
326 );
327 assert_eq!(
328 line.step(before, true),
329 Some(TextPosition {
330 offset: 3,
331 trailing: false
332 })
333 );
334 assert_eq!(line.selection_spans(0..3), [0.0..10.0, 20.0..30.0]);
335 }
336
337 #[test]
338 fn ligatures_and_combining_marks_preserve_grapheme_boundaries() {
339 let line = VisualTextLine::new("fi", [(0, 12.0)]);
340 assert_eq!(line.hit(6.0).offset, 1);
341 let line = VisualTextLine::new("a\u{301}b", [(0, 8.0), (1, 0.0), (3, 8.0)]);
342 assert_eq!(line.hit(7.0).offset, 3);
343 assert_eq!(line.selection_spans(0..3), [0.0..8.0]);
344 }
345}