text_layout.rs

  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        line_height: f32,
257        boundaries: impl IntoIterator<Item = ShapedBoundary>,
258        cx: &mut PaintContext,
259    ) {
260        let padding_top = (line_height - self.layout.ascent - self.layout.descent) / 2.;
261        let baseline_origin = vec2f(0., padding_top + self.layout.ascent);
262
263        let mut boundaries = boundaries.into_iter().peekable();
264        let mut color_runs = self.color_runs.iter();
265        let mut color_end = 0;
266        let mut color = Color::black();
267
268        let mut glyph_origin = baseline_origin;
269        let mut prev_position = 0.;
270        for run in &self.layout.runs {
271            for (glyph_ix, glyph) in run.glyphs.iter().enumerate() {
272                if boundaries.peek().map_or(false, |b| b.glyph_ix == glyph_ix) {
273                    boundaries.next();
274                    glyph_origin = vec2f(0., glyph_origin.y() + line_height);
275                } else {
276                    glyph_origin.set_x(glyph_origin.x() + glyph.position.x() - prev_position);
277                }
278                prev_position = glyph.position.x();
279
280                if glyph.index >= color_end {
281                    if let Some(next_run) = color_runs.next() {
282                        color_end += next_run.0 as usize;
283                        color = next_run.1;
284                    } else {
285                        color_end = self.layout.len;
286                        color = Color::black();
287                    }
288                }
289
290                cx.scene.push_glyph(scene::Glyph {
291                    font_id: run.font_id,
292                    font_size: self.layout.font_size,
293                    id: glyph.id,
294                    origin: origin + glyph_origin,
295                    color,
296                });
297            }
298        }
299    }
300}
301
302impl Run {
303    pub fn glyphs(&self) -> &[Glyph] {
304        &self.glyphs
305    }
306}
307
308#[derive(Copy, Clone, Debug, PartialEq, Eq)]
309pub struct Boundary {
310    pub ix: usize,
311    pub next_indent: u32,
312}
313
314#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
315pub struct ShapedBoundary {
316    pub run_ix: usize,
317    pub glyph_ix: usize,
318}
319
320impl Boundary {
321    fn new(ix: usize, next_indent: u32) -> Self {
322        Self { ix, next_indent }
323    }
324}
325
326pub struct LineWrapper {
327    font_system: Arc<dyn FontSystem>,
328    pub(crate) font_id: FontId,
329    pub(crate) font_size: f32,
330    cached_ascii_char_widths: [f32; 128],
331    cached_other_char_widths: HashMap<char, f32>,
332}
333
334impl LineWrapper {
335    pub const MAX_INDENT: u32 = 256;
336
337    pub fn new(font_id: FontId, font_size: f32, font_system: Arc<dyn FontSystem>) -> Self {
338        Self {
339            font_system,
340            font_id,
341            font_size,
342            cached_ascii_char_widths: [f32::NAN; 128],
343            cached_other_char_widths: HashMap::new(),
344        }
345    }
346
347    pub fn wrap_line<'a>(
348        &'a mut self,
349        line: &'a str,
350        wrap_width: f32,
351    ) -> impl Iterator<Item = Boundary> + 'a {
352        let mut width = 0.0;
353        let mut first_non_whitespace_ix = None;
354        let mut indent = None;
355        let mut last_candidate_ix = 0;
356        let mut last_candidate_width = 0.0;
357        let mut last_wrap_ix = 0;
358        let mut prev_c = '\0';
359        let mut char_indices = line.char_indices();
360        iter::from_fn(move || {
361            while let Some((ix, c)) = char_indices.next() {
362                if c == '\n' {
363                    continue;
364                }
365
366                if self.is_boundary(prev_c, c) && first_non_whitespace_ix.is_some() {
367                    last_candidate_ix = ix;
368                    last_candidate_width = width;
369                }
370
371                if c != ' ' && first_non_whitespace_ix.is_none() {
372                    first_non_whitespace_ix = Some(ix);
373                }
374
375                let char_width = self.width_for_char(c);
376                width += char_width;
377                if width > wrap_width && ix > last_wrap_ix {
378                    if let (None, Some(first_non_whitespace_ix)) = (indent, first_non_whitespace_ix)
379                    {
380                        indent = Some(
381                            Self::MAX_INDENT.min((first_non_whitespace_ix - last_wrap_ix) as u32),
382                        );
383                    }
384
385                    if last_candidate_ix > 0 {
386                        last_wrap_ix = last_candidate_ix;
387                        width -= last_candidate_width;
388                        last_candidate_ix = 0;
389                    } else {
390                        last_wrap_ix = ix;
391                        width = char_width;
392                    }
393
394                    let indent_width =
395                        indent.map(|indent| indent as f32 * self.width_for_char(' '));
396                    width += indent_width.unwrap_or(0.);
397
398                    return Some(Boundary::new(last_wrap_ix, indent.unwrap_or(0)));
399                }
400                prev_c = c;
401            }
402
403            None
404        })
405    }
406
407    pub fn wrap_shaped_line<'a>(
408        &'a mut self,
409        str: &'a str,
410        line: &'a Line,
411        wrap_width: f32,
412    ) -> impl Iterator<Item = ShapedBoundary> + 'a {
413        let mut first_non_whitespace_ix = None;
414        let mut last_candidate_ix = None;
415        let mut last_candidate_x = 0.0;
416        let mut last_wrap_ix = ShapedBoundary {
417            run_ix: 0,
418            glyph_ix: 0,
419        };
420        let mut last_wrap_x = 0.;
421        let mut prev_c = '\0';
422        let mut glyphs = line
423            .runs()
424            .iter()
425            .enumerate()
426            .flat_map(move |(run_ix, run)| {
427                run.glyphs()
428                    .iter()
429                    .enumerate()
430                    .map(move |(glyph_ix, glyph)| {
431                        let character = str[glyph.index..].chars().next().unwrap();
432                        (
433                            ShapedBoundary { run_ix, glyph_ix },
434                            character,
435                            glyph.position.x(),
436                        )
437                    })
438            })
439            .peekable();
440
441        iter::from_fn(move || {
442            while let Some((ix, c, x)) = glyphs.next() {
443                if c == '\n' {
444                    continue;
445                }
446
447                if self.is_boundary(prev_c, c) && first_non_whitespace_ix.is_some() {
448                    last_candidate_ix = Some(ix);
449                    last_candidate_x = x;
450                }
451
452                if c != ' ' && first_non_whitespace_ix.is_none() {
453                    first_non_whitespace_ix = Some(ix);
454                }
455
456                let next_x = glyphs.peek().map_or(line.width(), |(_, _, x)| *x);
457                let width = next_x - last_wrap_x;
458                if width > wrap_width && ix > last_wrap_ix {
459                    if let Some(last_candidate_ix) = last_candidate_ix.take() {
460                        last_wrap_ix = last_candidate_ix;
461                        last_wrap_x = last_candidate_x;
462                    } else {
463                        last_wrap_ix = ix;
464                        last_wrap_x = x;
465                    }
466
467                    return Some(last_wrap_ix);
468                }
469                prev_c = c;
470            }
471
472            None
473        })
474    }
475
476    fn is_boundary(&self, prev: char, next: char) -> bool {
477        (prev == ' ') && (next != ' ')
478    }
479
480    #[inline(always)]
481    fn width_for_char(&mut self, c: char) -> f32 {
482        if (c as u32) < 128 {
483            let mut width = self.cached_ascii_char_widths[c as usize];
484            if width.is_nan() {
485                width = self.compute_width_for_char(c);
486                self.cached_ascii_char_widths[c as usize] = width;
487            }
488            width
489        } else {
490            let mut width = self
491                .cached_other_char_widths
492                .get(&c)
493                .copied()
494                .unwrap_or(f32::NAN);
495            if width.is_nan() {
496                width = self.compute_width_for_char(c);
497                self.cached_other_char_widths.insert(c, width);
498            }
499            width
500        }
501    }
502
503    fn compute_width_for_char(&self, c: char) -> f32 {
504        self.font_system
505            .layout_line(
506                &c.to_string(),
507                self.font_size,
508                &[(1, self.font_id, Default::default())],
509            )
510            .width
511    }
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517    use crate::{
518        color::Color,
519        fonts::{Properties, Weight},
520    };
521
522    #[crate::test(self)]
523    fn test_wrap_line(cx: &mut crate::MutableAppContext) {
524        let font_cache = cx.font_cache().clone();
525        let font_system = cx.platform().fonts();
526        let family = font_cache.load_family(&["Courier"]).unwrap();
527        let font_id = font_cache.select_font(family, &Default::default()).unwrap();
528
529        let mut wrapper = LineWrapper::new(font_id, 16., font_system);
530        assert_eq!(
531            wrapper
532                .wrap_line("aa bbb cccc ddddd eeee", 72.0)
533                .collect::<Vec<_>>(),
534            &[
535                Boundary::new(7, 0),
536                Boundary::new(12, 0),
537                Boundary::new(18, 0)
538            ],
539        );
540        assert_eq!(
541            wrapper
542                .wrap_line("aaa aaaaaaaaaaaaaaaaaa", 72.0)
543                .collect::<Vec<_>>(),
544            &[
545                Boundary::new(4, 0),
546                Boundary::new(11, 0),
547                Boundary::new(18, 0)
548            ],
549        );
550        assert_eq!(
551            wrapper.wrap_line("     aaaaaaa", 72.).collect::<Vec<_>>(),
552            &[
553                Boundary::new(7, 5),
554                Boundary::new(9, 5),
555                Boundary::new(11, 5),
556            ]
557        );
558        assert_eq!(
559            wrapper
560                .wrap_line("                            ", 72.)
561                .collect::<Vec<_>>(),
562            &[
563                Boundary::new(7, 0),
564                Boundary::new(14, 0),
565                Boundary::new(21, 0)
566            ]
567        );
568        assert_eq!(
569            wrapper
570                .wrap_line("          aaaaaaaaaaaaaa", 72.)
571                .collect::<Vec<_>>(),
572            &[
573                Boundary::new(7, 0),
574                Boundary::new(14, 3),
575                Boundary::new(18, 3),
576                Boundary::new(22, 3),
577            ]
578        );
579    }
580
581    #[crate::test(self)]
582    fn test_wrap_shaped_line(cx: &mut crate::MutableAppContext) {
583        let font_cache = cx.font_cache().clone();
584        let font_system = cx.platform().fonts();
585        let text_layout_cache = TextLayoutCache::new(font_system.clone());
586
587        let family = font_cache.load_family(&["Helvetica"]).unwrap();
588        let font_id = font_cache.select_font(family, &Default::default()).unwrap();
589        let normal = font_cache.select_font(family, &Default::default()).unwrap();
590        let bold = font_cache
591            .select_font(
592                family,
593                &Properties {
594                    weight: Weight::BOLD,
595                    ..Default::default()
596                },
597            )
598            .unwrap();
599
600        let text = "aa bbb cccc ddddd eeee";
601        let line = text_layout_cache.layout_str(
602            text,
603            16.0,
604            &[
605                (4, normal, Color::default()),
606                (5, bold, Color::default()),
607                (6, normal, Color::default()),
608                (1, bold, Color::default()),
609                (7, normal, Color::default()),
610            ],
611        );
612
613        let mut wrapper = LineWrapper::new(font_id, 16., font_system);
614        assert_eq!(
615            wrapper
616                .wrap_shaped_line(&text, &line, 72.0)
617                .collect::<Vec<_>>(),
618            &[
619                ShapedBoundary {
620                    run_ix: 1,
621                    glyph_ix: 3
622                },
623                ShapedBoundary {
624                    run_ix: 2,
625                    glyph_ix: 3
626                },
627                ShapedBoundary {
628                    run_ix: 4,
629                    glyph_ix: 2
630                }
631            ],
632        );
633    }
634}