1use std::{
2 cell::{Cell, Ref, RefCell},
3 hash::{Hash, Hasher},
4 rc::Rc,
5 sync::Arc,
6};
7
8use cranpose_core::PackedU64;
9use cranpose_foundation::{
10 Constraints, DelegatableNode, DrawModifierNode, InvalidationKind, LayoutModifierNode,
11 Measurable, ModifierNode, ModifierNodeContext, ModifierNodeElement, NodeCapabilities,
12 NodeState, SemanticsConfiguration, SemanticsNode, Size,
13};
14use smallvec::SmallVec;
15
16use crate::{
17 density::Density,
18 text::{
19 AnnotatedString, TextLayoutOptions, TextStyle, layout_cache::CacheAdmission,
20 recent_values::RecentValues,
21 },
22};
23
24#[derive(Debug)]
34pub struct TextModifierNode {
35 layout: Rc<TextPreparedLayoutOwner>,
36 density: Density,
37 state: NodeState,
38}
39
40const PREPARED_LAYOUT_CACHE_CAPACITY: usize = 4;
41
42#[derive(Clone, Debug)]
43struct TextPreparedLayoutCacheEntry {
44 min_width: f32,
45 max_widths: cranpose_ui_layout::BoundRange,
48 text_generation: PackedU64,
49 font_scale_fingerprint: u32,
50 layout: Rc<crate::text::PreparedTextLayout>,
51}
52
53impl TextPreparedLayoutCacheEntry {
54 fn new(
55 min_width: f32,
56 (text_generation, font_scale_fingerprint): (u64, u32),
57 layout: Rc<crate::text::PreparedTextLayout>,
58 ) -> Self {
59 Self {
60 min_width,
61 max_widths: layout.max_widths_kept(min_width),
62 text_generation: PackedU64::new(text_generation),
63 font_scale_fingerprint,
64 layout,
65 }
66 }
67
68 fn keeps(&self, (min_width, max_width): (f32, f32), stamp: (u64, u32)) -> bool {
71 self.min_width.to_bits() == min_width.to_bits()
72 && (self.text_generation.get(), self.font_scale_fingerprint) == stamp
73 && self.max_widths.contains(max_width)
74 }
75}
76
77#[derive(Debug)]
81struct TextPreparedLayoutOwner {
82 source: RefCell<TextLayoutSource>,
83 measured_widths: Cell<Option<(f32, f32)>>,
84 cache: RefCell<SmallVec<[TextPreparedLayoutCacheEntry; 1]>>,
85 changed: Cell<bool>,
89}
90
91#[derive(Debug)]
93struct TextLayoutSource {
94 text: AnnotatedString,
95 style: Arc<TextStyle>,
96 style_hash: PackedU64,
97 options: TextLayoutOptions,
98 admission: CacheAdmission,
102}
103
104impl TextLayoutSource {
105 fn frame(&self, (min_width, max_width): (f32, f32)) -> crate::text::measure::TextFrame {
107 crate::text::measure::TextFrame {
108 min_width,
109 max_width,
110 options: self.options,
111 }
112 }
113}
114
115#[derive(Clone, Debug)]
116pub(crate) struct TextPreparedLayoutHandle {
117 owner: Rc<TextPreparedLayoutOwner>,
118}
119
120impl TextPreparedLayoutOwner {
121 fn new(text: AnnotatedString, style: Arc<TextStyle>, options: TextLayoutOptions) -> Self {
122 let style_hash = PackedU64::new(style.render_hash());
123 Self {
124 source: RefCell::new(TextLayoutSource {
125 text,
126 style,
127 style_hash,
128 options: options.normalized(),
129 admission: CacheAdmission::First,
130 }),
131 measured_widths: Cell::new(None),
132 changed: Cell::new(false),
133 cache: RefCell::new(SmallVec::new()),
134 }
135 }
136
137 fn update(&self, text: AnnotatedString, style: &Arc<TextStyle>, options: TextLayoutOptions) {
143 let mut source = self.source.borrow_mut();
144 let shared_style = Arc::ptr_eq(&source.style, style);
145 let same_style = shared_style || *source.style == **style;
146 if source.text == text && same_style && source.options == options {
147 return;
148 }
149 if !same_style {
150 source.style_hash = PackedU64::new(style.render_hash());
151 }
152 if !shared_style {
153 source.style = Arc::clone(style);
154 }
155 let replaced = std::mem::replace(&mut source.text, text);
156 source.options = options;
157 source.admission = CacheAdmission::Changed;
158 drop(source);
159 let mut cache = self.cache.borrow_mut();
160 let retired = crate::render_state::current_app_context().map(|context| {
161 let layouts = cache.drain(..).map(|entry| entry.layout);
162 context.text.retire(replaced, layouts);
163 });
164 if retired.is_none() {
165 cache.clear();
166 }
167 drop(cache);
168 self.changed.set(true);
169 }
170
171 fn annotated_text(&self) -> Ref<'_, AnnotatedString> {
172 Ref::map(self.source.borrow(), |source| &source.text)
173 }
174
175 fn style(&self) -> Ref<'_, TextStyle> {
176 Ref::map(self.source.borrow(), |source| &*source.style)
177 }
178
179 fn options(&self) -> TextLayoutOptions {
180 self.source.borrow().options
181 }
182
183 fn prepared(&self, widths: (f32, f32)) -> Ref<'_, Rc<crate::text::PreparedTextLayout>> {
188 let stamp = crate::render_state::text_layout_stamp();
189 {
190 let cache = self.cache.borrow();
191 if cache
192 .first()
193 .is_some_and(|latest| latest.keeps(widths, stamp))
194 {
195 return Ref::map(cache, |cache| &cache[0].layout);
196 }
197 }
198 if !self.bring_kept(widths, stamp) {
199 self.prepare(widths, stamp);
200 }
201 Ref::map(self.cache.borrow(), |cache| &cache[0].layout)
202 }
203
204 fn bring_kept(&self, widths: (f32, f32), stamp: (u64, u32)) -> bool {
209 let mut cache = self.cache.borrow_mut();
210 let Some(latest) = cache.first_mut() else {
211 return false;
212 };
213 if (latest.text_generation.get(), latest.font_scale_fingerprint) == stamp
215 && let Some(prepared) = Rc::get_mut(&mut latest.layout)
216 && prepared.try_realign(widths, prepared.visual_style.paragraph_style.text_align)
217 {
218 latest.min_width = widths.0;
219 latest.max_widths = prepared.max_widths_kept(widths.0);
220 return true;
221 }
222 let Some(index) = cache.iter().position(|entry| entry.keeps(widths, stamp)) else {
223 return false;
224 };
225 cache[..=index].rotate_right(1);
226 true
227 }
228
229 #[inline(never)]
232 fn prepare(&self, widths: (f32, f32), stamp: (u64, u32)) {
233 let source = self.source.borrow();
234 let frame = source.frame(widths);
235 let align = source.style.paragraph_style.text_align;
236 let spare = {
239 let mut cache = self.cache.borrow_mut();
240 (cache.len() >= PREPARED_LAYOUT_CACHE_CAPACITY)
241 .then(|| cache.pop())
242 .flatten()
243 .map(|entry| entry.layout)
244 };
245 let prepared = {
246 let cache = self.cache.borrow();
251 let latest = cache
252 .first()
253 .filter(|entry| {
254 (entry.text_generation.get(), entry.font_scale_fingerprint) == stamp
255 })
256 .map(|entry| &entry.layout);
257 match latest.filter(|latest| latest.layout.holds(widths.0, widths.1)) {
258 Some(latest) => latest.at_widths(widths, align, spare),
259 None => {
260 let text = crate::text::measure::SharedText {
261 text: &source.text,
262 style: &source.style,
263 style_hash: source.style_hash.get(),
264 };
265 let shaped = latest.map(|latest| &latest.layout);
266 crate::text::measure::prepare_shared(&text, frame, source.admission, shaped)
267 }
268 }
269 };
270 if Arc::ptr_eq(&prepared.visual_style, &source.style) {
271 let _ = prepared.visual_style_hash.set(source.style_hash);
272 }
273 drop(source);
274
275 let mut cache = self.cache.borrow_mut();
276 cache.insert(
277 0,
278 TextPreparedLayoutCacheEntry::new(widths.0, stamp, prepared),
279 );
280 cache.truncate(PREPARED_LAYOUT_CACHE_CAPACITY);
281 }
282
283 fn cached_widths(&self, widths: (f32, f32)) -> Option<(Size, cranpose_ui_layout::BoundRange)> {
286 let stamp = crate::render_state::text_layout_stamp();
287 let cache = self.cache.borrow();
288 let entry = cache.iter().find(|entry| entry.keeps(widths, stamp))?;
289 Some((entry.layout.size(), entry.max_widths))
290 }
291
292 fn min_intrinsic_width(&self) -> f32 {
294 let source = self.source.borrow();
295 crate::text::measure::min_intrinsic_text_width(&source.text, &source.style)
296 }
297
298 fn measure_text_content(&self, widths: (f32, f32)) -> Size {
299 self.prepared(widths).size()
300 }
301
302 fn measure_layout(&self, widths: (f32, f32)) -> (Size, cranpose_ui_layout::AlignmentLines) {
303 self.measured_widths.set(Some(widths));
304 let prepared = self.prepared(widths);
305 (prepared.size(), prepared.alignment_lines())
306 }
307
308 fn measured_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
309 self.measured_widths
310 .get()
311 .map(|widths| Rc::clone(&self.prepared(widths)))
312 }
313}
314
315impl TextPreparedLayoutHandle {
316 fn new(owner: Rc<TextPreparedLayoutOwner>) -> Self {
317 Self { owner }
318 }
319
320 pub(crate) fn annotated_text(&self) -> Ref<'_, AnnotatedString> {
321 self.owner.annotated_text()
322 }
323
324 pub(crate) fn style(&self) -> Ref<'_, TextStyle> {
325 self.owner.style()
326 }
327
328 pub(crate) fn options(&self) -> TextLayoutOptions {
329 self.owner.options()
330 }
331
332 pub(crate) fn measured_layout(&self) -> Option<Rc<crate::text::PreparedTextLayout>> {
333 self.owner.measured_layout()
334 }
335}
336
337impl TextModifierNode {
338 pub(crate) fn shows(
341 &self,
342 text: &crate::widgets::StaticText,
343 style: &Arc<TextStyle>,
344 options: TextLayoutOptions,
345 density: Density,
346 ) -> bool {
347 let source = self.layout.source.borrow();
348 text.is(&source.text)
349 && (Arc::ptr_eq(&source.style, style) || *source.style == **style)
350 && source.options == options
351 && self.density == density
352 }
353
354 pub(crate) fn show(
357 &mut self,
358 text: AnnotatedString,
359 style: &Arc<TextStyle>,
360 options: TextLayoutOptions,
361 density: Density,
362 ) {
363 self.density = density;
364 self.layout.update(text, style, options);
365 }
366
367 pub fn new(
369 text: AnnotatedString,
370 style: impl Into<Arc<TextStyle>>,
371 options: TextLayoutOptions,
372 density: Density,
373 ) -> Self {
374 Self {
375 layout: Rc::new(TextPreparedLayoutOwner::new(text, style.into(), options)),
376 density,
377 state: NodeState::new(),
378 }
379 }
380
381 fn pixel_size(&self, size: Size) -> Size {
385 Size {
386 width: self.density.ceil(size.width),
387 height: self.density.ceil(size.height),
388 }
389 }
390
391 pub fn text(&self) -> Ref<'_, str> {
393 Ref::map(self.layout.annotated_text(), AnnotatedString::text)
394 }
395
396 pub fn annotated_text(&self) -> AnnotatedString {
398 self.layout.annotated_text().clone()
399 }
400
401 pub fn style(&self) -> Ref<'_, TextStyle> {
403 self.layout.style()
404 }
405
406 pub fn options(&self) -> TextLayoutOptions {
408 self.layout.options()
409 }
410
411 fn measure_text_content(&self, widths: (f32, f32)) -> Size {
412 self.layout.measure_text_content(widths)
413 }
414
415 pub(crate) fn prepared_layout_handle(&self) -> TextPreparedLayoutHandle {
416 TextPreparedLayoutHandle::new(Rc::clone(&self.layout))
417 }
418}
419
420impl DelegatableNode for TextModifierNode {
421 fn node_state(&self) -> &NodeState {
422 &self.state
423 }
424}
425
426impl ModifierNode for TextModifierNode {
427 fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
428 context.invalidate(InvalidationKind::Layout);
429 context.invalidate(InvalidationKind::Draw);
430 context.invalidate(InvalidationKind::Semantics);
431 }
432
433 fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
434 Some(self)
435 }
436
437 fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
438 Some(self)
439 }
440
441 fn as_semantics_node(&self) -> Option<&dyn SemanticsNode> {
442 Some(self)
443 }
444
445 fn as_semantics_node_mut(&mut self) -> Option<&mut dyn SemanticsNode> {
446 Some(self)
447 }
448
449 fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
450 Some(self)
451 }
452
453 fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
454 Some(self)
455 }
456}
457
458impl LayoutModifierNode for TextModifierNode {
459 fn measure_hold(
462 &self,
463 _density: f32,
464 constraints: Constraints,
465 size: Size,
466 _wrapped: cranpose_ui_layout::WrappedHold,
467 ) -> Option<cranpose_ui_layout::ConstraintsHold> {
468 if self.layout.changed.take() {
471 return None;
472 }
473 let (text_size, max_widths) = self.layout.cached_widths(text_widths(constraints))?;
474 let text_size = self.pixel_size(text_size);
475 if size != text_size {
476 return None;
477 }
478 Some(cranpose_ui_layout::ConstraintsHold {
479 width: cranpose_ui_layout::AxisHold {
480 min: cranpose_ui_layout::BoundRange::exactly(constraints.min_width),
481 max: cranpose_ui_layout::BoundRange::from(text_size.width).intersect(max_widths)?,
482 },
483 height: cranpose_ui_layout::AxisHold::sized(text_size.height),
484 })
485 }
486
487 fn measure(
488 &self,
489 _context: &mut dyn ModifierNodeContext,
490 _measurable: &dyn Measurable,
491 constraints: Constraints,
492 ) -> cranpose_ui_layout::LayoutModifierMeasureResult {
493 let (text_size, alignment_lines) = self.layout.measure_layout(text_widths(constraints));
494 let text_size = self.pixel_size(text_size);
495
496 let width = text_size
497 .width
498 .clamp(constraints.min_width, constraints.max_width);
499 let height = text_size
500 .height
501 .clamp(constraints.min_height, constraints.max_height);
502
503 cranpose_ui_layout::LayoutModifierMeasureResult::with_size(Size { width, height })
504 .with_alignment_lines(alignment_lines)
505 }
506
507 fn min_intrinsic_width(
508 &self,
509 _measurable: &dyn Measurable,
510 _height: f32,
511 _density: f32,
512 ) -> f32 {
513 self.density.ceil(self.layout.min_intrinsic_width())
514 }
515
516 fn max_intrinsic_width(
517 &self,
518 _measurable: &dyn Measurable,
519 _height: f32,
520 _density: f32,
521 ) -> f32 {
522 self.pixel_size(self.measure_text_content((0.0, f32::INFINITY)))
523 .width
524 }
525
526 fn min_intrinsic_height(&self, _measurable: &dyn Measurable, width: f32, _density: f32) -> f32 {
527 self.pixel_size(self.measure_text_content((0.0, intrinsic_width(width))))
528 .height
529 }
530
531 fn max_intrinsic_height(&self, _measurable: &dyn Measurable, width: f32, _density: f32) -> f32 {
532 self.pixel_size(self.measure_text_content((0.0, intrinsic_width(width))))
533 .height
534 }
535}
536
537fn text_widths(constraints: Constraints) -> (f32, f32) {
540 (constraints.min_width.max(0.0), constraints.max_width)
541}
542
543fn intrinsic_width(width: f32) -> f32 {
546 if width.is_finite() && width > 0.0 {
547 width
548 } else {
549 f32::INFINITY
550 }
551}
552
553impl DrawModifierNode for TextModifierNode {}
554
555impl SemanticsNode for TextModifierNode {
556 fn merge_semantics(&self, config: &mut SemanticsConfiguration) {
557 config
558 .content_description
559 .get_or_insert_with(|| self.text().to_string());
560 }
561
562 fn reach(&self) -> cranpose_foundation::SemanticsReach {
563 cranpose_foundation::SemanticsReach::default()
564 }
565}
566
567#[derive(Debug, Clone)]
576pub struct TextModifierElement {
577 text: AnnotatedString,
578 style: Arc<TextStyle>,
581 options: TextLayoutOptions,
582 density: Density,
583}
584
585impl TextModifierElement {
586 #[expect(
589 clippy::needless_pass_by_value,
590 reason = "Compose's Text takes its style by value; the function shares it without a copy"
591 )]
592 pub fn new(
593 text: AnnotatedString,
594 style: TextStyle,
595 options: TextLayoutOptions,
596 density: Density,
597 ) -> Self {
598 Self::with_shared_style(text, shared_text_style(&style), options, density)
599 }
600
601 pub(crate) fn with_shared_style(
603 text: AnnotatedString,
604 style: Arc<TextStyle>,
605 options: TextLayoutOptions,
606 density: Density,
607 ) -> Self {
608 Self {
609 text,
610 style,
611 options: options.normalized(),
612 density,
613 }
614 }
615
616 fn shows(
618 &self,
619 text: &AnnotatedString,
620 style: &Arc<TextStyle>,
621 options: TextLayoutOptions,
622 density: Density,
623 ) -> bool {
624 self.text == *text
625 && (Arc::ptr_eq(&self.style, style) || self.style == *style)
626 && self.options == options
627 && self.density == density
628 }
629}
630
631impl PartialEq for TextModifierElement {
632 fn eq(&self, other: &Self) -> bool {
633 self.shows(&other.text, &other.style, other.options, other.density)
634 }
635}
636
637const SHARED_TEXT_STYLES: usize = 16;
639
640pub(crate) type RecentTextStyles = RecentValues<Arc<TextStyle>, SHARED_TEXT_STYLES>;
642
643pub(crate) fn shared_text_style(style: &TextStyle) -> Arc<TextStyle> {
650 crate::thread_state::with(|state| {
651 let mut recent = state.recent_text_styles.borrow_mut();
652 if let Some(kept) = recent.find(|kept| **kept == *style) {
653 return Arc::clone(kept);
654 }
655 Arc::clone(recent.keep(Arc::new(style.clone())))
656 })
657}
658
659impl Hash for TextModifierElement {
660 fn hash<H: Hasher>(&self, state: &mut H) {
661 self.text.render_hash().hash(state);
662 self.options.hash(state);
663 self.density.density().to_bits().hash(state);
664 }
665}
666
667impl ModifierNodeElement for TextModifierElement {
668 type Node = TextModifierNode;
669 const FROM_NODE: Option<fn(&TextModifierNode) -> Self> = Some(|node| {
670 let source = node.layout.source.borrow();
671 Self {
672 text: source.text.clone(),
673 style: Arc::clone(&source.style),
674 options: source.options,
675 density: node.density,
676 }
677 });
678
679 fn create(&self) -> Self::Node {
680 TextModifierNode::new(
681 self.text.clone(),
682 Arc::clone(&self.style),
683 self.options,
684 self.density,
685 )
686 }
687
688 fn update(&self, node: &mut Self::Node) {
689 node.show(self.text.clone(), &self.style, self.options, self.density);
690 }
691
692 fn equals_node(&self, node: &TextModifierNode) -> bool {
693 let source = node.layout.source.borrow();
694 self.shows(&source.text, &source.style, source.options, node.density)
695 }
696
697 fn capabilities(&self) -> NodeCapabilities {
698 NodeCapabilities::LAYOUT | NodeCapabilities::DRAW | NodeCapabilities::SEMANTICS
699 }
700}
701
702#[cfg(test)]
703#[path = "tests/text_modifier_node_tests.rs"]
704mod tests;