Skip to main content

cranpose_ui/text/
prepared_text_layout.rs

1use std::{cell::OnceCell, rc::Rc, sync::Arc};
2
3use cranpose_core::PackedU64;
4use cranpose_text::TextLayout;
5use cranpose_ui_graphics::{Size, TextLayoutHandle};
6
7use super::{
8    AnnotatedString, RenderString, TextAlign,
9    measure::{TextFrame, TextMetrics},
10    style::TextStyle,
11};
12use crate::text_layout_result::TextLayoutResult;
13
14/// A text laid out between two widths: its glyphs and lines, which every
15/// query, measurement and renderer reads, and the size it measures.
16#[derive(Clone, Debug)]
17pub struct PreparedTextLayout {
18    /// The text that was laid out, with its spans, shared with the text it
19    /// came from.
20    pub text: Arc<RenderString>,
21    /// The style the text draws in, shared with every render node drawn
22    /// from this layout.
23    pub visual_style: Arc<TextStyle>,
24    /// The lines and glyphs.
25    pub layout: TextLayout,
26    // The widest the text could be, and the fewest lines its height covers,
27    // which its metrics follow from with its layout.
28    max_width: f32,
29    min_lines: u32,
30    pub(crate) visual_style_hash: OnceCell<PackedU64>,
31    // The layout as a draw scope carries it, made on first use.
32    layout_handle: OnceCell<TextLayoutHandle>,
33}
34
35impl PreparedTextLayout {
36    // The prepared layout of `text` in `style` laid out as `layout`, `max_width`
37    // the widest it could be.
38    pub(super) fn new(
39        text: &AnnotatedString,
40        style: Arc<TextStyle>,
41        layout: TextLayout,
42        (max_width, min_lines): (f32, usize),
43    ) -> Self {
44        Self {
45            max_width,
46            min_lines: u32::try_from(min_lines).unwrap_or(u32::MAX),
47            text: Arc::clone(text.render_string()),
48            visual_style: style,
49            layout,
50            visual_style_hash: OnceCell::new(),
51            layout_handle: OnceCell::new(),
52        }
53    }
54
55    // Takes `text` in `style`, which its layout holds laid out already, in
56    // place of what it held.
57    pub(super) fn retext(
58        &mut self,
59        text: &AnnotatedString,
60        style: Arc<TextStyle>,
61        frame: TextFrame,
62    ) {
63        let min_lines = frame.options.normalized().min_lines;
64        self.max_width = frame.max_width;
65        self.min_lines = u32::try_from(min_lines).unwrap_or(u32::MAX);
66        self.text = Arc::clone(text.render_string());
67        self.visual_style = style;
68        self.visual_style_hash = OnceCell::new();
69        self.layout_handle = OnceCell::new();
70    }
71
72    // Lets go of what a layout keeps of the text it shows, as it waits for
73    // another: its draw scope handle, which shares its lines, and its string,
74    // which it returns.
75    pub(super) fn take_text(&mut self) -> Arc<RenderString> {
76        self.layout_handle = OnceCell::new();
77        std::mem::replace(
78            &mut self.text,
79            Arc::clone(AnnotatedString::default().render_string()),
80        )
81    }
82
83    /// The paragraph's width, within the widths it was laid out between, and
84    /// the height of all its lines together.
85    pub fn size(&self) -> Size {
86        Size::new(
87            self.layout.width().min(self.max_width),
88            self.layout.height(),
89        )
90    }
91
92    // The max widths at which the text laid out from `min_width` gives this
93    // layout again: its lines, its width and its size the same.
94    pub(crate) fn max_widths_kept(&self, min_width: f32) -> cranpose_ui_layout::BoundRange {
95        let width = self.layout.width();
96        // A paragraph wider than its max measures as the max, which moves
97        // with it.
98        if self.max_width < width {
99            return cranpose_ui_layout::BoundRange::exactly(self.max_width);
100        }
101        let (low, high) = self.layout.max_widths_kept(min_width);
102        cranpose_ui_layout::BoundRange {
103            low: low.max(width),
104            high,
105        }
106    }
107
108    /// Size and line count.
109    pub fn metrics(&self) -> TextMetrics {
110        let layout = &self.layout;
111        let size = self.size();
112        TextMetrics {
113            width: size.width,
114            height: size.height,
115            line_height: layout.line_advance(),
116            line_count: layout
117                .line_count()
118                .max(usize::try_from(self.min_lines).unwrap_or(usize::MAX)),
119        }
120    }
121
122    /// The first and last baselines.
123    pub fn alignment_lines(&self) -> cranpose_ui_layout::AlignmentLines {
124        let layout = &self.layout;
125        cranpose_ui_layout::AlignmentLines::new(
126            Some(layout.line_baseline(0)),
127            Some(layout.line_baseline(layout.line_count() - 1)),
128        )
129    }
130
131    /// True when the text did not fit: it had more lines than the line limit,
132    /// or was wider than the widest it could be.
133    pub fn did_overflow(&self) -> bool {
134        self.layout.did_overflow_height() || self.layout.did_overflow_width()
135    }
136
137    // The layout as a draw scope carries it to a renderer, made once for
138    // every frame that draws the same text.
139    pub(crate) fn layout_handle(&self) -> TextLayoutHandle {
140        self.layout_handle
141            .get_or_init(|| TextLayoutHandle::from(Arc::new(self.layout.clone())))
142            .clone()
143    }
144
145    // This layout at `widths`, at which it breaks into the same lines: itself when its width there is its own, else a copy whose
146    // lines `align` places across that width. The copy keeps the text as a
147    // renderer draws it and the style's hash, and takes the allocation of
148    // `spare` when nothing else holds it.
149    pub(crate) fn at_widths(
150        self: &Rc<Self>,
151        widths: (f32, f32),
152        align: TextAlign,
153        spare: Option<Rc<Self>>,
154    ) -> Rc<Self> {
155        let width = self.layout.width_between(widths.0, widths.1);
156        if width.to_bits() == self.layout.width().to_bits() {
157            return Rc::clone(self);
158        }
159        self.aligned_at(widths, align, spare)
160    }
161
162    // The copy `at_widths` makes. Out of line: the copy costs more than the
163    // call, and a layout held at its own width takes none.
164    #[inline(never)]
165    fn aligned_at(
166        self: &Rc<Self>,
167        widths: (f32, f32),
168        align: TextAlign,
169        spare: Option<Rc<Self>>,
170    ) -> Rc<Self> {
171        let mut aligned = Self {
172            text: Arc::clone(&self.text),
173            visual_style: Arc::clone(&self.visual_style),
174            layout: self.layout.clone(),
175            max_width: self.max_width,
176            min_lines: self.min_lines,
177            visual_style_hash: self.visual_style_hash.clone(),
178            layout_handle: OnceCell::new(),
179        };
180        aligned.realign(widths, align);
181        if let Some(mut spare) = spare
182            && let Some(slot) = Rc::get_mut(&mut spare)
183        {
184            *slot = aligned;
185            return spare;
186        }
187        Rc::new(aligned)
188    }
189
190    // Places the lines across `(min_width, max_width)`, at which the layout
191    // breaks into the same lines, as `align` says.
192    pub(crate) fn realign(&mut self, (min_width, max_width): (f32, f32), align: TextAlign) {
193        self.layout.align(min_width, max_width, align);
194        self.max_width = max_width;
195        self.layout_handle = OnceCell::new();
196    }
197
198    // `realign` when the layout breaks into the same lines between
199    // `(min_width, max_width)`; `false`, leaving it as it was, when not.
200    pub(crate) fn try_realign(
201        &mut self,
202        (min_width, max_width): (f32, f32),
203        align: TextAlign,
204    ) -> bool {
205        let held = self.layout.try_align(min_width, max_width, align);
206        if held {
207            self.max_width = max_width;
208            self.layout_handle = OnceCell::new();
209        }
210        held
211    }
212
213    /// The display text as a renderer draws it: the text's own content, so
214    /// every frame and scene rebuild drawing this layout hands over the same
215    /// allocation.
216    pub fn render_text(&self) -> Arc<RenderString> {
217        Arc::clone(&self.text)
218    }
219
220    /// [`TextStyle::render_hash`] of `visual_style`, hashed once for the
221    /// layout, or handed over by the node that knows its style's hash.
222    pub fn visual_style_hash(&self) -> u64 {
223        if let Some(hash) = self.visual_style_hash.get() {
224            return hash.get();
225        }
226        let hash = self.visual_style.render_hash();
227        let _ = self.visual_style_hash.set(PackedU64::new(hash));
228        hash
229    }
230
231    /// The layout's queries, as Compose's `TextLayoutResult` gives them.
232    pub fn result(&self) -> TextLayoutResult {
233        TextLayoutResult::new(self.layout.clone())
234    }
235}
236
237impl PartialEq for PreparedTextLayout {
238    fn eq(&self, other: &Self) -> bool {
239        self.text == other.text
240            && self.visual_style == other.visual_style
241            && self.metrics() == other.metrics()
242            && self.alignment_lines() == other.alignment_lines()
243            && self.did_overflow() == other.did_overflow()
244    }
245}