1use std::{
2 collections::{HashMap, HashSet},
3 ops::Deref,
4 ops::Range,
5 sync::Arc,
6};
7
8use sui_core::{Color, FontHandle, Point, Rect, Size, Vector};
9
10use crate::font::ResolvedTextFace;
11use crate::style::{FontFeatures, FontStretch, FontStyle, FontWeight};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
14pub enum TextAlign {
15 #[default]
16 Start,
17 End,
18 Left,
19 Right,
20 Center,
21 Justified,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
25pub enum TextWrap {
26 NoWrap,
27 #[default]
28 Word,
29 Character,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
33pub enum TextDirection {
34 #[default]
35 Auto,
36 LeftToRight,
37 RightToLeft,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
41pub enum TextWritingMode {
42 #[default]
43 Horizontal,
44 Vertical,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub enum TextFlowDirection {
49 LeftToRight,
50 RightToLeft,
51 TopToBottom,
52 BottomToTop,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub struct FontFamilyStack {
64 pub primary: &'static str,
65 pub fallbacks: &'static [&'static str],
66}
67
68impl FontFamilyStack {
69 pub const fn new(primary: &'static str, fallbacks: &'static [&'static str]) -> Self {
70 Self { primary, fallbacks }
71 }
72
73 pub fn iter(self) -> impl Iterator<Item = &'static str> {
74 std::iter::once(self.primary).chain(self.fallbacks.iter().copied())
75 }
76}
77
78#[derive(Debug, Clone, PartialEq)]
79pub struct TextStyle {
80 pub font: Option<FontHandle>,
81 pub font_families: Option<FontFamilyStack>,
83 pub font_size: f32,
84 pub line_height: f32,
85 pub color: Color,
86 pub weight: FontWeight,
88 pub style: FontStyle,
90 pub stretch: FontStretch,
92 pub features: FontFeatures,
94}
95
96impl TextStyle {
97 pub fn new(color: Color) -> Self {
98 Self {
99 color,
100 ..Self::default()
101 }
102 }
103}
104
105impl Default for TextStyle {
106 fn default() -> Self {
107 Self {
108 font: None,
109 font_families: None,
110 font_size: 14.0,
111 line_height: 18.0,
112 color: Color::WHITE,
113 weight: FontWeight::NORMAL,
114 style: FontStyle::Normal,
115 stretch: FontStretch::Normal,
116 features: FontFeatures::new(),
117 }
118 }
119}
120
121#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
122pub struct TextParagraphStyle {
123 pub align: TextAlign,
124 pub wrap: TextWrap,
125 pub direction: TextDirection,
126 pub writing_mode: TextWritingMode,
127}
128
129#[derive(Debug, Clone, PartialEq)]
130pub struct TextSpan {
131 pub text: String,
132 pub style: TextStyle,
133}
134
135impl TextSpan {
136 pub fn new(text: impl Into<String>, style: TextStyle) -> Self {
137 Self {
138 text: text.into(),
139 style,
140 }
141 }
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Hash)]
145pub struct TextSpanId {
146 pub paragraph_index: usize,
147 pub span_index: usize,
148}
149
150#[derive(Debug, Clone, PartialEq, Default)]
151pub struct TextParagraph {
152 pub style: TextParagraphStyle,
153 pub spans: Vec<TextSpan>,
154}
155
156impl TextParagraph {
157 pub fn new(text: impl Into<String>, style: TextStyle) -> Self {
158 Self {
159 style: TextParagraphStyle::default(),
160 spans: vec![TextSpan::new(text, style)],
161 }
162 }
163
164 pub fn from_spans(spans: Vec<TextSpan>) -> Self {
165 Self {
166 style: TextParagraphStyle::default(),
167 spans,
168 }
169 }
170
171 pub fn text(&self) -> String {
172 let mut text = String::new();
173 for span in &self.spans {
174 text.push_str(&span.text);
175 }
176 text
177 }
178}
179
180#[derive(Debug, Clone, PartialEq, Default)]
181pub struct TextDocument {
182 pub paragraphs: Vec<TextParagraph>,
183}
184
185impl TextDocument {
186 pub fn new() -> Self {
187 Self::default()
188 }
189
190 pub fn from_plain_text(text: impl Into<String>, style: TextStyle) -> Self {
191 let text = text.into();
192 let paragraphs = text
193 .split('\n')
194 .map(|segment| TextParagraph::new(segment, style.clone()))
195 .collect();
196 Self { paragraphs }
197 }
198
199 pub fn plain_text(&self) -> String {
200 let mut text = String::new();
201 for (index, paragraph) in self.paragraphs.iter().enumerate() {
202 if index > 0 {
203 text.push('\n');
204 }
205 text.push_str(¶graph.text());
206 }
207 text
208 }
209
210 pub fn primary_style(&self) -> TextStyle {
211 self.paragraphs
212 .iter()
213 .flat_map(|paragraph| paragraph.spans.iter())
214 .map(|span| span.style.clone())
215 .next()
216 .unwrap_or_default()
217 }
218
219 pub(crate) fn into_normalized(mut self) -> Self {
220 if self.paragraphs.is_empty() {
221 self.paragraphs
222 .push(TextParagraph::new(String::new(), TextStyle::default()));
223 }
224
225 for paragraph in &mut self.paragraphs {
226 if paragraph.spans.is_empty() {
227 paragraph
228 .spans
229 .push(TextSpan::new(String::new(), TextStyle::default()));
230 }
231 }
232
233 self
234 }
235
236 pub(crate) fn span_style(&self, span_id: TextSpanId) -> &TextStyle {
237 &self.paragraphs[span_id.paragraph_index].spans[span_id.span_index].style
238 }
239}
240
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
242pub struct TextLayoutId(u64);
243
244impl TextLayoutId {
245 pub const fn new(value: u64) -> Self {
246 Self(value)
247 }
248
249 pub const fn get(self) -> u64 {
250 self.0
251 }
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
255pub struct TextLayoutVersion(u64);
256
257impl TextLayoutVersion {
258 pub const fn new(value: u64) -> Self {
259 Self(value)
260 }
261
262 pub const fn get(self) -> u64 {
263 self.0
264 }
265}
266
267#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
268pub struct TextLayoutHandle(u64);
269
270impl TextLayoutHandle {
271 pub const fn new(value: u64) -> Self {
272 Self(value)
273 }
274
275 pub const fn get(self) -> u64 {
276 self.0
277 }
278
279 pub const fn from_layout_id(id: TextLayoutId) -> Self {
280 Self(id.get())
281 }
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
285pub struct TextLayoutMetadata {
286 pub id: TextLayoutId,
287 pub version: TextLayoutVersion,
288}
289
290#[derive(Debug, Clone, PartialEq)]
291pub struct TextLayoutRequest {
292 pub document: TextDocument,
293 pub box_size: Option<Size>,
294}
295
296impl TextLayoutRequest {
297 pub fn new(document: TextDocument) -> Self {
298 Self {
299 document,
300 box_size: None,
301 }
302 }
303
304 pub fn with_box_size(mut self, box_size: Size) -> Self {
305 self.box_size = Some(box_size);
306 self
307 }
308}
309
310#[derive(Debug, Clone, PartialEq)]
311pub struct TextRun {
312 pub rect: Rect,
313 pub text: String,
314 pub style: TextStyle,
315}
316
317#[derive(Debug, Clone, Copy, PartialEq)]
318pub struct TextMeasurement {
319 pub width: f32,
320 pub height: f32,
321 pub bounds: Rect,
322 pub ascent: f32,
323 pub descent: f32,
324 pub cap_height: Option<f32>,
325}
326
327#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
328pub enum TextAffinity {
329 Upstream,
330 #[default]
331 Downstream,
332}
333
334#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
335pub struct TextCursor {
336 pub utf8_offset: usize,
337 pub affinity: TextAffinity,
338}
339
340impl TextCursor {
341 pub const fn new(utf8_offset: usize) -> Self {
342 Self {
343 utf8_offset,
344 affinity: TextAffinity::Downstream,
345 }
346 }
347
348 pub const fn with_affinity(mut self, affinity: TextAffinity) -> Self {
349 self.affinity = affinity;
350 self
351 }
352}
353
354#[derive(Debug, Clone, PartialEq, Eq)]
355pub struct TextSelection {
356 pub anchor: TextCursor,
357 pub focus: TextCursor,
358}
359
360impl TextSelection {
361 pub const fn new(anchor: TextCursor, focus: TextCursor) -> Self {
362 Self { anchor, focus }
363 }
364
365 pub(crate) fn sorted_range(&self, text_len: usize) -> Range<usize> {
366 let start = self.anchor.utf8_offset.min(text_len);
367 let end = self.focus.utf8_offset.min(text_len);
368 if start <= end { start..end } else { end..start }
369 }
370}
371
372#[derive(Debug, Clone, PartialEq)]
373pub struct TextCaret {
374 pub cursor: TextCursor,
375 pub line_index: usize,
376 pub rect: Rect,
377}
378
379#[derive(Debug, Clone, PartialEq)]
380pub struct TextSelectionGeometry {
381 pub rects: Vec<Rect>,
382 pub bounds: Option<Rect>,
383}
384
385#[derive(Debug, Clone, PartialEq)]
386pub struct ShapedGlyph {
387 pub glyph_id: u16,
388 pub cluster: usize,
389 pub span_id: TextSpanId,
390 pub run_index: usize,
391 pub line_index: usize,
392 pub face_index: usize,
393 pub origin_x: f32,
394 pub origin_y: f32,
395 pub advance: Vector,
396 pub scale: f32,
397 pub bounds: Option<Rect>,
398}
399
400#[derive(Debug, Clone, PartialEq)]
401pub(crate) struct TextClusterGeometry {
402 pub range: Range<usize>,
403 pub x_start: f32,
404 pub x_end: f32,
405 pub glyph_range: Range<usize>,
406}
407
408#[derive(Debug, Clone, PartialEq)]
409pub struct TextParagraphLayout {
410 pub paragraph_index: usize,
411 pub byte_range: Range<usize>,
412 pub line_range: Range<usize>,
413 pub run_range: Range<usize>,
414 pub cluster_range: Range<usize>,
415 pub glyph_range: Range<usize>,
416 pub rect: Rect,
417 pub style: TextParagraphStyle,
418}
419
420#[derive(Debug, Clone, PartialEq)]
421pub struct TextCluster {
422 pub paragraph_index: usize,
423 pub line_index: usize,
424 pub byte_range: Range<usize>,
425 pub glyph_range: Range<usize>,
426 pub run_range: Range<usize>,
427 pub rect: Rect,
428}
429
430#[derive(Debug, Clone, PartialEq)]
431pub struct TextLayoutRun {
432 pub paragraph_index: usize,
433 pub line_index: usize,
434 pub span_id: TextSpanId,
435 pub byte_range: Range<usize>,
436 pub glyph_range: Range<usize>,
437 pub cluster_range: Range<usize>,
438 pub rect: Rect,
439 pub baseline: f32,
440 pub face_index: usize,
441 pub direction: TextFlowDirection,
442}
443
444#[derive(Debug, Clone, PartialEq)]
445pub struct TextLine {
446 pub paragraph_index: usize,
447 pub byte_range: Range<usize>,
448 pub run_range: Range<usize>,
449 pub cluster_range: Range<usize>,
450 pub glyph_range: Range<usize>,
451 pub rect: Rect,
452 pub baseline: f32,
453 pub ascent: f32,
454 pub descent: f32,
455 pub width: f32,
456 pub direction: TextFlowDirection,
457 pub(crate) clusters: Vec<TextClusterGeometry>,
458}
459
460impl TextLine {
461 pub(crate) fn x_for_offset(&self, offset: usize) -> f32 {
462 if self.clusters.is_empty() {
463 return self.rect.x();
464 }
465
466 let offset = offset.clamp(self.byte_range.start, self.byte_range.end);
467
468 if offset <= self.byte_range.start {
469 return self.clusters[0].x_start;
470 }
471
472 for cluster in &self.clusters {
473 if offset <= cluster.range.end {
474 let span = (cluster.range.end.saturating_sub(cluster.range.start)).max(1) as f32;
475 let local = offset.saturating_sub(cluster.range.start) as f32;
476 let t = (local / span).clamp(0.0, 1.0);
477 return cluster.x_start + ((cluster.x_end - cluster.x_start) * t);
478 }
479 }
480
481 self.clusters
482 .last()
483 .map(|cluster| cluster.x_end)
484 .unwrap_or(self.rect.max_x())
485 }
486
487 pub(crate) fn offset_for_x(&self, x: f32) -> usize {
488 let mut nearest_offset = self.byte_range.start;
489 let mut nearest_distance = f32::INFINITY;
490 for cluster in &self.clusters {
493 let cluster_min = cluster.x_start.min(cluster.x_end);
494 let cluster_max = cluster.x_start.max(cluster.x_end);
495 let midpoint = (cluster_min + cluster_max) * 0.5;
496 if cluster_min < cluster_max && x >= cluster_min && x <= cluster_max {
497 let ascending = cluster.x_start <= cluster.x_end;
498 return if x <= midpoint {
499 if ascending {
500 cluster.range.start
501 } else {
502 cluster.range.end
503 }
504 } else if ascending {
505 cluster.range.end
506 } else {
507 cluster.range.start
508 };
509 }
510 for (edge, offset) in [
512 (cluster.x_start, cluster.range.start),
513 (cluster.x_end, cluster.range.end),
514 ] {
515 let distance = (x - edge).abs();
516 if distance < nearest_distance {
517 nearest_distance = distance;
518 nearest_offset = offset;
519 }
520 }
521 }
522 nearest_offset
523 }
524}
525
526#[derive(Debug, Clone, PartialEq)]
527pub(crate) struct TextLayoutData {
528 pub metadata: TextLayoutMetadata,
529 pub text: String,
530 pub box_size: Size,
531 pub faces: Vec<ResolvedTextFace>,
532 pub measurement: TextMeasurement,
533 pub paragraphs: Vec<TextParagraphLayout>,
534 pub lines: Vec<TextLine>,
535 pub runs: Vec<TextLayoutRun>,
536 pub clusters: Vec<TextCluster>,
537 pub glyphs: Vec<ShapedGlyph>,
538}
539
540#[derive(Debug, Clone, PartialEq)]
541pub struct TextLayout {
542 pub(crate) data: Arc<TextLayoutData>,
543 pub(crate) document: Arc<TextDocument>,
544 pub(crate) primary_style: TextStyle,
545}
546
547#[derive(Debug, Clone, PartialEq)]
548pub struct PersistentTextLayout {
549 handle: TextLayoutHandle,
550 layout: TextLayout,
551}
552
553impl PersistentTextLayout {
554 pub fn new(handle: TextLayoutHandle, layout: TextLayout) -> Self {
555 Self { handle, layout }
556 }
557
558 pub fn handle(&self) -> TextLayoutHandle {
559 self.handle
560 }
561
562 pub fn version(&self) -> TextLayoutVersion {
563 self.layout.version()
564 }
565
566 pub fn metadata(&self) -> TextLayoutMetadata {
567 self.layout.metadata()
568 }
569
570 pub fn layout(&self) -> &TextLayout {
571 &self.layout
572 }
573
574 pub fn into_parts(self) -> (TextLayoutHandle, TextLayout) {
575 (self.handle, self.layout)
576 }
577}
578
579impl Deref for PersistentTextLayout {
580 type Target = TextLayout;
581
582 fn deref(&self) -> &Self::Target {
583 &self.layout
584 }
585}
586
587impl AsRef<TextLayout> for PersistentTextLayout {
588 fn as_ref(&self) -> &TextLayout {
589 &self.layout
590 }
591}
592
593#[derive(Debug, Clone, PartialEq, Default)]
594pub struct TextLayoutRegistry {
595 layouts: HashMap<TextLayoutHandle, TextLayout>,
596}
597
598impl TextLayoutRegistry {
599 pub fn get(&self, handle: TextLayoutHandle) -> Option<&TextLayout> {
600 self.layouts.get(&handle)
601 }
602
603 pub fn contains(&self, handle: TextLayoutHandle) -> bool {
604 self.layouts.contains_key(&handle)
605 }
606
607 pub fn len(&self) -> usize {
608 self.layouts.len()
609 }
610
611 pub fn is_empty(&self) -> bool {
612 self.layouts.is_empty()
613 }
614
615 pub fn iter(&self) -> impl Iterator<Item = (TextLayoutHandle, &TextLayout)> {
616 self.layouts
617 .iter()
618 .map(|(handle, layout)| (*handle, layout))
619 }
620
621 pub(crate) fn insert(&mut self, handle: TextLayoutHandle, layout: TextLayout) {
622 self.layouts.insert(handle, layout);
623 }
624
625 pub(crate) fn retain_handles(&mut self, handles: &HashSet<TextLayoutHandle>) {
626 self.layouts
627 .retain(|handle, _layout| handles.contains(handle));
628 }
629}
630
631#[derive(Debug, Clone)]
632pub struct TextLayoutView<'a> {
633 pub metadata: TextLayoutMetadata,
634 pub text: &'a str,
635 pub document: &'a TextDocument,
636 pub box_size: Size,
637 pub measurement: TextMeasurement,
638 pub faces: &'a [ResolvedTextFace],
639 pub paragraphs: &'a [TextParagraphLayout],
640 pub lines: &'a [TextLine],
641 pub runs: &'a [TextLayoutRun],
642 pub clusters: &'a [TextCluster],
643 pub glyphs: &'a [ShapedGlyph],
644}
645
646#[derive(Debug, Clone)]
647pub struct TextLineWindow<'a> {
648 layout: &'a TextLayout,
649 pub metadata: TextLayoutMetadata,
650 pub line_range: Range<usize>,
651 pub run_range: Range<usize>,
652 pub cluster_range: Range<usize>,
653 pub glyph_range: Range<usize>,
654}
655
656impl<'a> TextLineWindow<'a> {
657 pub fn lines(&self) -> &'a [TextLine] {
658 &self.layout.data.lines[self.line_range.clone()]
659 }
660
661 pub fn bounds(&self) -> Rect {
662 self.lines()
663 .iter()
664 .map(|line| line.rect)
665 .reduce(|bounds, rect| bounds.union(rect))
666 .unwrap_or(Rect::ZERO)
667 }
668
669 pub fn runs(&self) -> &'a [TextLayoutRun] {
670 &self.layout.data.runs[self.run_range.clone()]
671 }
672
673 pub fn clusters(&self) -> &'a [TextCluster] {
674 &self.layout.data.clusters[self.cluster_range.clone()]
675 }
676
677 pub fn glyphs(&self) -> &'a [ShapedGlyph] {
678 &self.layout.data.glyphs[self.glyph_range.clone()]
679 }
680
681 pub fn glyph_instances(&self) -> impl ExactSizeIterator<Item = TextGlyphInstance<'a>> + 'a {
682 (self.glyph_range.start..self.glyph_range.end)
683 .map(|index| self.layout.glyph_instance(index))
684 }
685}
686
687#[derive(Debug, Clone, Copy)]
688pub struct TextRunView<'a> {
689 pub index: usize,
690 pub run: &'a TextLayoutRun,
691 pub style: &'a TextStyle,
692 pub face: &'a ResolvedTextFace,
693 pub line: &'a TextLine,
694 pub clusters: &'a [TextCluster],
695 pub glyphs: &'a [ShapedGlyph],
696}
697
698#[derive(Debug, Clone, Copy)]
699pub struct TextGlyphInstance<'a> {
700 pub index: usize,
701 pub glyph: &'a ShapedGlyph,
702 pub style: &'a TextStyle,
703 pub face: &'a ResolvedTextFace,
704 pub run: &'a TextLayoutRun,
705 pub line: &'a TextLine,
706}
707
708impl TextLayout {
709 pub fn id(&self) -> TextLayoutId {
710 self.data.metadata.id
711 }
712
713 pub fn version(&self) -> TextLayoutVersion {
714 self.data.metadata.version
715 }
716
717 pub fn metadata(&self) -> TextLayoutMetadata {
718 self.data.metadata
719 }
720
721 pub fn text(&self) -> &str {
722 &self.data.text
723 }
724
725 pub fn document(&self) -> &TextDocument {
726 self.document.as_ref()
727 }
728
729 pub fn style(&self) -> &TextStyle {
730 &self.primary_style
731 }
732
733 pub fn box_size(&self) -> Size {
734 self.data.box_size
735 }
736
737 pub fn measurement(&self) -> TextMeasurement {
738 self.data.measurement
739 }
740
741 pub fn paragraphs(&self) -> &[TextParagraphLayout] {
742 &self.data.paragraphs
743 }
744
745 pub fn lines(&self) -> &[TextLine] {
746 &self.data.lines
747 }
748
749 pub fn runs(&self) -> &[TextLayoutRun] {
750 &self.data.runs
751 }
752
753 pub fn clusters(&self) -> &[TextCluster] {
754 &self.data.clusters
755 }
756
757 pub fn glyphs(&self) -> &[ShapedGlyph] {
758 &self.data.glyphs
759 }
760
761 pub fn faces(&self) -> &[ResolvedTextFace] {
762 &self.data.faces
763 }
764
765 pub fn view(&self) -> TextLayoutView<'_> {
766 TextLayoutView {
767 metadata: self.metadata(),
768 text: self.text(),
769 document: self.document(),
770 box_size: self.box_size(),
771 measurement: self.measurement(),
772 faces: self.faces(),
773 paragraphs: self.paragraphs(),
774 lines: self.lines(),
775 runs: self.runs(),
776 clusters: self.clusters(),
777 glyphs: self.glyphs(),
778 }
779 }
780
781 pub fn run_style(&self, run_index: usize) -> &TextStyle {
782 self.document
783 .span_style(self.data.runs[run_index].span_id.clone())
784 }
785
786 pub fn run_face(&self, run_index: usize) -> &ResolvedTextFace {
787 &self.data.faces[self.data.runs[run_index].face_index]
788 }
789
790 pub fn glyph_style(&self, glyph: &ShapedGlyph) -> &TextStyle {
791 self.document.span_style(glyph.span_id.clone())
792 }
793
794 pub fn glyph_face(&self, glyph: &ShapedGlyph) -> &ResolvedTextFace {
795 &self.data.faces[glyph.face_index]
796 }
797
798 pub fn run_view(&self, run_index: usize) -> TextRunView<'_> {
799 let run = &self.data.runs[run_index];
800 TextRunView {
801 index: run_index,
802 run,
803 style: self.run_style(run_index),
804 face: self.run_face(run_index),
805 line: &self.data.lines[run.line_index],
806 clusters: &self.data.clusters[run.cluster_range.clone()],
807 glyphs: &self.data.glyphs[run.glyph_range.clone()],
808 }
809 }
810
811 pub fn run_views(&self) -> impl ExactSizeIterator<Item = TextRunView<'_>> + '_ {
812 (0..self.data.runs.len()).map(|index| self.run_view(index))
813 }
814
815 pub fn glyph_instance(&self, glyph_index: usize) -> TextGlyphInstance<'_> {
816 let glyph = &self.data.glyphs[glyph_index];
817 TextGlyphInstance {
818 index: glyph_index,
819 glyph,
820 style: self.glyph_style(glyph),
821 face: self.glyph_face(glyph),
822 run: &self.data.runs[glyph.run_index],
823 line: &self.data.lines[glyph.line_index],
824 }
825 }
826
827 pub fn glyph_instances(&self) -> impl ExactSizeIterator<Item = TextGlyphInstance<'_>> + '_ {
828 (0..self.data.glyphs.len()).map(|index| self.glyph_instance(index))
829 }
830
831 pub fn line_window(&self, line_range: Range<usize>) -> TextLineWindow<'_> {
832 let line_start = line_range.start.min(self.data.lines.len());
833 let line_end = line_range.end.min(self.data.lines.len()).max(line_start);
834 let clamped_line_range = line_start..line_end;
835 let (run_range, cluster_range, glyph_range) = if clamped_line_range.is_empty() {
836 (0..0, 0..0, 0..0)
837 } else {
838 collapse_range(
839 self.data.lines[clamped_line_range.clone()]
840 .iter()
841 .map(|line| line.run_range.clone()),
842 )
843 .zip(collapse_range(
844 self.data.lines[clamped_line_range.clone()]
845 .iter()
846 .map(|line| line.cluster_range.clone()),
847 ))
848 .zip(collapse_range(
849 self.data.lines[clamped_line_range.clone()]
850 .iter()
851 .map(|line| line.glyph_range.clone()),
852 ))
853 .map(|((run_range, cluster_range), glyph_range)| {
854 (run_range, cluster_range, glyph_range)
855 })
856 .unwrap_or((0..0, 0..0, 0..0))
857 };
858
859 TextLineWindow {
860 layout: self,
861 metadata: self.metadata(),
862 line_range: clamped_line_range,
863 run_range,
864 cluster_range,
865 glyph_range,
866 }
867 }
868
869 pub fn caret(&self, cursor: TextCursor) -> TextCaret {
870 let line_index = self.line_index_for_offset(cursor.utf8_offset);
871 let line = &self.data.lines[line_index];
872 TextCaret {
873 cursor,
874 line_index,
875 rect: Rect::new(
876 line.x_for_offset(cursor.utf8_offset),
877 line.rect.y(),
878 1.0,
879 line.rect.height(),
880 ),
881 }
882 }
883
884 pub fn caret_rect(&self, utf8_offset: usize) -> Rect {
885 self.caret(TextCursor::new(utf8_offset)).rect
886 }
887
888 pub fn hit_test_point(&self, point: Point) -> TextCursor {
889 if self.data.lines.is_empty() {
890 return TextCursor::default();
891 }
892
893 let line = &self.data.lines[self.line_index_for_y(point.y)];
894 TextCursor::new(line.offset_for_x(point.x))
895 }
896
897 pub fn selection_geometry(&self, selection: &TextSelection) -> TextSelectionGeometry {
898 let range = selection.sorted_range(self.data.text.len());
899 if range.start == range.end {
900 return TextSelectionGeometry {
901 rects: Vec::new(),
902 bounds: None,
903 };
904 }
905
906 let mut rects = Vec::new();
907
908 for line in &self.data.lines {
909 let line_start = range.start.max(line.byte_range.start);
910 let line_end = range.end.min(line.byte_range.end);
911 if line_start >= line_end {
912 continue;
913 }
914
915 let x0 = line.x_for_offset(line_start);
916 let x1 = line.x_for_offset(line_end);
917 let left = x0.min(x1);
918 let right = x0.max(x1);
919 rects.push(Rect::new(
920 left,
921 line.rect.y(),
922 (right - left).max(0.0),
923 line.rect.height(),
924 ));
925 }
926
927 let bounds = rects
928 .iter()
929 .copied()
930 .reduce(|bounds, rect| bounds.union(rect));
931 TextSelectionGeometry { rects, bounds }
932 }
933
934 pub fn selection_rects(&self, range: Range<usize>) -> Vec<Rect> {
935 self.selection_geometry(&TextSelection::new(
936 TextCursor::new(range.start),
937 TextCursor::new(range.end),
938 ))
939 .rects
940 }
941
942 pub fn selection_bounds(&self, range: Range<usize>) -> Option<Rect> {
943 self.selection_geometry(&TextSelection::new(
944 TextCursor::new(range.start),
945 TextCursor::new(range.end),
946 ))
947 .bounds
948 }
949
950 pub(crate) fn line_index_for_offset(&self, utf8_offset: usize) -> usize {
951 let offset = utf8_offset.min(self.data.text.len());
952 self.data
953 .lines
954 .iter()
955 .position(|line| offset <= line.byte_range.end)
956 .unwrap_or_else(|| self.data.lines.len().saturating_sub(1))
957 }
958
959 fn line_index_for_y(&self, y: f32) -> usize {
960 self.data
961 .lines
962 .iter()
963 .enumerate()
964 .min_by(|(_, left), (_, right)| {
965 let left_center = left.rect.y() + (left.rect.height() * 0.5);
966 let right_center = right.rect.y() + (right.rect.height() * 0.5);
967 (left_center - y)
968 .abs()
969 .partial_cmp(&(right_center - y).abs())
970 .unwrap_or(std::cmp::Ordering::Equal)
971 })
972 .map(|(index, _)| index)
973 .unwrap_or_else(|| self.data.lines.len().saturating_sub(1))
974 }
975
976 pub(crate) fn with_document(mut self, document: TextDocument) -> Self {
977 self.primary_style = document.primary_style();
978 self.document = Arc::new(document);
979 self
980 }
981
982 #[cfg(test)]
983 pub(crate) fn shares_storage_with(&self, other: &Self) -> bool {
984 Arc::ptr_eq(&self.data, &other.data)
985 }
986}
987
988fn collapse_range(ranges: impl Iterator<Item = Range<usize>>) -> Option<Range<usize>> {
989 ranges.fold(None, |current: Option<Range<usize>>, range| {
990 Some(match current {
991 Some(existing) => existing.start.min(range.start)..existing.end.max(range.end),
992 None => range,
993 })
994 })
995}
996
997#[derive(Debug, Clone, PartialEq)]
998pub struct ShapedText {
999 pub origin: Point,
1000 pub layout_handle: TextLayoutHandle,
1001 pub layout_version: TextLayoutVersion,
1002 pub bounds: Rect,
1003 pub color_override: Option<Color>,
1004}
1005
1006impl ShapedText {
1007 pub fn new(origin: Point, layout: &PersistentTextLayout) -> Self {
1008 Self {
1009 origin,
1010 layout_handle: layout.handle(),
1011 layout_version: layout.version(),
1012 bounds: layout.measurement().bounds,
1013 color_override: None,
1014 }
1015 }
1016
1017 pub fn from_layout(
1018 origin: Point,
1019 layout_handle: TextLayoutHandle,
1020 layout: &TextLayout,
1021 ) -> Self {
1022 Self {
1023 origin,
1024 layout_handle,
1025 layout_version: layout.version(),
1026 bounds: layout.measurement().bounds,
1027 color_override: None,
1028 }
1029 }
1030
1031 pub fn with_color(mut self, color: Color) -> Self {
1032 self.color_override = Some(color);
1033 self
1034 }
1035
1036 pub fn translated_bounds(&self) -> Rect {
1037 self.bounds.translate(self.origin.to_vector())
1038 }
1039
1040 pub fn resolve<'a>(&self, registry: &'a TextLayoutRegistry) -> Option<&'a TextLayout> {
1041 let layout = registry.get(self.layout_handle)?;
1042 (layout.version() == self.layout_version).then_some(layout)
1043 }
1044}
1045
1046#[derive(Debug, Clone, PartialEq)]
1047pub struct ShapedTextWindow {
1048 pub origin: Point,
1049 pub layout_handle: TextLayoutHandle,
1050 pub layout_version: TextLayoutVersion,
1051 pub line_range: Range<usize>,
1052 pub bounds: Rect,
1053 pub color_override: Option<Color>,
1054}
1055
1056impl ShapedTextWindow {
1057 pub fn new(origin: Point, layout: &PersistentTextLayout, line_range: Range<usize>) -> Self {
1058 Self::from_layout(origin, layout.handle(), layout, line_range)
1059 }
1060
1061 pub fn from_layout(
1062 origin: Point,
1063 layout_handle: TextLayoutHandle,
1064 layout: &TextLayout,
1065 line_range: Range<usize>,
1066 ) -> Self {
1067 let window = layout.line_window(line_range);
1068 Self {
1069 origin,
1070 layout_handle,
1071 layout_version: layout.version(),
1072 line_range: window.line_range.clone(),
1073 bounds: window.bounds(),
1074 color_override: None,
1075 }
1076 }
1077
1078 pub fn with_color(mut self, color: Color) -> Self {
1079 self.color_override = Some(color);
1080 self
1081 }
1082
1083 pub fn translated_bounds(&self) -> Rect {
1084 self.bounds.translate(self.origin.to_vector())
1085 }
1086
1087 pub fn resolve<'a>(&self, registry: &'a TextLayoutRegistry) -> Option<&'a TextLayout> {
1088 let layout = registry.get(self.layout_handle)?;
1089 (layout.version() == self.layout_version).then_some(layout)
1090 }
1091}