1use epaint::text::{ByteIndex, ByteRangeExt as _, CharIndex, Galley, cursor::CCursor};
4use unicode_segmentation::UnicodeSegmentation as _;
5
6use crate::{NumExt as _, Rect, Response, Ui, epaint};
7
8use super::CCursorRange;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub(crate) enum SelectGranularity {
15 Char,
16 Word,
17 Line,
18}
19
20#[derive(Clone, Copy, Debug, PartialEq)]
24pub(crate) struct GranularDragSelect {
25 pub granularity: SelectGranularity,
27
28 pub anchor: CCursorRange,
38}
39
40impl SelectGranularity {
41 pub(crate) fn of_press(ui: &Ui) -> Self {
43 match ui.input(|i| i.pointer.press_click_count()) {
44 0 | 1 => Self::Char,
45 2 => Self::Word,
46 _ => Self::Line,
47 }
48 }
49}
50
51#[derive(Clone, Copy, Debug, Default)]
55#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
56#[cfg_attr(feature = "serde", serde(default))]
57pub struct TextCursorState {
58 ccursor_range: Option<CCursorRange>,
59
60 #[cfg_attr(feature = "serde", serde(skip))]
62 granular_drag: Option<GranularDragSelect>,
63}
64
65impl From<CCursorRange> for TextCursorState {
66 fn from(ccursor_range: CCursorRange) -> Self {
67 Self {
68 ccursor_range: Some(ccursor_range),
69 granular_drag: None,
70 }
71 }
72}
73
74impl TextCursorState {
75 pub fn is_empty(&self) -> bool {
76 self.ccursor_range.is_none()
77 }
78
79 pub fn char_range(&self) -> Option<CCursorRange> {
81 self.ccursor_range
82 }
83
84 pub fn range(&self, galley: &Galley) -> Option<CCursorRange> {
87 self.ccursor_range.map(|mut range| {
88 range.primary = galley.clamp_cursor(&range.primary);
89 range.secondary = galley.clamp_cursor(&range.secondary);
90 range
91 })
92 }
93
94 pub fn set_char_range(&mut self, ccursor_range: Option<CCursorRange>) {
96 let sorted_indices =
97 |range: Option<CCursorRange>| range.map(|r| r.sorted_cursors().map(|c| c.index));
98 if sorted_indices(ccursor_range) != sorted_indices(self.ccursor_range) {
99 self.granular_drag = None;
102 }
103 self.ccursor_range = ccursor_range;
104 }
105
106 pub(crate) fn granular_drag(&self) -> Option<GranularDragSelect> {
108 self.granular_drag
109 }
110
111 pub(crate) fn set_granular_drag(&mut self, granular_drag: Option<GranularDragSelect>) {
115 self.granular_drag = granular_drag;
116 }
117
118 fn anchor_range_within(&self, selection: CCursorRange, text: &str) -> Option<CCursorRange> {
121 let anchor = self.granular_drag?.anchor;
122 let [anchor_min, anchor_max] = anchor.sorted_cursors();
123 let [sel_min, sel_max] = selection.sorted_cursors();
124 let num_chars = text.chars().count();
125 (!anchor.is_empty()
126 && anchor_max.index.0 <= num_chars
127 && sel_min.index <= anchor_min.index
128 && anchor_max.index <= sel_max.index)
129 .then_some(anchor)
130 }
131}
132
133impl TextCursorState {
134 pub fn pointer_interaction(
138 &mut self,
139 ui: &Ui,
140 response: &Response,
141 cursor_at_pointer: CCursor,
142 galley: &Galley,
143 is_being_dragged: bool,
144 ) -> bool {
145 let text = galley.text();
146
147 let shift = ui.input(|i| i.modifiers.shift);
150
151 if response.double_clicked() && !shift {
152 let ccursor_range = select_word_at(text, cursor_at_pointer);
154 self.set_char_range(Some(ccursor_range));
155 true
156 } else if response.triple_clicked() && !shift {
157 let ccursor_range = select_line_at(text, cursor_at_pointer);
159 self.set_char_range(Some(ccursor_range));
160 true
161 } else if response.sense.senses_drag() {
162 if response.hovered() && ui.input(|i| i.pointer.any_pressed()) {
163 let granularity = SelectGranularity::of_press(ui);
167 let existing_range = if shift { self.range(galley) } else { None };
168
169 if let Some(mut cursor_range) = existing_range {
170 let anchor = self
176 .anchor_range_within(cursor_range, text)
177 .unwrap_or_else(|| CCursorRange::one(cursor_range.secondary));
178
179 if granularity == SelectGranularity::Char && anchor.is_empty() {
180 self.granular_drag = None;
182 cursor_range.primary = cursor_at_pointer;
183 self.ccursor_range = Some(cursor_range);
184 } else {
185 self.granular_drag = Some(GranularDragSelect {
187 granularity,
188 anchor,
189 });
190 self.ccursor_range = Some(extend_granular_select(
191 granularity,
192 anchor,
193 text,
194 cursor_at_pointer,
195 ));
196 }
197 } else if granularity == SelectGranularity::Char {
198 self.granular_drag = None;
199 self.ccursor_range = Some(CCursorRange::one(cursor_at_pointer));
200 } else {
201 self.begin_granular_drag(granularity, text, cursor_at_pointer);
202 }
203 true
204 } else if is_being_dragged {
205 if let Some(granular) = self.granular_drag {
207 let new_range = extend_granular_select(
209 granular.granularity,
210 granular.anchor,
211 text,
212 cursor_at_pointer,
213 );
214 self.ccursor_range = Some(new_range);
215 } else if let Some(mut cursor_range) = self.range(galley) {
216 cursor_range.primary = cursor_at_pointer;
217 self.set_char_range(Some(cursor_range));
218 }
219 true
220 } else {
221 false
222 }
223 } else {
224 false
225 }
226 }
227
228 fn begin_granular_drag(
231 &mut self,
232 granularity: SelectGranularity,
233 text: &str,
234 cursor_at_pointer: CCursor,
235 ) {
236 let anchor = select_unit_at(granularity, text, cursor_at_pointer);
237 self.granular_drag = Some(GranularDragSelect {
238 granularity,
239 anchor,
240 });
241 self.ccursor_range = Some(anchor);
242 }
243}
244
245pub(crate) fn select_unit_at(
247 granularity: SelectGranularity,
248 text: &str,
249 ccursor: CCursor,
250) -> CCursorRange {
251 match granularity {
252 SelectGranularity::Char => CCursorRange::one(ccursor),
253 SelectGranularity::Word => select_word_at(text, ccursor),
254 SelectGranularity::Line => select_line_at(text, ccursor),
255 }
256}
257
258pub(crate) fn extend_granular_select(
266 granularity: SelectGranularity,
267 anchor: CCursorRange,
268 text: &str,
269 cursor_at_pointer: CCursor,
270) -> CCursorRange {
271 let unit = select_unit_at(granularity, text, cursor_at_pointer);
272 let [anchor_min, anchor_max] = anchor.sorted_cursors();
273 let [unit_min, unit_max] = unit.sorted_cursors();
274
275 if cursor_at_pointer.index < anchor_min.index {
276 CCursorRange {
278 primary: unit_min,
279 secondary: anchor_max,
280 h_pos: None,
281 }
282 } else if anchor_max.index < cursor_at_pointer.index || anchor.is_empty() {
283 CCursorRange {
285 primary: unit_max,
286 secondary: anchor_min,
287 h_pos: None,
288 }
289 } else {
290 anchor
292 }
293}
294
295fn select_word_at(text: &str, ccursor: CCursor) -> CCursorRange {
296 if text.is_empty() {
297 return CCursorRange::one(ccursor);
298 }
299
300 let line_start = find_line_start(text, ccursor);
301 let line_end = ccursor_next_line(text, line_start);
302
303 let line_range = line_start.index..line_end.index;
304 let current_line_text = slice_char_range(text, line_range.clone());
305
306 let relative_idx = ccursor.index - line_start.index;
307 let relative_ccursor = CCursor::new(relative_idx);
308
309 let min = ccursor_previous_word(current_line_text, relative_ccursor);
310 let max = ccursor_next_word(current_line_text, relative_ccursor);
311
312 CCursorRange::two(
313 CCursor::new(line_start.index + min.index),
314 CCursor::new(line_start.index + max.index),
315 )
316}
317
318fn select_line_at(text: &str, ccursor: CCursor) -> CCursorRange {
319 if ccursor.index == CharIndex::ZERO {
320 CCursorRange::two(ccursor, ccursor_next_line(text, ccursor))
321 } else {
322 let it = text.chars();
323 let mut it = it.skip(ccursor.index.0 - 1);
324 if let Some(char_before_cursor) = it.next() {
325 if let Some(char_after_cursor) = it.next() {
326 if (!is_linebreak(char_before_cursor)) && (!is_linebreak(char_after_cursor)) {
327 let min = ccursor_previous_line(text, ccursor + 1);
328 let max = ccursor_next_line(text, min);
329 CCursorRange::two(min, max)
330 } else if !is_linebreak(char_before_cursor) {
331 let min = ccursor_previous_line(text, ccursor);
332 let max = ccursor_next_line(text, min);
333 CCursorRange::two(min, max)
334 } else if is_linebreak(char_after_cursor) {
335 let min = ccursor_previous_line(text, ccursor);
336 let max = ccursor_next_line(text, ccursor);
337 CCursorRange::two(min, max)
338 } else {
339 let max = ccursor_next_line(text, ccursor);
340 CCursorRange::two(ccursor, max)
341 }
342 } else {
343 let min = ccursor_previous_line(text, ccursor);
344 CCursorRange::two(min, ccursor)
345 }
346 } else {
347 let max = ccursor_next_line(text, ccursor);
348 CCursorRange::two(ccursor, max)
349 }
350 }
351}
352
353pub fn ccursor_next_word(text: &str, ccursor: CCursor) -> CCursor {
354 CCursor {
355 index: next_word_boundary_char_index(text, ccursor.index),
356 prefer_next_row: false,
357 }
358}
359
360fn ccursor_next_line(text: &str, ccursor: CCursor) -> CCursor {
361 CCursor {
362 index: next_line_boundary_char_index(text.chars(), ccursor.index),
363 prefer_next_row: false,
364 }
365}
366
367pub fn ccursor_previous_word(text: &str, ccursor: CCursor) -> CCursor {
368 let num_chars = CharIndex(text.chars().count());
369 let reversed: String = text.graphemes(true).rev().collect();
370 let boundary = next_word_boundary_char_index(&reversed, num_chars - ccursor.index);
371 CCursor {
372 index: num_chars - boundary.min(num_chars),
373 prefer_next_row: true,
374 }
375}
376
377fn ccursor_previous_line(text: &str, ccursor: CCursor) -> CCursor {
378 let num_chars = CharIndex(text.chars().count());
379 let boundary = next_line_boundary_char_index(text.chars().rev(), num_chars - ccursor.index);
380 CCursor {
381 index: num_chars - boundary,
382 prefer_next_row: true,
383 }
384}
385
386fn next_word_boundary_char_index(text: &str, cursor_ci: CharIndex) -> CharIndex {
387 let mut current_char_idx = CharIndex::ZERO;
388
389 for (_word_byte_index, word) in text.split_word_bound_indices() {
390 let word_ci = current_char_idx;
391
392 let mut word_char_count = 0;
395 for chr in word.chars() {
396 let dot_ci = word_ci + word_char_count;
397 if chr == '.' && cursor_ci < dot_ci {
398 return dot_ci;
399 }
400 word_char_count += 1;
401 }
402
403 if cursor_ci < word_ci && !all_word_chars(word) {
408 return word_ci;
409 }
410
411 current_char_idx += word_char_count;
412 }
413
414 current_char_idx
415}
416
417fn all_word_chars(text: &str) -> bool {
418 text.chars().all(is_word_char)
419}
420
421fn next_line_boundary_char_index(
422 it: impl Iterator<Item = char>,
423 mut index: CharIndex,
424) -> CharIndex {
425 let mut it = it.skip(index.0);
426 if let Some(_first) = it.next() {
427 index += 1;
428
429 if let Some(second) = it.next() {
430 index += 1;
431 for next in it {
432 if is_linebreak(next) != is_linebreak(second) {
433 break;
434 }
435 index += 1;
436 }
437 }
438 }
439 index
440}
441
442pub fn is_word_char(c: char) -> bool {
443 c.is_alphanumeric() || c == '_'
444}
445
446fn is_linebreak(c: char) -> bool {
447 c == '\r' || c == '\n'
448}
449
450pub fn find_line_start(text: &str, current_index: CCursor) -> CCursor {
452 let byte_idx = byte_index_from_char_index(text, current_index.index);
453 let text_before = (ByteIndex::ZERO..byte_idx).slice(text);
454
455 if let Some(last_newline_byte) = text_before.rfind('\n') {
456 let char_idx = char_index_from_byte_index(text, ByteIndex(last_newline_byte + 1));
457 CCursor::new(char_idx)
458 } else {
459 CCursor::new(0)
460 }
461}
462
463pub fn byte_index_from_char_index(s: &str, char_index: CharIndex) -> ByteIndex {
464 for (ci, (bi, _)) in s.char_indices().enumerate() {
465 if ci == char_index.0 {
466 return ByteIndex(bi);
467 }
468 }
469 ByteIndex(s.len())
470}
471
472pub fn char_index_from_byte_index(input: &str, byte_index: ByteIndex) -> CharIndex {
473 for (ci, (bi, _)) in input.char_indices().enumerate() {
474 if bi == byte_index.0 {
475 return CharIndex(ci);
476 }
477 }
478
479 CharIndex(input.chars().count())
482}
483
484pub fn slice_char_range(s: &str, char_range: core::ops::Range<CharIndex>) -> &str {
485 assert!(
486 char_range.start <= char_range.end,
487 "Invalid range, start must be less than end, but start = {}, end = {}",
488 char_range.start,
489 char_range.end
490 );
491 let start_byte = byte_index_from_char_index(s, char_range.start);
492 let end_byte = byte_index_from_char_index(s, char_range.end);
493 (start_byte..end_byte).slice(s)
494}
495
496pub fn cursor_rect(galley: &Galley, cursor: &CCursor, row_height: f32) -> Rect {
498 let mut cursor_pos = galley.pos_from_cursor(*cursor);
499
500 cursor_pos.max.y = cursor_pos.max.y.at_least(cursor_pos.min.y + row_height);
502
503 cursor_pos = cursor_pos.expand(1.5); cursor_pos
506}
507
508#[cfg(test)]
509mod test {
510 use super::*;
511
512 #[test]
513 fn test_next_word_boundary_char_index() {
514 let text = "abc d3f g_h i-j";
516 assert_eq!(next_word_boundary_char_index(text, CharIndex(1)).0, 3);
517 assert_eq!(next_word_boundary_char_index(text, CharIndex(3)).0, 7);
518 assert_eq!(next_word_boundary_char_index(text, CharIndex(9)).0, 11);
519 assert_eq!(next_word_boundary_char_index(text, CharIndex(12)).0, 13);
520 assert_eq!(next_word_boundary_char_index(text, CharIndex(13)).0, 15);
521 assert_eq!(next_word_boundary_char_index(text, CharIndex(15)).0, 15);
522
523 assert_eq!(next_word_boundary_char_index("", CharIndex(0)).0, 0);
524 assert_eq!(next_word_boundary_char_index("", CharIndex(1)).0, 0);
525
526 let text = "abc.def.ghi";
528 assert_eq!(next_word_boundary_char_index(text, CharIndex(1)).0, 3);
529 assert_eq!(next_word_boundary_char_index(text, CharIndex(3)).0, 7);
530 assert_eq!(next_word_boundary_char_index(text, CharIndex(7)).0, 11);
531
532 let text = "β€οΈπ skvΔlΓ‘ knihovna πβ€οΈ";
538 assert_eq!(next_word_boundary_char_index(text, CharIndex(0)).0, 2);
539 assert_eq!(next_word_boundary_char_index(text, CharIndex(2)).0, 3); assert_eq!(next_word_boundary_char_index(text, CharIndex(6)).0, 10);
541 assert_eq!(next_word_boundary_char_index(text, CharIndex(9)).0, 10);
542 assert_eq!(next_word_boundary_char_index(text, CharIndex(12)).0, 19);
543 assert_eq!(next_word_boundary_char_index(text, CharIndex(15)).0, 19);
544 assert_eq!(next_word_boundary_char_index(text, CharIndex(19)).0, 20);
545 assert_eq!(next_word_boundary_char_index(text, CharIndex(20)).0, 21);
546 }
547
548 #[test]
549 fn test_previous_word() {
550 let text = "abc def ghi";
551 assert_eq!(ccursor_previous_word(text, CCursor::new(7)).index.0, 4);
552 assert_eq!(ccursor_previous_word(text, CCursor::new(5)).index.0, 4);
553 assert_eq!(ccursor_previous_word(text, CCursor::new(4)).index.0, 0);
554 assert_eq!(ccursor_previous_word(text, CCursor::new(0)).index.0, 0);
555 }
556
557 #[test]
558 fn test_next_word() {
559 let text = "abc def ghi";
560 assert_eq!(ccursor_next_word(text, CCursor::new(0)).index.0, 3);
561 assert_eq!(ccursor_next_word(text, CCursor::new(3)).index.0, 7);
562 assert_eq!(ccursor_next_word(text, CCursor::new(7)).index.0, 11);
563 assert_eq!(ccursor_next_word(text, CCursor::new(11)).index.0, 11);
564 }
565
566 #[test]
567 fn test_index_conversion_roundtrip() {
568 let text = "aΓ©πb";
570 let char_count = text.chars().count(); assert_eq!(char_count, 4);
572
573 assert_eq!(byte_index_from_char_index(text, CharIndex(0)).0, 0);
575 assert_eq!(byte_index_from_char_index(text, CharIndex(1)).0, 1);
576 assert_eq!(byte_index_from_char_index(text, CharIndex(2)).0, 3);
577 assert_eq!(byte_index_from_char_index(text, CharIndex(3)).0, 7);
578 assert_eq!(byte_index_from_char_index(text, CharIndex(4)).0, 8);
579 assert_eq!(
581 byte_index_from_char_index(text, CharIndex(99)).0,
582 text.len()
583 );
584
585 assert_eq!(char_index_from_byte_index(text, ByteIndex(0)).0, 0);
587 assert_eq!(char_index_from_byte_index(text, ByteIndex(1)).0, 1);
588 assert_eq!(char_index_from_byte_index(text, ByteIndex(3)).0, 2);
589 assert_eq!(char_index_from_byte_index(text, ByteIndex(7)).0, 3);
590 assert_eq!(char_index_from_byte_index(text, ByteIndex(text.len())).0, 4);
592 assert_eq!(char_index_from_byte_index(text, ByteIndex(99)).0, 4);
594
595 assert_eq!(byte_index_from_char_index("", CharIndex(0)).0, 0);
597 assert_eq!(char_index_from_byte_index("", ByteIndex(0)).0, 0);
598 }
599
600 #[test]
601 fn test_select_word_at() {
602 let text = "hello world";
604 let range = select_word_at(text, CCursor::new(2));
605 let (lo, hi) = (
606 range.primary.index.min(range.secondary.index),
607 range.primary.index.max(range.secondary.index),
608 );
609 assert_eq!(lo.0, 0);
610 assert_eq!(hi.0, 5);
611
612 let range = select_word_at(text, CCursor::new(8));
613 let (lo, hi) = (
614 range.primary.index.min(range.secondary.index),
615 range.primary.index.max(range.secondary.index),
616 );
617 assert_eq!(lo.0, 6);
618 assert_eq!(hi.0, 11);
619 }
620
621 #[test]
622 fn test_extend_granular_select_words() {
623 let text = "alpha beta gamma";
624 let anchor = select_word_at(text, CCursor::new(8)); assert_eq!(anchor.slice_str(text), "beta");
626
627 let range = extend_granular_select(SelectGranularity::Word, anchor, text, CCursor::new(13));
629 assert_eq!(range.slice_str(text), "beta gamma");
630 assert_eq!(
631 range.primary.index.0, 16,
632 "primary should be at the pointer end"
633 );
634
635 let range = extend_granular_select(SelectGranularity::Word, anchor, text, CCursor::new(2));
637 assert_eq!(range.slice_str(text), "alpha beta");
638 assert_eq!(
639 range.primary.index.0, 0,
640 "primary should be at the pointer end"
641 );
642
643 let range = extend_granular_select(SelectGranularity::Word, anchor, text, CCursor::new(7));
645 assert_eq!(range.slice_str(text), "beta");
646 }
647
648 #[test]
649 fn test_extend_granular_select_lines() {
650 let text = "first\nsecond\nthird";
651 let anchor = select_line_at(text, CCursor::new(8)); assert_eq!(anchor.slice_str(text), "second");
653
654 let range = extend_granular_select(SelectGranularity::Line, anchor, text, CCursor::new(15));
655 assert_eq!(range.slice_str(text), "second\nthird");
656
657 let range = extend_granular_select(SelectGranularity::Line, anchor, text, CCursor::new(2));
658 assert_eq!(range.slice_str(text), "first\nsecond");
659 }
660
661 #[test]
662 fn test_word_boundary_large_text_performance() {
663 let large_text = "word ".repeat(200_000); let len = large_text.chars().count();
666
667 let start = std::time::Instant::now();
668
669 let next = ccursor_next_word(&large_text, CCursor::new(len - 10));
670 assert!(next.index.0 <= len);
671
672 let prev = ccursor_previous_word(&large_text, CCursor::new(len - 10));
673 assert!(prev.index.0 < len);
674
675 let range = select_word_at(&large_text, CCursor::new(len - 3));
676 let lo = range.primary.index.min(range.secondary.index);
677 let hi = range.primary.index.max(range.secondary.index);
678 assert!(lo < hi, "Expected a non-empty word selection");
679
680 let elapsed = start.elapsed();
681 assert!(
682 elapsed.as_secs() < 5,
683 "Word boundary operations on 1MB text took {elapsed:?}, expected < 5s"
684 );
685 }
686}
687
688#[cfg(test)]
689mod tests {
690 use super::*;
691
692 #[test]
693 fn test_previous_word_graphemes() {
694 let cases = [
695 ("", 0, 0),
696 ("hello", 0, 0),
697 ("hello", "hello".chars().count(), 0),
698 ("hello world", 6, 0),
699 ("hello world", 8, 6),
700 ("hello world", "hello world".chars().count(), 6),
701 ("hello world ", "hello world ".chars().count(), 6),
702 ("hello world", "hello world".chars().count(), 8),
703 (" ", " ".chars().count(), 0),
704 ("hello, world", "hello, world".chars().count(), 7),
705 ("www.example.com", "www.example.com".chars().count(), 12),
706 ("μλ
! π μΈμ", 8, 6),
707 ("β€οΈπ skvΔlΓ‘ knihovna πβ€οΈ", 18, 11),
708 (
709 "a e\u{301} b",
710 "a e\u{301} b".chars().count(),
711 "a e\u{301} ".chars().count(),
712 ),
713 (
714 "hi π world",
715 "hi π world".chars().count(),
716 "hi π ".chars().count(),
717 ),
718 (
719 "hi π¨βπ©βπ§βπ¦ world",
720 "hi π¨βπ©βπ§βπ¦ world".chars().count(),
721 "hi π¨βπ©βπ§βπ¦ ".chars().count(),
722 ),
723 ];
724
725 for (text, cursor, expected) in cases {
726 let result = ccursor_previous_word(text, CCursor::new(cursor));
727 assert_eq!(
728 result.index.0, expected,
729 "text={text:?}, cursor={cursor}, got={}, expected={expected}",
730 result.index.0
731 );
732 }
733 }
734}