1use crate::style::{FontStyle, TextAlign, TextStyle, TextWrap};
4use crate::system::{GlyphKey, TextSystem};
5use cosmic_text::{Attrs, Buffer, Family, Metrics, Shaping};
6use kova_native_core::{Bounds, Color, Point, Size};
7use measure_cache_impl::SmallCache;
8
9#[derive(Clone, Copy, Debug)]
11pub struct GlyphInstance {
12 pub key: GlyphKey,
13 pub x: i32,
16 pub y: i32,
17 pub color: Option<Color>,
18}
19
20#[derive(Clone, Copy, Debug, PartialEq)]
22pub struct LineMetrics {
23 pub paragraph: usize,
25 pub top: f32,
26 pub baseline: f32,
27 pub height: f32,
28 pub x: f32,
30 pub width: f32,
31}
32
33pub struct TextLayout {
39 buffer: Buffer,
40 text: String,
41 style: Option<TextStyle>,
42 width: Option<f32>,
43 measure_cache: SmallCache,
44}
45
46mod measure_cache_impl {
47 use kova_native_core::Size;
48
49 #[derive(Default)]
51 pub struct SmallCache {
52 entries: Vec<(Option<u32>, Size)>,
53 }
54
55 impl SmallCache {
56 pub fn get(&self, width: Option<f32>) -> Option<Size> {
57 let key = width.map(f32::to_bits);
58 self.entries
59 .iter()
60 .find(|(k, _)| *k == key)
61 .map(|(_, s)| *s)
62 }
63
64 pub fn insert(&mut self, width: Option<f32>, size: Size) {
65 if self.entries.len() >= 8 {
66 self.entries.remove(0);
67 }
68 self.entries.push((width.map(f32::to_bits), size));
69 }
70
71 pub fn clear(&mut self) {
72 self.entries.clear();
73 }
74 }
75}
76
77impl TextLayout {
78 pub fn new() -> Self {
79 TextLayout {
80 buffer: Buffer::new_empty(Metrics::new(14.0, 20.0)),
81 text: String::new(),
82 style: None,
83 width: None,
84 measure_cache: SmallCache::default(),
85 }
86 }
87
88 pub fn text(&self) -> &str {
89 &self.text
90 }
91
92 pub fn style(&self) -> Option<&TextStyle> {
93 self.style.as_ref()
94 }
95
96 pub fn set(&mut self, ts: &mut TextSystem, text: &str, style: &TextStyle) -> bool {
99 let layout_changed =
100 self.text != text || self.style.as_ref().is_none_or(|s| !s.same_layout(style));
101 if !layout_changed {
102 self.style = Some(style.clone());
103 return false;
104 }
105 self.text.clear();
106 self.text.push_str(text);
107 self.style = Some(style.clone());
108 self.measure_cache.clear();
109
110 let line_height = style.line_height.resolve(style.size);
111 self.buffer
112 .set_metrics(Metrics::new(style.size, line_height));
113 self.buffer.set_wrap(match style.wrap {
114 TextWrap::Word => cosmic_text::Wrap::WordOrGlyph,
115 TextWrap::Glyph => cosmic_text::Wrap::Glyph,
116 TextWrap::None => cosmic_text::Wrap::None,
117 });
118 let family = ts.resolve_family(style.family.as_deref()).to_string();
119 let attrs = Attrs::new()
120 .family(Family::Name(&family))
121 .weight(cosmic_text::Weight(style.weight.0))
122 .style(match style.style {
123 FontStyle::Normal => cosmic_text::Style::Normal,
124 FontStyle::Italic => cosmic_text::Style::Italic,
125 })
126 .letter_spacing(if style.size > 0.0 {
127 style.letter_spacing / style.size
128 } else {
129 0.0
130 });
131 let align = match style.align {
132 TextAlign::Left => None,
133 TextAlign::Center => Some(cosmic_text::Align::Center),
134 TextAlign::Right => Some(cosmic_text::Align::Right),
135 TextAlign::Justify => Some(cosmic_text::Align::Justified),
136 };
137 self.buffer.set_text(text, &attrs, Shaping::Advanced, align);
138 self.width = None;
139 self.buffer.set_size(None, None);
140 true
141 }
142
143 fn line_height(&self) -> f32 {
144 self.buffer.metrics().line_height
145 }
146
147 pub fn measure(&mut self, ts: &mut TextSystem, max_width: Option<f32>) -> Size {
149 if let Some(size) = self.measure_cache.get(max_width) {
150 return size;
151 }
152 self.apply_width(ts, max_width);
153 let size = self.current_size();
154 self.measure_cache.insert(max_width, size);
155 size
156 }
157
158 pub fn layout(&mut self, ts: &mut TextSystem, width: Option<f32>) -> Size {
160 self.apply_width(ts, width.map(|w| w + 0.05));
163 self.current_size()
164 }
165
166 fn apply_width(&mut self, ts: &mut TextSystem, width: Option<f32>) {
167 let width = width.map(|w| w.max(0.0));
168 if self.width != width {
169 self.width = width;
170 self.buffer.set_size(width, None);
171 }
172 self.buffer.shape_until_scroll(&mut ts.fonts, false);
173 }
174
175 fn current_size(&self) -> Size {
176 let mut width: f32 = 0.0;
177 let mut height: f32 = 0.0;
178 for run in self.buffer.layout_runs() {
179 width = width.max(run.line_w);
180 height = height.max(run.line_top + run.line_height);
181 }
182 if height == 0.0 {
183 height = self.line_height();
184 }
185 Size::new((width * 64.0).ceil() / 64.0, height)
187 }
188
189 pub fn size(&self) -> Size {
191 self.current_size()
192 }
193
194 pub fn lines(&self) -> Vec<LineMetrics> {
196 self.buffer
197 .layout_runs()
198 .map(|run| {
199 let x = run.glyphs.first().map_or(0.0, |g| g.x);
200 let right = run.glyphs.last().map_or(0.0, |g| g.x + g.w);
201 LineMetrics {
202 paragraph: run.line_i,
203 top: run.line_top,
204 baseline: run.line_y,
205 height: run.line_height,
206 x,
207 width: (right - x).max(0.0),
208 }
209 })
210 .collect()
211 }
212
213 pub fn for_each_glyph(&self, origin: Point, scale: f32, mut f: impl FnMut(GlyphInstance)) {
216 let ox = origin.x * scale;
217 let oy = origin.y * scale;
218 for run in self.buffer.layout_runs() {
219 let baseline = oy + run.line_y * scale;
220 for glyph in run.glyphs {
221 let physical = glyph.physical((ox, baseline), scale);
222 f(GlyphInstance {
223 key: GlyphKey(physical.cache_key),
224 x: physical.x,
225 y: physical.y,
226 color: glyph
227 .color_opt
228 .map(|c| Color::from_rgba8(c.r(), c.g(), c.b(), c.a())),
229 });
230 }
231 }
232 }
233
234 fn paragraph_offsets(&self) -> Vec<usize> {
235 let mut offsets = Vec::with_capacity(self.buffer.lines.len());
236 let mut offset = 0;
237 for line in &self.buffer.lines {
238 offsets.push(offset);
239 offset += line.text().len() + line.ending().as_str().len();
240 }
241 offsets
242 }
243
244 fn to_offset(&self, cursor: cosmic_text::Cursor) -> usize {
245 let offsets = self.paragraph_offsets();
246 offsets
247 .get(cursor.line)
248 .map_or(self.text.len(), |o| o + cursor.index)
249 }
250
251 fn to_cursor(&self, offset: usize) -> cosmic_text::Cursor {
252 let offsets = self.paragraph_offsets();
253 let mut line = 0;
254 for (i, start) in offsets.iter().enumerate() {
255 if *start <= offset {
256 line = i;
257 }
258 }
259 let len = self.buffer.lines.get(line).map_or(0, |l| l.text().len());
260 cosmic_text::Cursor::new(
261 line,
262 (offset - offsets.get(line).copied().unwrap_or(0)).min(len),
263 )
264 }
265
266 pub fn hit_test(&self, point: Point) -> usize {
269 match self.buffer.hit(point.x, point.y) {
270 Some(cursor) => self.to_offset(cursor),
271 None => {
272 if point.y < 0.0 {
273 0
274 } else {
275 self.text.len()
276 }
277 }
278 }
279 }
280
281 pub fn caret_bounds(&self, offset: usize) -> Bounds {
283 let cursor = self.to_cursor(offset);
284 let line_height = self.line_height();
285 for run in self.buffer.layout_runs() {
286 if run.line_i != cursor.line {
287 continue;
288 }
289 let first = run.glyphs.first();
290 let last = run.glyphs.last();
291 let in_run = match (first, last) {
292 (Some(f), Some(l)) => cursor.index >= f.start && cursor.index <= l.end,
293 _ => true,
294 };
295 if !in_run {
296 continue;
297 }
298 let x = run
299 .glyphs
300 .iter()
301 .find(|g| cursor.index >= g.start && cursor.index < g.end)
302 .map(|g| {
303 let span = (g.end - g.start).max(1) as f32;
305 g.x + g.w * ((cursor.index - g.start) as f32 / span)
306 })
307 .unwrap_or_else(|| last.map_or(0.0, |g| g.x + g.w));
308 return Bounds::new(Point::new(x, run.line_top), Size::new(1.0, run.line_height));
309 }
310 Bounds::new(
311 Point::new(0.0, cursor.line as f32 * line_height),
312 Size::new(1.0, line_height),
313 )
314 }
315
316 pub fn selection_bounds(&self, start: usize, end: usize) -> Vec<Bounds> {
318 let (start, end) = if start <= end {
319 (start, end)
320 } else {
321 (end, start)
322 };
323 let a = self.to_cursor(start);
324 let b = self.to_cursor(end);
325 let mut rects = Vec::new();
326 for run in self.buffer.layout_runs() {
327 for (x, w) in run.highlight(a, b) {
328 rects.push(Bounds::new(
329 Point::new(x, run.line_top),
330 Size::new(w.max(1.0), run.line_height),
331 ));
332 }
333 }
334 rects
335 }
336}
337
338impl Default for TextLayout {
339 fn default() -> Self {
340 Self::new()
341 }
342}