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
460/// A rectangle for each horizontal piece, spanning `line`'s height.
461fn pieces_to_rects(line: &TextLine, pieces: &[(f32, f32)], rects: &mut Vec<Rect>) {
462    for (left, right) in pieces {
463        rects.push(Rect::new(
464            *left,
465            line.rect.y(),
466            (right - left).max(0.0),
467            line.rect.height(),
468        ));
469    }
470}
471
472impl TextLine {
473    /// The horizontal extents on screen of the text in `range`, left to
474    /// right, with touching pieces merged. Text in mixed directions can
475    /// cover several separate pieces.
476    fn selected_pieces(&self, range: Range<usize>) -> Vec<(f32, f32)> {
477        let mut pieces = self
478            .clusters
479            .iter()
480            .filter(|cluster| cluster.range.start < range.end && cluster.range.end > range.start)
481            .map(|cluster| {
482                // Part of a cluster, such as a ligature, takes its share.
483                let span = cluster.range.len().max(1) as f32;
484                let x_at = |offset: usize| {
485                    let t =
486                        (offset.saturating_sub(cluster.range.start) as f32 / span).clamp(0.0, 1.0);
487                    cluster.x_start + (cluster.x_end - cluster.x_start) * t
488                };
489                let a = x_at(range.start.max(cluster.range.start));
490                let b = x_at(range.end.min(cluster.range.end));
491                (a.min(b), a.max(b))
492            })
493            .collect::<Vec<_>>();
494        pieces.sort_by(|left, right| left.0.total_cmp(&right.0));
495        let mut merged: Vec<(f32, f32)> = Vec::with_capacity(pieces.len());
496        for (left, right) in pieces {
497            match merged.last_mut() {
498                Some(last) if left <= last.1 + 0.5 => last.1 = last.1.max(right),
499                _ => merged.push((left, right)),
500            }
501        }
502        merged
503    }
504
505    pub(crate) fn x_for_offset(&self, offset: usize) -> f32 {
506        if self.clusters.is_empty() {
507            return self.rect.x();
508        }
509
510        let offset = offset.clamp(self.byte_range.start, self.byte_range.end);
511
512        if offset <= self.byte_range.start {
513            return self.clusters[0].x_start;
514        }
515
516        for cluster in &self.clusters {
517            if offset <= cluster.range.end {
518                let span = (cluster.range.end.saturating_sub(cluster.range.start)).max(1) as f32;
519                let local = offset.saturating_sub(cluster.range.start) as f32;
520                let t = (local / span).clamp(0.0, 1.0);
521                return cluster.x_start + ((cluster.x_end - cluster.x_start) * t);
522            }
523        }
524
525        self.clusters
526            .last()
527            .map(|cluster| cluster.x_end)
528            .unwrap_or(self.rect.max_x())
529    }
530
531    pub(crate) fn offset_for_x(&self, x: f32) -> usize {
532        let mut nearest_offset = self.byte_range.start;
533        let mut nearest_distance = f32::INFINITY;
534        // Clusters are stored in logical text order, which can run in either
535        // direction on screen. Find the visual cluster containing the point.
536        for cluster in &self.clusters {
537            let cluster_min = cluster.x_start.min(cluster.x_end);
538            let cluster_max = cluster.x_start.max(cluster.x_end);
539            let midpoint = (cluster_min + cluster_max) * 0.5;
540            if cluster_min < cluster_max && x >= cluster_min && x <= cluster_max {
541                let ascending = cluster.x_start <= cluster.x_end;
542                return if x <= midpoint {
543                    if ascending {
544                        cluster.range.start
545                    } else {
546                        cluster.range.end
547                    }
548                } else if ascending {
549                    cluster.range.end
550                } else {
551                    cluster.range.start
552                };
553            }
554            // Outside the text (or in a visual gap), use the nearest edge.
555            for (edge, offset) in [
556                (cluster.x_start, cluster.range.start),
557                (cluster.x_end, cluster.range.end),
558            ] {
559                let distance = (x - edge).abs();
560                if distance < nearest_distance {
561                    nearest_distance = distance;
562                    nearest_offset = offset;
563                }
564            }
565        }
566        nearest_offset
567    }
568}
569
570#[derive(Debug, Clone, PartialEq)]
571pub(crate) struct TextLayoutData {
572    pub metadata: TextLayoutMetadata,
573    pub text: String,
574    pub box_size: Size,
575    pub faces: Vec<ResolvedTextFace>,
576    pub measurement: TextMeasurement,
577    pub paragraphs: Vec<TextParagraphLayout>,
578    pub lines: Vec<TextLine>,
579    pub runs: Vec<TextLayoutRun>,
580    pub clusters: Vec<TextCluster>,
581    pub glyphs: Vec<ShapedGlyph>,
582}
583
584#[derive(Debug, Clone, PartialEq)]
585pub struct TextLayout {
586    pub(crate) data: Arc<TextLayoutData>,
587    pub(crate) document: Arc<TextDocument>,
588    pub(crate) primary_style: TextStyle,
589}
590
591#[derive(Debug, Clone, PartialEq)]
592pub struct PersistentTextLayout {
593    handle: TextLayoutHandle,
594    layout: TextLayout,
595}
596
597impl PersistentTextLayout {
598    pub fn new(handle: TextLayoutHandle, layout: TextLayout) -> Self {
599        Self { handle, layout }
600    }
601
602    pub fn handle(&self) -> TextLayoutHandle {
603        self.handle
604    }
605
606    pub fn version(&self) -> TextLayoutVersion {
607        self.layout.version()
608    }
609
610    pub fn metadata(&self) -> TextLayoutMetadata {
611        self.layout.metadata()
612    }
613
614    pub fn layout(&self) -> &TextLayout {
615        &self.layout
616    }
617
618    pub fn into_parts(self) -> (TextLayoutHandle, TextLayout) {
619        (self.handle, self.layout)
620    }
621}
622
623impl Deref for PersistentTextLayout {
624    type Target = TextLayout;
625
626    fn deref(&self) -> &Self::Target {
627        &self.layout
628    }
629}
630
631impl AsRef<TextLayout> for PersistentTextLayout {
632    fn as_ref(&self) -> &TextLayout {
633        &self.layout
634    }
635}
636
637#[derive(Debug, Clone, PartialEq, Default)]
638pub struct TextLayoutRegistry {
639    layouts: HashMap<TextLayoutHandle, TextLayout>,
640}
641
642impl TextLayoutRegistry {
643    pub fn get(&self, handle: TextLayoutHandle) -> Option<&TextLayout> {
644        self.layouts.get(&handle)
645    }
646
647    pub fn contains(&self, handle: TextLayoutHandle) -> bool {
648        self.layouts.contains_key(&handle)
649    }
650
651    pub fn len(&self) -> usize {
652        self.layouts.len()
653    }
654
655    pub fn is_empty(&self) -> bool {
656        self.layouts.is_empty()
657    }
658
659    pub fn iter(&self) -> impl Iterator<Item = (TextLayoutHandle, &TextLayout)> {
660        self.layouts
661            .iter()
662            .map(|(handle, layout)| (*handle, layout))
663    }
664
665    pub(crate) fn insert(&mut self, handle: TextLayoutHandle, layout: TextLayout) {
666        self.layouts.insert(handle, layout);
667    }
668
669    pub(crate) fn retain_handles(&mut self, handles: &HashSet<TextLayoutHandle>) {
670        self.layouts
671            .retain(|handle, _layout| handles.contains(handle));
672    }
673}
674
675#[derive(Debug, Clone)]
676pub struct TextLayoutView<'a> {
677    pub metadata: TextLayoutMetadata,
678    pub text: &'a str,
679    pub document: &'a TextDocument,
680    pub box_size: Size,
681    pub measurement: TextMeasurement,
682    pub faces: &'a [ResolvedTextFace],
683    pub paragraphs: &'a [TextParagraphLayout],
684    pub lines: &'a [TextLine],
685    pub runs: &'a [TextLayoutRun],
686    pub clusters: &'a [TextCluster],
687    pub glyphs: &'a [ShapedGlyph],
688}
689
690#[derive(Debug, Clone)]
691pub struct TextLineWindow<'a> {
692    layout: &'a TextLayout,
693    pub metadata: TextLayoutMetadata,
694    pub line_range: Range<usize>,
695    pub run_range: Range<usize>,
696    pub cluster_range: Range<usize>,
697    pub glyph_range: Range<usize>,
698}
699
700impl<'a> TextLineWindow<'a> {
701    pub fn lines(&self) -> &'a [TextLine] {
702        &self.layout.data.lines[self.line_range.clone()]
703    }
704
705    pub fn bounds(&self) -> Rect {
706        self.lines()
707            .iter()
708            .map(|line| line.rect)
709            .reduce(|bounds, rect| bounds.union(rect))
710            .unwrap_or(Rect::ZERO)
711    }
712
713    pub fn runs(&self) -> &'a [TextLayoutRun] {
714        &self.layout.data.runs[self.run_range.clone()]
715    }
716
717    pub fn clusters(&self) -> &'a [TextCluster] {
718        &self.layout.data.clusters[self.cluster_range.clone()]
719    }
720
721    pub fn glyphs(&self) -> &'a [ShapedGlyph] {
722        &self.layout.data.glyphs[self.glyph_range.clone()]
723    }
724
725    pub fn glyph_instances(&self) -> impl ExactSizeIterator<Item = TextGlyphInstance<'a>> + 'a {
726        (self.glyph_range.start..self.glyph_range.end)
727            .map(|index| self.layout.glyph_instance(index))
728    }
729}
730
731#[derive(Debug, Clone, Copy)]
732pub struct TextRunView<'a> {
733    pub index: usize,
734    pub run: &'a TextLayoutRun,
735    pub style: &'a TextStyle,
736    pub face: &'a ResolvedTextFace,
737    pub line: &'a TextLine,
738    pub clusters: &'a [TextCluster],
739    pub glyphs: &'a [ShapedGlyph],
740}
741
742#[derive(Debug, Clone, Copy)]
743pub struct TextGlyphInstance<'a> {
744    pub index: usize,
745    pub glyph: &'a ShapedGlyph,
746    pub style: &'a TextStyle,
747    pub face: &'a ResolvedTextFace,
748    pub run: &'a TextLayoutRun,
749    pub line: &'a TextLine,
750}
751
752impl TextLayout {
753    pub fn id(&self) -> TextLayoutId {
754        self.data.metadata.id
755    }
756
757    pub fn version(&self) -> TextLayoutVersion {
758        self.data.metadata.version
759    }
760
761    pub fn metadata(&self) -> TextLayoutMetadata {
762        self.data.metadata
763    }
764
765    pub fn text(&self) -> &str {
766        &self.data.text
767    }
768
769    pub fn document(&self) -> &TextDocument {
770        self.document.as_ref()
771    }
772
773    pub fn style(&self) -> &TextStyle {
774        &self.primary_style
775    }
776
777    pub fn box_size(&self) -> Size {
778        self.data.box_size
779    }
780
781    pub fn measurement(&self) -> TextMeasurement {
782        self.data.measurement
783    }
784
785    pub fn paragraphs(&self) -> &[TextParagraphLayout] {
786        &self.data.paragraphs
787    }
788
789    pub fn lines(&self) -> &[TextLine] {
790        &self.data.lines
791    }
792
793    pub fn runs(&self) -> &[TextLayoutRun] {
794        &self.data.runs
795    }
796
797    pub fn clusters(&self) -> &[TextCluster] {
798        &self.data.clusters
799    }
800
801    pub fn glyphs(&self) -> &[ShapedGlyph] {
802        &self.data.glyphs
803    }
804
805    pub fn faces(&self) -> &[ResolvedTextFace] {
806        &self.data.faces
807    }
808
809    pub fn view(&self) -> TextLayoutView<'_> {
810        TextLayoutView {
811            metadata: self.metadata(),
812            text: self.text(),
813            document: self.document(),
814            box_size: self.box_size(),
815            measurement: self.measurement(),
816            faces: self.faces(),
817            paragraphs: self.paragraphs(),
818            lines: self.lines(),
819            runs: self.runs(),
820            clusters: self.clusters(),
821            glyphs: self.glyphs(),
822        }
823    }
824
825    pub fn run_style(&self, run_index: usize) -> &TextStyle {
826        self.document
827            .span_style(self.data.runs[run_index].span_id.clone())
828    }
829
830    pub fn run_face(&self, run_index: usize) -> &ResolvedTextFace {
831        &self.data.faces[self.data.runs[run_index].face_index]
832    }
833
834    pub fn glyph_style(&self, glyph: &ShapedGlyph) -> &TextStyle {
835        self.document.span_style(glyph.span_id.clone())
836    }
837
838    pub fn glyph_face(&self, glyph: &ShapedGlyph) -> &ResolvedTextFace {
839        &self.data.faces[glyph.face_index]
840    }
841
842    pub fn run_view(&self, run_index: usize) -> TextRunView<'_> {
843        let run = &self.data.runs[run_index];
844        TextRunView {
845            index: run_index,
846            run,
847            style: self.run_style(run_index),
848            face: self.run_face(run_index),
849            line: &self.data.lines[run.line_index],
850            clusters: &self.data.clusters[run.cluster_range.clone()],
851            glyphs: &self.data.glyphs[run.glyph_range.clone()],
852        }
853    }
854
855    pub fn run_views(&self) -> impl ExactSizeIterator<Item = TextRunView<'_>> + '_ {
856        (0..self.data.runs.len()).map(|index| self.run_view(index))
857    }
858
859    pub fn glyph_instance(&self, glyph_index: usize) -> TextGlyphInstance<'_> {
860        let glyph = &self.data.glyphs[glyph_index];
861        TextGlyphInstance {
862            index: glyph_index,
863            glyph,
864            style: self.glyph_style(glyph),
865            face: self.glyph_face(glyph),
866            run: &self.data.runs[glyph.run_index],
867            line: &self.data.lines[glyph.line_index],
868        }
869    }
870
871    pub fn glyph_instances(&self) -> impl ExactSizeIterator<Item = TextGlyphInstance<'_>> + '_ {
872        (0..self.data.glyphs.len()).map(|index| self.glyph_instance(index))
873    }
874
875    pub fn line_window(&self, line_range: Range<usize>) -> TextLineWindow<'_> {
876        let line_start = line_range.start.min(self.data.lines.len());
877        let line_end = line_range.end.min(self.data.lines.len()).max(line_start);
878        let clamped_line_range = line_start..line_end;
879        let (run_range, cluster_range, glyph_range) = if clamped_line_range.is_empty() {
880            (0..0, 0..0, 0..0)
881        } else {
882            collapse_range(
883                self.data.lines[clamped_line_range.clone()]
884                    .iter()
885                    .map(|line| line.run_range.clone()),
886            )
887            .zip(collapse_range(
888                self.data.lines[clamped_line_range.clone()]
889                    .iter()
890                    .map(|line| line.cluster_range.clone()),
891            ))
892            .zip(collapse_range(
893                self.data.lines[clamped_line_range.clone()]
894                    .iter()
895                    .map(|line| line.glyph_range.clone()),
896            ))
897            .map(|((run_range, cluster_range), glyph_range)| {
898                (run_range, cluster_range, glyph_range)
899            })
900            .unwrap_or((0..0, 0..0, 0..0))
901        };
902
903        TextLineWindow {
904            layout: self,
905            metadata: self.metadata(),
906            line_range: clamped_line_range,
907            run_range,
908            cluster_range,
909            glyph_range,
910        }
911    }
912
913    pub fn caret(&self, cursor: TextCursor) -> TextCaret {
914        let line_index = self.line_index_for_offset(cursor.utf8_offset);
915        let line = &self.data.lines[line_index];
916        TextCaret {
917            cursor,
918            line_index,
919            rect: Rect::new(
920                line.x_for_offset(cursor.utf8_offset),
921                line.rect.y(),
922                1.0,
923                line.rect.height(),
924            ),
925        }
926    }
927
928    pub fn caret_rect(&self, utf8_offset: usize) -> Rect {
929        self.caret(TextCursor::new(utf8_offset)).rect
930    }
931
932    pub fn hit_test_point(&self, point: Point) -> TextCursor {
933        if self.data.lines.is_empty() {
934            return TextCursor::default();
935        }
936
937        let line = &self.data.lines[self.line_index_for_y(point.y)];
938        TextCursor::new(line.offset_for_x(point.x))
939    }
940
941    pub fn selection_geometry(&self, selection: &TextSelection) -> TextSelectionGeometry {
942        let range = selection.sorted_range(self.data.text.len());
943        if range.start == range.end {
944            return TextSelectionGeometry {
945                rects: Vec::new(),
946                bounds: None,
947            };
948        }
949
950        let mut rects = Vec::new();
951
952        for line in &self.data.lines {
953            let line_start = range.start.max(line.byte_range.start);
954            let line_end = range.end.min(line.byte_range.end);
955            if line_start >= line_end {
956                continue;
957            }
958
959            let pieces = line.selected_pieces(line_start..line_end);
960            if pieces.is_empty() {
961                let x0 = line.x_for_offset(line_start);
962                let x1 = line.x_for_offset(line_end);
963                pieces_to_rects(line, &[(x0.min(x1), x0.max(x1))], &mut rects);
964            } else {
965                pieces_to_rects(line, &pieces, &mut rects);
966            }
967        }
968
969        let bounds = rects
970            .iter()
971            .copied()
972            .reduce(|bounds, rect| bounds.union(rect));
973        TextSelectionGeometry { rects, bounds }
974    }
975
976    pub fn selection_rects(&self, range: Range<usize>) -> Vec<Rect> {
977        self.selection_geometry(&TextSelection::new(
978            TextCursor::new(range.start),
979            TextCursor::new(range.end),
980        ))
981        .rects
982    }
983
984    pub fn selection_bounds(&self, range: Range<usize>) -> Option<Rect> {
985        self.selection_geometry(&TextSelection::new(
986            TextCursor::new(range.start),
987            TextCursor::new(range.end),
988        ))
989        .bounds
990    }
991
992    pub(crate) fn line_index_for_offset(&self, utf8_offset: usize) -> usize {
993        let offset = utf8_offset.min(self.data.text.len());
994        self.data
995            .lines
996            .iter()
997            .position(|line| offset <= line.byte_range.end)
998            .unwrap_or_else(|| self.data.lines.len().saturating_sub(1))
999    }
1000
1001    fn line_index_for_y(&self, y: f32) -> usize {
1002        self.data
1003            .lines
1004            .iter()
1005            .enumerate()
1006            .min_by(|(_, left), (_, right)| {
1007                let left_center = left.rect.y() + (left.rect.height() * 0.5);
1008                let right_center = right.rect.y() + (right.rect.height() * 0.5);
1009                (left_center - y)
1010                    .abs()
1011                    .partial_cmp(&(right_center - y).abs())
1012                    .unwrap_or(std::cmp::Ordering::Equal)
1013            })
1014            .map(|(index, _)| index)
1015            .unwrap_or_else(|| self.data.lines.len().saturating_sub(1))
1016    }
1017
1018    pub(crate) fn with_document(mut self, document: TextDocument) -> Self {
1019        self.primary_style = document.primary_style();
1020        self.document = Arc::new(document);
1021        self
1022    }
1023
1024    #[cfg(test)]
1025    pub(crate) fn shares_storage_with(&self, other: &Self) -> bool {
1026        Arc::ptr_eq(&self.data, &other.data)
1027    }
1028}
1029
1030fn collapse_range(ranges: impl Iterator<Item = Range<usize>>) -> Option<Range<usize>> {
1031    ranges.fold(None, |current: Option<Range<usize>>, range| {
1032        Some(match current {
1033            Some(existing) => existing.start.min(range.start)..existing.end.max(range.end),
1034            None => range,
1035        })
1036    })
1037}
1038
1039#[derive(Debug, Clone, PartialEq)]
1040pub struct ShapedText {
1041    pub origin: Point,
1042    pub layout_handle: TextLayoutHandle,
1043    pub layout_version: TextLayoutVersion,
1044    pub bounds: Rect,
1045    pub color_override: Option<Color>,
1046}
1047
1048impl ShapedText {
1049    pub fn new(origin: Point, layout: &PersistentTextLayout) -> Self {
1050        Self {
1051            origin,
1052            layout_handle: layout.handle(),
1053            layout_version: layout.version(),
1054            bounds: layout.measurement().bounds,
1055            color_override: None,
1056        }
1057    }
1058
1059    pub fn from_layout(
1060        origin: Point,
1061        layout_handle: TextLayoutHandle,
1062        layout: &TextLayout,
1063    ) -> Self {
1064        Self {
1065            origin,
1066            layout_handle,
1067            layout_version: layout.version(),
1068            bounds: layout.measurement().bounds,
1069            color_override: None,
1070        }
1071    }
1072
1073    pub fn with_color(mut self, color: Color) -> Self {
1074        self.color_override = Some(color);
1075        self
1076    }
1077
1078    pub fn translated_bounds(&self) -> Rect {
1079        self.bounds.translate(self.origin.to_vector())
1080    }
1081
1082    pub fn resolve<'a>(&self, registry: &'a TextLayoutRegistry) -> Option<&'a TextLayout> {
1083        let layout = registry.get(self.layout_handle)?;
1084        (layout.version() == self.layout_version).then_some(layout)
1085    }
1086}
1087
1088#[derive(Debug, Clone, PartialEq)]
1089pub struct ShapedTextWindow {
1090    pub origin: Point,
1091    pub layout_handle: TextLayoutHandle,
1092    pub layout_version: TextLayoutVersion,
1093    pub line_range: Range<usize>,
1094    pub bounds: Rect,
1095    pub color_override: Option<Color>,
1096}
1097
1098impl ShapedTextWindow {
1099    pub fn new(origin: Point, layout: &PersistentTextLayout, line_range: Range<usize>) -> Self {
1100        Self::from_layout(origin, layout.handle(), layout, line_range)
1101    }
1102
1103    pub fn from_layout(
1104        origin: Point,
1105        layout_handle: TextLayoutHandle,
1106        layout: &TextLayout,
1107        line_range: Range<usize>,
1108    ) -> Self {
1109        let window = layout.line_window(line_range);
1110        Self {
1111            origin,
1112            layout_handle,
1113            layout_version: layout.version(),
1114            line_range: window.line_range.clone(),
1115            bounds: window.bounds(),
1116            color_override: None,
1117        }
1118    }
1119
1120    pub fn with_color(mut self, color: Color) -> Self {
1121        self.color_override = Some(color);
1122        self
1123    }
1124
1125    pub fn translated_bounds(&self) -> Rect {
1126        self.bounds.translate(self.origin.to_vector())
1127    }
1128
1129    pub fn resolve<'a>(&self, registry: &'a TextLayoutRegistry) -> Option<&'a TextLayout> {
1130        let layout = registry.get(self.layout_handle)?;
1131        (layout.version() == self.layout_version).then_some(layout)
1132    }
1133}