1use std::{cell::OnceCell, hash::Hasher, sync::Arc};
6
7use cranpose_text::SynthesizedStyle;
8use cranpose_ui::{
9 Brush, Color, TextStyle,
10 text::{RangeStyle, SpanStyle, TextDecoration, TextDrawStyle, TextMotion},
11};
12use cranpose_ui_graphics::FxHasher;
13
14use crate::glyph_reach::InkSpread;
15
16#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct TextPaint {
19 pub plain: bool,
23 pub color: Color,
26 pub baseline_shift: f32,
28 pub style_hash: u64,
31 pub static_motion: bool,
34 pub casts_shadow: bool,
37 pub spread: InkSpread,
40 font_size: f32,
43 synthesized: SynthesizedStyle,
44}
45
46impl TextPaint {
47 pub fn of(
50 style: &TextStyle,
51 style_hash: u64,
52 spans: &[RangeStyle<SpanStyle>],
53 (font_size, layout): (f32, &cranpose_text::TextLayout),
54 ) -> Self {
55 let span_style = &style.span_style;
56 let span_paint = SpanPaint::of(spans);
57 let plain = span_style.background.is_none()
58 && span_style.shadow.is_none()
59 && span_style.brush.is_none()
60 && !matches!(
61 span_style.draw_style,
62 Some(TextDrawStyle::Stroke { width }) if width.is_finite() && width > 0.0
63 )
64 && !span_paint.foreground
65 && !decorates(span_style.text_decoration)
66 && !span_paint.decoration;
67 Self {
68 plain,
69 color: resolve_text_color_without_gradient_fallback(style, Color::WHITE),
70 baseline_shift: span_style
71 .baseline_shift
72 .filter(|shift| shift.is_specified())
73 .map_or(0.0, |shift| -(shift.0 * font_size)),
74 style_hash,
75 static_motion: style
76 .paragraph_style
77 .text_motion
78 .unwrap_or(TextMotion::Static)
79 == TextMotion::Static,
80 casts_shadow: span_style.shadow.is_some() || span_paint.shadow,
81 spread: if plain && !span_paint.shadow {
84 InkSpread::of(0.0, layout.synthesized_style())
85 } else {
86 InkSpread::of_text(style, spans, layout)
87 },
88 font_size,
89 synthesized: layout.synthesized_style(),
90 }
91 }
92
93 fn made_at(&self, style_hash: u64, font_size: f32, synthesized: SynthesizedStyle) -> bool {
96 self.style_hash == style_hash
97 && self.font_size.to_bits() == font_size.to_bits()
98 && self.synthesized == synthesized
99 }
100}
101
102fn shared_paint(
107 style: &TextStyle,
108 style_hash: u64,
109 (font_size, layout): (f32, &cranpose_text::TextLayout),
110) -> Arc<TextPaint> {
111 let synthesized = layout.synthesized_style();
112 let bold = synthesized.bold_size.map_or(0, f32::to_bits);
113 let mut key = FxHasher::default();
114 key.write_u64(style_hash);
115 key.write_u64(u64::from(font_size.to_bits()) << 32 | u64::from(bold));
116 key.write_u8(u8::from(synthesized.italic) | u8::from(synthesized.bold_size.is_some()) << 1);
117 crate::thread_state::with(|state| {
118 state.text_paints.borrow_mut().with(
119 key.finish(),
120 |kept| kept.made_at(style_hash, font_size, synthesized),
121 || Arc::new(TextPaint::of(style, style_hash, &[], (font_size, layout))),
122 Arc::clone,
123 )
124 })
125}
126
127struct SpanPaint {
129 foreground: bool,
131 decoration: bool,
133 shadow: bool,
135}
136
137impl SpanPaint {
138 fn of(spans: &[RangeStyle<SpanStyle>]) -> Self {
140 let none = Self {
141 foreground: false,
142 decoration: false,
143 shadow: false,
144 };
145 spans.iter().fold(none, |paint, span| Self {
146 foreground: paint.foreground | span_has_foreground_override(&span.item),
147 decoration: paint.decoration | decorates(span.item.text_decoration),
148 shadow: paint.shadow | span.item.shadow.is_some(),
149 })
150 }
151}
152
153fn decorates(decoration: Option<TextDecoration>) -> bool {
155 decoration.is_some_and(|decoration| decoration != TextDecoration::NONE)
156}
157
158#[derive(Clone, Debug, Default)]
162pub struct TextPaintCache(OnceCell<Arc<TextPaint>>);
163
164impl TextPaintCache {
165 pub fn of_text(
170 style: &TextStyle,
171 style_hash: u64,
172 spans: &[RangeStyle<SpanStyle>],
173 text: (f32, &cranpose_text::TextLayout),
174 ) -> Self {
175 let paint = if spans.is_empty() {
176 shared_paint(style, style_hash, text)
177 } else {
178 Arc::new(TextPaint::of(style, style_hash, spans, text))
179 };
180 Self(OnceCell::from(paint))
181 }
182
183 pub fn get_or(&self, compute: impl FnOnce() -> TextPaint) -> &TextPaint {
186 self.0.get_or_init(|| Arc::new(compute()))
187 }
188}
189
190impl PartialEq for TextPaintCache {
191 fn eq(&self, _other: &Self) -> bool {
192 true
193 }
194}
195
196pub fn resolve_text_color_without_gradient_fallback(
199 text_style: &TextStyle,
200 default: Color,
201) -> Color {
202 let mut color = text_style
203 .span_style
204 .color
205 .or(match text_style.span_style.brush.as_ref() {
206 Some(Brush::Solid(color)) => Some(*color),
207 _ => None,
208 })
209 .unwrap_or(default);
210 if let Some(alpha) = text_style.span_style.alpha {
211 color.3 *= alpha.clamp(0.0, 1.0);
212 }
213 color
214}
215
216fn span_has_foreground_override(span_style: &SpanStyle) -> bool {
217 matches!(
218 span_style.brush.as_ref(),
219 Some(
220 Brush::LinearGradient { .. }
221 | Brush::RadialGradient { .. }
222 | Brush::SweepGradient { .. }
223 )
224 ) || span_style.alpha.is_some()
225 || span_style.draw_style.is_some()
226}
227
228pub fn spans_override_foreground(spans: &[RangeStyle<SpanStyle>]) -> bool {
231 spans
232 .iter()
233 .any(|span| span_has_foreground_override(&span.item))
234}
235
236pub fn spans_cast_shadow(spans: &[RangeStyle<SpanStyle>]) -> bool {
238 spans.iter().any(|span| span.item.shadow.is_some())
239}
240
241pub fn spans_override_foreground_color(spans: &[RangeStyle<SpanStyle>]) -> bool {
243 spans
244 .iter()
245 .any(|span| span.item.color.is_some() || matches!(span.item.brush, Some(Brush::Solid(_))))
246}