Skip to main content

gpui/text_system/
line_layout.rs

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