Skip to main content

gpui_core/text_system/
line_layout.rs

1use crate::{FontId, GlyphId, Pixels, PlatformTextSystem, Point, SharedString, Size, point, px};
2use collections::FxHashMap;
3use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
4use smallvec::SmallVec;
5use std::{
6    borrow::Borrow,
7    hash::{Hash, Hasher},
8    ops::Range,
9    sync::{
10        Arc,
11        atomic::{AtomicU64, Ordering},
12    },
13};
14
15use super::LineWrapper;
16
17/// A laid out and styled line of text
18#[derive(Default, Debug)]
19pub struct LineLayout {
20    /// The font size for this line
21    pub font_size: Pixels,
22    /// The width of the line
23    pub width: Pixels,
24    /// The ascent of the line
25    pub ascent: Pixels,
26    /// The descent of the line
27    pub descent: Pixels,
28    /// The shaped runs that make up this line
29    pub runs: Vec<ShapedRun>,
30    /// The length of the line in utf-8 bytes
31    pub len: usize,
32}
33
34/// A run of text that has been shaped .
35#[derive(Debug, Clone)]
36pub struct ShapedRun {
37    /// The font id for this run
38    pub font_id: FontId,
39    /// The glyphs that make up this run
40    pub glyphs: Vec<ShapedGlyph>,
41}
42
43/// A single glyph, ready to paint.
44#[derive(Clone, Debug)]
45pub struct ShapedGlyph {
46    /// The ID for this glyph, as determined by the text system.
47    pub id: GlyphId,
48
49    /// The position of this glyph in its containing line.
50    pub position: Point<Pixels>,
51
52    /// The index of this glyph in the original text.
53    pub index: usize,
54
55    /// Whether this glyph is an emoji
56    pub is_emoji: bool,
57}
58
59impl LineLayout {
60    /// The index for the character at the given x coordinate
61    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
62        if x >= self.width {
63            None
64        } else {
65            for run in self.runs.iter().rev() {
66                for glyph in run.glyphs.iter().rev() {
67                    if glyph.position.x <= x {
68                        return Some(glyph.index);
69                    }
70                }
71            }
72            Some(0)
73        }
74    }
75
76    /// closest_index_for_x returns the character boundary closest to the given x coordinate
77    /// (e.g. to handle aligning up/down arrow keys)
78    pub fn closest_index_for_x(&self, x: Pixels) -> usize {
79        let mut prev_index = 0;
80        let mut prev_x = px(0.);
81
82        for run in self.runs.iter() {
83            for glyph in run.glyphs.iter() {
84                if glyph.position.x >= x {
85                    if glyph.position.x - x < x - prev_x {
86                        return glyph.index;
87                    } else {
88                        return prev_index;
89                    }
90                }
91                prev_index = glyph.index;
92                prev_x = glyph.position.x;
93            }
94        }
95
96        if self.len == 1 {
97            if x > self.width / 2. {
98                return 1;
99            } else {
100                return 0;
101            }
102        }
103
104        self.len
105    }
106
107    /// The x position of the character at the given index
108    pub fn x_for_index(&self, index: usize) -> Pixels {
109        for run in &self.runs {
110            for glyph in &run.glyphs {
111                if glyph.index >= index {
112                    return glyph.position.x;
113                }
114            }
115        }
116        self.width
117    }
118
119    /// The corresponding Font at the given index
120    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
121        for run in &self.runs {
122            for glyph in &run.glyphs {
123                if glyph.index >= index {
124                    return Some(run.font_id);
125                }
126            }
127        }
128        None
129    }
130
131    /// Split this layout at a byte index, returning `(prefix, suffix)`.
132    ///
133    /// - `prefix` contains glyphs for bytes `[0, byte_index)` with original positions.
134    ///   Its width equals the x-advance up to the split point.
135    /// - `suffix` contains glyphs for bytes `[byte_index, len)` with positions
136    ///   shifted left so the first glyph starts at x=0, and byte indices rebased to 0.
137    /// - `font_size`, `ascent`, and `descent` are copied to both halves.
138    pub fn split_at(&self, byte_index: usize) -> (LineLayout, LineLayout) {
139        let x_offset = self.x_for_index(byte_index);
140
141        // Partition glyph runs. A single run may contribute glyphs to both halves.
142        let mut left_runs = Vec::new();
143        let mut right_runs = Vec::new();
144
145        for run in &self.runs {
146            let split_pos = run.glyphs.partition_point(|g| g.index < byte_index);
147
148            if split_pos > 0 {
149                left_runs.push(ShapedRun {
150                    font_id: run.font_id,
151                    glyphs: run.glyphs[..split_pos].to_vec(),
152                });
153            }
154
155            if split_pos < run.glyphs.len() {
156                let right_glyphs = run.glyphs[split_pos..]
157                    .iter()
158                    .map(|g| ShapedGlyph {
159                        id: g.id,
160                        position: point(g.position.x - x_offset, g.position.y),
161                        index: g.index - byte_index,
162                        is_emoji: g.is_emoji,
163                    })
164                    .collect();
165                right_runs.push(ShapedRun {
166                    font_id: run.font_id,
167                    glyphs: right_glyphs,
168                });
169            }
170        }
171
172        let left = LineLayout {
173            font_size: self.font_size,
174            width: x_offset,
175            ascent: self.ascent,
176            descent: self.descent,
177            runs: left_runs,
178            len: byte_index,
179        };
180
181        let right = LineLayout {
182            font_size: self.font_size,
183            width: self.width - x_offset,
184            ascent: self.ascent,
185            descent: self.descent,
186            runs: right_runs,
187            len: self.len - byte_index,
188        };
189
190        (left, right)
191    }
192
193    fn compute_wrap_boundaries(
194        &self,
195        text: &str,
196        wrap_width: Pixels,
197        max_lines: Option<usize>,
198    ) -> SmallVec<[WrapBoundary; 1]> {
199        let mut boundaries = SmallVec::new();
200        let mut first_non_whitespace_ix = None;
201        let mut last_candidate_ix = None;
202        let mut last_candidate_x = px(0.);
203        let mut last_boundary = WrapBoundary {
204            run_ix: 0,
205            glyph_ix: 0,
206        };
207        let mut last_boundary_x = px(0.);
208        let mut prev_ch = '\0';
209        let mut glyphs = self
210            .runs
211            .iter()
212            .enumerate()
213            .flat_map(move |(run_ix, run)| {
214                run.glyphs.iter().enumerate().map(move |(glyph_ix, glyph)| {
215                    let character = text[glyph.index..].chars().next().unwrap();
216                    (
217                        WrapBoundary { run_ix, glyph_ix },
218                        character,
219                        glyph.position.x,
220                    )
221                })
222            })
223            .peekable();
224
225        while let Some((boundary, ch, x)) = glyphs.next() {
226            if ch == '\n' {
227                continue;
228            }
229
230            // Here is very similar to `LineWrapper::wrap_line` to determine text wrapping,
231            // but there are some differences, so we have to duplicate the code here.
232            if LineWrapper::is_word_char(ch) {
233                if prev_ch == ' ' && ch != ' ' && first_non_whitespace_ix.is_some() {
234                    last_candidate_ix = Some(boundary);
235                    last_candidate_x = x;
236                }
237            } else {
238                if ch != ' ' && first_non_whitespace_ix.is_some() {
239                    last_candidate_ix = Some(boundary);
240                    last_candidate_x = x;
241                }
242            }
243
244            if ch != ' ' && first_non_whitespace_ix.is_none() {
245                first_non_whitespace_ix = Some(boundary);
246            }
247
248            let next_x = glyphs.peek().map_or(self.width, |(_, _, x)| *x);
249            let width = next_x - last_boundary_x;
250
251            if width > wrap_width && boundary > last_boundary {
252                // When used line_clamp, we should limit the number of lines.
253                if let Some(max_lines) = max_lines
254                    && boundaries.len() >= max_lines.saturating_sub(1)
255                {
256                    break;
257                }
258
259                if let Some(last_candidate_ix) = last_candidate_ix.take() {
260                    last_boundary = last_candidate_ix;
261                    last_boundary_x = last_candidate_x;
262                } else {
263                    last_boundary = boundary;
264                    last_boundary_x = x;
265                }
266                boundaries.push(last_boundary);
267            }
268            prev_ch = ch;
269        }
270
271        boundaries
272    }
273}
274
275/// A line of text that has been wrapped to fit a given width
276#[derive(Default, Debug)]
277pub struct WrappedLineLayout {
278    /// The line layout, pre-wrapping.
279    pub unwrapped_layout: Arc<LineLayout>,
280
281    /// The boundaries at which the line was wrapped
282    pub wrap_boundaries: SmallVec<[WrapBoundary; 1]>,
283
284    /// The width of the line, if it was wrapped
285    pub wrap_width: Option<Pixels>,
286}
287
288/// A boundary at which a line was wrapped
289#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
290pub struct WrapBoundary {
291    /// The index in the run just before the line was wrapped
292    pub run_ix: usize,
293    /// The index of the glyph just before the line was wrapped
294    pub glyph_ix: usize,
295}
296
297impl WrappedLineLayout {
298    /// The length of the underlying text, in utf8 bytes.
299    #[allow(clippy::len_without_is_empty)]
300    pub fn len(&self) -> usize {
301        self.unwrapped_layout.len
302    }
303
304    /// The width of this line, in pixels, whether or not it was wrapped.
305    pub fn width(&self) -> Pixels {
306        self.wrap_width
307            .unwrap_or(Pixels::MAX)
308            .min(self.unwrapped_layout.width)
309    }
310
311    /// The size of the whole wrapped text, for the given line_height.
312    /// can span multiple lines if there are multiple wrap boundaries.
313    pub fn size(&self, line_height: Pixels) -> Size<Pixels> {
314        Size {
315            width: self.width(),
316            height: line_height * (self.wrap_boundaries.len() + 1),
317        }
318    }
319
320    /// The ascent of a line in this layout
321    pub fn ascent(&self) -> Pixels {
322        self.unwrapped_layout.ascent
323    }
324
325    /// The descent of a line in this layout
326    pub fn descent(&self) -> Pixels {
327        self.unwrapped_layout.descent
328    }
329
330    /// The wrap boundaries in this layout
331    pub fn wrap_boundaries(&self) -> &[WrapBoundary] {
332        &self.wrap_boundaries
333    }
334
335    /// The font size of this layout
336    pub fn font_size(&self) -> Pixels {
337        self.unwrapped_layout.font_size
338    }
339
340    /// The runs in this layout, sans wrapping
341    pub fn runs(&self) -> &[ShapedRun] {
342        &self.unwrapped_layout.runs
343    }
344
345    /// The index corresponding to a given position in this layout for the given line height.
346    ///
347    /// See also [`Self::closest_index_for_position`].
348    pub fn index_for_position(
349        &self,
350        position: Point<Pixels>,
351        line_height: Pixels,
352    ) -> Result<usize, usize> {
353        self._index_for_position(position, line_height, false)
354    }
355
356    /// The closest index to a given position in this layout for the given line height.
357    ///
358    /// Closest means the character boundary closest to the given position.
359    ///
360    /// See also [`LineLayout::closest_index_for_x`].
361    pub fn closest_index_for_position(
362        &self,
363        position: Point<Pixels>,
364        line_height: Pixels,
365    ) -> Result<usize, usize> {
366        self._index_for_position(position, line_height, true)
367    }
368
369    fn _index_for_position(
370        &self,
371        mut position: Point<Pixels>,
372        line_height: Pixels,
373        closest: bool,
374    ) -> Result<usize, usize> {
375        let wrapped_line_ix = (position.y / line_height) as usize;
376
377        let wrapped_line_start_index;
378        let wrapped_line_start_x;
379        if wrapped_line_ix > 0 {
380            let Some(line_start_boundary) = self.wrap_boundaries.get(wrapped_line_ix - 1) else {
381                return Err(0);
382            };
383            let run = &self.unwrapped_layout.runs[line_start_boundary.run_ix];
384            let glyph = &run.glyphs[line_start_boundary.glyph_ix];
385            wrapped_line_start_index = glyph.index;
386            wrapped_line_start_x = glyph.position.x;
387        } else {
388            wrapped_line_start_index = 0;
389            wrapped_line_start_x = Pixels::ZERO;
390        };
391
392        let wrapped_line_end_index;
393        let wrapped_line_end_x;
394        if wrapped_line_ix < self.wrap_boundaries.len() {
395            let next_wrap_boundary_ix = wrapped_line_ix;
396            let next_wrap_boundary = self.wrap_boundaries[next_wrap_boundary_ix];
397            let run = &self.unwrapped_layout.runs[next_wrap_boundary.run_ix];
398            let glyph = &run.glyphs[next_wrap_boundary.glyph_ix];
399            wrapped_line_end_index = glyph.index;
400            wrapped_line_end_x = glyph.position.x;
401        } else {
402            wrapped_line_end_index = self.unwrapped_layout.len;
403            wrapped_line_end_x = self.unwrapped_layout.width;
404        };
405
406        let mut position_in_unwrapped_line = position;
407        position_in_unwrapped_line.x += wrapped_line_start_x;
408        if position_in_unwrapped_line.x < wrapped_line_start_x {
409            Err(wrapped_line_start_index)
410        } else if position_in_unwrapped_line.x >= wrapped_line_end_x {
411            Err(wrapped_line_end_index)
412        } else {
413            if closest {
414                Ok(self
415                    .unwrapped_layout
416                    .closest_index_for_x(position_in_unwrapped_line.x))
417            } else {
418                Ok(self
419                    .unwrapped_layout
420                    .index_for_x(position_in_unwrapped_line.x)
421                    .unwrap())
422            }
423        }
424    }
425
426    /// Returns the pixel position for the given byte index.
427    pub fn position_for_index(&self, index: usize, line_height: Pixels) -> Option<Point<Pixels>> {
428        let mut line_start_ix = 0;
429        let mut line_end_indices = self
430            .wrap_boundaries
431            .iter()
432            .map(|wrap_boundary| {
433                let run = &self.unwrapped_layout.runs[wrap_boundary.run_ix];
434                let glyph = &run.glyphs[wrap_boundary.glyph_ix];
435                glyph.index
436            })
437            .chain([self.len()])
438            .enumerate();
439        for (ix, line_end_ix) in line_end_indices {
440            let line_y = ix as f32 * line_height;
441            if index < line_start_ix {
442                break;
443            } else if index > line_end_ix {
444                line_start_ix = line_end_ix;
445                continue;
446            } else {
447                let line_start_x = self.unwrapped_layout.x_for_index(line_start_ix);
448                let x = self.unwrapped_layout.x_for_index(index) - line_start_x;
449                return Some(point(x, line_y));
450            }
451        }
452
453        None
454    }
455}
456
457struct GlobalCacheEntry<T> {
458    value: T,
459    last_access: AtomicU64,
460}
461
462pub(crate) struct GlobalLineLayoutCache {
463    max_entries: usize,
464    low_watermark: usize,
465    lines: RwLock<FxHashMap<Arc<CacheKey>, GlobalCacheEntry<Arc<LineLayout>>>>,
466    wrapped_lines: RwLock<FxHashMap<Arc<CacheKey>, GlobalCacheEntry<Arc<WrappedLineLayout>>>>,
467    access_counter: AtomicU64,
468}
469
470impl GlobalLineLayoutCache {
471    pub fn new(max_entries: usize, low_watermark: usize) -> Self {
472        let max_entries = max_entries.max(1);
473        // Ensure low_watermark is always less than max_entries to avoid
474        // degenerate eviction behaviour.
475        let low_watermark = low_watermark.min(max_entries.saturating_sub(1));
476        Self {
477            max_entries,
478            low_watermark,
479            lines: RwLock::new(FxHashMap::default()),
480            wrapped_lines: RwLock::new(FxHashMap::default()),
481            access_counter: AtomicU64::new(0),
482        }
483    }
484
485    #[cfg(test)]
486    pub(crate) fn budget_for_test(&self) -> (usize, usize) {
487        (self.max_entries, self.low_watermark)
488    }
489
490    /// Drop every cached line and wrapped-line layout.
491    ///
492    /// Useful when an application enters a low-memory state (for example, the
493    /// last visible window is hidden) and wants to release the heap held by
494    /// shaped text. The cache will repopulate naturally as text is laid out
495    /// again.
496    pub fn clear(&self) {
497        self.lines.write().clear();
498        self.wrapped_lines.write().clear();
499    }
500
501    /// Returns `(line_entries, wrapped_line_entries)` for diagnostics.
502    pub fn entry_counts(&self) -> (usize, usize) {
503        (self.lines.read().len(), self.wrapped_lines.read().len())
504    }
505
506    fn get_line(&self, key: &dyn AsCacheKeyRef) -> Option<Arc<LineLayout>> {
507        let lines = self.lines.read();
508        if let Some(entry) = lines.get(key) {
509            // Relaxed is fine — this is just for approximate LRU ordering
510            entry.last_access.store(
511                self.access_counter.fetch_add(1, Ordering::Relaxed),
512                Ordering::Relaxed,
513            );
514            Some(entry.value.clone())
515        } else {
516            None
517        }
518    }
519
520    fn insert_line(&self, key: Arc<CacheKey>, layout: Arc<LineLayout>) {
521        let mut lines = self.lines.write();
522        if lines.len() >= self.max_entries {
523            Self::evict_to_watermark(&mut lines, self.low_watermark);
524        }
525        lines.insert(
526            key,
527            GlobalCacheEntry {
528                value: layout,
529                last_access: AtomicU64::new(self.access_counter.fetch_add(1, Ordering::Relaxed)),
530            },
531        );
532    }
533
534    fn get_wrapped_line(&self, key: &dyn AsCacheKeyRef) -> Option<Arc<WrappedLineLayout>> {
535        let wrapped = self.wrapped_lines.read();
536        if let Some(entry) = wrapped.get(key) {
537            entry.last_access.store(
538                self.access_counter.fetch_add(1, Ordering::Relaxed),
539                Ordering::Relaxed,
540            );
541            Some(entry.value.clone())
542        } else {
543            None
544        }
545    }
546
547    fn insert_wrapped_line(&self, key: Arc<CacheKey>, layout: Arc<WrappedLineLayout>) {
548        let mut wrapped = self.wrapped_lines.write();
549        if wrapped.len() >= self.max_entries {
550            Self::evict_to_watermark(&mut wrapped, self.low_watermark);
551        }
552        wrapped.insert(
553            key,
554            GlobalCacheEntry {
555                value: layout,
556                last_access: AtomicU64::new(self.access_counter.fetch_add(1, Ordering::Relaxed)),
557            },
558        );
559    }
560
561    /// Evict oldest entries until the map size is at or below `target_size`.
562    fn evict_to_watermark<V>(
563        map: &mut FxHashMap<Arc<CacheKey>, GlobalCacheEntry<V>>,
564        target_size: usize,
565    ) {
566        if map.len() <= target_size {
567            return;
568        }
569        let to_remove = map.len() - target_size;
570        let mut entries: Vec<_> = map
571            .iter()
572            .map(|(k, entry)| (k.clone(), entry.last_access.load(Ordering::Relaxed)))
573            .collect();
574        entries.sort_by_key(|(_, access)| *access);
575        for (key, _) in entries.into_iter().take(to_remove) {
576            map.remove(&key);
577        }
578    }
579}
580
581pub(crate) struct LineLayoutCache {
582    previous_frame: Mutex<FrameCache>,
583    current_frame: RwLock<FrameCache>,
584    platform_text_system: Arc<dyn PlatformTextSystem>,
585    global_cache: Arc<GlobalLineLayoutCache>,
586}
587
588#[derive(Default)]
589struct FrameCache {
590    lines: FxHashMap<Arc<CacheKey>, Arc<LineLayout>>,
591    wrapped_lines: FxHashMap<Arc<CacheKey>, Arc<WrappedLineLayout>>,
592    used_lines: Vec<Arc<CacheKey>>,
593    used_wrapped_lines: Vec<Arc<CacheKey>>,
594}
595
596#[derive(Clone, Default)]
597pub(crate) struct LineLayoutIndex {
598    lines_index: usize,
599    wrapped_lines_index: usize,
600}
601
602impl LineLayoutCache {
603    pub fn new(
604        platform_text_system: Arc<dyn PlatformTextSystem>,
605        global_cache: Arc<GlobalLineLayoutCache>,
606    ) -> Self {
607        Self {
608            previous_frame: Mutex::default(),
609            current_frame: RwLock::default(),
610            platform_text_system,
611            global_cache,
612        }
613    }
614
615    pub fn layout_index(&self) -> LineLayoutIndex {
616        let frame = self.current_frame.read();
617        LineLayoutIndex {
618            lines_index: frame.used_lines.len(),
619            wrapped_lines_index: frame.used_wrapped_lines.len(),
620        }
621    }
622
623    pub fn reuse_layouts(&self, range: Range<LineLayoutIndex>) {
624        let mut previous_frame = &mut *self.previous_frame.lock();
625        let mut current_frame = &mut *self.current_frame.write();
626
627        for key in &previous_frame.used_lines[range.start.lines_index..range.end.lines_index] {
628            if let Some((key, line)) = previous_frame.lines.remove_entry(key) {
629                current_frame.lines.insert(key, line);
630            }
631            current_frame.used_lines.push(key.clone());
632        }
633
634        for key in &previous_frame.used_wrapped_lines
635            [range.start.wrapped_lines_index..range.end.wrapped_lines_index]
636        {
637            if let Some((key, line)) = previous_frame.wrapped_lines.remove_entry(key) {
638                current_frame.wrapped_lines.insert(key, line);
639            }
640            current_frame.used_wrapped_lines.push(key.clone());
641        }
642    }
643
644    pub fn truncate_layouts(&self, index: LineLayoutIndex) {
645        let mut current_frame = &mut *self.current_frame.write();
646        current_frame.used_lines.truncate(index.lines_index);
647        current_frame
648            .used_wrapped_lines
649            .truncate(index.wrapped_lines_index);
650    }
651
652    pub fn finish_frame(&self) {
653        let mut prev_frame = self.previous_frame.lock();
654        let mut curr_frame = self.current_frame.write();
655        std::mem::swap(&mut *prev_frame, &mut *curr_frame);
656        curr_frame.lines.clear();
657        curr_frame.wrapped_lines.clear();
658        curr_frame.used_lines.clear();
659        curr_frame.used_wrapped_lines.clear();
660    }
661
662    pub fn layout_wrapped_line<Text>(
663        &self,
664        text: Text,
665        font_size: Pixels,
666        runs: &[FontRun],
667        wrap_width: Option<Pixels>,
668        max_lines: Option<usize>,
669    ) -> Arc<WrappedLineLayout>
670    where
671        Text: AsRef<str>,
672        SharedString: From<Text>,
673    {
674        let key = &CacheKeyRef {
675            text: text.as_ref(),
676            font_size,
677            runs,
678            wrap_width,
679            force_width: None,
680            letter_spacing: None,
681        } as &dyn AsCacheKeyRef;
682
683        let current_frame = self.current_frame.upgradable_read();
684        if let Some(layout) = current_frame.wrapped_lines.get(key) {
685            return layout.clone();
686        }
687
688        let previous_frame_entry = self.previous_frame.lock().wrapped_lines.remove_entry(key);
689        if let Some((key, layout)) = previous_frame_entry {
690            let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
691            current_frame
692                .wrapped_lines
693                .insert(key.clone(), layout.clone());
694            current_frame.used_wrapped_lines.push(key);
695            layout
696        } else {
697            // Check global cross-window cache
698            if let Some(layout) = self.global_cache.get_wrapped_line(key) {
699                let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
700                let key = Arc::new(CacheKey {
701                    text: SharedString::from(text),
702                    font_size,
703                    runs: SmallVec::from(runs),
704                    wrap_width,
705                    force_width: None,
706                    letter_spacing: None,
707                });
708                current_frame
709                    .wrapped_lines
710                    .insert(key.clone(), layout.clone());
711                current_frame.used_wrapped_lines.push(key);
712                return layout;
713            }
714
715            drop(current_frame);
716            let text = SharedString::from(text);
717            let unwrapped_layout = self.layout_line::<&SharedString>(&text, font_size, runs, None);
718            let wrap_boundaries = if let Some(wrap_width) = wrap_width {
719                unwrapped_layout.compute_wrap_boundaries(text.as_ref(), wrap_width, max_lines)
720            } else {
721                SmallVec::new()
722            };
723            let layout = Arc::new(WrappedLineLayout {
724                unwrapped_layout,
725                wrap_boundaries,
726                wrap_width,
727            });
728            let key = Arc::new(CacheKey {
729                text,
730                font_size,
731                runs: SmallVec::from(runs),
732                wrap_width,
733                force_width: None,
734                letter_spacing: None,
735            });
736
737            let mut current_frame = self.current_frame.write();
738            current_frame
739                .wrapped_lines
740                .insert(key.clone(), layout.clone());
741            current_frame.used_wrapped_lines.push(key.clone());
742            self.global_cache.insert_wrapped_line(key, layout.clone());
743
744            layout
745        }
746    }
747
748    pub fn layout_line<Text>(
749        &self,
750        text: Text,
751        font_size: Pixels,
752        runs: &[FontRun],
753        force_width: Option<Pixels>,
754    ) -> Arc<LineLayout>
755    where
756        Text: AsRef<str>,
757        SharedString: From<Text>,
758    {
759        self.layout_line_with_spacing(text, font_size, runs, force_width, None)
760    }
761
762    pub fn layout_line_with_spacing<Text>(
763        &self,
764        text: Text,
765        font_size: Pixels,
766        runs: &[FontRun],
767        force_width: Option<Pixels>,
768        letter_spacing: Option<Pixels>,
769    ) -> Arc<LineLayout>
770    where
771        Text: AsRef<str>,
772        SharedString: From<Text>,
773    {
774        let key = &CacheKeyRef {
775            text: text.as_ref(),
776            font_size,
777            runs,
778            wrap_width: None,
779            force_width,
780            letter_spacing,
781        } as &dyn AsCacheKeyRef;
782
783        let current_frame = self.current_frame.upgradable_read();
784        if let Some(layout) = current_frame.lines.get(key) {
785            return layout.clone();
786        }
787
788        let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
789        if let Some((key, layout)) = self.previous_frame.lock().lines.remove_entry(key) {
790            current_frame.lines.insert(key.clone(), layout.clone());
791            current_frame.used_lines.push(key);
792            return layout;
793        }
794
795        // Check global cross-window cache
796        if let Some(layout) = self.global_cache.get_line(key) {
797            let key = Arc::new(CacheKey {
798                text: SharedString::from(text),
799                font_size,
800                runs: SmallVec::from(runs),
801                wrap_width: None,
802                force_width,
803                letter_spacing,
804            });
805            current_frame.lines.insert(key.clone(), layout.clone());
806            current_frame.used_lines.push(key);
807            return layout;
808        }
809
810        let text = SharedString::from(text);
811        let mut layout = self
812            .platform_text_system
813            .layout_line(&text, font_size, runs);
814
815        if let Some(force_width) = force_width {
816            apply_force_width_to_layout(&mut layout, force_width);
817        }
818
819        if let Some(spacing) = letter_spacing {
820            apply_letter_spacing_to_layout(&mut layout, spacing, force_width);
821        }
822
823        let key = Arc::new(CacheKey {
824            text,
825            font_size,
826            runs: SmallVec::from(runs),
827            wrap_width: None,
828            force_width,
829            letter_spacing,
830        });
831        let layout = Arc::new(layout);
832        current_frame.lines.insert(key.clone(), layout.clone());
833        current_frame.used_lines.push(key.clone());
834        self.global_cache.insert_line(key, layout.clone());
835        layout
836    }
837}
838
839// Combining marks are shaped at the same x position as their base character.
840// Forced monospace layout must keep them anchored instead of advancing a cell.
841fn apply_force_width_to_layout(layout: &mut LineLayout, force_width: Pixels) {
842    let mut glyph_pos: usize = 0;
843    let mut last_base_shaped_x = px(f32::NEG_INFINITY);
844    let mut last_base_actual_x = px(0.);
845
846    for run in layout.runs.iter_mut() {
847        for glyph in run.glyphs.iter_mut() {
848            let shaped_x = glyph.position.x;
849
850            if shaped_x > last_base_shaped_x + force_width * 0.5 {
851                let forced_x = glyph_pos * force_width;
852                if (shaped_x - forced_x).abs() > px(1.) {
853                    glyph.position.x = forced_x;
854                }
855                last_base_shaped_x = shaped_x;
856                last_base_actual_x = glyph.position.x;
857                glyph_pos += 1;
858            } else {
859                glyph.position.x = last_base_actual_x + (shaped_x - last_base_shaped_x);
860            }
861        }
862    }
863}
864
865fn apply_letter_spacing_to_layout(
866    layout: &mut LineLayout,
867    spacing: Pixels,
868    force_width: Option<Pixels>,
869) {
870    let glyph_count = if let Some(force_width) = force_width {
871        let mut base_glyph_count: usize = 0;
872        let mut last_base_x = px(f32::NEG_INFINITY);
873        let mut last_base_spacing = px(0.);
874
875        for run in layout.runs.iter_mut() {
876            for glyph in run.glyphs.iter_mut() {
877                let x = glyph.position.x;
878
879                if x > last_base_x + force_width * 0.5 {
880                    last_base_spacing = spacing * base_glyph_count as f32;
881                    glyph.position.x = x + last_base_spacing;
882                    last_base_x = x;
883                    base_glyph_count += 1;
884                } else {
885                    glyph.position.x = x + last_base_spacing;
886                }
887            }
888        }
889
890        base_glyph_count
891    } else {
892        let mut glyph_count: usize = 0;
893        for run in layout.runs.iter_mut() {
894            for glyph in run.glyphs.iter_mut() {
895                glyph.position.x = glyph.position.x + spacing * glyph_count as f32;
896                glyph_count += 1;
897            }
898        }
899
900        glyph_count
901    };
902
903    if glyph_count > 1 {
904        layout.width = layout.width + spacing * (glyph_count - 1) as f32;
905    }
906}
907
908/// A run of text with a single font.
909#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
910#[allow(missing_docs)]
911pub struct FontRun {
912    pub len: usize,
913    pub font_id: FontId,
914}
915
916trait AsCacheKeyRef {
917    fn as_cache_key_ref(&self) -> CacheKeyRef<'_>;
918}
919
920#[derive(Clone, Debug, Eq)]
921struct CacheKey {
922    text: SharedString,
923    font_size: Pixels,
924    runs: SmallVec<[FontRun; 1]>,
925    wrap_width: Option<Pixels>,
926    force_width: Option<Pixels>,
927    letter_spacing: Option<Pixels>,
928}
929
930#[derive(Copy, Clone, PartialEq, Eq, Hash)]
931struct CacheKeyRef<'a> {
932    text: &'a str,
933    font_size: Pixels,
934    runs: &'a [FontRun],
935    wrap_width: Option<Pixels>,
936    force_width: Option<Pixels>,
937    letter_spacing: Option<Pixels>,
938}
939
940impl PartialEq for dyn AsCacheKeyRef + '_ {
941    fn eq(&self, other: &dyn AsCacheKeyRef) -> bool {
942        self.as_cache_key_ref() == other.as_cache_key_ref()
943    }
944}
945
946impl Eq for dyn AsCacheKeyRef + '_ {}
947
948impl Hash for dyn AsCacheKeyRef + '_ {
949    fn hash<H: Hasher>(&self, state: &mut H) {
950        self.as_cache_key_ref().hash(state)
951    }
952}
953
954impl AsCacheKeyRef for CacheKey {
955    fn as_cache_key_ref(&self) -> CacheKeyRef<'_> {
956        CacheKeyRef {
957            text: &self.text,
958            font_size: self.font_size,
959            runs: self.runs.as_slice(),
960            wrap_width: self.wrap_width,
961            force_width: self.force_width,
962            letter_spacing: self.letter_spacing,
963        }
964    }
965}
966
967impl PartialEq for CacheKey {
968    fn eq(&self, other: &Self) -> bool {
969        self.as_cache_key_ref().eq(&other.as_cache_key_ref())
970    }
971}
972
973impl Hash for CacheKey {
974    fn hash<H: Hasher>(&self, state: &mut H) {
975        self.as_cache_key_ref().hash(state);
976    }
977}
978
979impl<'a> Borrow<dyn AsCacheKeyRef + 'a> for Arc<CacheKey> {
980    fn borrow(&self) -> &(dyn AsCacheKeyRef + 'a) {
981        self.as_ref() as &dyn AsCacheKeyRef
982    }
983}
984
985impl AsCacheKeyRef for CacheKeyRef<'_> {
986    fn as_cache_key_ref(&self) -> CacheKeyRef<'_> {
987        *self
988    }
989}
990
991#[cfg(test)]
992mod tests {
993    use super::*;
994    use crate::GlyphId;
995
996    fn glyph_at(x: f32, index: usize) -> ShapedGlyph {
997        ShapedGlyph {
998            id: GlyphId(0),
999            position: point(px(x), px(0.)),
1000            index,
1001            is_emoji: false,
1002        }
1003    }
1004
1005    fn make_layout(glyphs: Vec<ShapedGlyph>) -> LineLayout {
1006        LineLayout {
1007            font_size: px(16.),
1008            width: px(100.),
1009            ascent: px(12.),
1010            descent: px(4.),
1011            runs: vec![ShapedRun {
1012                font_id: FontId(0),
1013                glyphs,
1014            }],
1015            len: 0,
1016        }
1017    }
1018
1019    fn glyph_x_positions(layout: &LineLayout) -> Vec<f32> {
1020        layout.runs[0]
1021            .glyphs
1022            .iter()
1023            .map(|glyph| f32::from(glyph.position.x))
1024            .collect()
1025    }
1026
1027    fn make_global_cache_key(text: &str) -> Arc<CacheKey> {
1028        Arc::new(CacheKey {
1029            text: SharedString::from(text.to_owned()),
1030            font_size: px(16.),
1031            runs: SmallVec::new(),
1032            wrap_width: None,
1033            force_width: None,
1034            letter_spacing: None,
1035        })
1036    }
1037
1038    #[test]
1039    fn test_global_layout_cache_clear_drops_all_entries() {
1040        let cache = GlobalLineLayoutCache::new(64, 32);
1041        let layout = Arc::new(make_layout(vec![glyph_at(0., 0)]));
1042        cache.insert_line(make_global_cache_key("hello"), layout.clone());
1043        cache.insert_line(make_global_cache_key("world"), layout);
1044
1045        assert_eq!(cache.entry_counts(), (2, 0));
1046
1047        cache.clear();
1048
1049        assert_eq!(cache.entry_counts(), (0, 0));
1050    }
1051
1052    #[test]
1053    fn test_split_at_partitions_glyphs_and_rebases_suffix() {
1054        let layout = LineLayout {
1055            font_size: px(16.),
1056            width: px(30.),
1057            ascent: px(12.),
1058            descent: px(4.),
1059            runs: vec![ShapedRun {
1060                font_id: FontId(0),
1061                glyphs: vec![glyph_at(0., 0), glyph_at(10., 1), glyph_at(20., 2)],
1062            }],
1063            len: 3,
1064        };
1065
1066        let (left, right) = layout.split_at(1);
1067
1068        assert_eq!(left.len, 1);
1069        assert_eq!(left.width, px(10.));
1070        assert_eq!(left.font_size, layout.font_size);
1071        assert_eq!(left.ascent, layout.ascent);
1072        assert_eq!(left.descent, layout.descent);
1073        assert_eq!(glyph_x_positions(&left), vec![0.]);
1074        assert_eq!(left.runs[0].glyphs[0].index, 0);
1075
1076        assert_eq!(right.len, 2);
1077        assert_eq!(right.width, px(20.));
1078        assert_eq!(glyph_x_positions(&right), vec![0., 10.]);
1079        assert_eq!(
1080            right.runs[0]
1081                .glyphs
1082                .iter()
1083                .map(|glyph| glyph.index)
1084                .collect::<Vec<_>>(),
1085            vec![0, 1]
1086        );
1087    }
1088
1089    #[test]
1090    fn test_split_at_mid_run_and_empty_sides() {
1091        let layout = LineLayout {
1092            font_size: px(16.),
1093            width: px(20.),
1094            ascent: px(12.),
1095            descent: px(4.),
1096            runs: vec![
1097                ShapedRun {
1098                    font_id: FontId(0),
1099                    glyphs: vec![glyph_at(0., 0), glyph_at(8., 1)],
1100                },
1101                ShapedRun {
1102                    font_id: FontId(1),
1103                    glyphs: vec![glyph_at(16., 2)],
1104                },
1105            ],
1106            len: 3,
1107        };
1108
1109        let (left, right) = layout.split_at(2);
1110        assert_eq!(left.runs.len(), 1);
1111        assert_eq!(left.runs[0].glyphs.len(), 2);
1112        assert_eq!(right.runs.len(), 1);
1113        assert_eq!(right.runs[0].font_id, FontId(1));
1114        assert_eq!(glyph_x_positions(&right), vec![0.]);
1115
1116        let (empty_left, all_right) = layout.split_at(0);
1117        assert!(empty_left.runs.is_empty());
1118        assert_eq!(empty_left.width, px(0.));
1119        assert_eq!(all_right.len, 3);
1120        assert_eq!(all_right.runs.len(), 2);
1121
1122        let (all_left, empty_right) = layout.split_at(3);
1123        assert_eq!(all_left.runs.len(), 2);
1124        assert!(empty_right.runs.is_empty());
1125        assert_eq!(empty_right.width, px(0.));
1126    }
1127
1128    #[test]
1129    fn test_force_width_latin_unchanged() {
1130        let cell_width = px(8.);
1131        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(8., 1), glyph_at(16., 2)]);
1132
1133        apply_force_width_to_layout(&mut layout, cell_width);
1134
1135        assert_eq!(glyph_x_positions(&layout), vec![0., 8., 16.]);
1136    }
1137
1138    #[test]
1139    fn test_force_width_combining_marks_not_advanced() {
1140        let cell_width = px(8.);
1141        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(0., 3)]);
1142
1143        apply_force_width_to_layout(&mut layout, cell_width);
1144
1145        assert_eq!(glyph_x_positions(&layout), vec![0., 0.]);
1146    }
1147
1148    #[test]
1149    fn test_force_width_base_after_combining_mark() {
1150        let cell_width = px(8.);
1151        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(0., 3), glyph_at(8., 6)]);
1152
1153        apply_force_width_to_layout(&mut layout, cell_width);
1154
1155        assert_eq!(glyph_x_positions(&layout), vec![0., 0., 8.]);
1156    }
1157
1158    #[test]
1159    fn test_force_width_multiple_combining_marks() {
1160        let cell_width = px(8.);
1161        let mut layout = make_layout(vec![
1162            glyph_at(0., 0),
1163            glyph_at(0., 3),
1164            glyph_at(0., 6),
1165            glyph_at(8., 9),
1166        ]);
1167
1168        apply_force_width_to_layout(&mut layout, cell_width);
1169
1170        assert_eq!(glyph_x_positions(&layout), vec![0., 0., 0., 8.]);
1171    }
1172
1173    #[test]
1174    fn test_force_width_corrects_drifted_base_positions() {
1175        let cell_width = px(8.);
1176        let mut layout = make_layout(vec![glyph_at(0.5, 0), glyph_at(10.2, 1), glyph_at(19.8, 2)]);
1177
1178        apply_force_width_to_layout(&mut layout, cell_width);
1179
1180        assert_eq!(glyph_x_positions(&layout), vec![0.5, 8., 16.]);
1181    }
1182
1183    #[test]
1184    fn test_force_width_combining_mark_after_within_tolerance_base() {
1185        let cell_width = px(8.);
1186        let mut layout = make_layout(vec![glyph_at(0.5, 0), glyph_at(0.5, 3)]);
1187
1188        apply_force_width_to_layout(&mut layout, cell_width);
1189
1190        assert_eq!(glyph_x_positions(&layout), vec![0.5, 0.5]);
1191    }
1192
1193    #[test]
1194    fn test_force_width_with_letter_spacing_keeps_combining_marks_anchored() {
1195        let cell_width = px(8.);
1196        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(0., 3), glyph_at(8., 6)]);
1197
1198        apply_force_width_to_layout(&mut layout, cell_width);
1199        apply_letter_spacing_to_layout(&mut layout, px(1.), Some(cell_width));
1200
1201        assert_eq!(glyph_x_positions(&layout), vec![0., 0., 9.]);
1202        assert_eq!(layout.width, px(101.));
1203    }
1204}