Skip to main content

cranpose_ui/
text_modifier_node.rs

1use std::{
2    cell::{Cell, Ref, RefCell},
3    hash::{Hash, Hasher},
4    rc::Rc,
5    sync::Arc,
6};
7
8use cranpose_foundation::{
9    Constraints, DelegatableNode, DrawModifierNode, InvalidationKind, LayoutModifierNode,
10    Measurable, ModifierNode, ModifierNodeContext, ModifierNodeElement, NodeCapabilities,
11    NodeState, SemanticsConfiguration, SemanticsNode, Size,
12};
13use smallvec::SmallVec;
14
15use crate::{
16    density::Density,
17    text::{AnnotatedString, TextLayoutOptions, TextStyle},
18};
19
20/// Node that stores text content and handles measurement, drawing, and semantics.
21///
22/// This node implements three capabilities:
23/// - **Layout**: Measures text and returns appropriate size
24/// - **Draw**: Supplies prepared text state consumed by scene building
25/// - **Semantics**: Provides text content for accessibility
26///
27/// Matches Jetpack Compose: `TextStringSimpleNode` in
28/// `compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/modifiers/TextStringSimpleNode.kt`
29#[derive(Debug)]
30pub struct TextModifierNode {
31    layout: Rc<TextPreparedLayoutOwner>,
32    density: Density,
33    state: NodeState,
34}
35
36const PREPARED_LAYOUT_CACHE_CAPACITY: usize = 4;
37
38#[derive(Clone, Debug)]
39struct TextPreparedLayoutCacheEntry {
40    widths: crate::text::measure::PreparedWidths,
41    text_generation: u64,
42    font_scale_fingerprint: u32,
43    layout: Rc<crate::text::PreparedTextLayout>,
44}
45
46/// A text node's text and its prepared layouts. The node and the slices
47/// built from it share one owner for the node's life: an update changes its
48/// source in place, so the slices read the new text without being rebuilt.
49#[derive(Debug)]
50struct TextPreparedLayoutOwner {
51    source: RefCell<TextLayoutSource>,
52    node_id: Cell<Option<cranpose_core::NodeId>>,
53    measured_max_width: Cell<Option<Option<f32>>>,
54    cache: RefCell<SmallVec<[TextPreparedLayoutCacheEntry; 1]>>,
55}
56
57/// What a text is laid out from.
58#[derive(Debug)]
59struct TextLayoutSource {
60    text: Rc<AnnotatedString>,
61    style: Arc<TextStyle>,
62    style_hash: u64,
63    options: TextLayoutOptions,
64    /// Whether layouts come from the text service's shared cache. A text
65    /// changed in place, as a ticker's is every frame, lays out unshared.
66    shares_layouts: bool,
67}
68
69#[derive(Clone, Debug)]
70pub(crate) struct TextPreparedLayoutHandle {
71    owner: Rc<TextPreparedLayoutOwner>,
72}
73
74impl TextPreparedLayoutOwner {
75    fn new(text: Rc<AnnotatedString>, style: Arc<TextStyle>, options: TextLayoutOptions) -> Self {
76        let style_hash = style.render_hash();
77        Self {
78            source: RefCell::new(TextLayoutSource {
79                text,
80                style,
81                style_hash,
82                options: options.normalized(),
83                shares_layouts: true,
84            }),
85            node_id: Cell::new(None),
86            measured_max_width: Cell::new(None),
87            cache: RefCell::new(SmallVec::new()),
88        }
89    }
90
91    /// Lays the text out from `text`, `style` and normalized `options` from
92    /// now on, dropping the layouts prepared from the old ones. The source
93    /// takes the element's style even when it equals the current one, so
94    /// the element, the source and the layouts prepared next share one
95    /// copy; the old one leaves with the layouts that hold it.
96    fn update(
97        &self,
98        text: &Rc<AnnotatedString>,
99        style: &Arc<TextStyle>,
100        options: TextLayoutOptions,
101    ) {
102        let mut source = self.source.borrow_mut();
103        let shared_style = Arc::ptr_eq(&source.style, style);
104        let same_style = shared_style || *source.style == **style;
105        if source.text == *text && same_style && source.options == options {
106            return;
107        }
108        if !same_style {
109            source.style_hash = style.render_hash();
110        }
111        if !shared_style {
112            source.style = Arc::clone(style);
113        }
114        source.text = Rc::clone(text);
115        source.options = options;
116        source.shares_layouts = false;
117        drop(source);
118        self.cache.borrow_mut().clear();
119    }
120
121    fn annotated_text(&self) -> Ref<'_, Rc<AnnotatedString>> {
122        Ref::map(self.source.borrow(), |source| &source.text)
123    }
124
125    fn style(&self) -> Ref<'_, TextStyle> {
126        Ref::map(self.source.borrow(), |source| &*source.style)
127    }
128
129    fn options(&self) -> TextLayoutOptions {
130        self.source.borrow().options
131    }
132
133    fn node_id(&self) -> Option<cranpose_core::NodeId> {
134        self.node_id.get()
135    }
136
137    fn set_node_id(&self, node_id: Option<cranpose_core::NodeId>) {
138        if self.node_id.replace(node_id) != node_id {
139            self.cache.borrow_mut().clear();
140        }
141    }
142
143    fn with_prepared<R>(
144        &self,
145        max_width: Option<f32>,
146        read: impl FnOnce(&Rc<crate::text::PreparedTextLayout>) -> R,
147    ) -> R {
148        let normalized_max_width = max_width.filter(|width| width.is_finite() && *width > 0.0);
149        let (text_generation, font_scale_fingerprint) = crate::render_state::text_layout_stamp();
150
151        {
152            let mut cache = self.cache.borrow_mut();
153            if let Some(index) = cache.iter().position(|entry| {
154                entry.widths.hold(normalized_max_width)
155                    && entry.text_generation == text_generation
156                    && entry.font_scale_fingerprint == font_scale_fingerprint
157            }) {
158                cache[..=index].rotate_right(1);
159                return read(&cache[0].layout);
160            }
161        }
162
163        let source = self.source.borrow();
164        let prepare = if source.shares_layouts {
165            crate::text::prepare_text_layout_for_node
166        } else {
167            crate::text::measure::prepare_unshared_text_layout_for_node
168        };
169        let prepared = prepare(
170            self.node_id(),
171            &source.text,
172            &source.style,
173            source.options,
174            normalized_max_width,
175        );
176        if Arc::ptr_eq(&prepared.visual_style, &source.style) {
177            let _ = prepared.visual_style_hash.set(source.style_hash);
178        }
179        let widths = crate::text::measure::PreparedWidths::of(
180            source.text.as_ref(),
181            source.options,
182            normalized_max_width,
183            &prepared,
184        );
185        drop(source);
186
187        let mut cache = self.cache.borrow_mut();
188        cache.insert(
189            0,
190            TextPreparedLayoutCacheEntry {
191                widths,
192                text_generation,
193                font_scale_fingerprint,
194                layout: prepared,
195            },
196        );
197        cache.truncate(PREPARED_LAYOUT_CACHE_CAPACITY);
198        read(&cache[0].layout)
199    }
200
201    /// The size of the layout the cache holds for `max_width` and the max
202    /// widths that layout holds for; `None` when the cache holds none.
203    fn cached_widths(
204        &self,
205        max_width: Option<f32>,
206    ) -> Option<(Size, crate::text::measure::PreparedWidths)> {
207        let normalized_max_width = max_width.filter(|width| width.is_finite() && *width > 0.0);
208        let (text_generation, font_scale_fingerprint) = crate::render_state::text_layout_stamp();
209        self.cache
210            .borrow()
211            .iter()
212            .find(|entry| {
213                entry.widths.hold(normalized_max_width)
214                    && entry.text_generation == text_generation
215                    && entry.font_scale_fingerprint == font_scale_fingerprint
216            })
217            .map(|entry| {
218                (
219                    Size::new(entry.layout.metrics.width, entry.layout.metrics.height),
220                    entry.widths,
221                )
222            })
223    }
224
225    fn measure_text_content(&self, max_width: Option<f32>) -> Size {
226        self.with_prepared(max_width, |prepared| Size {
227            width: prepared.metrics.width,
228            height: prepared.metrics.height,
229        })
230    }
231
232    fn measure_layout(&self, max_width: Option<f32>) -> (Size, cranpose_ui_layout::AlignmentLines) {
233        self.measured_max_width.set(Some(max_width));
234        self.with_prepared(max_width, |prepared| {
235            (
236                Size::new(prepared.metrics.width, prepared.metrics.height),
237                prepared.alignment_lines,
238            )
239        })
240    }
241
242    fn measured_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
243        self.measured_max_width
244            .get()
245            .map(|max_width| self.with_prepared(max_width, Rc::clone))
246    }
247}
248
249impl TextPreparedLayoutHandle {
250    fn new(owner: Rc<TextPreparedLayoutOwner>) -> Self {
251        Self { owner }
252    }
253
254    pub(crate) fn annotated_text(&self) -> Ref<'_, Rc<AnnotatedString>> {
255        self.owner.annotated_text()
256    }
257
258    pub(crate) fn style(&self) -> Ref<'_, TextStyle> {
259        self.owner.style()
260    }
261
262    pub(crate) fn options(&self) -> TextLayoutOptions {
263        self.owner.options()
264    }
265
266    pub(crate) fn measured_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
267        self.owner.measured_layout()
268    }
269}
270
271impl TextModifierNode {
272    /// A text node sized on `density`'s device pixel grid.
273    pub fn new(
274        text: Rc<AnnotatedString>,
275        style: impl Into<Arc<TextStyle>>,
276        options: TextLayoutOptions,
277        density: Density,
278    ) -> Self {
279        Self {
280            layout: Rc::new(TextPreparedLayoutOwner::new(text, style.into(), options)),
281            density,
282            state: NodeState::new(),
283        }
284    }
285
286    /// The text's size rounded up to whole device pixels, as Compose sizes a
287    /// text node (`TextLayoutResult.size` is the paragraph's size, `ceil`ed),
288    /// so whatever follows it starts on the pixel grid.
289    fn pixel_size(&self, size: Size) -> Size {
290        Size {
291            width: self.density.ceil(size.width),
292            height: self.density.ceil(size.height),
293        }
294    }
295
296    pub fn text(&self) -> Ref<'_, str> {
297        Ref::map(self.layout.annotated_text(), |text| text.text.as_str())
298    }
299
300    pub fn annotated_text(&self) -> Rc<AnnotatedString> {
301        Rc::clone(&self.layout.annotated_text())
302    }
303
304    pub fn style(&self) -> Ref<'_, TextStyle> {
305        self.layout.style()
306    }
307
308    pub fn options(&self) -> TextLayoutOptions {
309        self.layout.options()
310    }
311
312    fn measure_text_content(&self, max_width: Option<f32>) -> Size {
313        self.layout.measure_text_content(max_width)
314    }
315
316    pub(crate) fn prepared_layout_handle(&self) -> TextPreparedLayoutHandle {
317        TextPreparedLayoutHandle::new(self.layout.clone())
318    }
319}
320
321impl DelegatableNode for TextModifierNode {
322    fn node_state(&self) -> &NodeState {
323        &self.state
324    }
325}
326
327impl ModifierNode for TextModifierNode {
328    fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
329        self.layout.set_node_id(context.node_id());
330        context.invalidate(InvalidationKind::Layout);
331        context.invalidate(InvalidationKind::Draw);
332        context.invalidate(InvalidationKind::Semantics);
333    }
334
335    fn on_detach(&mut self) {
336        self.layout.set_node_id(None);
337    }
338
339    fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
340        Some(self)
341    }
342
343    fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
344        Some(self)
345    }
346
347    fn as_semantics_node(&self) -> Option<&dyn SemanticsNode> {
348        Some(self)
349    }
350
351    fn as_semantics_node_mut(&mut self) -> Option<&mut dyn SemanticsNode> {
352        Some(self)
353    }
354
355    fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
356        Some(self)
357    }
358
359    fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
360        Some(self)
361    }
362}
363
364impl LayoutModifierNode for TextModifierNode {
365    /// A text holds while its layout does and the bounds keep its size: it
366    /// measures nothing it wraps.
367    fn measure_hold(
368        &self,
369        _density: f32,
370        constraints: Constraints,
371        size: Size,
372        _wrapped: cranpose_ui_layout::WrappedHold,
373    ) -> Option<cranpose_ui_layout::ConstraintsHold> {
374        let max_width = constraints
375            .max_width
376            .is_finite()
377            .then_some(constraints.max_width);
378        let (text_size, widths) = self.layout.cached_widths(max_width)?;
379        let text_size = self.pixel_size(text_size);
380        if size != text_size {
381            return None;
382        }
383        Some(cranpose_ui_layout::ConstraintsHold {
384            width: cranpose_ui_layout::AxisHold {
385                min: cranpose_ui_layout::BoundRange::up_to(text_size.width),
386                max: cranpose_ui_layout::BoundRange::from(text_size.width)
387                    .intersect(widths.max_width_range())?,
388            },
389            height: cranpose_ui_layout::AxisHold::sized(text_size.height),
390        })
391    }
392
393    fn measure(
394        &self,
395        _context: &mut dyn ModifierNodeContext,
396        _measurable: &dyn Measurable,
397        constraints: Constraints,
398    ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
399        let max_width = constraints
400            .max_width
401            .is_finite()
402            .then_some(constraints.max_width);
403        let (text_size, alignment_lines) = self.layout.measure_layout(max_width);
404        let text_size = self.pixel_size(text_size);
405
406        let width = text_size
407            .width
408            .clamp(constraints.min_width, constraints.max_width);
409        let height = text_size
410            .height
411            .clamp(constraints.min_height, constraints.max_height);
412
413        cranpose_ui_layout::LayoutModifierMeasureResult::with_size(Size { width, height })
414            .with_alignment_lines(alignment_lines)
415    }
416
417    fn min_intrinsic_width(
418        &self,
419        _measurable: &dyn Measurable,
420        _height: f32,
421        _density: f32,
422    ) -> f32 {
423        self.pixel_size(self.measure_text_content(None)).width
424    }
425
426    fn max_intrinsic_width(
427        &self,
428        _measurable: &dyn Measurable,
429        _height: f32,
430        _density: f32,
431    ) -> f32 {
432        self.pixel_size(self.measure_text_content(None)).width
433    }
434
435    fn min_intrinsic_height(&self, _measurable: &dyn Measurable, width: f32, _density: f32) -> f32 {
436        self.pixel_size(
437            self.measure_text_content(Some(width).filter(|w| w.is_finite() && *w > 0.0)),
438        )
439        .height
440    }
441
442    fn max_intrinsic_height(&self, _measurable: &dyn Measurable, width: f32, _density: f32) -> f32 {
443        self.pixel_size(
444            self.measure_text_content(Some(width).filter(|w| w.is_finite() && *w > 0.0)),
445        )
446        .height
447    }
448}
449
450impl DrawModifierNode for TextModifierNode {}
451
452impl SemanticsNode for TextModifierNode {
453    fn merge_semantics(&self, config: &mut SemanticsConfiguration) {
454        config
455            .content_description
456            .get_or_insert_with(|| self.text().to_string());
457    }
458
459    fn reach(&self) -> cranpose_foundation::SemanticsReach {
460        cranpose_foundation::SemanticsReach::default()
461    }
462}
463
464/// Element that creates and updates TextModifierNode instances.
465///
466/// This follows the modifier element pattern where the element is responsible for:
467/// - Creating new nodes (via `create`)
468/// - Updating existing nodes when properties change (via `update`)
469/// - Declaring capabilities (LAYOUT | DRAW | SEMANTICS)
470///
471/// Matches Jetpack Compose: `TextStringSimpleElement` in BasicText.kt
472#[derive(Debug, Clone)]
473pub struct TextModifierElement {
474    text: Rc<AnnotatedString>,
475    /// One copy for every text composed with an equal style: see
476    /// [`shared_text_style`].
477    style: Arc<TextStyle>,
478    options: TextLayoutOptions,
479    density: Density,
480}
481
482impl TextModifierElement {
483    /// A text laid out on `density`'s device pixel grid, the composition's
484    /// [`crate::density::density`] where a `Text` is composed.
485    pub fn new(
486        text: Rc<AnnotatedString>,
487        style: TextStyle,
488        options: TextLayoutOptions,
489        density: Density,
490    ) -> Self {
491        Self::with_shared_style(text, shared_text_style(style), options, density)
492    }
493
494    /// [`Self::new`] for a style [`shared_text_style`] already shared.
495    pub(crate) fn with_shared_style(
496        text: Rc<AnnotatedString>,
497        style: Arc<TextStyle>,
498        options: TextLayoutOptions,
499        density: Density,
500    ) -> Self {
501        Self {
502            text,
503            style,
504            options: options.normalized(),
505            density,
506        }
507    }
508}
509
510impl PartialEq for TextModifierElement {
511    fn eq(&self, other: &Self) -> bool {
512        self.text == other.text
513            && (Arc::ptr_eq(&self.style, &other.style) || self.style == other.style)
514            && self.options == other.options
515            && self.density == other.density
516    }
517}
518
519/// How many recent text styles [`shared_text_style`] keeps.
520const SHARED_TEXT_STYLES: usize = 16;
521
522thread_local! {
523    /// Styles texts were composed with, those in use toward the front.
524    static RECENT_TEXT_STYLES: RefCell<Vec<Arc<TextStyle>>> = const { RefCell::new(Vec::new()) };
525}
526
527/// `style` shared with the texts recently composed with an equal one, so a
528/// screen of texts in a few styles keeps a few copies, not one a text, and
529/// a node updated to an element of the same style compares pointers. A
530/// style none of the kept [`SHARED_TEXT_STYLES`] equals gets a copy of its
531/// own, kept first; the last kept one goes.
532pub(crate) fn shared_text_style(style: TextStyle) -> Arc<TextStyle> {
533    RECENT_TEXT_STYLES.with_borrow_mut(|recent| {
534        match recent.iter().position(|kept| **kept == style) {
535            Some(0) => Arc::clone(&recent[0]),
536            // One step toward the front: styles in use stay among the first
537            // compared, without moving the whole list on every hit.
538            Some(index) => {
539                recent.swap(index, index - 1);
540                Arc::clone(&recent[index - 1])
541            }
542            None => {
543                let shared = Arc::new(style);
544                recent.truncate(SHARED_TEXT_STYLES - 1);
545                recent.insert(0, Arc::clone(&shared));
546                shared
547            }
548        }
549    })
550}
551
552impl Hash for TextModifierElement {
553    fn hash<H: Hasher>(&self, state: &mut H) {
554        self.text.render_hash().hash(state);
555        self.options.hash(state);
556        self.density.density().to_bits().hash(state);
557    }
558}
559
560impl ModifierNodeElement for TextModifierElement {
561    type Node = TextModifierNode;
562
563    fn create(&self) -> Self::Node {
564        TextModifierNode::new(
565            self.text.clone(),
566            Arc::clone(&self.style),
567            self.options,
568            self.density,
569        )
570    }
571
572    fn update(&self, node: &mut Self::Node) {
573        node.density = self.density;
574        node.layout.update(&self.text, &self.style, self.options);
575    }
576
577    fn capabilities(&self) -> NodeCapabilities {
578        NodeCapabilities::LAYOUT | NodeCapabilities::DRAW | NodeCapabilities::SEMANTICS
579    }
580}
581
582#[cfg(test)]
583#[path = "tests/text_modifier_node_tests.rs"]
584mod tests;