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
27#[derive(Copy, Clone, Debug, PartialEq, Eq)]
28pub struct RunStyle {
29 pub color: Color,
30 pub font_id: FontId,
31 pub underline: bool,
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)]
168pub struct Line {
169 layout: Arc<LineLayout>,
170 style_runs: SmallVec<[(u32, Color, bool); 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(Debug)]
190pub struct Glyph {
191 pub id: GlyphId,
192 pub position: Vector2F,
193 pub index: usize,
194}
195
196impl Line {
197 fn new(layout: Arc<LineLayout>, runs: &[(usize, RunStyle)]) -> Self {
198 let mut style_runs = SmallVec::new();
199 for (len, style) in runs {
200 style_runs.push((*len as u32, style.color, style.underline));
201 }
202 Self { layout, style_runs }
203 }
204
205 pub fn runs(&self) -> &[Run] {
206 &self.layout.runs
207 }
208
209 pub fn width(&self) -> f32 {
210 self.layout.width
211 }
212
213 pub fn x_for_index(&self, index: usize) -> f32 {
214 for run in &self.layout.runs {
215 for glyph in &run.glyphs {
216 if glyph.index == index {
217 return glyph.position.x();
218 }
219 }
220 }
221 self.layout.width
222 }
223
224 pub fn index_for_x(&self, x: f32) -> Option<usize> {
225 if x >= self.layout.width {
226 None
227 } else {
228 for run in self.layout.runs.iter().rev() {
229 for glyph in run.glyphs.iter().rev() {
230 if glyph.position.x() <= x {
231 return Some(glyph.index);
232 }
233 }
234 }
235 Some(0)
236 }
237 }
238
239 pub fn paint(
240 &self,
241 origin: Vector2F,
242 visible_bounds: RectF,
243 line_height: f32,
244 cx: &mut PaintContext,
245 ) {
246 let padding_top = (line_height - self.layout.ascent - self.layout.descent) / 2.;
247 let baseline_offset = vec2f(0., padding_top + self.layout.ascent);
248
249 let mut style_runs = self.style_runs.iter();
250 let mut run_end = 0;
251 let mut color = Color::black();
252 let mut underline_start = None;
253
254 for run in &self.layout.runs {
255 let max_glyph_width = cx
256 .font_cache
257 .bounding_box(run.font_id, self.layout.font_size)
258 .x();
259
260 for glyph in &run.glyphs {
261 let glyph_origin = origin + baseline_offset + glyph.position;
262
263 if glyph_origin.x() + max_glyph_width < visible_bounds.origin().x() {
264 continue;
265 }
266 if glyph_origin.x() > visible_bounds.upper_right().x() {
267 break;
268 }
269
270 if glyph.index >= run_end {
271 if let Some((run_len, run_color, run_underlined)) = style_runs.next() {
272 if let Some(underline_origin) = underline_start {
273 if !*run_underlined || *run_color != color {
274 cx.scene.push_underline(scene::Quad {
275 bounds: RectF::from_points(
276 underline_origin,
277 glyph_origin + vec2f(0., 1.),
278 ),
279 background: Some(color),
280 border: Default::default(),
281 corner_radius: 0.,
282 });
283 underline_start = None;
284 }
285 }
286
287 if *run_underlined {
288 underline_start.get_or_insert(glyph_origin);
289 }
290
291 run_end += *run_len as usize;
292 color = *run_color;
293 } else {
294 run_end = self.layout.len;
295 color = Color::black();
296 }
297 }
298
299 cx.scene.push_glyph(scene::Glyph {
300 font_id: run.font_id,
301 font_size: self.layout.font_size,
302 id: glyph.id,
303 origin: glyph_origin,
304 color,
305 });
306 }
307
308 if let Some(underline_start) = underline_start.take() {
309 let line_end = origin + baseline_offset + vec2f(self.layout.width, 0.);
310
311 cx.scene.push_underline(scene::Quad {
312 bounds: RectF::from_points(underline_start, line_end + vec2f(0., 1.)),
313 background: Some(color),
314 border: Default::default(),
315 corner_radius: 0.,
316 });
317 }
318 }
319 }
320
321 pub fn paint_wrapped(
322 &self,
323 origin: Vector2F,
324 visible_bounds: RectF,
325 line_height: f32,
326 boundaries: impl IntoIterator<Item = ShapedBoundary>,
327 cx: &mut PaintContext,
328 ) {
329 let padding_top = (line_height - self.layout.ascent - self.layout.descent) / 2.;
330 let baseline_origin = vec2f(0., padding_top + self.layout.ascent);
331
332 let mut boundaries = boundaries.into_iter().peekable();
333 let mut color_runs = self.style_runs.iter();
334 let mut color_end = 0;
335 let mut color = Color::black();
336
337 let mut glyph_origin = vec2f(0., 0.);
338 let mut prev_position = 0.;
339 for run in &self.layout.runs {
340 for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
341 if boundaries.peek().map_or(false, |b| b.glyph_ix == glyph_ix) {
342 boundaries.next();
343 glyph_origin = vec2f(0., glyph_origin.y() + line_height);
344 } else {
345 glyph_origin.set_x(glyph_origin.x() + glyph.position.x() - prev_position);
346 }
347 prev_position = glyph.position.x();
348
349 if glyph.index >= color_end {
350 if let Some(next_run) = color_runs.next() {
351 color_end += next_run.0 as usize;
352 color = next_run.1;
353 } else {
354 color_end = self.layout.len;
355 color = Color::black();
356 }
357 }
358
359 let glyph_bounds = RectF::new(
360 origin + glyph_origin,
361 cx.font_cache
362 .bounding_box(run.font_id, self.layout.font_size),
363 );
364 if glyph_bounds.intersects(visible_bounds) {
365 cx.scene.push_glyph(scene::Glyph {
366 font_id: run.font_id,
367 font_size: self.layout.font_size,
368 id: glyph.id,
369 origin: glyph_bounds.origin() + baseline_origin,
370 color,
371 });
372 }
373 }
374 }
375 }
376}
377
378impl Run {
379 pub fn glyphs(&self) -> &[Glyph] {
380 &self.glyphs
381 }
382}
383
384#[derive(Copy, Clone, Debug, PartialEq, Eq)]
385pub struct Boundary {
386 pub ix: usize,
387 pub next_indent: u32,
388}
389
390#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
391pub struct ShapedBoundary {
392 pub run_ix: usize,
393 pub glyph_ix: usize,
394}
395
396impl Boundary {
397 fn new(ix: usize, next_indent: u32) -> Self {
398 Self { ix, next_indent }
399 }
400}
401
402pub struct LineWrapper {
403 font_system: Arc<dyn FontSystem>,
404 pub(crate) font_id: FontId,
405 pub(crate) font_size: f32,
406 cached_ascii_char_widths: [f32; 128],
407 cached_other_char_widths: HashMap<char, f32>,
408}
409
410impl LineWrapper {
411 pub const MAX_INDENT: u32 = 256;
412
413 pub fn new(font_id: FontId, font_size: f32, font_system: Arc<dyn FontSystem>) -> Self {
414 Self {
415 font_system,
416 font_id,
417 font_size,
418 cached_ascii_char_widths: [f32::NAN; 128],
419 cached_other_char_widths: HashMap::new(),
420 }
421 }
422
423 pub fn wrap_line<'a>(
424 &'a mut self,
425 line: &'a str,
426 wrap_width: f32,
427 ) -> impl Iterator<Item = Boundary> + 'a {
428 let mut width = 0.0;
429 let mut first_non_whitespace_ix = None;
430 let mut indent = None;
431 let mut last_candidate_ix = 0;
432 let mut last_candidate_width = 0.0;
433 let mut last_wrap_ix = 0;
434 let mut prev_c = '\0';
435 let mut char_indices = line.char_indices();
436 iter::from_fn(move || {
437 while let Some((ix, c)) = char_indices.next() {
438 if c == '\n' {
439 continue;
440 }
441
442 if self.is_boundary(prev_c, c) && first_non_whitespace_ix.is_some() {
443 last_candidate_ix = ix;
444 last_candidate_width = width;
445 }
446
447 if c != ' ' && first_non_whitespace_ix.is_none() {
448 first_non_whitespace_ix = Some(ix);
449 }
450
451 let char_width = self.width_for_char(c);
452 width += char_width;
453 if width > wrap_width && ix > last_wrap_ix {
454 if let (None, Some(first_non_whitespace_ix)) = (indent, first_non_whitespace_ix)
455 {
456 indent = Some(
457 Self::MAX_INDENT.min((first_non_whitespace_ix - last_wrap_ix) as u32),
458 );
459 }
460
461 if last_candidate_ix > 0 {
462 last_wrap_ix = last_candidate_ix;
463 width -= last_candidate_width;
464 last_candidate_ix = 0;
465 } else {
466 last_wrap_ix = ix;
467 width = char_width;
468 }
469
470 let indent_width =
471 indent.map(|indent| indent as f32 * self.width_for_char(' '));
472 width += indent_width.unwrap_or(0.);
473
474 return Some(Boundary::new(last_wrap_ix, indent.unwrap_or(0)));
475 }
476 prev_c = c;
477 }
478
479 None
480 })
481 }
482
483 pub fn wrap_shaped_line<'a>(
484 &'a mut self,
485 str: &'a str,
486 line: &'a Line,
487 wrap_width: f32,
488 ) -> impl Iterator<Item = ShapedBoundary> + 'a {
489 let mut first_non_whitespace_ix = None;
490 let mut last_candidate_ix = None;
491 let mut last_candidate_x = 0.0;
492 let mut last_wrap_ix = ShapedBoundary {
493 run_ix: 0,
494 glyph_ix: 0,
495 };
496 let mut last_wrap_x = 0.;
497 let mut prev_c = '\0';
498 let mut glyphs = line
499 .runs()
500 .iter()
501 .enumerate()
502 .flat_map(move |(run_ix, run)| {
503 run.glyphs()
504 .iter()
505 .enumerate()
506 .map(move |(glyph_ix, glyph)| {
507 let character = str[glyph.index..].chars().next().unwrap();
508 (
509 ShapedBoundary { run_ix, glyph_ix },
510 character,
511 glyph.position.x(),
512 )
513 })
514 })
515 .peekable();
516
517 iter::from_fn(move || {
518 while let Some((ix, c, x)) = glyphs.next() {
519 if c == '\n' {
520 continue;
521 }
522
523 if self.is_boundary(prev_c, c) && first_non_whitespace_ix.is_some() {
524 last_candidate_ix = Some(ix);
525 last_candidate_x = x;
526 }
527
528 if c != ' ' && first_non_whitespace_ix.is_none() {
529 first_non_whitespace_ix = Some(ix);
530 }
531
532 let next_x = glyphs.peek().map_or(line.width(), |(_, _, x)| *x);
533 let width = next_x - last_wrap_x;
534 if width > wrap_width && ix > last_wrap_ix {
535 if let Some(last_candidate_ix) = last_candidate_ix.take() {
536 last_wrap_ix = last_candidate_ix;
537 last_wrap_x = last_candidate_x;
538 } else {
539 last_wrap_ix = ix;
540 last_wrap_x = x;
541 }
542
543 return Some(last_wrap_ix);
544 }
545 prev_c = c;
546 }
547
548 None
549 })
550 }
551
552 fn is_boundary(&self, prev: char, next: char) -> bool {
553 (prev == ' ') && (next != ' ')
554 }
555
556 #[inline(always)]
557 fn width_for_char(&mut self, c: char) -> f32 {
558 if (c as u32) < 128 {
559 let mut width = self.cached_ascii_char_widths[c as usize];
560 if width.is_nan() {
561 width = self.compute_width_for_char(c);
562 self.cached_ascii_char_widths[c as usize] = width;
563 }
564 width
565 } else {
566 let mut width = self
567 .cached_other_char_widths
568 .get(&c)
569 .copied()
570 .unwrap_or(f32::NAN);
571 if width.is_nan() {
572 width = self.compute_width_for_char(c);
573 self.cached_other_char_widths.insert(c, width);
574 }
575 width
576 }
577 }
578
579 fn compute_width_for_char(&self, c: char) -> f32 {
580 self.font_system
581 .layout_line(
582 &c.to_string(),
583 self.font_size,
584 &[(
585 1,
586 RunStyle {
587 font_id: self.font_id,
588 color: Default::default(),
589 underline: false,
590 },
591 )],
592 )
593 .width
594 }
595}
596
597#[cfg(test)]
598mod tests {
599 use super::*;
600 use crate::fonts::{Properties, Weight};
601
602 #[crate::test(self)]
603 fn test_wrap_line(cx: &mut crate::MutableAppContext) {
604 let font_cache = cx.font_cache().clone();
605 let font_system = cx.platform().fonts();
606 let family = font_cache.load_family(&["Courier"]).unwrap();
607 let font_id = font_cache.select_font(family, &Default::default()).unwrap();
608
609 let mut wrapper = LineWrapper::new(font_id, 16., font_system);
610 assert_eq!(
611 wrapper
612 .wrap_line("aa bbb cccc ddddd eeee", 72.0)
613 .collect::<Vec<_>>(),
614 &[
615 Boundary::new(7, 0),
616 Boundary::new(12, 0),
617 Boundary::new(18, 0)
618 ],
619 );
620 assert_eq!(
621 wrapper
622 .wrap_line("aaa aaaaaaaaaaaaaaaaaa", 72.0)
623 .collect::<Vec<_>>(),
624 &[
625 Boundary::new(4, 0),
626 Boundary::new(11, 0),
627 Boundary::new(18, 0)
628 ],
629 );
630 assert_eq!(
631 wrapper.wrap_line(" aaaaaaa", 72.).collect::<Vec<_>>(),
632 &[
633 Boundary::new(7, 5),
634 Boundary::new(9, 5),
635 Boundary::new(11, 5),
636 ]
637 );
638 assert_eq!(
639 wrapper
640 .wrap_line(" ", 72.)
641 .collect::<Vec<_>>(),
642 &[
643 Boundary::new(7, 0),
644 Boundary::new(14, 0),
645 Boundary::new(21, 0)
646 ]
647 );
648 assert_eq!(
649 wrapper
650 .wrap_line(" aaaaaaaaaaaaaa", 72.)
651 .collect::<Vec<_>>(),
652 &[
653 Boundary::new(7, 0),
654 Boundary::new(14, 3),
655 Boundary::new(18, 3),
656 Boundary::new(22, 3),
657 ]
658 );
659 }
660
661 #[crate::test(self)]
662 fn test_wrap_shaped_line(cx: &mut crate::MutableAppContext) {
663 let font_cache = cx.font_cache().clone();
664 let font_system = cx.platform().fonts();
665 let text_layout_cache = TextLayoutCache::new(font_system.clone());
666
667 let family = font_cache.load_family(&["Helvetica"]).unwrap();
668 let font_id = font_cache.select_font(family, &Default::default()).unwrap();
669 let normal = RunStyle {
670 font_id,
671 color: Default::default(),
672 underline: false,
673 };
674 let bold = RunStyle {
675 font_id: font_cache
676 .select_font(
677 family,
678 &Properties {
679 weight: Weight::BOLD,
680 ..Default::default()
681 },
682 )
683 .unwrap(),
684 color: Default::default(),
685 underline: false,
686 };
687
688 let text = "aa bbb cccc ddddd eeee";
689 let line = text_layout_cache.layout_str(
690 text,
691 16.0,
692 &[(4, normal), (5, bold), (6, normal), (1, bold), (7, normal)],
693 );
694
695 let mut wrapper = LineWrapper::new(font_id, 16., font_system);
696 assert_eq!(
697 wrapper
698 .wrap_shaped_line(&text, &line, 72.0)
699 .collect::<Vec<_>>(),
700 &[
701 ShapedBoundary {
702 run_ix: 1,
703 glyph_ix: 3
704 },
705 ShapedBoundary {
706 run_ix: 2,
707 glyph_ix: 3
708 },
709 ShapedBoundary {
710 run_ix: 4,
711 glyph_ix: 2
712 }
713 ],
714 );
715 }
716}