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