egui 0.37.0

An easy-to-use immediate mode GUI that runs on both web and native
Documentation
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
//! Text cursor changes/interaction, without modifying the text.

use epaint::text::{ByteIndex, ByteRangeExt as _, CharIndex, Galley, cursor::CCursor};
use unicode_segmentation::UnicodeSegmentation as _;

use crate::{NumExt as _, Rect, Response, Ui, epaint};

use super::CCursorRange;

/// The unit by which a click or mouse-drag extends a text selection:
/// characters after a single click, whole words after a double-click,
/// whole lines after a triple-click.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SelectGranularity {
    Char,
    Word,
    Line,
}

/// A selection that started with a double- or triple-click,
/// remembered so that dragging and shift-clicking extend it by whole words or lines
/// while always keeping the originally clicked word or line selected.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct GranularDragSelect {
    /// The unit of the current gesture (e.g. a shift-click extends by characters).
    pub granularity: SelectGranularity,

    /// The word or line that was initially double- or triple-clicked.
    ///
    /// Extending the selection before this range keeps its end fixed,
    /// and extending it after this range keeps its start fixed,
    /// so the anchor word or line always stays selected (like on macOS).
    ///
    /// For a shift-double-click (or triple-click) of a selection
    /// that did not start with a double- or triple-click,
    /// this is instead the (empty) far end of the selection that is being extended.
    pub anchor: CCursorRange,
}

impl SelectGranularity {
    /// The granularity of the current press: by characters, words, or lines.
    pub(crate) fn of_press(ui: &Ui) -> Self {
        match ui.input(|i| i.pointer.press_click_count()) {
            0 | 1 => Self::Char,
            2 => Self::Word,
            _ => Self::Line,
        }
    }
}

/// The state of a text cursor selection.
///
/// Used for [`crate::TextEdit`] and [`crate::Label`].
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct TextCursorState {
    ccursor_range: Option<CCursorRange>,

    /// Transient state of the current mouse gesture, so not serialized.
    #[cfg_attr(feature = "serde", serde(skip))]
    granular_drag: Option<GranularDragSelect>,
}

impl From<CCursorRange> for TextCursorState {
    fn from(ccursor_range: CCursorRange) -> Self {
        Self {
            ccursor_range: Some(ccursor_range),
            granular_drag: None,
        }
    }
}

impl TextCursorState {
    pub fn is_empty(&self) -> bool {
        self.ccursor_range.is_none()
    }

    /// The currently selected range of characters.
    pub fn char_range(&self) -> Option<CCursorRange> {
        self.ccursor_range
    }

    /// The currently selected range of characters, clamped within the character
    /// range of the given [`Galley`].
    pub fn range(&self, galley: &Galley) -> Option<CCursorRange> {
        self.ccursor_range.map(|mut range| {
            range.primary = galley.clamp_cursor(&range.primary);
            range.secondary = galley.clamp_cursor(&range.secondary);
            range
        })
    }

    /// Sets the currently selected range of characters.
    pub fn set_char_range(&mut self, ccursor_range: Option<CCursorRange>) {
        let sorted_indices =
            |range: Option<CCursorRange>| range.map(|r| r.sorted_cursors().map(|c| c.index));
        if sorted_indices(ccursor_range) != sorted_indices(self.ccursor_range) {
            // The selection was changed by something else than the mouse (e.g. typing),
            // so forget the double- or triple-clicked word or line that anchored it:
            self.granular_drag = None;
        }
        self.ccursor_range = ccursor_range;
    }

    /// If the selection started with a double- or triple-click, the word or line that anchors it.
    pub(crate) fn granular_drag(&self) -> Option<GranularDragSelect> {
        self.granular_drag
    }

    /// Restore the anchor of a selection that started with a double- or triple-click.
    ///
    /// Used by labels, whose [`TextCursorState`] is recreated each pass.
    pub(crate) fn set_granular_drag(&mut self, granular_drag: Option<GranularDragSelect>) {
        self.granular_drag = granular_drag;
    }

    /// The remembered double- or triple-clicked word or line,
    /// if it is still non-empty and part of the given selection.
    fn anchor_range_within(&self, selection: CCursorRange, text: &str) -> Option<CCursorRange> {
        let anchor = self.granular_drag?.anchor;
        let [anchor_min, anchor_max] = anchor.sorted_cursors();
        let [sel_min, sel_max] = selection.sorted_cursors();
        let num_chars = text.chars().count();
        (!anchor.is_empty()
            && anchor_max.index.0 <= num_chars
            && sel_min.index <= anchor_min.index
            && anchor_max.index <= sel_max.index)
            .then_some(anchor)
    }
}

impl TextCursorState {
    /// Handle clicking and/or dragging text.
    ///
    /// Returns `true` if there was interaction.
    pub fn pointer_interaction(
        &mut self,
        ui: &Ui,
        response: &Response,
        cursor_at_pointer: CCursor,
        galley: &Galley,
        is_being_dragged: bool,
    ) -> bool {
        let text = galley.text();

        // Shift-click extends the existing selection (handled on press, below),
        // so don't replace it with the clicked word/line when the click is released:
        let shift = ui.input(|i| i.modifiers.shift);

        if response.double_clicked() && !shift {
            // Select word:
            let ccursor_range = select_word_at(text, cursor_at_pointer);
            self.set_char_range(Some(ccursor_range));
            true
        } else if response.triple_clicked() && !shift {
            // Select line:
            let ccursor_range = select_line_at(text, cursor_at_pointer);
            self.set_char_range(Some(ccursor_range));
            true
        } else if response.sense.senses_drag() {
            if response.hovered() && ui.input(|i| i.pointer.any_pressed()) {
                // The start of a drag (or a click).
                // Clicks are counted on release, but for double-click-and-drag
                // we need to select the word (or line) already on the second (or third) press:
                let granularity = SelectGranularity::of_press(ui);
                let existing_range = if shift { self.range(galley) } else { None };

                if let Some(mut cursor_range) = existing_range {
                    // Shift-click: extend the selection, by characters, words, or lines.
                    // If the selection started with a double- or triple-click,
                    // the clicked word/line stays selected, even if we now extend the selection
                    // in the other direction (like on macOS).
                    // Otherwise the far end (secondary) of the selection stays fixed.
                    let anchor = self
                        .anchor_range_within(cursor_range, text)
                        .unwrap_or_else(|| CCursorRange::one(cursor_range.secondary));

                    if granularity == SelectGranularity::Char && anchor.is_empty() {
                        // Plain shift-click of a plain selection:
                        self.granular_drag = None;
                        cursor_range.primary = cursor_at_pointer;
                        self.ccursor_range = Some(cursor_range);
                    } else {
                        // A subsequent drag continues extending by the same granularity:
                        self.granular_drag = Some(GranularDragSelect {
                            granularity,
                            anchor,
                        });
                        self.ccursor_range = Some(extend_granular_select(
                            granularity,
                            anchor,
                            text,
                            cursor_at_pointer,
                        ));
                    }
                } else if granularity == SelectGranularity::Char {
                    self.granular_drag = None;
                    self.ccursor_range = Some(CCursorRange::one(cursor_at_pointer));
                } else {
                    self.begin_granular_drag(granularity, text, cursor_at_pointer);
                }
                true
            } else if is_being_dragged {
                // Drag to select text:
                if let Some(granular) = self.granular_drag {
                    // Extend the selection by whole words or lines:
                    let new_range = extend_granular_select(
                        granular.granularity,
                        granular.anchor,
                        text,
                        cursor_at_pointer,
                    );
                    self.ccursor_range = Some(new_range);
                } else if let Some(mut cursor_range) = self.range(galley) {
                    cursor_range.primary = cursor_at_pointer;
                    self.set_char_range(Some(cursor_range));
                }
                true
            } else {
                false
            }
        } else {
            false
        }
    }

    /// Start a double- or triple-click selection: select the whole word (or line) at the pointer,
    /// and remember it so that a subsequent drag extends the selection by that granularity.
    fn begin_granular_drag(
        &mut self,
        granularity: SelectGranularity,
        text: &str,
        cursor_at_pointer: CCursor,
    ) {
        let anchor = select_unit_at(granularity, text, cursor_at_pointer);
        self.granular_drag = Some(GranularDragSelect {
            granularity,
            anchor,
        });
        self.ccursor_range = Some(anchor);
    }
}

/// The whole word or line at the given position.
pub(crate) fn select_unit_at(
    granularity: SelectGranularity,
    text: &str,
    ccursor: CCursor,
) -> CCursorRange {
    match granularity {
        SelectGranularity::Char => CCursorRange::one(ccursor),
        SelectGranularity::Word => select_word_at(text, ccursor),
        SelectGranularity::Line => select_line_at(text, ccursor),
    }
}

/// Extend a selection to also cover the character, word, or line at the pointer.
///
/// Returns the union of the anchor and the character/word/line at the pointer,
/// with `primary` at the pointer end.
///
/// The anchor is usually the word/line that was double/triple-clicked,
/// but for a shift-double-click it may be the (empty) far end of the previous selection.
pub(crate) fn extend_granular_select(
    granularity: SelectGranularity,
    anchor: CCursorRange,
    text: &str,
    cursor_at_pointer: CCursor,
) -> CCursorRange {
    let unit = select_unit_at(granularity, text, cursor_at_pointer);
    let [anchor_min, anchor_max] = anchor.sorted_cursors();
    let [unit_min, unit_max] = unit.sorted_cursors();

    if cursor_at_pointer.index < anchor_min.index {
        // Dragging backwards, before the anchor:
        CCursorRange {
            primary: unit_min,
            secondary: anchor_max,
            h_pos: None,
        }
    } else if anchor_max.index < cursor_at_pointer.index || anchor.is_empty() {
        // Dragging forwards, after the anchor:
        CCursorRange {
            primary: unit_max,
            secondary: anchor_min,
            h_pos: None,
        }
    } else {
        // The pointer is inside the anchor word/line:
        anchor
    }
}

fn select_word_at(text: &str, ccursor: CCursor) -> CCursorRange {
    if text.is_empty() {
        return CCursorRange::one(ccursor);
    }

    let line_start = find_line_start(text, ccursor);
    let line_end = ccursor_next_line(text, line_start);

    let line_range = line_start.index..line_end.index;
    let current_line_text = slice_char_range(text, line_range.clone());

    let relative_idx = ccursor.index - line_start.index;
    let relative_ccursor = CCursor::new(relative_idx);

    let min = ccursor_previous_word(current_line_text, relative_ccursor);
    let max = ccursor_next_word(current_line_text, relative_ccursor);

    CCursorRange::two(
        CCursor::new(line_start.index + min.index),
        CCursor::new(line_start.index + max.index),
    )
}

fn select_line_at(text: &str, ccursor: CCursor) -> CCursorRange {
    if ccursor.index == CharIndex::ZERO {
        CCursorRange::two(ccursor, ccursor_next_line(text, ccursor))
    } else {
        let it = text.chars();
        let mut it = it.skip(ccursor.index.0 - 1);
        if let Some(char_before_cursor) = it.next() {
            if let Some(char_after_cursor) = it.next() {
                if (!is_linebreak(char_before_cursor)) && (!is_linebreak(char_after_cursor)) {
                    let min = ccursor_previous_line(text, ccursor + 1);
                    let max = ccursor_next_line(text, min);
                    CCursorRange::two(min, max)
                } else if !is_linebreak(char_before_cursor) {
                    let min = ccursor_previous_line(text, ccursor);
                    let max = ccursor_next_line(text, min);
                    CCursorRange::two(min, max)
                } else if is_linebreak(char_after_cursor) {
                    let min = ccursor_previous_line(text, ccursor);
                    let max = ccursor_next_line(text, ccursor);
                    CCursorRange::two(min, max)
                } else {
                    let max = ccursor_next_line(text, ccursor);
                    CCursorRange::two(ccursor, max)
                }
            } else {
                let min = ccursor_previous_line(text, ccursor);
                CCursorRange::two(min, ccursor)
            }
        } else {
            let max = ccursor_next_line(text, ccursor);
            CCursorRange::two(ccursor, max)
        }
    }
}

pub fn ccursor_next_word(text: &str, ccursor: CCursor) -> CCursor {
    CCursor {
        index: next_word_boundary_char_index(text, ccursor.index),
        prefer_next_row: false,
    }
}

fn ccursor_next_line(text: &str, ccursor: CCursor) -> CCursor {
    CCursor {
        index: next_line_boundary_char_index(text.chars(), ccursor.index),
        prefer_next_row: false,
    }
}

pub fn ccursor_previous_word(text: &str, ccursor: CCursor) -> CCursor {
    let num_chars = CharIndex(text.chars().count());
    let reversed: String = text.graphemes(true).rev().collect();
    let boundary = next_word_boundary_char_index(&reversed, num_chars - ccursor.index);
    CCursor {
        index: num_chars - boundary.min(num_chars),
        prefer_next_row: true,
    }
}

fn ccursor_previous_line(text: &str, ccursor: CCursor) -> CCursor {
    let num_chars = CharIndex(text.chars().count());
    let boundary = next_line_boundary_char_index(text.chars().rev(), num_chars - ccursor.index);
    CCursor {
        index: num_chars - boundary,
        prefer_next_row: true,
    }
}

fn next_word_boundary_char_index(text: &str, cursor_ci: CharIndex) -> CharIndex {
    let mut current_char_idx = CharIndex::ZERO;

    for (_word_byte_index, word) in text.split_word_bound_indices() {
        let word_ci = current_char_idx;

        // We consider `.` a word boundary.
        // At least that's how Mac works when navigating something like `www.example.com`.
        let mut word_char_count = 0;
        for chr in word.chars() {
            let dot_ci = word_ci + word_char_count;
            if chr == '.' && cursor_ci < dot_ci {
                return dot_ci;
            }
            word_char_count += 1;
        }

        // Splitting considers contiguous whitespace as one word, such words must be skipped,
        // this handles cases for example ' abc' (a space and a word), the cursor is at the beginning
        // (before space) - this jumps at the end of 'abc' (this is consistent with text editors
        // or browsers)
        if cursor_ci < word_ci && !all_word_chars(word) {
            return word_ci;
        }

        current_char_idx += word_char_count;
    }

    current_char_idx
}

fn all_word_chars(text: &str) -> bool {
    text.chars().all(is_word_char)
}

fn next_line_boundary_char_index(
    it: impl Iterator<Item = char>,
    mut index: CharIndex,
) -> CharIndex {
    let mut it = it.skip(index.0);
    if let Some(_first) = it.next() {
        index += 1;

        if let Some(second) = it.next() {
            index += 1;
            for next in it {
                if is_linebreak(next) != is_linebreak(second) {
                    break;
                }
                index += 1;
            }
        }
    }
    index
}

pub fn is_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

fn is_linebreak(c: char) -> bool {
    c == '\r' || c == '\n'
}

/// Accepts and returns character offset (NOT byte offset!).
pub fn find_line_start(text: &str, current_index: CCursor) -> CCursor {
    let byte_idx = byte_index_from_char_index(text, current_index.index);
    let text_before = (ByteIndex::ZERO..byte_idx).slice(text);

    if let Some(last_newline_byte) = text_before.rfind('\n') {
        let char_idx = char_index_from_byte_index(text, ByteIndex(last_newline_byte + 1));
        CCursor::new(char_idx)
    } else {
        CCursor::new(0)
    }
}

pub fn byte_index_from_char_index(s: &str, char_index: CharIndex) -> ByteIndex {
    for (ci, (bi, _)) in s.char_indices().enumerate() {
        if ci == char_index.0 {
            return ByteIndex(bi);
        }
    }
    ByteIndex(s.len())
}

pub fn char_index_from_byte_index(input: &str, byte_index: ByteIndex) -> CharIndex {
    for (ci, (bi, _)) in input.char_indices().enumerate() {
        if bi == byte_index.0 {
            return CharIndex(ci);
        }
    }

    // `byte_index` is at or past the end of the string (or not on a char boundary):
    // return the total number of characters.
    CharIndex(input.chars().count())
}

pub fn slice_char_range(s: &str, char_range: core::ops::Range<CharIndex>) -> &str {
    assert!(
        char_range.start <= char_range.end,
        "Invalid range, start must be less than end, but start = {}, end = {}",
        char_range.start,
        char_range.end
    );
    let start_byte = byte_index_from_char_index(s, char_range.start);
    let end_byte = byte_index_from_char_index(s, char_range.end);
    (start_byte..end_byte).slice(s)
}

/// The thin rectangle of one end of the selection, e.g. the primary cursor, in local galley coordinates.
pub fn cursor_rect(galley: &Galley, cursor: &CCursor, row_height: f32) -> Rect {
    let mut cursor_pos = galley.pos_from_cursor(*cursor);

    // Handle completely empty galleys
    cursor_pos.max.y = cursor_pos.max.y.at_least(cursor_pos.min.y + row_height);

    cursor_pos = cursor_pos.expand(1.5); // slightly above/below row

    cursor_pos
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_next_word_boundary_char_index() {
        // ASCII only
        let text = "abc d3f g_h i-j";
        assert_eq!(next_word_boundary_char_index(text, CharIndex(1)).0, 3);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(3)).0, 7);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(9)).0, 11);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(12)).0, 13);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(13)).0, 15);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(15)).0, 15);

        assert_eq!(next_word_boundary_char_index("", CharIndex(0)).0, 0);
        assert_eq!(next_word_boundary_char_index("", CharIndex(1)).0, 0);

        // ASCII only
        let text = "abc.def.ghi";
        assert_eq!(next_word_boundary_char_index(text, CharIndex(1)).0, 3);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(3)).0, 7);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(7)).0, 11);

        // Unicode graphemes, some of which consist of multiple Unicode characters,
        // !!! Unicode character is not always what is tranditionally considered a character,
        // the values below are correct despite not seeming that way on the first look,
        // handling of and around emojis is kind of weird and is not consistent across
        // text editors and browsers
        let text = "β€οΈπŸ‘ skvΔ›lΓ‘ knihovna πŸ‘β€οΈ";
        assert_eq!(next_word_boundary_char_index(text, CharIndex(0)).0, 2);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(2)).0, 3); // this does not skip the space between thumbs-up and 'skvΔ›lΓ‘'
        assert_eq!(next_word_boundary_char_index(text, CharIndex(6)).0, 10);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(9)).0, 10);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(12)).0, 19);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(15)).0, 19);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(19)).0, 20);
        assert_eq!(next_word_boundary_char_index(text, CharIndex(20)).0, 21);
    }

    #[test]
    fn test_previous_word() {
        let text = "abc def ghi";
        assert_eq!(ccursor_previous_word(text, CCursor::new(7)).index.0, 4);
        assert_eq!(ccursor_previous_word(text, CCursor::new(5)).index.0, 4);
        assert_eq!(ccursor_previous_word(text, CCursor::new(4)).index.0, 0);
        assert_eq!(ccursor_previous_word(text, CCursor::new(0)).index.0, 0);
    }

    #[test]
    fn test_next_word() {
        let text = "abc def ghi";
        assert_eq!(ccursor_next_word(text, CCursor::new(0)).index.0, 3);
        assert_eq!(ccursor_next_word(text, CCursor::new(3)).index.0, 7);
        assert_eq!(ccursor_next_word(text, CCursor::new(7)).index.0, 11);
        assert_eq!(ccursor_next_word(text, CCursor::new(11)).index.0, 11);
    }

    #[test]
    fn test_index_conversion_roundtrip() {
        // "Γ©" is 2 bytes, "πŸ‘" is 4 bytes.
        let text = "aΓ©πŸ‘b";
        let char_count = text.chars().count(); // 4
        assert_eq!(char_count, 4);

        // char -> byte, including the end index
        assert_eq!(byte_index_from_char_index(text, CharIndex(0)).0, 0);
        assert_eq!(byte_index_from_char_index(text, CharIndex(1)).0, 1);
        assert_eq!(byte_index_from_char_index(text, CharIndex(2)).0, 3);
        assert_eq!(byte_index_from_char_index(text, CharIndex(3)).0, 7);
        assert_eq!(byte_index_from_char_index(text, CharIndex(4)).0, 8);
        // Past the end clamps to the byte length:
        assert_eq!(
            byte_index_from_char_index(text, CharIndex(99)).0,
            text.len()
        );

        // byte -> char, including the end index
        assert_eq!(char_index_from_byte_index(text, ByteIndex(0)).0, 0);
        assert_eq!(char_index_from_byte_index(text, ByteIndex(1)).0, 1);
        assert_eq!(char_index_from_byte_index(text, ByteIndex(3)).0, 2);
        assert_eq!(char_index_from_byte_index(text, ByteIndex(7)).0, 3);
        // The end byte index must map to the character count, not to some byte offset:
        assert_eq!(char_index_from_byte_index(text, ByteIndex(text.len())).0, 4);
        // Past the end clamps to the character count:
        assert_eq!(char_index_from_byte_index(text, ByteIndex(99)).0, 4);

        // Empty string:
        assert_eq!(byte_index_from_char_index("", CharIndex(0)).0, 0);
        assert_eq!(char_index_from_byte_index("", ByteIndex(0)).0, 0);
    }

    #[test]
    fn test_select_word_at() {
        // CCursorRange::two(min, max) sets primary=max, secondary=min
        let text = "hello world";
        let range = select_word_at(text, CCursor::new(2));
        let (lo, hi) = (
            range.primary.index.min(range.secondary.index),
            range.primary.index.max(range.secondary.index),
        );
        assert_eq!(lo.0, 0);
        assert_eq!(hi.0, 5);

        let range = select_word_at(text, CCursor::new(8));
        let (lo, hi) = (
            range.primary.index.min(range.secondary.index),
            range.primary.index.max(range.secondary.index),
        );
        assert_eq!(lo.0, 6);
        assert_eq!(hi.0, 11);
    }

    #[test]
    fn test_extend_granular_select_words() {
        let text = "alpha beta gamma";
        let anchor = select_word_at(text, CCursor::new(8)); // "beta"
        assert_eq!(anchor.slice_str(text), "beta");

        // Dragging forward into "gamma" extends the selection to the end of that word:
        let range = extend_granular_select(SelectGranularity::Word, anchor, text, CCursor::new(13));
        assert_eq!(range.slice_str(text), "beta gamma");
        assert_eq!(
            range.primary.index.0, 16,
            "primary should be at the pointer end"
        );

        // Dragging backward into "alpha" extends the selection to the start of that word:
        let range = extend_granular_select(SelectGranularity::Word, anchor, text, CCursor::new(2));
        assert_eq!(range.slice_str(text), "alpha beta");
        assert_eq!(
            range.primary.index.0, 0,
            "primary should be at the pointer end"
        );

        // With the pointer still inside the anchor word, the selection stays the anchor word:
        let range = extend_granular_select(SelectGranularity::Word, anchor, text, CCursor::new(7));
        assert_eq!(range.slice_str(text), "beta");
    }

    #[test]
    fn test_extend_granular_select_lines() {
        let text = "first\nsecond\nthird";
        let anchor = select_line_at(text, CCursor::new(8)); // "second"
        assert_eq!(anchor.slice_str(text), "second");

        let range = extend_granular_select(SelectGranularity::Line, anchor, text, CCursor::new(15));
        assert_eq!(range.slice_str(text), "second\nthird");

        let range = extend_granular_select(SelectGranularity::Line, anchor, text, CCursor::new(2));
        assert_eq!(range.slice_str(text), "first\nsecond");
    }

    #[test]
    fn test_word_boundary_large_text_performance() {
        // Before the O(nΒ²) β†’ O(n) fix, this would take minutes on large text.
        let large_text = "word ".repeat(200_000); // ~1MB
        let len = large_text.chars().count();

        let start = std::time::Instant::now();

        let next = ccursor_next_word(&large_text, CCursor::new(len - 10));
        assert!(next.index.0 <= len);

        let prev = ccursor_previous_word(&large_text, CCursor::new(len - 10));
        assert!(prev.index.0 < len);

        let range = select_word_at(&large_text, CCursor::new(len - 3));
        let lo = range.primary.index.min(range.secondary.index);
        let hi = range.primary.index.max(range.secondary.index);
        assert!(lo < hi, "Expected a non-empty word selection");

        let elapsed = start.elapsed();
        assert!(
            elapsed.as_secs() < 5,
            "Word boundary operations on 1MB text took {elapsed:?}, expected < 5s"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_previous_word_graphemes() {
        let cases = [
            ("", 0, 0),
            ("hello", 0, 0),
            ("hello", "hello".chars().count(), 0),
            ("hello world", 6, 0),
            ("hello world", 8, 6),
            ("hello world", "hello world".chars().count(), 6),
            ("hello world   ", "hello world   ".chars().count(), 6),
            ("hello   world", "hello   world".chars().count(), 8),
            ("   ", "   ".chars().count(), 0),
            ("hello, world", "hello, world".chars().count(), 7),
            ("www.example.com", "www.example.com".chars().count(), 12),
            ("μ•ˆλ…•! 😊 세상", 8, 6),
            ("β€οΈπŸ‘ skvΔ›lΓ‘ knihovna πŸ‘β€οΈ", 18, 11),
            (
                "a e\u{301} b",
                "a e\u{301} b".chars().count(),
                "a e\u{301} ".chars().count(),
            ),
            (
                "hi πŸ™‚ world",
                "hi πŸ™‚ world".chars().count(),
                "hi πŸ™‚ ".chars().count(),
            ),
            (
                "hi πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ world",
                "hi πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ world".chars().count(),
                "hi πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ ".chars().count(),
            ),
        ];

        for (text, cursor, expected) in cases {
            let result = ccursor_previous_word(text, CCursor::new(cursor));
            assert_eq!(
                result.index.0, expected,
                "text={text:?}, cursor={cursor}, got={}, expected={expected}",
                result.index.0
            );
        }
    }
}