1use crate::{
2 color::Color,
3 fonts::{FontId, GlyphId},
4 geometry::{
5 rect::RectF,
6 vector::{vec2f, Vector2F},
7 },
8 platform, scene, FontSystem, PaintContext,
9};
10use ordered_float::OrderedFloat;
11use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
12use smallvec::SmallVec;
13use std::{
14 borrow::Borrow,
15 collections::HashMap,
16 hash::{Hash, Hasher},
17 iter,
18 sync::Arc,
19};
20
21pub struct TextLayoutCache {
22 prev_frame: Mutex<HashMap<CacheKeyValue, Arc<LineLayout>>>,
23 curr_frame: RwLock<HashMap<CacheKeyValue, Arc<LineLayout>>>,
24 fonts: Arc<dyn platform::FontSystem>,
25}
26
27impl TextLayoutCache {
28 pub fn new(fonts: Arc<dyn platform::FontSystem>) -> Self {
29 Self {
30 prev_frame: Mutex::new(HashMap::new()),
31 curr_frame: RwLock::new(HashMap::new()),
32 fonts,
33 }
34 }
35
36 pub fn finish_frame(&self) {
37 let mut prev_frame = self.prev_frame.lock();
38 let mut curr_frame = self.curr_frame.write();
39 std::mem::swap(&mut *prev_frame, &mut *curr_frame);
40 curr_frame.clear();
41 }
42
43 pub fn layout_str<'a>(
44 &'a self,
45 text: &'a str,
46 font_size: f32,
47 runs: &'a [(usize, FontId, Color)],
48 ) -> Line {
49 let key = &CacheKeyRef {
50 text,
51 font_size: OrderedFloat(font_size),
52 runs,
53 } as &dyn CacheKey;
54 let curr_frame = self.curr_frame.upgradable_read();
55 if let Some(layout) = curr_frame.get(key) {
56 return Line::new(layout.clone(), runs);
57 }
58
59 let mut curr_frame = RwLockUpgradableReadGuard::upgrade(curr_frame);
60 if let Some((key, layout)) = self.prev_frame.lock().remove_entry(key) {
61 curr_frame.insert(key, layout.clone());
62 Line::new(layout.clone(), runs)
63 } else {
64 let layout = Arc::new(self.fonts.layout_line(text, font_size, runs));
65 let key = CacheKeyValue {
66 text: text.into(),
67 font_size: OrderedFloat(font_size),
68 runs: SmallVec::from(runs),
69 };
70 curr_frame.insert(key, layout.clone());
71 Line::new(layout, runs)
72 }
73 }
74}
75
76trait CacheKey {
77 fn key<'a>(&'a self) -> CacheKeyRef<'a>;
78}
79
80impl<'a> PartialEq for (dyn CacheKey + 'a) {
81 fn eq(&self, other: &dyn CacheKey) -> bool {
82 self.key() == other.key()
83 }
84}
85
86impl<'a> Eq for (dyn CacheKey + 'a) {}
87
88impl<'a> Hash for (dyn CacheKey + 'a) {
89 fn hash<H: Hasher>(&self, state: &mut H) {
90 self.key().hash(state)
91 }
92}
93
94#[derive(Eq, PartialEq)]
95struct CacheKeyValue {
96 text: String,
97 font_size: OrderedFloat<f32>,
98 runs: SmallVec<[(usize, FontId, Color); 1]>,
99}
100
101impl CacheKey for CacheKeyValue {
102 fn key<'a>(&'a self) -> CacheKeyRef<'a> {
103 CacheKeyRef {
104 text: &self.text.as_str(),
105 font_size: self.font_size,
106 runs: self.runs.as_slice(),
107 }
108 }
109}
110
111impl Hash for CacheKeyValue {
112 fn hash<H: Hasher>(&self, state: &mut H) {
113 self.key().hash(state);
114 }
115}
116
117impl<'a> Borrow<dyn CacheKey + 'a> for CacheKeyValue {
118 fn borrow(&self) -> &(dyn CacheKey + 'a) {
119 self as &dyn CacheKey
120 }
121}
122
123#[derive(Copy, Clone, PartialEq, Eq, Hash)]
124struct CacheKeyRef<'a> {
125 text: &'a str,
126 font_size: OrderedFloat<f32>,
127 runs: &'a [(usize, FontId, Color)],
128}
129
130impl<'a> CacheKey for CacheKeyRef<'a> {
131 fn key<'b>(&'b self) -> CacheKeyRef<'b> {
132 *self
133 }
134}
135
136#[derive(Default, Debug)]
137pub struct Line {
138 layout: Arc<LineLayout>,
139 color_runs: SmallVec<[(u32, Color); 32]>,
140}
141
142#[derive(Default, Debug)]
143pub struct LineLayout {
144 pub width: f32,
145 pub ascent: f32,
146 pub descent: f32,
147 pub runs: Vec<Run>,
148 pub len: usize,
149 pub font_size: f32,
150}
151
152#[derive(Debug)]
153pub struct Run {
154 pub font_id: FontId,
155 pub glyphs: Vec<Glyph>,
156}
157
158#[derive(Debug)]
159pub struct Glyph {
160 pub id: GlyphId,
161 pub position: Vector2F,
162 pub index: usize,
163}
164
165impl Line {
166 fn new(layout: Arc<LineLayout>, runs: &[(usize, FontId, Color)]) -> Self {
167 let mut color_runs = SmallVec::new();
168 for (len, _, color) in runs {
169 color_runs.push((*len as u32, *color));
170 }
171 Self { layout, color_runs }
172 }
173
174 pub fn runs(&self) -> &[Run] {
175 &self.layout.runs
176 }
177
178 pub fn width(&self) -> f32 {
179 self.layout.width
180 }
181
182 pub fn x_for_index(&self, index: usize) -> f32 {
183 for run in &self.layout.runs {
184 for glyph in &run.glyphs {
185 if glyph.index == index {
186 return glyph.position.x();
187 }
188 }
189 }
190 self.layout.width
191 }
192
193 pub fn index_for_x(&self, x: f32) -> Option<usize> {
194 if x >= self.layout.width {
195 None
196 } else {
197 for run in self.layout.runs.iter().rev() {
198 for glyph in run.glyphs.iter().rev() {
199 if glyph.position.x() <= x {
200 return Some(glyph.index);
201 }
202 }
203 }
204 Some(0)
205 }
206 }
207
208 pub fn paint(&self, origin: Vector2F, visible_bounds: RectF, cx: &mut PaintContext) {
209 let padding_top = (visible_bounds.height() - self.layout.ascent - self.layout.descent) / 2.;
210 let baseline_origin = vec2f(0., padding_top + self.layout.ascent);
211
212 let mut color_runs = self.color_runs.iter();
213 let mut color_end = 0;
214 let mut color = Color::black();
215
216 for run in &self.layout.runs {
217 let max_glyph_width = cx
218 .font_cache
219 .bounding_box(run.font_id, self.layout.font_size)
220 .x();
221
222 for glyph in &run.glyphs {
223 let glyph_origin = baseline_origin + glyph.position;
224
225 if glyph_origin.x() + max_glyph_width < visible_bounds.origin().x() {
226 continue;
227 }
228 if glyph_origin.x() > visible_bounds.upper_right().x() {
229 break;
230 }
231
232 if glyph.index >= color_end {
233 if let Some(next_run) = color_runs.next() {
234 color_end += next_run.0 as usize;
235 color = next_run.1;
236 } else {
237 color_end = self.layout.len;
238 color = Color::black();
239 }
240 }
241
242 cx.scene.push_glyph(scene::Glyph {
243 font_id: run.font_id,
244 font_size: self.layout.font_size,
245 id: glyph.id,
246 origin: origin + glyph_origin,
247 color,
248 });
249 }
250 }
251 }
252
253 pub fn paint_wrapped(
254 &self,
255 origin: Vector2F,
256 visible_bounds: RectF,
257 line_height: f32,
258 boundaries: impl IntoIterator<Item = ShapedBoundary>,
259 cx: &mut PaintContext,
260 ) {
261 let padding_top = (line_height - self.layout.ascent - self.layout.descent) / 2.;
262 let baseline_origin = vec2f(0., padding_top + self.layout.ascent);
263
264 let mut boundaries = boundaries.into_iter().peekable();
265 let mut color_runs = self.color_runs.iter();
266 let mut color_end = 0;
267 let mut color = Color::black();
268
269 let mut glyph_origin = baseline_origin;
270 let mut prev_position = 0.;
271 for run in &self.layout.runs {
272 for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
273 if boundaries.peek().map_or(false, |b| b.glyph_ix == glyph_ix) {
274 boundaries.next();
275 glyph_origin = vec2f(0., glyph_origin.y() + line_height);
276 } else {
277 glyph_origin.set_x(glyph_origin.x() + glyph.position.x() - prev_position);
278 }
279 prev_position = glyph.position.x();
280
281 if glyph.index >= color_end {
282 if let Some(next_run) = color_runs.next() {
283 color_end += next_run.0 as usize;
284 color = next_run.1;
285 } else {
286 color_end = self.layout.len;
287 color = Color::black();
288 }
289 }
290
291 let glyph_bounds = RectF::new(
292 origin + glyph_origin,
293 cx.font_cache
294 .bounding_box(run.font_id, self.layout.font_size),
295 );
296 if glyph_bounds.intersects(visible_bounds) {
297 cx.scene.push_glyph(scene::Glyph {
298 font_id: run.font_id,
299 font_size: self.layout.font_size,
300 id: glyph.id,
301 origin: origin + glyph_origin,
302 color,
303 });
304 }
305 }
306 }
307 }
308}
309
310impl Run {
311 pub fn glyphs(&self) -> &[Glyph] {
312 &self.glyphs
313 }
314}
315
316#[derive(Copy, Clone, Debug, PartialEq, Eq)]
317pub struct Boundary {
318 pub ix: usize,
319 pub next_indent: u32,
320}
321
322#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
323pub struct ShapedBoundary {
324 pub run_ix: usize,
325 pub glyph_ix: usize,
326}
327
328impl Boundary {
329 fn new(ix: usize, next_indent: u32) -> Self {
330 Self { ix, next_indent }
331 }
332}
333
334pub struct LineWrapper {
335 font_system: Arc<dyn FontSystem>,
336 pub(crate) font_id: FontId,
337 pub(crate) font_size: f32,
338 cached_ascii_char_widths: [f32; 128],
339 cached_other_char_widths: HashMap<char, f32>,
340}
341
342impl LineWrapper {
343 pub const MAX_INDENT: u32 = 256;
344
345 pub fn new(font_id: FontId, font_size: f32, font_system: Arc<dyn FontSystem>) -> Self {
346 Self {
347 font_system,
348 font_id,
349 font_size,
350 cached_ascii_char_widths: [f32::NAN; 128],
351 cached_other_char_widths: HashMap::new(),
352 }
353 }
354
355 pub fn wrap_line<'a>(
356 &'a mut self,
357 line: &'a str,
358 wrap_width: f32,
359 ) -> impl Iterator<Item = Boundary> + 'a {
360 let mut width = 0.0;
361 let mut first_non_whitespace_ix = None;
362 let mut indent = None;
363 let mut last_candidate_ix = 0;
364 let mut last_candidate_width = 0.0;
365 let mut last_wrap_ix = 0;
366 let mut prev_c = '\0';
367 let mut char_indices = line.char_indices();
368 iter::from_fn(move || {
369 while let Some((ix, c)) = char_indices.next() {
370 if c == '\n' {
371 continue;
372 }
373
374 if self.is_boundary(prev_c, c) && first_non_whitespace_ix.is_some() {
375 last_candidate_ix = ix;
376 last_candidate_width = width;
377 }
378
379 if c != ' ' && first_non_whitespace_ix.is_none() {
380 first_non_whitespace_ix = Some(ix);
381 }
382
383 let char_width = self.width_for_char(c);
384 width += char_width;
385 if width > wrap_width && ix > last_wrap_ix {
386 if let (None, Some(first_non_whitespace_ix)) = (indent, first_non_whitespace_ix)
387 {
388 indent = Some(
389 Self::MAX_INDENT.min((first_non_whitespace_ix - last_wrap_ix) as u32),
390 );
391 }
392
393 if last_candidate_ix > 0 {
394 last_wrap_ix = last_candidate_ix;
395 width -= last_candidate_width;
396 last_candidate_ix = 0;
397 } else {
398 last_wrap_ix = ix;
399 width = char_width;
400 }
401
402 let indent_width =
403 indent.map(|indent| indent as f32 * self.width_for_char(' '));
404 width += indent_width.unwrap_or(0.);
405
406 return Some(Boundary::new(last_wrap_ix, indent.unwrap_or(0)));
407 }
408 prev_c = c;
409 }
410
411 None
412 })
413 }
414
415 pub fn wrap_shaped_line<'a>(
416 &'a mut self,
417 str: &'a str,
418 line: &'a Line,
419 wrap_width: f32,
420 ) -> impl Iterator<Item = ShapedBoundary> + 'a {
421 let mut first_non_whitespace_ix = None;
422 let mut last_candidate_ix = None;
423 let mut last_candidate_x = 0.0;
424 let mut last_wrap_ix = ShapedBoundary {
425 run_ix: 0,
426 glyph_ix: 0,
427 };
428 let mut last_wrap_x = 0.;
429 let mut prev_c = '\0';
430 let mut glyphs = line
431 .runs()
432 .iter()
433 .enumerate()
434 .flat_map(move |(run_ix, run)| {
435 run.glyphs()
436 .iter()
437 .enumerate()
438 .map(move |(glyph_ix, glyph)| {
439 let character = str[glyph.index..].chars().next().unwrap();
440 (
441 ShapedBoundary { run_ix, glyph_ix },
442 character,
443 glyph.position.x(),
444 )
445 })
446 })
447 .peekable();
448
449 iter::from_fn(move || {
450 while let Some((ix, c, x)) = glyphs.next() {
451 if c == '\n' {
452 continue;
453 }
454
455 if self.is_boundary(prev_c, c) && first_non_whitespace_ix.is_some() {
456 last_candidate_ix = Some(ix);
457 last_candidate_x = x;
458 }
459
460 if c != ' ' && first_non_whitespace_ix.is_none() {
461 first_non_whitespace_ix = Some(ix);
462 }
463
464 let next_x = glyphs.peek().map_or(line.width(), |(_, _, x)| *x);
465 let width = next_x - last_wrap_x;
466 if width > wrap_width && ix > last_wrap_ix {
467 if let Some(last_candidate_ix) = last_candidate_ix.take() {
468 last_wrap_ix = last_candidate_ix;
469 last_wrap_x = last_candidate_x;
470 } else {
471 last_wrap_ix = ix;
472 last_wrap_x = x;
473 }
474
475 return Some(last_wrap_ix);
476 }
477 prev_c = c;
478 }
479
480 None
481 })
482 }
483
484 fn is_boundary(&self, prev: char, next: char) -> bool {
485 (prev == ' ') && (next != ' ')
486 }
487
488 #[inline(always)]
489 fn width_for_char(&mut self, c: char) -> f32 {
490 if (c as u32) < 128 {
491 let mut width = self.cached_ascii_char_widths[c as usize];
492 if width.is_nan() {
493 width = self.compute_width_for_char(c);
494 self.cached_ascii_char_widths[c as usize] = width;
495 }
496 width
497 } else {
498 let mut width = self
499 .cached_other_char_widths
500 .get(&c)
501 .copied()
502 .unwrap_or(f32::NAN);
503 if width.is_nan() {
504 width = self.compute_width_for_char(c);
505 self.cached_other_char_widths.insert(c, width);
506 }
507 width
508 }
509 }
510
511 fn compute_width_for_char(&self, c: char) -> f32 {
512 self.font_system
513 .layout_line(
514 &c.to_string(),
515 self.font_size,
516 &[(1, self.font_id, Default::default())],
517 )
518 .width
519 }
520}
521
522#[cfg(test)]
523mod tests {
524 use super::*;
525 use crate::{
526 color::Color,
527 fonts::{Properties, Weight},
528 };
529
530 #[crate::test(self)]
531 fn test_wrap_line(cx: &mut crate::MutableAppContext) {
532 let font_cache = cx.font_cache().clone();
533 let font_system = cx.platform().fonts();
534 let family = font_cache.load_family(&["Courier"]).unwrap();
535 let font_id = font_cache.select_font(family, &Default::default()).unwrap();
536
537 let mut wrapper = LineWrapper::new(font_id, 16., font_system);
538 assert_eq!(
539 wrapper
540 .wrap_line("aa bbb cccc ddddd eeee", 72.0)
541 .collect::<Vec<_>>(),
542 &[
543 Boundary::new(7, 0),
544 Boundary::new(12, 0),
545 Boundary::new(18, 0)
546 ],
547 );
548 assert_eq!(
549 wrapper
550 .wrap_line("aaa aaaaaaaaaaaaaaaaaa", 72.0)
551 .collect::<Vec<_>>(),
552 &[
553 Boundary::new(4, 0),
554 Boundary::new(11, 0),
555 Boundary::new(18, 0)
556 ],
557 );
558 assert_eq!(
559 wrapper.wrap_line(" aaaaaaa", 72.).collect::<Vec<_>>(),
560 &[
561 Boundary::new(7, 5),
562 Boundary::new(9, 5),
563 Boundary::new(11, 5),
564 ]
565 );
566 assert_eq!(
567 wrapper
568 .wrap_line(" ", 72.)
569 .collect::<Vec<_>>(),
570 &[
571 Boundary::new(7, 0),
572 Boundary::new(14, 0),
573 Boundary::new(21, 0)
574 ]
575 );
576 assert_eq!(
577 wrapper
578 .wrap_line(" aaaaaaaaaaaaaa", 72.)
579 .collect::<Vec<_>>(),
580 &[
581 Boundary::new(7, 0),
582 Boundary::new(14, 3),
583 Boundary::new(18, 3),
584 Boundary::new(22, 3),
585 ]
586 );
587 }
588
589 #[crate::test(self)]
590 fn test_wrap_shaped_line(cx: &mut crate::MutableAppContext) {
591 let font_cache = cx.font_cache().clone();
592 let font_system = cx.platform().fonts();
593 let text_layout_cache = TextLayoutCache::new(font_system.clone());
594
595 let family = font_cache.load_family(&["Helvetica"]).unwrap();
596 let font_id = font_cache.select_font(family, &Default::default()).unwrap();
597 let normal = font_cache.select_font(family, &Default::default()).unwrap();
598 let bold = font_cache
599 .select_font(
600 family,
601 &Properties {
602 weight: Weight::BOLD,
603 ..Default::default()
604 },
605 )
606 .unwrap();
607
608 let text = "aa bbb cccc ddddd eeee";
609 let line = text_layout_cache.layout_str(
610 text,
611 16.0,
612 &[
613 (4, normal, Color::default()),
614 (5, bold, Color::default()),
615 (6, normal, Color::default()),
616 (1, bold, Color::default()),
617 (7, normal, Color::default()),
618 ],
619 );
620
621 let mut wrapper = LineWrapper::new(font_id, 16., font_system);
622 assert_eq!(
623 wrapper
624 .wrap_shaped_line(&text, &line, 72.0)
625 .collect::<Vec<_>>(),
626 &[
627 ShapedBoundary {
628 run_ix: 1,
629 glyph_ix: 3
630 },
631 ShapedBoundary {
632 run_ix: 2,
633 glyph_ix: 3
634 },
635 ShapedBoundary {
636 run_ix: 4,
637 glyph_ix: 2
638 }
639 ],
640 );
641 }
642}