1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//! Text selection model: anchor/focus positions, byte↔grapheme mapping,
//! highlight rect computation, and word/line boundary navigation.
use crate::GlyphPosition;
// ── Selection ─────────────────────────────────────────────────────────────────
/// A text selection defined by two byte offsets into the source string.
///
/// When `anchor == focus` the selection is a collapsed caret.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Selection {
/// Byte offset where the selection started (the fixed end).
pub anchor: usize,
/// Byte offset of the current cursor / the moving end.
pub focus: usize,
}
impl Selection {
/// Create a collapsed selection (caret) at `offset`.
pub fn new(offset: usize) -> Self {
Self {
anchor: offset,
focus: offset,
}
}
/// Extend the selection so that the focus moves to `focus`.
pub fn extend_to(&mut self, focus: usize) {
self.focus = focus;
}
/// Returns `true` when anchor and focus are at the same position.
pub fn is_collapsed(&self) -> bool {
self.anchor == self.focus
}
/// Returns `(start, end)` in ascending byte-offset order.
pub fn normalized(&self) -> (usize, usize) {
if self.anchor <= self.focus {
(self.anchor, self.focus)
} else {
(self.focus, self.anchor)
}
}
// ── Grapheme ↔ Byte conversion ────────────────────────────────────────
/// Convert a UTF-8 byte offset to a grapheme cluster index.
///
/// A "grapheme cluster" here is defined as a sequence of bytes whose
/// first byte has the form `0b0xxx_xxxx` (ASCII) or `0b11xx_xxxx`
/// (leading multibyte byte). This is a simplified model; for full
/// Unicode grapheme cluster segmentation use the `unicode-segmentation`
/// crate (not a dependency here per the Pure Rust / no-extra-crate
/// policy).
pub fn byte_to_grapheme(text: &str, byte_offset: usize) -> usize {
let capped = byte_offset.min(text.len());
text[..capped].char_indices().count()
}
/// Convert a grapheme cluster index to the byte offset of its first byte.
pub fn grapheme_to_byte(text: &str, grapheme_idx: usize) -> usize {
text.char_indices()
.nth(grapheme_idx)
.map(|(i, _)| i)
.unwrap_or(text.len())
}
// ── Highlight rects ───────────────────────────────────────────────────
/// Compute highlight rectangles for the selected region.
///
/// Returns `Vec<(x, y, w, h)>` — one rect per line that is (even
/// partially) covered by the selection.
pub fn highlight_rects(
&self,
glyphs: &[Vec<GlyphPosition>],
line_height: f32,
) -> Vec<(f32, f32, f32, f32)> {
if self.is_collapsed() {
return Vec::new();
}
let (sel_start, sel_end) = self.normalized();
let mut rects: Vec<(f32, f32, f32, f32)> = Vec::new();
for line in glyphs {
if line.is_empty() {
continue;
}
// Find glyphs that overlap the selection range.
let mut x_start: Option<f32> = None;
let mut x_end = 0.0_f32;
let mut line_y = 0.0_f32;
for glyph in line {
if glyph.byte_offset >= sel_end {
break;
}
if glyph.byte_offset >= sel_start {
if x_start.is_none() {
x_start = Some(glyph.x);
line_y = glyph.y;
}
x_end = glyph.x + glyph.width;
}
}
if let Some(x0) = x_start {
let w = (x_end - x0).max(1.0);
rects.push((x0, line_y, w, line_height));
}
}
rects
}
// ── Word navigation ───────────────────────────────────────────────────
/// Return the byte offset just past the end of the word that starts at
/// or after `byte_offset`.
pub fn extend_word_forward(text: &str, byte_offset: usize) -> usize {
if byte_offset >= text.len() {
return text.len();
}
let rest = &text[byte_offset..];
// Skip leading whitespace first.
let leading: usize = rest
.char_indices()
.take_while(|(_, c)| c.is_whitespace())
.last()
.map(|(i, c)| i + c.len_utf8())
.unwrap_or(0);
// Then skip to end of next non-whitespace word.
let word_end: usize = rest[leading..]
.char_indices()
.take_while(|(_, c)| !c.is_whitespace())
.last()
.map(|(i, c)| i + c.len_utf8())
.unwrap_or(0);
byte_offset + leading + word_end
}
/// Return the byte offset of the start of the word at or before
/// `byte_offset`.
pub fn extend_word_backward(text: &str, byte_offset: usize) -> usize {
let capped = byte_offset.min(text.len());
let before = &text[..capped];
// Skip trailing whitespace.
let trailing: usize = before
.char_indices()
.rev()
.take_while(|(_, c)| c.is_whitespace())
.last()
.map(|(i, _)| i)
.unwrap_or(capped);
// Then walk back to the start of the preceding non-whitespace word.
let word_start: usize = before[..trailing]
.char_indices()
.rev()
.take_while(|(_, c)| !c.is_whitespace())
.last()
.map(|(i, _)| i)
.unwrap_or(0);
word_start
}
// ── Line navigation ───────────────────────────────────────────────────
/// Return the byte offset of the first glyph on the line that contains
/// `byte_offset`.
pub fn extend_line_start(glyphs: &[Vec<GlyphPosition>], byte_offset: usize) -> usize {
for line in glyphs {
let offsets: Vec<usize> = line.iter().map(|g| g.byte_offset).collect();
if offsets.contains(&byte_offset)
|| (offsets.first().copied().unwrap_or(usize::MAX) <= byte_offset
&& offsets.last().copied().unwrap_or(0) >= byte_offset)
{
return offsets.first().copied().unwrap_or(0);
}
}
0
}
/// Return the byte offset past the last glyph on the line that contains
/// `byte_offset`.
pub fn extend_line_end(glyphs: &[Vec<GlyphPosition>], byte_offset: usize) -> usize {
for line in glyphs {
if line.is_empty() {
continue;
}
let first = line.first().map(|g| g.byte_offset).unwrap_or(usize::MAX);
let last = line.last().map(|g| g.byte_offset).unwrap_or(0);
if first <= byte_offset && byte_offset <= last {
// Offset past the last glyph on this line.
return last + line.last().map(|g| g.width.round() as usize).unwrap_or(1);
}
}
byte_offset
}
}
// ── Tests ─────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn selection_collapsed_is_caret() {
assert!(Selection::new(5).is_collapsed());
}
#[test]
fn selection_extend_not_collapsed() {
let mut sel = Selection::new(0);
sel.extend_to(5);
assert!(!sel.is_collapsed());
}
#[test]
fn selection_normalized_order() {
let sel = Selection {
anchor: 10,
focus: 3,
};
assert_eq!(sel.normalized(), (3, 10));
}
#[test]
fn selection_extend_forward_to_word() {
// "hello world" — start at 0 → forward to end of "hello" = 5
assert_eq!(Selection::extend_word_forward("hello world", 0), 5);
}
#[test]
fn selection_extend_word_forward_skips_whitespace() {
// Start at 5 (space) → skip space, skip "world" → 11
assert_eq!(Selection::extend_word_forward("hello world", 5), 11);
}
#[test]
fn selection_extend_word_backward_basic() {
// "hello world", offset=11 → start of "world" = 6
assert_eq!(Selection::extend_word_backward("hello world", 11), 6);
}
#[test]
fn selection_grapheme_byte_roundtrip() {
let text = "héllo";
for (byte_off, _) in text.char_indices() {
let g = Selection::byte_to_grapheme(text, byte_off);
let recovered = Selection::grapheme_to_byte(text, g);
assert_eq!(recovered, byte_off);
}
}
#[test]
fn selection_highlight_rect_count() {
// Build a fake single-line layout.
let line = vec![
GlyphPosition {
byte_offset: 0,
x: 0.0,
y: 0.0,
width: 10.0,
height: 16.0,
},
GlyphPosition {
byte_offset: 1,
x: 10.0,
y: 0.0,
width: 10.0,
height: 16.0,
},
GlyphPosition {
byte_offset: 2,
x: 20.0,
y: 0.0,
width: 10.0,
height: 16.0,
},
];
let glyphs = vec![line];
let sel = Selection {
anchor: 0,
focus: 3,
};
let rects = sel.highlight_rects(&glyphs, 16.0);
assert!(!rects.is_empty(), "non-empty selection must yield ≥1 rect");
}
#[test]
fn selection_collapsed_no_highlight() {
let glyphs: Vec<Vec<GlyphPosition>> = vec![vec![GlyphPosition {
byte_offset: 0,
x: 0.0,
y: 0.0,
width: 10.0,
height: 16.0,
}]];
let sel = Selection::new(0);
assert!(sel.highlight_rects(&glyphs, 16.0).is_empty());
}
}