text_layout.rs

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