lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
use std::{
  ops::Range,
  sync::{Arc, OnceLock},
};

// Short fields use a direct scan without retaining a line table.
const CARET_INDEX_MIN_POSITIONS: usize = 256;

/// Immutable geometry and line ranges shared by the shaping cache and node states.
#[derive(Clone)]
pub(crate) struct CaretPositions(Arc<CaretData>);

impl CaretPositions {
  /// Whether `other` is these very positions, not only equal ones.
  pub(crate) fn same(&self, other: &Self) -> bool {
    Arc::ptr_eq(&self.0, &other.0)
  }
}

struct CaretData {
  positions: OnceLock<Vec<CaretPosition>>,
  segments: Vec<CaretSegment>,
  len: usize,
  index: OnceLock<CaretIndex>,
}

struct CaretLine {
  start: usize,
  end: usize,
  min_index: usize,
  max_index: usize,
  y: f32,
}

#[derive(Default)]
pub(crate) struct CaretIndex {
  lines: Vec<CaretLine>,
  ordered_indices: bool,
  ordered_y: bool,
}

impl From<Vec<CaretPosition>> for CaretPositions {
  fn from(positions: Vec<CaretPosition>) -> Self {
    Self(Arc::new(CaretData {
      len: positions.len(),
      positions: OnceLock::from(positions),
      segments: Vec::new(),
      index: OnceLock::new(),
    }))
  }
}

// The legacy test oracle can request a flat slice. Runtime callers cannot
// accidentally materialize a document through slice coercion.
#[cfg(test)]
impl std::ops::Deref for CaretPositions {
  type Target = [CaretPosition];

  fn deref(&self) -> &Self::Target {
    self.0.positions.get_or_init(|| self.iter().collect())
  }
}

impl CaretPositions {
  pub(crate) fn with_index(positions: Vec<CaretPosition>, mut index: CaretIndex) -> Self {
    if positions.len() < CARET_INDEX_MIN_POSITIONS {
      return positions.into();
    }
    index.finish();
    Self(Arc::new(CaretData {
      len: positions.len(),
      positions: OnceLock::from(positions),
      segments: Vec::new(),
      index: OnceLock::from(index),
    }))
  }

  pub(crate) fn len(&self) -> usize {
    self.0.len
  }

  /// Approximate heap bytes of the caret data, divided among its current
  /// holders: node states, cached layout results and the shaping cache share
  /// one allocation.
  pub(crate) fn estimated_shared_memory_bytes(&self) -> usize {
    let positions = self.0.positions.get().map_or(0, |positions| {
      positions.capacity() * std::mem::size_of::<CaretPosition>()
    });
    let segments = self.0.segments.capacity() * std::mem::size_of::<CaretSegment>();
    let index = self
      .0
      .index
      .get()
      .map_or(0, |index| index.lines.capacity() * std::mem::size_of::<CaretLine>());
    (std::mem::size_of::<CaretData>() + positions + segments + index) / Arc::strong_count(&self.0)
  }

  fn is_empty(&self) -> bool {
    self.len() == 0
  }

  pub(crate) fn iter(&self) -> impl Iterator<Item = CaretPosition> + '_ {
    self.slice(0..self.len()).iter()
  }

  fn get(&self, index: usize) -> Option<CaretPosition> {
    if index >= self.len() {
      return None;
    }
    self.slice(index..index + 1).iter().next()
  }

  fn last(&self) -> Option<CaretPosition> {
    self.len().checked_sub(1).and_then(|i| self.get(i))
  }

  /// Mask remapping detaches a flat copy and cannot keep a stale line index.
  pub(crate) fn make_mut(&mut self) -> &mut [CaretPosition] {
    if !self.0.segments.is_empty() || Arc::get_mut(&mut self.0).is_none() {
      let positions = if self.0.segments.is_empty() {
        self.0.positions.get().unwrap().clone()
      } else {
        self.iter().collect()
      };
      *self = positions.into();
    }
    let data = Arc::get_mut(&mut self.0).unwrap();
    data.index.take();
    data.positions.get_mut().unwrap()
  }

  fn index(&self) -> Option<&CaretIndex> {
    if self.len() < CARET_INDEX_MIN_POSITIONS && self.0.segments.is_empty() {
      return None;
    }
    Some(
      self
        .0
        .index
        .get_or_init(|| CaretIndex::new(self.0.positions.get().expect("flat caret geometry"))),
    )
  }

  fn slice(&self, range: Range<usize>) -> CaretSlice<'_> {
    CaretSlice { positions: self, range }
  }

  fn matching_positions(&self, start: usize, end: usize) -> CaretSlice<'_> {
    let Some(index) = self.index() else {
      return self.slice(0..self.len());
    };
    let lines = index.matching_lines(start, end);
    match (lines.first(), lines.last()) {
      (Some(first), Some(last)) => self.slice(first.start..last.end),
      _ => self.slice(0..0),
    }
  }
}

/// Paragraph-local positions stay unchanged when preceding text grows or shrinks.
/// Each visual row supplies its exact document y separately, avoiding float drift.
pub(crate) struct ParagraphCarets {
  positions: Vec<CaretPosition>,
  runs: Vec<Range<usize>>,
  bytes: usize,
}

impl ParagraphCarets {
  /// The carets of a paragraph's laid-out rows; `text` is the paragraph's
  /// text, which its glyphs index.
  pub(crate) fn new(text: &str, layouts: &[cosmic_text::LayoutLine]) -> Self {
    let count = layouts.iter().map(|line| (line.glyphs.len() * 2).max(1)).sum();
    let mut positions = Vec::with_capacity(count);
    let mut runs = Vec::with_capacity(layouts.len());
    for line in layouts {
      let start = positions.len();
      if line.glyphs.is_empty() {
        positions.push(CaretPosition {
          index: 0,
          x: 0.0,
          y: 0.0,
        });
      }
      for glyph in &line.glyphs {
        positions.extend(glyph_carets(glyph, text).map(|(index, x)| CaretPosition { index, x, y: 0.0 }));
      }
      runs.push(start..positions.len());
    }
    let bytes = std::mem::size_of::<Self>()
      + 2 * std::mem::size_of::<usize>()
      + positions.capacity() * std::mem::size_of::<CaretPosition>()
      + runs.capacity() * std::mem::size_of::<Range<usize>>();
    Self { positions, runs, bytes }
  }

  #[cfg(feature = "perf_profile")]
  pub(crate) fn len(&self) -> usize {
    self.positions.len()
  }

  pub(crate) fn bytes(&self) -> usize {
    self.bytes
  }
}

struct CaretSegment {
  paragraph: Arc<ParagraphCarets>,
  range: Range<usize>,
  text_offset: usize,
  y: f32,
  start: usize,
}

impl CaretSegment {
  fn position(&self, index: usize) -> CaretPosition {
    let p = self.paragraph.positions[self.range.start + (index - self.start)];
    CaretPosition {
      index: self.text_offset + p.index,
      x: p.x,
      y: self.y,
    }
  }
}

#[derive(Default)]
pub(crate) struct CaretPositionsBuilder {
  segments: Vec<CaretSegment>,
  index: CaretIndex,
  len: usize,
  last: Option<CaretPosition>,
  text_len: usize,
  has_text_end: bool,
}

impl CaretPositionsBuilder {
  pub(crate) fn new(text_len: usize, runs: usize) -> Self {
    Self {
      text_len,
      segments: Vec::with_capacity(runs + 1),
      index: CaretIndex {
        lines: Vec::with_capacity(runs),
        ..CaretIndex::default()
      },
      ..Self::default()
    }
  }

  pub(crate) fn push_run(
    &mut self,
    paragraph: Arc<ParagraphCarets>,
    run: usize,
    text_offset: usize,
    text_len: usize,
    y: f32,
  ) {
    let range = paragraph.runs[run].clone();
    if text_offset + text_len == self.text_len {
      self.has_text_end |= paragraph.positions[range.clone()].iter().any(|p| p.index == text_len);
    }
    let end = self.len + range.len();
    self
      .index
      .push_line(self.len, end, text_offset, text_offset + text_len, y);
    let segment = CaretSegment {
      paragraph,
      range,
      text_offset,
      y,
      start: self.len,
    };
    self.last = Some(segment.position(end - 1));
    self.segments.push(segment);
    self.len = end;
  }

  pub(crate) fn finish(mut self) -> CaretPositions {
    if self.len == 0 || !self.has_text_end {
      let last = self.last.unwrap_or(CaretPosition {
        index: 0,
        x: 0.0,
        y: 0.0,
      });
      // Preserve the legacy empty-document origin and final missing endpoint.
      if self.len == 0 {
        self.push_point(CaretPosition {
          index: 0,
          x: 0.0,
          y: 0.0,
        });
      }
      if !self.has_text_end {
        self.push_point(CaretPosition {
          index: self.text_len,
          x: last.x,
          y: last.y,
        });
      }
    }
    self.index.finish();
    CaretPositions(Arc::new(CaretData {
      positions: OnceLock::new(),
      segments: self.segments,
      len: self.len,
      index: OnceLock::from(self.index),
    }))
  }

  // `runs` is a list of ranges, and a point has the one.
  #[allow(clippy::single_range_in_vec_init)]
  fn push_point(&mut self, point: CaretPosition) {
    let paragraph = Arc::new(ParagraphCarets {
      positions: vec![CaretPosition {
        index: 0,
        x: point.x,
        y: 0.0,
      }],
      runs: vec![0..1],
      bytes: std::mem::size_of::<ParagraphCarets>()
        + 2 * std::mem::size_of::<usize>()
        + std::mem::size_of::<CaretPosition>()
        + std::mem::size_of::<Range<usize>>(),
    });
    self.push_run(paragraph, 0, point.index, 0, point.y);
  }
}

struct CaretSlice<'a> {
  positions: &'a CaretPositions,
  range: Range<usize>,
}

impl<'a> CaretSlice<'a> {
  fn first(&self) -> Option<CaretPosition> {
    if self.range.is_empty() {
      None
    } else {
      self.positions.get(self.range.start)
    }
  }

  fn last(&self) -> Option<CaretPosition> {
    if self.range.is_empty() {
      None
    } else {
      self.positions.get(self.range.end - 1)
    }
  }

  fn iter(&self) -> CaretIter<'a> {
    let data = &self.positions.0;
    if data.segments.is_empty() {
      CaretIter::Flat(data.positions.get().unwrap()[self.range.clone()].iter().copied())
    } else {
      let segment = data
        .segments
        .partition_point(|s| s.start <= self.range.start)
        .saturating_sub(1);
      CaretIter::Segments {
        segments: &data.segments,
        range: self.range.clone(),
        segment,
      }
    }
  }
}

enum CaretIter<'a> {
  Flat(std::iter::Copied<std::slice::Iter<'a, CaretPosition>>),
  Segments {
    segments: &'a [CaretSegment],
    range: Range<usize>,
    segment: usize,
  },
}

impl Iterator for CaretIter<'_> {
  type Item = CaretPosition;

  fn next(&mut self) -> Option<Self::Item> {
    match self {
      Self::Flat(iter) => iter.next(),
      Self::Segments {
        segments,
        range,
        segment,
      } => {
        if range.start >= range.end {
          return None;
        }
        while *segment + 1 < segments.len() && segments[*segment + 1].start <= range.start {
          *segment += 1;
        }
        let position = segments[*segment].position(range.start);
        range.start += 1;
        Some(position)
      }
    }
  }
  fn size_hint(&self) -> (usize, Option<usize>) {
    match self {
      Self::Flat(iter) => iter.size_hint(),
      Self::Segments { range, .. } => (range.len(), Some(range.len())),
    }
  }
}

impl CaretIndex {
  fn new(positions: &[CaretPosition]) -> Self {
    let mut lines = Vec::new();
    let mut start = 0;
    while start < positions.len() {
      let first = positions[start];
      let mut end = start + 1;
      let mut min_index = first.index;
      let mut max_index = first.index;
      while end < positions.len() && (positions[end].y - first.y).abs() <= f32::EPSILON {
        min_index = min_index.min(positions[end].index);
        max_index = max_index.max(positions[end].index);
        end += 1;
      }
      lines.push(CaretLine {
        start,
        end,
        min_index,
        max_index,
        y: first.y,
      });
      start = end;
    }
    let mut index = Self {
      lines,
      ..Self::default()
    };
    index.finish();
    index
  }

  /// Shaping already knows each run's paragraph range. These conservative byte
  /// bounds avoid a second glyph walk and include every wrapped or bidi caret.
  pub(crate) fn push_line(&mut self, start: usize, end: usize, min_index: usize, max_index: usize, y: f32) {
    if let Some(last) = self.lines.last_mut()
      && (last.y - y).abs() <= f32::EPSILON
    {
      last.end = end;
      last.min_index = last.min_index.min(min_index);
      last.max_index = last.max_index.max(max_index);
      return;
    }
    self.lines.push(CaretLine {
      start,
      end,
      min_index,
      max_index,
      y,
    });
  }

  fn finish(&mut self) {
    // Bidi glyph order need not follow byte order. Only use binary search when
    // the line ranges are monotonic, preserving visual order and tie behavior.
    self.ordered_indices = self
      .lines
      .windows(2)
      .all(|pair| pair[0].min_index <= pair[1].min_index && pair[0].max_index <= pair[1].max_index);
    self.ordered_y =
      self.lines.iter().all(|line| line.y.is_finite()) && self.lines.windows(2).all(|pair| pair[0].y < pair[1].y);
  }

  fn matching_lines(&self, start: usize, end: usize) -> &[CaretLine] {
    if !self.ordered_indices {
      return &self.lines;
    }
    let first = self.lines.partition_point(|line| line.max_index < start);
    let last = self.lines.partition_point(|line| line.min_index <= end);
    &self.lines[first.min(last)..last]
  }
}

/// The x of the caret before `glyph`'s cluster and of the one after it. A
/// left-to-right glyph starts at its left edge; a right-to-left glyph at its
/// right edge, so the caret after its cluster is at its left.
fn glyph_caret_edges(glyph: &cosmic_text::LayoutGlyph) -> (f32, f32) {
  if glyph.level.is_rtl() {
    (glyph.x + glyph.w, glyph.x)
  } else {
    (glyph.x, glyph.x + glyph.w)
  }
}

/// The carets of `glyph`, as `(byte index, x)` in the text its line holds,
/// `line_text`: one before its cluster, one after it, and one between every
/// two graphemes of the cluster. A ligature draws several characters as one
/// glyph (DejaVu Sans' "fi", a programming font's "--"); its advance is
/// split evenly among its graphemes, as cosmic-text's own hit-testing and
/// highlight split it, so a caret or a selection that ends inside it is
/// drawn there.
pub(crate) fn glyph_carets<'a>(
  glyph: &'a cosmic_text::LayoutGlyph,
  line_text: &'a str,
) -> impl Iterator<Item = (usize, f32)> + 'a {
  use unicode_segmentation::UnicodeSegmentation;

  let (start_x, end_x) = glyph_caret_edges(glyph);
  let cluster = line_text.get(glyph.start..glyph.end).unwrap_or_default();
  // Most clusters are one character: no grapheme walk for them.
  let several = cluster.chars().nth(1).is_some();
  let graphemes = if several { cluster.graphemes(true).count() } else { 1 } as f32;
  let inner = several
    .then(|| cluster.grapheme_indices(true).skip(1).enumerate())
    .into_iter()
    .flatten()
    .map(move |(before, (offset, _))| {
      let share = (before + 1) as f32 / graphemes;
      (glyph.start + offset, start_x + (end_x - start_x) * share)
    });
  std::iter::once((glyph.start, start_x))
    .chain(inner)
    .chain(std::iter::once((glyph.end, end_x)))
}

#[derive(Clone, Copy)]
pub(crate) struct CaretPosition {
  pub(crate) index: usize,
  pub(crate) x: f32,
  pub(crate) y: f32,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct TextSelectionRange {
  pub(crate) x: f32,
  pub(crate) y: f32,
  pub(crate) width: f32,
}

pub(crate) fn selection_range_indices(value: &str, anchor: Option<usize>, caret: usize) -> Option<(usize, usize)> {
  let anchor = clamp_to_char_boundary(value, anchor?);
  let caret = clamp_to_char_boundary(value, caret);
  if anchor == caret {
    return None;
  }
  Some((anchor.min(caret), anchor.max(caret)))
}

pub(crate) fn caret_x_for_index(positions: &CaretPositions, index: usize) -> f32 {
  positions
    .matching_positions(index, index)
    .iter()
    .find(|position| position.index == index)
    .map(|position| position.x)
    .unwrap_or_else(|| positions.last().map(|position| position.x).unwrap_or(0.0))
}

pub(crate) fn caret_y_for_index(positions: &CaretPositions, index: usize) -> Option<f32> {
  positions
    .matching_positions(index, index)
    .iter()
    .find(|position| position.index == index)
    .map(|position| position.y)
}

/// The length of the line break `text` ends with: `\r\n` and `\n\r` are one
/// break of two bytes with no caret between them, as text layout reads them;
/// `\n` and `\r` are one byte. 0 when `text` ends with no line break.
pub(crate) fn trailing_break_len(text: &str) -> usize {
  if text.ends_with("\r\n") || text.ends_with("\n\r") {
    2
  } else if text.ends_with('\n') || text.ends_with('\r') {
    1
  } else {
    0
  }
}

/// The top of the empty row that follows `text` when it ends with a line
/// break: one `line_height` below the row the break ends, which already
/// counts the rows its paragraph wrapped into. Falls back to one row per line
/// break when the layout has no caret before the break.
pub(crate) fn trailing_break_row_y(positions: &CaretPositions, text: &str, line_height: f32) -> f32 {
  let break_index = text.len().saturating_sub(trailing_break_len(text));
  caret_y_for_index(positions, break_index).map_or_else(
    || text.matches('\n').count() as f32 * line_height,
    |row| row + line_height,
  )
}

/// The highlight of the bytes `start..end`, one range per laid-out row the
/// selection touches, in the text's coordinates less the scroll. A row's
/// range covers the advances of its selected glyphs, from the caret before
/// the first to the caret after the last. With `text`, the text the
/// positions index, a row that the text wrapped (one that ends neither with
/// a line break nor with the text) stops at its last glyph that draws: the
/// whitespace and invisible marks at its end hang past it and draw nothing;
/// a row that ends with a line break or the text's end keeps its trailing
/// spaces. Without `text` (a text input, whose selected whitespace stays
/// visible) every row keeps its end. There is no marker for a line break.
pub(crate) fn selection_ranges_for_positions(
  positions: &CaretPositions,
  text: Option<&str>,
  start: usize,
  end: usize,
  scroll_x: f32,
  scroll_y: f32,
) -> Vec<TextSelectionRange> {
  let mut ranges = Vec::new();
  if let Some(index) = positions.index() {
    for line in index.matching_lines(start, end) {
      append_selection_range(
        &mut ranges,
        positions.slice(line.start..line.end),
        text,
        start,
        end,
        scroll_x,
        scroll_y,
      );
    }
  } else {
    let mut line_start = 0;
    while line_start < positions.len() {
      let y = positions.get(line_start).unwrap().y;
      let mut line_end = line_start + 1;
      while line_end < positions.len() && (positions.get(line_end).unwrap().y - y).abs() <= f32::EPSILON {
        line_end += 1;
      }
      append_selection_range(
        &mut ranges,
        positions.slice(line_start..line_end),
        text,
        start,
        end,
        scroll_x,
        scroll_y,
      );
      line_start = line_end;
    }
  }
  ranges
}

fn append_selection_range(
  ranges: &mut Vec<TextSelectionRange>,
  positions: CaretSlice<'_>,
  text: Option<&str>,
  start: usize,
  end: usize,
  scroll_x: f32,
  scroll_y: f32,
) {
  let Some((row_start, row_end)) = row_index_bounds(positions.iter()) else {
    return;
  };
  if start > row_end || end < row_start {
    return;
  }
  let selection_start = start.clamp(row_start, row_end);
  let drawn_end = text.map_or(row_end, |text| drawn_row_end(text, row_start, row_end));
  let selection_end = end.clamp(row_start, drawn_end);
  if selection_start >= selection_end {
    return;
  }
  let last_x = positions.last().map_or(0.0, |position| position.x);
  let x_for_index = |index| {
    positions
      .iter()
      .find(|position| position.index == index)
      .map(|position| position.x)
      .unwrap_or(last_x)
  };
  let start_x = x_for_index(selection_start);
  let end_x = x_for_index(selection_end);
  ranges.push(TextSelectionRange {
    x: start_x.min(end_x) - scroll_x,
    y: positions.first().map_or(0.0, |position| position.y) - scroll_y,
    width: (start_x - end_x).abs().max(1.0),
  });
}

/// The least and greatest byte index among a row's carets, which bidi may
/// have put in any visual order.
pub(crate) fn row_index_bounds(positions: impl Iterator<Item = CaretPosition>) -> Option<(usize, usize)> {
  positions.fold(None, |bounds, position| {
    let (min, max) = bounds.unwrap_or((position.index, position.index));
    Some((min.min(position.index), max.max(position.index)))
  })
}

/// Where the highlight of the row `row_start..row_end` of `text` ends: at
/// `row_end` when the row ends with a line break or the text, else past the
/// last character that draws something.
pub(crate) fn drawn_row_end(text: &str, row_start: usize, row_end: usize) -> usize {
  let Some(after) = text.get(row_end..) else {
    return row_end;
  };
  if after.is_empty() || after.starts_with(['\n', '\r']) {
    return row_end;
  }
  let mut end = row_end;
  while end > row_start {
    let Some(ch) = text.get(..end).and_then(|before| before.chars().next_back()) else {
      break;
    };
    if !hangs_past_a_wrap(ch) {
      break;
    }
    end -= ch.len_utf8();
  }
  end.max(row_start)
}

/// Whether `ch` draws nothing where a wrapped row ends: whitespace, which
/// the layout lets hang past the row, or an invisible mark or joiner.
fn hangs_past_a_wrap(ch: char) -> bool {
  ch.is_whitespace()
    || matches!(
      ch,
      '\u{200B}'..='\u{200F}' | '\u{2060}' | '\u{2066}'..='\u{2069}' | '\u{202A}'..='\u{202E}' | '\u{061C}' | '\u{FEFF}'
    )
}

pub(crate) fn line_bounds(value: &str, index: usize) -> (usize, usize) {
  let index = clamp_to_char_boundary(value, index);
  let line_start = value[..index].rfind('\n').map(|position| position + 1).unwrap_or(0);
  let line_end = value[index..]
    .find('\n')
    .map(|position| index + position)
    .unwrap_or(value.len());
  (line_start, line_end)
}

pub(crate) fn word_selection_bounds(value: &str, index: usize) -> (usize, usize) {
  if value.is_empty() {
    return (0, 0);
  }

  let index = clamp_to_char_boundary(value, index);
  let (seed_index, seed_class) = if let Some((idx, ch)) = char_at_or_after(value, index)
    && !ch.is_whitespace()
  {
    (idx, word_selection_class(ch))
  } else if let Some((idx, ch)) = char_before(value, index) {
    (idx, word_selection_class(ch))
  } else if let Some((idx, ch)) = char_at_or_after(value, index) {
    (idx, word_selection_class(ch))
  } else {
    return (0, 0);
  };

  let mut start = seed_index;
  while let Some((previous, ch)) = char_before(value, start) {
    if word_selection_class(ch) != seed_class {
      break;
    }
    start = previous;
  }

  let mut end = seed_index + value[seed_index..].chars().next().unwrap().len_utf8();
  while end < value.len() {
    let ch = value[end..].chars().next().unwrap();
    if word_selection_class(ch) != seed_class {
      break;
    }
    end += ch.len_utf8();
  }

  (start, end)
}

/// How far apart two caret positions' `y` may be and still sit on one row.
const ROW_EPSILON: f32 = 0.5;

/// The caret on the laid-out row next to the one at `y`, above it or below
/// (`down`), nearest to `x`. Rows are visual: a soft-wrapped paragraph has
/// one per wrapped line. `None` when no row lies that way.
pub(crate) fn closest_caret_on_adjacent_row(positions: &CaretPositions, y: f32, x: f32, down: bool) -> Option<usize> {
  let row = positions
    .iter()
    .map(|position| position.y)
    .filter(|&row| {
      if down {
        row > y + ROW_EPSILON
      } else {
        row < y - ROW_EPSILON
      }
    })
    .reduce(if down { f32::min } else { f32::max })?;
  let on_row = |position: &CaretPosition| (position.y - row).abs() <= ROW_EPSILON;
  // Where a paragraph wraps, one index ends a row and starts the next, and
  // the caret shows it at the end of the first. Only that row may take it,
  // so a move down from the start of a row does not land back on it.
  let shown_on_row = |position: &CaretPosition| {
    caret_y_for_index(positions, position.index).is_some_and(|shown| (shown - row).abs() <= ROW_EPSILON)
  };
  let nearest = |candidates: &mut dyn Iterator<Item = CaretPosition>| {
    candidates
      .min_by(|a, b| (a.x - x).abs().total_cmp(&(b.x - x).abs()))
      .map(|position| position.index)
  };
  nearest(
    &mut positions
      .iter()
      .filter(|position| on_row(position) && shown_on_row(position)),
  )
  .or_else(|| nearest(&mut positions.iter().filter(on_row)))
}

pub(crate) fn closest_caret_to_point(positions: &CaretPositions, x: f32, y: f32) -> usize {
  let line = if let Some(index) = positions.index().filter(|index| index.ordered_y && y.is_finite()) {
    let line = &index.lines[index.lines.partition_point(|line| line.y <= y).saturating_sub(1)];
    Some((line.start, line.end))
  } else {
    line_range_for_y(positions, y)
  };
  let Some((line_start, line_end)) = line else {
    return 0;
  };

  positions
    .slice(line_start..line_end)
    .iter()
    .min_by(|a, b| {
      (a.x - x)
        .abs()
        .partial_cmp(&(b.x - x).abs())
        .unwrap_or(std::cmp::Ordering::Equal)
    })
    .map(|position| position.index)
    .unwrap_or(0)
}

fn line_range_for_y(positions: &CaretPositions, y: f32) -> Option<(usize, usize)> {
  if positions.is_empty() {
    return None;
  }

  let mut line_start = 0;
  let mut previous_line = None;
  while line_start < positions.len() {
    let line_y = positions.get(line_start).unwrap().y;
    let mut line_end = line_start + 1;
    while line_end < positions.len() && (positions.get(line_end).unwrap().y - line_y).abs() <= f32::EPSILON {
      line_end += 1;
    }

    if y < line_y {
      return Some(previous_line.unwrap_or((line_start, line_end)));
    }

    let next_line_y = positions.get(line_end).map(|position| position.y);
    if next_line_y.is_none_or(|next_y| y < next_y) {
      return Some((line_start, line_end));
    }

    previous_line = Some((line_start, line_end));
    line_start = line_end;
  }

  previous_line
}

pub(crate) fn previous_word_boundary(value: &str, index: usize) -> usize {
  let mut index = clamp_to_char_boundary(value, index);
  while let Some((previous, ch)) = char_before(value, index) {
    if !ch.is_whitespace() {
      break;
    }
    index = previous;
  }
  while let Some((previous, ch)) = char_before(value, index) {
    if ch.is_whitespace() {
      break;
    }
    index = previous;
  }
  index
}

pub(crate) fn next_word_boundary(value: &str, index: usize) -> usize {
  let mut index = clamp_to_char_boundary(value, index);
  while index < value.len() {
    let ch = value[index..].chars().next().unwrap();
    if ch.is_whitespace() {
      break;
    }
    index += ch.len_utf8();
  }
  while index < value.len() {
    let ch = value[index..].chars().next().unwrap();
    if !ch.is_whitespace() {
      break;
    }
    index += ch.len_utf8();
  }
  index
}

pub(crate) fn previous_char_boundary(value: &str, index: usize) -> usize {
  let index = clamp_to_char_boundary(value, index);
  value[..index].char_indices().last().map(|(idx, _)| idx).unwrap_or(0)
}

pub(crate) fn next_char_boundary(value: &str, index: usize) -> usize {
  let index = clamp_to_char_boundary(value, index);
  value[index..]
    .char_indices()
    .nth(1)
    .map(|(offset, _)| index + offset)
    .unwrap_or(value.len())
}

/// Where Backspace at `index` deletes back to: one character, or the whole of an emoji made of several. A
/// thumbs-up with a skin tone, a flag, a face with a variation selector and a family joined by zero-width
/// joiners are each one picture, typed with one key and deleted with one. An accent on a letter is still
/// deleted on its own, as editors do: it was typed on its own.
pub(crate) fn previous_delete_boundary(value: &str, index: usize) -> usize {
  use unicode_segmentation::UnicodeSegmentation;
  let index = clamp_to_char_boundary(value, index);
  match value[..index].grapheme_indices(true).next_back() {
    Some((start, cluster)) if is_emoji_sequence(cluster) => start,
    _ => previous_char_boundary(value, index),
  }
}

/// Where Delete at `index` deletes up to; see [`previous_delete_boundary`].
pub(crate) fn next_delete_boundary(value: &str, index: usize) -> usize {
  use unicode_segmentation::UnicodeSegmentation;
  let index = clamp_to_char_boundary(value, index);
  match value[index..].graphemes(true).next() {
    Some(cluster) if is_emoji_sequence(cluster) => index + cluster.len(),
    _ => next_char_boundary(value, index),
  }
}

/// Whether a grapheme cluster of several characters is an emoji: it has a pictograph, a regional indicator, a
/// variation selector that asks for the emoji form, a zero-width joiner or a keycap mark.
fn is_emoji_sequence(cluster: &str) -> bool {
  cluster.chars().nth(1).is_some()
    && cluster.chars().any(|character| {
      matches!(
        character,
        '\u{FE0F}' | '\u{200D}' | '\u{20E3}' | '\u{1F1E6}'..='\u{1F1FF}' | '\u{1F300}'..='\u{1FAFF}'
      )
    })
}

pub(crate) fn clamp_to_char_boundary(value: &str, index: usize) -> usize {
  let mut index = index.min(value.len());
  while index > 0 && !value.is_char_boundary(index) {
    index -= 1;
  }
  index
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum WordSelectionClass {
  Word,
  Whitespace,
  Other,
}

fn word_selection_class(ch: char) -> WordSelectionClass {
  if ch.is_alphanumeric() || ch == '_' {
    WordSelectionClass::Word
  } else if ch.is_whitespace() {
    WordSelectionClass::Whitespace
  } else {
    WordSelectionClass::Other
  }
}

fn char_before(value: &str, index: usize) -> Option<(usize, char)> {
  let index = clamp_to_char_boundary(value, index);
  value[..index].char_indices().last()
}

fn char_at_or_after(value: &str, index: usize) -> Option<(usize, char)> {
  let index = clamp_to_char_boundary(value, index);
  value[index..].chars().next().map(|ch| (index, ch))
}

#[cfg(test)]
mod tests;

#[cfg(test)]
mod delete_boundary_tests {
  use super::{next_delete_boundary, previous_delete_boundary};

  /// What one Backspace at the end of `text` leaves.
  fn backspaced(text: &str) -> &str {
    &text[..previous_delete_boundary(text, text.len())]
  }

  #[test]
  fn backspace_deletes_an_emoji_of_several_characters_whole() {
    // A variation selector, a skin tone, a flag, a family joined by zero-width joiners, a keycap.
    for emoji in ["✌\u{fe0f}", "πŸ‘πŸ½", "πŸ‡ΊπŸ‡¦", "πŸ‘¨\u{200d}πŸ‘©\u{200d}πŸ‘§", "1\u{fe0f}\u{20e3}"] {
      assert_eq!(backspaced(&format!("ab{emoji}")), "ab", "{emoji}");
    }
    assert_eq!(backspaced("abπŸ˜€"), "ab");
  }

  #[test]
  fn backspace_deletes_an_accent_on_its_own_and_one_letter_at_a_time() {
    assert_eq!(backspaced("cafe\u{301}"), "cafe");
    assert_eq!(backspaced("ΠΏΡ€ΠΈΠ²Ρ–Ρ‚"), "ΠΏΡ€ΠΈΠ²Ρ–");
    assert_eq!(backspaced(""), "");
  }

  #[test]
  fn delete_takes_the_emoji_after_the_caret_whole() {
    let text = "aπŸ‘πŸ½b";
    assert_eq!(&text[next_delete_boundary(text, 1)..], "b");
    assert_eq!(&text[next_delete_boundary(text, 0)..], "πŸ‘πŸ½b");
    assert_eq!(next_delete_boundary(text, text.len()), text.len());
  }
}