Skip to main content

sui_text/
model.rs

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/// An ordered, theme-owned font-family preference list.
56///
57/// Family names may be concrete installed families (for example, `Segoe UI`)
58/// or CSS-compatible generic aliases such as `ui-sans-serif`, `system-ui`,
59/// `sans-serif`, `ui-serif`, and `ui-monospace`. The text system resolves the
60/// first available family for the active platform. An explicitly registered
61/// [`FontHandle`] on [`TextStyle`] still takes precedence over this stack.
62#[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    /// Theme or caller supplied family preferences used when `font` is not set.
82    pub font_families: Option<FontFamilyStack>,
83    pub font_size: f32,
84    pub line_height: f32,
85    pub color: Color,
86    /// Weight axis / weight class (drives the variable `wght` axis and bold-face selection).
87    pub weight: FontWeight,
88    /// Slant (italic / oblique face selection).
89    pub style: FontStyle,
90    /// Width / stretch (condensed..expanded face selection).
91    pub stretch: FontStretch,
92    /// OpenType feature settings applied to this run.
93    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(&paragraph.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        if self.clusters.is_empty() {
489            return self.byte_range.start;
490        }
491
492        let first = &self.clusters[0];
493        let first_min = first.x_start.min(first.x_end);
494        if x <= first_min {
495            return if first.x_start <= first.x_end {
496                first.range.start
497            } else {
498                first.range.end
499            };
500        }
501
502        for cluster in &self.clusters {
503            let cluster_min = cluster.x_start.min(cluster.x_end);
504            let cluster_max = cluster.x_start.max(cluster.x_end);
505            let midpoint = (cluster_min + cluster_max) * 0.5;
506            if x <= cluster_max {
507                let ascending = cluster.x_start <= cluster.x_end;
508                return if x <= midpoint {
509                    if ascending {
510                        cluster.range.start
511                    } else {
512                        cluster.range.end
513                    }
514                } else if ascending {
515                    cluster.range.end
516                } else {
517                    cluster.range.start
518                };
519            }
520        }
521
522        let last = self
523            .clusters
524            .last()
525            .expect("text lines with clusters should have a last cluster");
526        if last.x_start <= last.x_end {
527            last.range.end
528        } else {
529            last.range.start
530        }
531    }
532}
533
534#[derive(Debug, Clone, PartialEq)]
535pub(crate) struct TextLayoutData {
536    pub metadata: TextLayoutMetadata,
537    pub text: String,
538    pub box_size: Size,
539    pub faces: Vec<ResolvedTextFace>,
540    pub measurement: TextMeasurement,
541    pub paragraphs: Vec<TextParagraphLayout>,
542    pub lines: Vec<TextLine>,
543    pub runs: Vec<TextLayoutRun>,
544    pub clusters: Vec<TextCluster>,
545    pub glyphs: Vec<ShapedGlyph>,
546}
547
548#[derive(Debug, Clone, PartialEq)]
549pub struct TextLayout {
550    pub(crate) data: Arc<TextLayoutData>,
551    pub(crate) document: Arc<TextDocument>,
552    pub(crate) primary_style: TextStyle,
553}
554
555#[derive(Debug, Clone, PartialEq)]
556pub struct PersistentTextLayout {
557    handle: TextLayoutHandle,
558    layout: TextLayout,
559}
560
561impl PersistentTextLayout {
562    pub fn new(handle: TextLayoutHandle, layout: TextLayout) -> Self {
563        Self { handle, layout }
564    }
565
566    pub fn handle(&self) -> TextLayoutHandle {
567        self.handle
568    }
569
570    pub fn version(&self) -> TextLayoutVersion {
571        self.layout.version()
572    }
573
574    pub fn metadata(&self) -> TextLayoutMetadata {
575        self.layout.metadata()
576    }
577
578    pub fn layout(&self) -> &TextLayout {
579        &self.layout
580    }
581
582    pub fn into_parts(self) -> (TextLayoutHandle, TextLayout) {
583        (self.handle, self.layout)
584    }
585}
586
587impl Deref for PersistentTextLayout {
588    type Target = TextLayout;
589
590    fn deref(&self) -> &Self::Target {
591        &self.layout
592    }
593}
594
595impl AsRef<TextLayout> for PersistentTextLayout {
596    fn as_ref(&self) -> &TextLayout {
597        &self.layout
598    }
599}
600
601#[derive(Debug, Clone, PartialEq, Default)]
602pub struct TextLayoutRegistry {
603    layouts: HashMap<TextLayoutHandle, TextLayout>,
604}
605
606impl TextLayoutRegistry {
607    pub fn get(&self, handle: TextLayoutHandle) -> Option<&TextLayout> {
608        self.layouts.get(&handle)
609    }
610
611    pub fn contains(&self, handle: TextLayoutHandle) -> bool {
612        self.layouts.contains_key(&handle)
613    }
614
615    pub fn len(&self) -> usize {
616        self.layouts.len()
617    }
618
619    pub fn is_empty(&self) -> bool {
620        self.layouts.is_empty()
621    }
622
623    pub fn iter(&self) -> impl Iterator<Item = (TextLayoutHandle, &TextLayout)> {
624        self.layouts
625            .iter()
626            .map(|(handle, layout)| (*handle, layout))
627    }
628
629    pub(crate) fn insert(&mut self, handle: TextLayoutHandle, layout: TextLayout) {
630        self.layouts.insert(handle, layout);
631    }
632
633    pub(crate) fn retain_handles(&mut self, handles: &HashSet<TextLayoutHandle>) {
634        self.layouts
635            .retain(|handle, _layout| handles.contains(handle));
636    }
637}
638
639#[derive(Debug, Clone)]
640pub struct TextLayoutView<'a> {
641    pub metadata: TextLayoutMetadata,
642    pub text: &'a str,
643    pub document: &'a TextDocument,
644    pub box_size: Size,
645    pub measurement: TextMeasurement,
646    pub faces: &'a [ResolvedTextFace],
647    pub paragraphs: &'a [TextParagraphLayout],
648    pub lines: &'a [TextLine],
649    pub runs: &'a [TextLayoutRun],
650    pub clusters: &'a [TextCluster],
651    pub glyphs: &'a [ShapedGlyph],
652}
653
654#[derive(Debug, Clone)]
655pub struct TextLineWindow<'a> {
656    layout: &'a TextLayout,
657    pub metadata: TextLayoutMetadata,
658    pub line_range: Range<usize>,
659    pub run_range: Range<usize>,
660    pub cluster_range: Range<usize>,
661    pub glyph_range: Range<usize>,
662}
663
664impl<'a> TextLineWindow<'a> {
665    pub fn lines(&self) -> &'a [TextLine] {
666        &self.layout.data.lines[self.line_range.clone()]
667    }
668
669    pub fn bounds(&self) -> Rect {
670        self.lines()
671            .iter()
672            .map(|line| line.rect)
673            .reduce(|bounds, rect| bounds.union(rect))
674            .unwrap_or(Rect::ZERO)
675    }
676
677    pub fn runs(&self) -> &'a [TextLayoutRun] {
678        &self.layout.data.runs[self.run_range.clone()]
679    }
680
681    pub fn clusters(&self) -> &'a [TextCluster] {
682        &self.layout.data.clusters[self.cluster_range.clone()]
683    }
684
685    pub fn glyphs(&self) -> &'a [ShapedGlyph] {
686        &self.layout.data.glyphs[self.glyph_range.clone()]
687    }
688
689    pub fn glyph_instances(&self) -> impl ExactSizeIterator<Item = TextGlyphInstance<'a>> + 'a {
690        (self.glyph_range.start..self.glyph_range.end)
691            .map(|index| self.layout.glyph_instance(index))
692    }
693}
694
695#[derive(Debug, Clone, Copy)]
696pub struct TextRunView<'a> {
697    pub index: usize,
698    pub run: &'a TextLayoutRun,
699    pub style: &'a TextStyle,
700    pub face: &'a ResolvedTextFace,
701    pub line: &'a TextLine,
702    pub clusters: &'a [TextCluster],
703    pub glyphs: &'a [ShapedGlyph],
704}
705
706#[derive(Debug, Clone, Copy)]
707pub struct TextGlyphInstance<'a> {
708    pub index: usize,
709    pub glyph: &'a ShapedGlyph,
710    pub style: &'a TextStyle,
711    pub face: &'a ResolvedTextFace,
712    pub run: &'a TextLayoutRun,
713    pub line: &'a TextLine,
714}
715
716impl TextLayout {
717    pub fn id(&self) -> TextLayoutId {
718        self.data.metadata.id
719    }
720
721    pub fn version(&self) -> TextLayoutVersion {
722        self.data.metadata.version
723    }
724
725    pub fn metadata(&self) -> TextLayoutMetadata {
726        self.data.metadata
727    }
728
729    pub fn text(&self) -> &str {
730        &self.data.text
731    }
732
733    pub fn document(&self) -> &TextDocument {
734        self.document.as_ref()
735    }
736
737    pub fn style(&self) -> &TextStyle {
738        &self.primary_style
739    }
740
741    pub fn box_size(&self) -> Size {
742        self.data.box_size
743    }
744
745    pub fn measurement(&self) -> TextMeasurement {
746        self.data.measurement
747    }
748
749    pub fn paragraphs(&self) -> &[TextParagraphLayout] {
750        &self.data.paragraphs
751    }
752
753    pub fn lines(&self) -> &[TextLine] {
754        &self.data.lines
755    }
756
757    pub fn runs(&self) -> &[TextLayoutRun] {
758        &self.data.runs
759    }
760
761    pub fn clusters(&self) -> &[TextCluster] {
762        &self.data.clusters
763    }
764
765    pub fn glyphs(&self) -> &[ShapedGlyph] {
766        &self.data.glyphs
767    }
768
769    pub fn faces(&self) -> &[ResolvedTextFace] {
770        &self.data.faces
771    }
772
773    pub fn view(&self) -> TextLayoutView<'_> {
774        TextLayoutView {
775            metadata: self.metadata(),
776            text: self.text(),
777            document: self.document(),
778            box_size: self.box_size(),
779            measurement: self.measurement(),
780            faces: self.faces(),
781            paragraphs: self.paragraphs(),
782            lines: self.lines(),
783            runs: self.runs(),
784            clusters: self.clusters(),
785            glyphs: self.glyphs(),
786        }
787    }
788
789    pub fn run_style(&self, run_index: usize) -> &TextStyle {
790        self.document
791            .span_style(self.data.runs[run_index].span_id.clone())
792    }
793
794    pub fn run_face(&self, run_index: usize) -> &ResolvedTextFace {
795        &self.data.faces[self.data.runs[run_index].face_index]
796    }
797
798    pub fn glyph_style(&self, glyph: &ShapedGlyph) -> &TextStyle {
799        self.document.span_style(glyph.span_id.clone())
800    }
801
802    pub fn glyph_face(&self, glyph: &ShapedGlyph) -> &ResolvedTextFace {
803        &self.data.faces[glyph.face_index]
804    }
805
806    pub fn run_view(&self, run_index: usize) -> TextRunView<'_> {
807        let run = &self.data.runs[run_index];
808        TextRunView {
809            index: run_index,
810            run,
811            style: self.run_style(run_index),
812            face: self.run_face(run_index),
813            line: &self.data.lines[run.line_index],
814            clusters: &self.data.clusters[run.cluster_range.clone()],
815            glyphs: &self.data.glyphs[run.glyph_range.clone()],
816        }
817    }
818
819    pub fn run_views(&self) -> impl ExactSizeIterator<Item = TextRunView<'_>> + '_ {
820        (0..self.data.runs.len()).map(|index| self.run_view(index))
821    }
822
823    pub fn glyph_instance(&self, glyph_index: usize) -> TextGlyphInstance<'_> {
824        let glyph = &self.data.glyphs[glyph_index];
825        TextGlyphInstance {
826            index: glyph_index,
827            glyph,
828            style: self.glyph_style(glyph),
829            face: self.glyph_face(glyph),
830            run: &self.data.runs[glyph.run_index],
831            line: &self.data.lines[glyph.line_index],
832        }
833    }
834
835    pub fn glyph_instances(&self) -> impl ExactSizeIterator<Item = TextGlyphInstance<'_>> + '_ {
836        (0..self.data.glyphs.len()).map(|index| self.glyph_instance(index))
837    }
838
839    pub fn line_window(&self, line_range: Range<usize>) -> TextLineWindow<'_> {
840        let line_start = line_range.start.min(self.data.lines.len());
841        let line_end = line_range.end.min(self.data.lines.len()).max(line_start);
842        let clamped_line_range = line_start..line_end;
843        let (run_range, cluster_range, glyph_range) = if clamped_line_range.is_empty() {
844            (0..0, 0..0, 0..0)
845        } else {
846            collapse_range(
847                self.data.lines[clamped_line_range.clone()]
848                    .iter()
849                    .map(|line| line.run_range.clone()),
850            )
851            .zip(collapse_range(
852                self.data.lines[clamped_line_range.clone()]
853                    .iter()
854                    .map(|line| line.cluster_range.clone()),
855            ))
856            .zip(collapse_range(
857                self.data.lines[clamped_line_range.clone()]
858                    .iter()
859                    .map(|line| line.glyph_range.clone()),
860            ))
861            .map(|((run_range, cluster_range), glyph_range)| {
862                (run_range, cluster_range, glyph_range)
863            })
864            .unwrap_or((0..0, 0..0, 0..0))
865        };
866
867        TextLineWindow {
868            layout: self,
869            metadata: self.metadata(),
870            line_range: clamped_line_range,
871            run_range,
872            cluster_range,
873            glyph_range,
874        }
875    }
876
877    pub fn caret(&self, cursor: TextCursor) -> TextCaret {
878        let line_index = self.line_index_for_offset(cursor.utf8_offset);
879        let line = &self.data.lines[line_index];
880        TextCaret {
881            cursor,
882            line_index,
883            rect: Rect::new(
884                line.x_for_offset(cursor.utf8_offset),
885                line.rect.y(),
886                1.0,
887                line.rect.height(),
888            ),
889        }
890    }
891
892    pub fn caret_rect(&self, utf8_offset: usize) -> Rect {
893        self.caret(TextCursor::new(utf8_offset)).rect
894    }
895
896    pub fn hit_test_point(&self, point: Point) -> TextCursor {
897        if self.data.lines.is_empty() {
898            return TextCursor::default();
899        }
900
901        let line = &self.data.lines[self.line_index_for_y(point.y)];
902        TextCursor::new(line.offset_for_x(point.x))
903    }
904
905    pub fn selection_geometry(&self, selection: &TextSelection) -> TextSelectionGeometry {
906        let range = selection.sorted_range(self.data.text.len());
907        if range.start == range.end {
908            return TextSelectionGeometry {
909                rects: Vec::new(),
910                bounds: None,
911            };
912        }
913
914        let mut rects = Vec::new();
915
916        for line in &self.data.lines {
917            let line_start = range.start.max(line.byte_range.start);
918            let line_end = range.end.min(line.byte_range.end);
919            if line_start >= line_end {
920                continue;
921            }
922
923            let x0 = line.x_for_offset(line_start);
924            let x1 = line.x_for_offset(line_end);
925            let left = x0.min(x1);
926            let right = x0.max(x1);
927            rects.push(Rect::new(
928                left,
929                line.rect.y(),
930                (right - left).max(0.0),
931                line.rect.height(),
932            ));
933        }
934
935        let bounds = rects
936            .iter()
937            .copied()
938            .reduce(|bounds, rect| bounds.union(rect));
939        TextSelectionGeometry { rects, bounds }
940    }
941
942    pub fn selection_rects(&self, range: Range<usize>) -> Vec<Rect> {
943        self.selection_geometry(&TextSelection::new(
944            TextCursor::new(range.start),
945            TextCursor::new(range.end),
946        ))
947        .rects
948    }
949
950    pub fn selection_bounds(&self, range: Range<usize>) -> Option<Rect> {
951        self.selection_geometry(&TextSelection::new(
952            TextCursor::new(range.start),
953            TextCursor::new(range.end),
954        ))
955        .bounds
956    }
957
958    pub(crate) fn line_index_for_offset(&self, utf8_offset: usize) -> usize {
959        let offset = utf8_offset.min(self.data.text.len());
960        self.data
961            .lines
962            .iter()
963            .position(|line| offset <= line.byte_range.end)
964            .unwrap_or_else(|| self.data.lines.len().saturating_sub(1))
965    }
966
967    fn line_index_for_y(&self, y: f32) -> usize {
968        self.data
969            .lines
970            .iter()
971            .enumerate()
972            .min_by(|(_, left), (_, right)| {
973                let left_center = left.rect.y() + (left.rect.height() * 0.5);
974                let right_center = right.rect.y() + (right.rect.height() * 0.5);
975                (left_center - y)
976                    .abs()
977                    .partial_cmp(&(right_center - y).abs())
978                    .unwrap_or(std::cmp::Ordering::Equal)
979            })
980            .map(|(index, _)| index)
981            .unwrap_or_else(|| self.data.lines.len().saturating_sub(1))
982    }
983
984    pub(crate) fn with_document(mut self, document: TextDocument) -> Self {
985        self.primary_style = document.primary_style();
986        self.document = Arc::new(document);
987        self
988    }
989
990    #[cfg(test)]
991    pub(crate) fn shares_storage_with(&self, other: &Self) -> bool {
992        Arc::ptr_eq(&self.data, &other.data)
993    }
994}
995
996fn collapse_range(ranges: impl Iterator<Item = Range<usize>>) -> Option<Range<usize>> {
997    ranges.fold(None, |current: Option<Range<usize>>, range| {
998        Some(match current {
999            Some(existing) => existing.start.min(range.start)..existing.end.max(range.end),
1000            None => range,
1001        })
1002    })
1003}
1004
1005#[derive(Debug, Clone, PartialEq)]
1006pub struct ShapedText {
1007    pub origin: Point,
1008    pub layout_handle: TextLayoutHandle,
1009    pub layout_version: TextLayoutVersion,
1010    pub bounds: Rect,
1011    pub color_override: Option<Color>,
1012}
1013
1014impl ShapedText {
1015    pub fn new(origin: Point, layout: &PersistentTextLayout) -> Self {
1016        Self {
1017            origin,
1018            layout_handle: layout.handle(),
1019            layout_version: layout.version(),
1020            bounds: layout.measurement().bounds,
1021            color_override: None,
1022        }
1023    }
1024
1025    pub fn from_layout(
1026        origin: Point,
1027        layout_handle: TextLayoutHandle,
1028        layout: &TextLayout,
1029    ) -> Self {
1030        Self {
1031            origin,
1032            layout_handle,
1033            layout_version: layout.version(),
1034            bounds: layout.measurement().bounds,
1035            color_override: None,
1036        }
1037    }
1038
1039    pub fn with_color(mut self, color: Color) -> Self {
1040        self.color_override = Some(color);
1041        self
1042    }
1043
1044    pub fn translated_bounds(&self) -> Rect {
1045        self.bounds.translate(self.origin.to_vector())
1046    }
1047
1048    pub fn resolve<'a>(&self, registry: &'a TextLayoutRegistry) -> Option<&'a TextLayout> {
1049        let layout = registry.get(self.layout_handle)?;
1050        (layout.version() == self.layout_version).then_some(layout)
1051    }
1052}
1053
1054#[derive(Debug, Clone, PartialEq)]
1055pub struct ShapedTextWindow {
1056    pub origin: Point,
1057    pub layout_handle: TextLayoutHandle,
1058    pub layout_version: TextLayoutVersion,
1059    pub line_range: Range<usize>,
1060    pub bounds: Rect,
1061    pub color_override: Option<Color>,
1062}
1063
1064impl ShapedTextWindow {
1065    pub fn new(origin: Point, layout: &PersistentTextLayout, line_range: Range<usize>) -> Self {
1066        Self::from_layout(origin, layout.handle(), layout, line_range)
1067    }
1068
1069    pub fn from_layout(
1070        origin: Point,
1071        layout_handle: TextLayoutHandle,
1072        layout: &TextLayout,
1073        line_range: Range<usize>,
1074    ) -> Self {
1075        let window = layout.line_window(line_range);
1076        Self {
1077            origin,
1078            layout_handle,
1079            layout_version: layout.version(),
1080            line_range: window.line_range.clone(),
1081            bounds: window.bounds(),
1082            color_override: None,
1083        }
1084    }
1085
1086    pub fn with_color(mut self, color: Color) -> Self {
1087        self.color_override = Some(color);
1088        self
1089    }
1090
1091    pub fn translated_bounds(&self) -> Rect {
1092        self.bounds.translate(self.origin.to_vector())
1093    }
1094
1095    pub fn resolve<'a>(&self, registry: &'a TextLayoutRegistry) -> Option<&'a TextLayout> {
1096        let layout = registry.get(self.layout_handle)?;
1097        (layout.version() == self.layout_version).then_some(layout)
1098    }
1099}