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    /// The paragraph's width, within the widths it was laid out between, and
73    /// the height of all its lines together.
74    pub fn size(&self) -> Size {
75        Size::new(
76            self.layout.width().min(self.max_width),
77            self.layout.height(),
78        )
79    }
80
81    // The max widths at which the text laid out from `min_width` gives this
82    // layout again: its lines, its width and its size the same.
83    pub(crate) fn max_widths_kept(&self, min_width: f32) -> cranpose_ui_layout::BoundRange {
84        let width = self.layout.width();
85        // A paragraph wider than its max measures as the max, which moves
86        // with it.
87        if self.max_width < width {
88            return cranpose_ui_layout::BoundRange::exactly(self.max_width);
89        }
90        let (low, high) = self.layout.max_widths_kept(min_width);
91        cranpose_ui_layout::BoundRange {
92            low: low.max(width),
93            high,
94        }
95    }
96
97    /// Size and line count.
98    pub fn metrics(&self) -> TextMetrics {
99        let layout = &self.layout;
100        let size = self.size();
101        TextMetrics {
102            width: size.width,
103            height: size.height,
104            line_height: layout.line_advance(),
105            line_count: layout
106                .line_count()
107                .max(usize::try_from(self.min_lines).unwrap_or(usize::MAX)),
108        }
109    }
110
111    /// The first and last baselines.
112    pub fn alignment_lines(&self) -> cranpose_ui_layout::AlignmentLines {
113        let layout = &self.layout;
114        cranpose_ui_layout::AlignmentLines::new(
115            Some(layout.line_baseline(0)),
116            Some(layout.line_baseline(layout.line_count() - 1)),
117        )
118    }
119
120    /// True when the text did not fit: it had more lines than the line limit,
121    /// or was wider than the widest it could be.
122    pub fn did_overflow(&self) -> bool {
123        self.layout.did_overflow_height() || self.layout.did_overflow_width()
124    }
125
126    // The layout as a draw scope carries it to a renderer, made once for
127    // every frame that draws the same text.
128    pub(crate) fn layout_handle(&self) -> TextLayoutHandle {
129        self.layout_handle
130            .get_or_init(|| TextLayoutHandle::from(Arc::new(self.layout.clone())))
131            .clone()
132    }
133
134    // This layout at `widths`, at which it breaks into the same lines: itself when its width there is its own, else a copy whose
135    // lines `align` places across that width. The copy keeps the text as a
136    // renderer draws it and the style's hash, and takes the allocation of
137    // `spare` when nothing else holds it.
138    pub(crate) fn at_widths(
139        self: &Rc<Self>,
140        widths: (f32, f32),
141        align: TextAlign,
142        spare: Option<Rc<Self>>,
143    ) -> Rc<Self> {
144        let width = self.layout.width_between(widths.0, widths.1);
145        if width.to_bits() == self.layout.width().to_bits() {
146            return Rc::clone(self);
147        }
148        self.aligned_at(widths, align, spare)
149    }
150
151    // The copy `at_widths` makes. Out of line: the copy costs more than the
152    // call, and a layout held at its own width takes none.
153    #[inline(never)]
154    fn aligned_at(
155        self: &Rc<Self>,
156        widths: (f32, f32),
157        align: TextAlign,
158        spare: Option<Rc<Self>>,
159    ) -> Rc<Self> {
160        let mut aligned = Self {
161            text: Arc::clone(&self.text),
162            visual_style: Arc::clone(&self.visual_style),
163            layout: self.layout.clone(),
164            max_width: self.max_width,
165            min_lines: self.min_lines,
166            visual_style_hash: self.visual_style_hash.clone(),
167            layout_handle: OnceCell::new(),
168        };
169        aligned.realign(widths, align);
170        if let Some(mut spare) = spare
171            && let Some(slot) = Rc::get_mut(&mut spare)
172        {
173            *slot = aligned;
174            return spare;
175        }
176        Rc::new(aligned)
177    }
178
179    // Places the lines across `(min_width, max_width)`, at which the layout
180    // breaks into the same lines, as `align` says.
181    pub(crate) fn realign(&mut self, (min_width, max_width): (f32, f32), align: TextAlign) {
182        self.layout.align(min_width, max_width, align);
183        self.max_width = max_width;
184        self.layout_handle = OnceCell::new();
185    }
186
187    // `realign` when the layout breaks into the same lines between
188    // `(min_width, max_width)`; `false`, leaving it as it was, when not.
189    pub(crate) fn try_realign(
190        &mut self,
191        (min_width, max_width): (f32, f32),
192        align: TextAlign,
193    ) -> bool {
194        let held = self.layout.try_align(min_width, max_width, align);
195        if held {
196            self.max_width = max_width;
197            self.layout_handle = OnceCell::new();
198        }
199        held
200    }
201
202    /// The display text as a renderer draws it: the text's own content, so
203    /// every frame and scene rebuild drawing this layout hands over the same
204    /// allocation.
205    pub fn render_text(&self) -> Arc<RenderString> {
206        Arc::clone(&self.text)
207    }
208
209    /// [`TextStyle::render_hash`] of `visual_style`, hashed once for the
210    /// layout, or handed over by the node that knows its style's hash.
211    pub fn visual_style_hash(&self) -> u64 {
212        if let Some(hash) = self.visual_style_hash.get() {
213            return hash.get();
214        }
215        let hash = self.visual_style.render_hash();
216        let _ = self.visual_style_hash.set(PackedU64::new(hash));
217        hash
218    }
219
220    /// The layout's queries, as Compose's `TextLayoutResult` gives them.
221    pub fn result(&self) -> TextLayoutResult {
222        TextLayoutResult::new(self.layout.clone())
223    }
224}
225
226impl PartialEq for PreparedTextLayout {
227    fn eq(&self, other: &Self) -> bool {
228        self.text == other.text
229            && self.visual_style == other.visual_style
230            && self.metrics() == other.metrics()
231            && self.alignment_lines() == other.alignment_lines()
232            && self.did_overflow() == other.did_overflow()
233    }
234}