Skip to main content

gpui/text_system/
line_layout.rs

1// Modified by Longbridge for gpui-fast.
2use crate::{FontId, GlyphId, Pixels, PlatformTextSystem, Point, SharedString, Size, point, px};
3use collections::FxHashMap;
4use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
5use smallvec::SmallVec;
6use std::{
7    borrow::Borrow,
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    ) -> SmallVec<[WrapBoundary; 1]> {
200        let mut boundaries = SmallVec::new();
201        let mut first_non_whitespace_ix = None;
202        let mut last_candidate_ix = None;
203        let mut last_candidate_x = px(0.);
204        let mut last_boundary = WrapBoundary {
205            run_ix: 0,
206            glyph_ix: 0,
207        };
208        let mut last_boundary_x = px(0.);
209        let mut prev_ch = '\0';
210        let mut glyphs = self
211            .runs
212            .iter()
213            .enumerate()
214            .flat_map(move |(run_ix, run)| {
215                run.glyphs.iter().enumerate().map(move |(glyph_ix, glyph)| {
216                    let character = text[glyph.index..].chars().next().unwrap();
217                    (
218                        WrapBoundary { run_ix, glyph_ix },
219                        character,
220                        glyph.position.x,
221                    )
222                })
223            })
224            .peekable();
225
226        while let Some((boundary, ch, x)) = glyphs.next() {
227            if ch == '\n' {
228                continue;
229            }
230
231            // Here is very similar to `LineWrapper::wrap_line` to determine text wrapping,
232            // but there are some differences, so we have to duplicate the code here.
233            if LineWrapper::is_word_char(ch) {
234                if prev_ch == ' ' && ch != ' ' && first_non_whitespace_ix.is_some() {
235                    last_candidate_ix = Some(boundary);
236                    last_candidate_x = x;
237                }
238            } else {
239                if ch != ' ' && first_non_whitespace_ix.is_some() {
240                    last_candidate_ix = Some(boundary);
241                    last_candidate_x = x;
242                }
243            }
244
245            if ch != ' ' && first_non_whitespace_ix.is_none() {
246                first_non_whitespace_ix = Some(boundary);
247            }
248
249            let next_x = glyphs.peek().map_or(self.width, |(_, _, x)| *x);
250            let width = next_x - last_boundary_x;
251
252            if width > wrap_width && boundary > last_boundary {
253                // When used line_clamp, we should limit the number of lines.
254                if let Some(max_lines) = max_lines
255                    && boundaries.len() >= max_lines.saturating_sub(1)
256                {
257                    break;
258                }
259
260                if let Some(last_candidate_ix) = last_candidate_ix.take() {
261                    last_boundary = last_candidate_ix;
262                    last_boundary_x = last_candidate_x;
263                } else {
264                    last_boundary = boundary;
265                    last_boundary_x = x;
266                }
267                boundaries.push(last_boundary);
268            }
269            prev_ch = ch;
270        }
271
272        boundaries
273    }
274}
275
276/// A line of text that has been wrapped to fit a given width
277#[derive(Default, Debug)]
278pub struct WrappedLineLayout {
279    /// The line layout, pre-wrapping.
280    pub unwrapped_layout: Arc<LineLayout>,
281
282    /// The boundaries at which the line was wrapped
283    pub wrap_boundaries: SmallVec<[WrapBoundary; 1]>,
284
285    /// The width of the line, if it was wrapped
286    pub wrap_width: Option<Pixels>,
287}
288
289/// A boundary at which a line was wrapped
290#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
291pub struct WrapBoundary {
292    /// The index in the run just before the line was wrapped
293    pub run_ix: usize,
294    /// The index of the glyph just before the line was wrapped
295    pub glyph_ix: usize,
296}
297
298impl WrappedLineLayout {
299    /// The length of the underlying text, in utf8 bytes.
300    #[allow(clippy::len_without_is_empty)]
301    pub fn len(&self) -> usize {
302        self.unwrapped_layout.len
303    }
304
305    /// The width of this line, in pixels, whether or not it was wrapped.
306    pub fn width(&self) -> Pixels {
307        self.wrap_width
308            .unwrap_or(Pixels::MAX)
309            .min(self.unwrapped_layout.width)
310    }
311
312    /// The size of the whole wrapped text, for the given line_height.
313    /// can span multiple lines if there are multiple wrap boundaries.
314    pub fn size(&self, line_height: Pixels) -> Size<Pixels> {
315        Size {
316            width: self.width(),
317            height: line_height * (self.wrap_boundaries.len() + 1),
318        }
319    }
320
321    /// The ascent of a line in this layout
322    pub fn ascent(&self) -> Pixels {
323        self.unwrapped_layout.ascent
324    }
325
326    /// The descent of a line in this layout
327    pub fn descent(&self) -> Pixels {
328        self.unwrapped_layout.descent
329    }
330
331    /// The wrap boundaries in this layout
332    pub fn wrap_boundaries(&self) -> &[WrapBoundary] {
333        &self.wrap_boundaries
334    }
335
336    /// The font size of this layout
337    pub fn font_size(&self) -> Pixels {
338        self.unwrapped_layout.font_size
339    }
340
341    /// The runs in this layout, sans wrapping
342    pub fn runs(&self) -> &[ShapedRun] {
343        &self.unwrapped_layout.runs
344    }
345
346    /// The index corresponding to a given position in this layout for the given line height.
347    ///
348    /// See also [`Self::closest_index_for_position`].
349    pub fn index_for_position(
350        &self,
351        position: Point<Pixels>,
352        line_height: Pixels,
353    ) -> Result<usize, usize> {
354        self._index_for_position(position, line_height, false)
355    }
356
357    /// The closest index to a given position in this layout for the given line height.
358    ///
359    /// Closest means the character boundary closest to the given position.
360    ///
361    /// See also [`LineLayout::closest_index_for_x`].
362    pub fn closest_index_for_position(
363        &self,
364        position: Point<Pixels>,
365        line_height: Pixels,
366    ) -> Result<usize, usize> {
367        self._index_for_position(position, line_height, true)
368    }
369
370    fn _index_for_position(
371        &self,
372        mut position: Point<Pixels>,
373        line_height: Pixels,
374        closest: bool,
375    ) -> Result<usize, usize> {
376        let wrapped_line_ix = (position.y / line_height) as usize;
377
378        let wrapped_line_start_index;
379        let wrapped_line_start_x;
380        if wrapped_line_ix > 0 {
381            let Some(line_start_boundary) = self.wrap_boundaries.get(wrapped_line_ix - 1) else {
382                return Err(0);
383            };
384            let run = &self.unwrapped_layout.runs[line_start_boundary.run_ix];
385            let glyph = &run.glyphs[line_start_boundary.glyph_ix];
386            wrapped_line_start_index = glyph.index;
387            wrapped_line_start_x = glyph.position.x;
388        } else {
389            wrapped_line_start_index = 0;
390            wrapped_line_start_x = Pixels::ZERO;
391        };
392
393        let wrapped_line_end_index;
394        let wrapped_line_end_x;
395        if wrapped_line_ix < self.wrap_boundaries.len() {
396            let next_wrap_boundary_ix = wrapped_line_ix;
397            let next_wrap_boundary = self.wrap_boundaries[next_wrap_boundary_ix];
398            let run = &self.unwrapped_layout.runs[next_wrap_boundary.run_ix];
399            let glyph = &run.glyphs[next_wrap_boundary.glyph_ix];
400            wrapped_line_end_index = glyph.index;
401            wrapped_line_end_x = glyph.position.x;
402        } else {
403            wrapped_line_end_index = self.unwrapped_layout.len;
404            wrapped_line_end_x = self.unwrapped_layout.width;
405        };
406
407        let mut position_in_unwrapped_line = position;
408        position_in_unwrapped_line.x += wrapped_line_start_x;
409        if position_in_unwrapped_line.x < wrapped_line_start_x {
410            Err(wrapped_line_start_index)
411        } else if position_in_unwrapped_line.x >= wrapped_line_end_x {
412            Err(wrapped_line_end_index)
413        } else {
414            if closest {
415                Ok(self
416                    .unwrapped_layout
417                    .closest_index_for_x(position_in_unwrapped_line.x))
418            } else {
419                // The shaper can place a trailing zero-width wrap boundary glyph slightly past
420                // the line's width, so the row can extend past where `index_for_x` has glyphs.
421                self.unwrapped_layout
422                    .index_for_x(position_in_unwrapped_line.x)
423                    .ok_or(wrapped_line_end_index)
424            }
425        }
426    }
427
428    /// Returns the pixel position for the given byte index.
429    pub fn position_for_index(&self, index: usize, line_height: Pixels) -> Option<Point<Pixels>> {
430        let mut line_start_ix = 0;
431        let mut line_end_indices = self
432            .wrap_boundaries
433            .iter()
434            .map(|wrap_boundary| {
435                let run = &self.unwrapped_layout.runs[wrap_boundary.run_ix];
436                let glyph = &run.glyphs[wrap_boundary.glyph_ix];
437                glyph.index
438            })
439            .chain([self.len()])
440            .enumerate();
441        for (ix, line_end_ix) in line_end_indices {
442            let line_y = ix as f32 * line_height;
443            if index < line_start_ix {
444                break;
445            } else if index > line_end_ix {
446                line_start_ix = line_end_ix;
447                continue;
448            } else {
449                let line_start_x = self.unwrapped_layout.x_for_index(line_start_ix);
450                let x = self.unwrapped_layout.x_for_index(index) - line_start_x;
451                return Some(point(x, line_y));
452            }
453        }
454
455        None
456    }
457}
458
459pub(crate) struct LineLayoutCache {
460    pub(crate) previous_frame: Mutex<FrameCache>,
461    pub(crate) current_frame: RwLock<FrameCache>,
462    pub(crate) platform_text_system: Arc<dyn PlatformTextSystem>,
463    /// Advances when [`TextSystem::add_fonts`] successfully changes the font database.
464    font_generation: Arc<AtomicUsize>,
465    /// Records the generation represented by both frame caches.
466    cached_font_generation: AtomicUsize,
467    pub(crate) shaping: crate::fast::text::LineShaping,
468}
469
470#[derive(Default)]
471pub(crate) struct FrameCache {
472    pub(crate) lines: FxHashMap<Arc<CacheKey>, Arc<LineLayout>>,
473    pub(crate) wrapped_lines: FxHashMap<Arc<CacheKey>, Arc<WrappedLineLayout>>,
474    pub(crate) used_lines: Vec<Arc<CacheKey>>,
475    pub(crate) used_wrapped_lines: Vec<Arc<CacheKey>>,
476
477    // Content-addressable caches keyed by caller-provided text hash + layout params.
478    // These allow cache hits without materializing a contiguous `SharedString`.
479    //
480    // IMPORTANT: To support allocation-free lookups, we store these maps using a key type
481    // (`HashedCacheKeyRef`) that can be computed without building a contiguous `&str`/`SharedString`.
482    // On miss, we allocate once and store under an owned `HashedCacheKey`.
483    pub(crate) lines_by_hash: FxHashMap<Arc<HashedCacheKey>, Arc<LineLayout>>,
484    pub(crate) wrapped_lines_by_hash: FxHashMap<Arc<HashedCacheKey>, Arc<WrappedLineLayout>>,
485    pub(crate) used_lines_by_hash: Vec<Arc<HashedCacheKey>>,
486    pub(crate) used_wrapped_lines_by_hash: Vec<Arc<HashedCacheKey>>,
487}
488
489#[derive(Clone, Default)]
490pub(crate) struct LineLayoutIndex {
491    pub(crate) font_generation: usize,
492    pub(crate) lines_index: usize,
493    pub(crate) wrapped_lines_index: usize,
494    pub(crate) lines_by_hash_index: usize,
495    pub(crate) wrapped_lines_by_hash_index: usize,
496}
497
498impl LineLayoutCache {
499    pub fn new(
500        platform_text_system: Arc<dyn PlatformTextSystem>,
501        font_generation: Arc<AtomicUsize>,
502    ) -> Self {
503        let cached_font_generation = font_generation.load(Ordering::Acquire);
504        Self {
505            previous_frame: Mutex::default(),
506            current_frame: RwLock::default(),
507            platform_text_system,
508            font_generation,
509            cached_font_generation: AtomicUsize::new(cached_font_generation),
510            shaping: crate::fast::text::LineShaping::default(),
511        }
512    }
513
514    pub fn layout_index(&self) -> LineLayoutIndex {
515        let font_generation = self.clear_if_font_generation_changed();
516        let frame = self.current_frame.read();
517        LineLayoutIndex {
518            font_generation,
519            lines_index: frame.used_lines.len(),
520            wrapped_lines_index: frame.used_wrapped_lines.len(),
521            lines_by_hash_index: frame.used_lines_by_hash.len(),
522            wrapped_lines_by_hash_index: frame.used_wrapped_lines_by_hash.len(),
523        }
524    }
525
526    pub fn reuse_layouts(&self, range: Range<LineLayoutIndex>) {
527        let font_generation = self.clear_if_font_generation_changed();
528        if range.start.font_generation != font_generation
529            || range.end.font_generation != font_generation
530        {
531            return;
532        }
533        let mut current_frame = &mut *self.current_frame.write();
534        let mut previous_frame = &mut *self.previous_frame.lock();
535
536        for key in &previous_frame.used_lines[range.start.lines_index..range.end.lines_index] {
537            if let Some((key, line)) = previous_frame.lines.remove_entry(key) {
538                current_frame.lines.insert(key, line);
539            }
540            current_frame.used_lines.push(key.clone());
541        }
542
543        for key in &previous_frame.used_wrapped_lines
544            [range.start.wrapped_lines_index..range.end.wrapped_lines_index]
545        {
546            if let Some((key, line)) = previous_frame.wrapped_lines.remove_entry(key) {
547                current_frame.wrapped_lines.insert(key, line);
548            }
549            current_frame.used_wrapped_lines.push(key.clone());
550        }
551
552        for key in &previous_frame.used_lines_by_hash
553            [range.start.lines_by_hash_index..range.end.lines_by_hash_index]
554        {
555            if let Some((key, line)) = previous_frame.lines_by_hash.remove_entry(key) {
556                current_frame.lines_by_hash.insert(key, line);
557            }
558            current_frame.used_lines_by_hash.push(key.clone());
559        }
560
561        for key in &previous_frame.used_wrapped_lines_by_hash
562            [range.start.wrapped_lines_by_hash_index..range.end.wrapped_lines_by_hash_index]
563        {
564            if let Some((key, line)) = previous_frame.wrapped_lines_by_hash.remove_entry(key) {
565                current_frame.wrapped_lines_by_hash.insert(key, line);
566            }
567            current_frame.used_wrapped_lines_by_hash.push(key.clone());
568        }
569    }
570
571    pub fn truncate_layouts(&self, index: LineLayoutIndex) {
572        let font_generation = self.clear_if_font_generation_changed();
573        if index.font_generation != font_generation {
574            return;
575        }
576        let mut current_frame = &mut *self.current_frame.write();
577        current_frame.used_lines.truncate(index.lines_index);
578        current_frame
579            .used_wrapped_lines
580            .truncate(index.wrapped_lines_index);
581        current_frame
582            .used_lines_by_hash
583            .truncate(index.lines_by_hash_index);
584        current_frame
585            .used_wrapped_lines_by_hash
586            .truncate(index.wrapped_lines_by_hash_index);
587    }
588
589    pub fn finish_frame(&self) {
590        let _font_generation = self.clear_if_font_generation_changed();
591        let mut curr_frame = self.current_frame.write();
592        let mut prev_frame = self.previous_frame.lock();
593        crate::fast::text::carry_over_line_layouts(&mut prev_frame, &mut curr_frame);
594    }
595
596    pub fn layout_wrapped_line<Text>(
597        &self,
598        text: Text,
599        font_size: Pixels,
600        runs: &[FontRun],
601        wrap_width: Option<Pixels>,
602        max_lines: Option<usize>,
603    ) -> Arc<WrappedLineLayout>
604    where
605        Text: AsRef<str>,
606        SharedString: From<Text>,
607    {
608        let _font_generation = self.clear_if_font_generation_changed();
609        let key = &CacheKeyRef {
610            text: text.as_ref(),
611            font_size,
612            runs,
613            wrap_width,
614            force_width: None,
615        } as &dyn AsCacheKeyRef;
616
617        let current_frame = self.current_frame.upgradable_read();
618        if let Some(layout) = current_frame.wrapped_lines.get(key) {
619            return layout.clone();
620        }
621
622        let previous_frame_entry = self.previous_frame.lock().wrapped_lines.remove_entry(key);
623        if let Some((key, layout)) = previous_frame_entry {
624            let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
625            current_frame
626                .wrapped_lines
627                .insert(key.clone(), layout.clone());
628            current_frame.used_wrapped_lines.push(key);
629            layout
630        } else {
631            drop(current_frame);
632            let text = SharedString::from(text);
633            let unwrapped_layout = self.layout_line::<&SharedString>(&text, font_size, runs, None);
634            let wrap_boundaries = if let Some(wrap_width) = wrap_width {
635                unwrapped_layout.compute_wrap_boundaries(text.as_ref(), wrap_width, max_lines)
636            } else {
637                SmallVec::new()
638            };
639            let layout = Arc::new(WrappedLineLayout {
640                unwrapped_layout,
641                wrap_boundaries,
642                wrap_width,
643            });
644            let key = Arc::new(CacheKey {
645                text,
646                font_size,
647                runs: SmallVec::from(runs),
648                wrap_width,
649                force_width: None,
650            });
651
652            let mut current_frame = self.current_frame.write();
653            current_frame
654                .wrapped_lines
655                .insert(key.clone(), layout.clone());
656            current_frame.used_wrapped_lines.push(key);
657
658            layout
659        }
660    }
661
662    pub fn layout_line<Text>(
663        &self,
664        text: Text,
665        font_size: Pixels,
666        runs: &[FontRun],
667        force_width: Option<Pixels>,
668    ) -> Arc<LineLayout>
669    where
670        Text: AsRef<str>,
671        SharedString: From<Text>,
672    {
673        let _font_generation = self.clear_if_font_generation_changed();
674        let key = &CacheKeyRef {
675            text: text.as_ref(),
676            font_size,
677            runs,
678            wrap_width: None,
679            force_width,
680        } as &dyn AsCacheKeyRef;
681
682        let current_frame = self.current_frame.upgradable_read();
683        if let Some(layout) = current_frame.lines.get(key) {
684            return layout.clone();
685        }
686
687        let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
688        if let Some((key, layout)) = self.previous_frame.lock().lines.remove_entry(key) {
689            current_frame.lines.insert(key.clone(), layout.clone());
690            current_frame.used_lines.push(key);
691            layout
692        } else {
693            let text = SharedString::from(text);
694            let mut layout = crate::fast::text::shape_line(self, &text, font_size, runs);
695
696            if let Some(force_width) = force_width {
697                apply_force_width_to_layout(&mut layout, force_width);
698            }
699
700            let key = Arc::new(CacheKey {
701                text,
702                font_size,
703                runs: SmallVec::from(runs),
704                wrap_width: None,
705                force_width,
706            });
707            let layout = Arc::new(layout);
708            current_frame.lines.insert(key.clone(), layout.clone());
709            current_frame.used_lines.push(key);
710            layout
711        }
712    }
713
714    /// Try to retrieve a previously-shaped line layout using a caller-provided content hash.
715    ///
716    /// This is a *non-allocating* cache probe: it does not materialize any text. If the layout
717    /// is not already cached in either the current frame or previous frame, returns `None`.
718    ///
719    /// Contract (caller enforced):
720    /// - Same `text_hash` implies identical text content (collision risk accepted by caller).
721    /// - `text_len` should be the UTF-8 byte length of the text (helps reduce accidental collisions).
722    pub fn try_layout_line_by_hash(
723        &self,
724        text_hash: u64,
725        text_len: usize,
726        font_size: Pixels,
727        runs: &[FontRun],
728        force_width: Option<Pixels>,
729    ) -> Option<Arc<LineLayout>> {
730        let _font_generation = self.clear_if_font_generation_changed();
731        let key_ref = HashedCacheKeyRef {
732            text_hash,
733            text_len,
734            font_size,
735            runs,
736            wrap_width: None,
737            force_width,
738        };
739
740        let current_frame = self.current_frame.read();
741        if let Some((_, layout)) = current_frame.lines_by_hash.iter().find(|(key, _)| {
742            HashedCacheKeyRef {
743                text_hash: key.text_hash,
744                text_len: key.text_len,
745                font_size: key.font_size,
746                runs: key.runs.as_slice(),
747                wrap_width: key.wrap_width,
748                force_width: key.force_width,
749            } == key_ref
750        }) {
751            return Some(layout.clone());
752        }
753
754        let previous_frame = self.previous_frame.lock();
755        if let Some((_, layout)) = previous_frame.lines_by_hash.iter().find(|(key, _)| {
756            HashedCacheKeyRef {
757                text_hash: key.text_hash,
758                text_len: key.text_len,
759                font_size: key.font_size,
760                runs: key.runs.as_slice(),
761                wrap_width: key.wrap_width,
762                force_width: key.force_width,
763            } == key_ref
764        }) {
765            return Some(layout.clone());
766        }
767
768        None
769    }
770
771    /// Layout a line of text using a caller-provided content hash as the cache key.
772    ///
773    /// This enables cache hits without materializing a contiguous `SharedString` for `text`.
774    /// If the cache misses, `materialize_text` is invoked to produce the `SharedString` for shaping.
775    ///
776    /// Contract (caller enforced):
777    /// - Same `text_hash` implies identical text content (collision risk accepted by caller).
778    /// - `text_len` should be the UTF-8 byte length of the text (helps reduce accidental collisions).
779    pub fn layout_line_by_hash(
780        &self,
781        text_hash: u64,
782        text_len: usize,
783        font_size: Pixels,
784        runs: &[FontRun],
785        force_width: Option<Pixels>,
786        materialize_text: impl FnOnce() -> SharedString,
787    ) -> Arc<LineLayout> {
788        let _font_generation = self.clear_if_font_generation_changed();
789        let key_ref = HashedCacheKeyRef {
790            text_hash,
791            text_len,
792            font_size,
793            runs,
794            wrap_width: None,
795            force_width,
796        };
797
798        // Fast path: already cached (no allocation).
799        let current_frame = self.current_frame.upgradable_read();
800        if let Some((_, layout)) = current_frame.lines_by_hash.iter().find(|(key, _)| {
801            HashedCacheKeyRef {
802                text_hash: key.text_hash,
803                text_len: key.text_len,
804                font_size: key.font_size,
805                runs: key.runs.as_slice(),
806                wrap_width: key.wrap_width,
807                force_width: key.force_width,
808            } == key_ref
809        }) {
810            return layout.clone();
811        }
812
813        let mut current_frame = RwLockUpgradableReadGuard::upgrade(current_frame);
814
815        // Try to reuse from previous frame without allocating; do a linear scan to find a matching key.
816        // (We avoid `drain()` here because it would eagerly move all entries.)
817        let mut previous_frame = self.previous_frame.lock();
818        if let Some(existing_key) = previous_frame
819            .used_lines_by_hash
820            .iter()
821            .find(|key| {
822                HashedCacheKeyRef {
823                    text_hash: key.text_hash,
824                    text_len: key.text_len,
825                    font_size: key.font_size,
826                    runs: key.runs.as_slice(),
827                    wrap_width: key.wrap_width,
828                    force_width: key.force_width,
829                } == key_ref
830            })
831            .cloned()
832        {
833            if let Some((key, layout)) = previous_frame.lines_by_hash.remove_entry(&existing_key) {
834                current_frame
835                    .lines_by_hash
836                    .insert(key.clone(), layout.clone());
837                current_frame.used_lines_by_hash.push(key);
838                return layout;
839            }
840        }
841
842        let text = materialize_text();
843        let mut layout = crate::fast::text::shape_line(self, &text, font_size, runs);
844
845        if let Some(force_width) = force_width {
846            apply_force_width_to_layout(&mut layout, force_width);
847        }
848
849        let key = Arc::new(HashedCacheKey {
850            text_hash,
851            text_len,
852            font_size,
853            runs: SmallVec::from(runs),
854            wrap_width: None,
855            force_width,
856        });
857        let layout = Arc::new(layout);
858        current_frame
859            .lines_by_hash
860            .insert(key.clone(), layout.clone());
861        current_frame.used_lines_by_hash.push(key);
862        layout
863    }
864
865    fn clear_if_font_generation_changed(&self) -> usize {
866        let font_generation = self.font_generation.load(Ordering::Acquire);
867        if self.cached_font_generation.load(Ordering::Acquire) == font_generation {
868            return font_generation;
869        }
870
871        let mut current_frame = self.current_frame.write();
872        if self.cached_font_generation.load(Ordering::Acquire) == font_generation {
873            return font_generation;
874        }
875
876        *current_frame = FrameCache::default();
877        *self.previous_frame.lock() = FrameCache::default();
878        self.cached_font_generation
879            .store(font_generation, Ordering::Release);
880        font_generation
881    }
882}
883
884// Combining marks (e.g. Thai vowel signs, Arabic diacritics) are shaped by
885// HarfBuzz at the same x position as their base character. The force-width
886// loop must not advance the cell counter for these zero-advance glyphs,
887// otherwise they get displaced into the next cell. We detect them by checking
888// whether shaped x has advanced by at least half a cell beyond the last base.
889fn apply_force_width_to_layout(layout: &mut LineLayout, force_width: Pixels) {
890    let mut glyph_pos: usize = 0;
891    // NEG_INFINITY ensures the first glyph is always classified as a base.
892    let mut last_base_shaped_x = px(f32::NEG_INFINITY);
893    let mut last_base_actual_x = px(0.);
894
895    for run in layout.runs.iter_mut() {
896        for glyph in run.glyphs.iter_mut() {
897            let shaped_x = glyph.position.x;
898
899            if shaped_x > last_base_shaped_x + force_width * 0.5 {
900                let forced_x = glyph_pos * force_width;
901                if (shaped_x - forced_x).abs() > px(1.) {
902                    glyph.position.x = forced_x;
903                }
904                last_base_shaped_x = shaped_x;
905                last_base_actual_x = glyph.position.x;
906                glyph_pos += 1;
907            } else {
908                glyph.position.x = last_base_actual_x + (shaped_x - last_base_shaped_x);
909            }
910        }
911    }
912}
913
914/// A run of text with a single font.
915#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
916#[expect(missing_docs)]
917pub struct FontRun {
918    pub len: usize,
919    pub font_id: FontId,
920}
921
922trait AsCacheKeyRef {
923    fn as_cache_key_ref(&self) -> CacheKeyRef<'_>;
924}
925
926#[derive(Clone, Debug, Eq)]
927pub(crate) struct CacheKey {
928    text: SharedString,
929    font_size: Pixels,
930    runs: SmallVec<[FontRun; 1]>,
931    wrap_width: Option<Pixels>,
932    force_width: Option<Pixels>,
933}
934
935#[derive(Copy, Clone, PartialEq, Eq, Hash)]
936struct CacheKeyRef<'a> {
937    text: &'a str,
938    font_size: Pixels,
939    runs: &'a [FontRun],
940    wrap_width: Option<Pixels>,
941    force_width: Option<Pixels>,
942}
943
944#[derive(Clone, Debug)]
945pub(crate) struct HashedCacheKey {
946    text_hash: u64,
947    text_len: usize,
948    font_size: Pixels,
949    runs: SmallVec<[FontRun; 1]>,
950    wrap_width: Option<Pixels>,
951    force_width: Option<Pixels>,
952}
953
954#[derive(Copy, Clone)]
955struct HashedCacheKeyRef<'a> {
956    text_hash: u64,
957    text_len: usize,
958    font_size: Pixels,
959    runs: &'a [FontRun],
960    wrap_width: Option<Pixels>,
961    force_width: Option<Pixels>,
962}
963
964impl PartialEq for dyn AsCacheKeyRef + '_ {
965    fn eq(&self, other: &dyn AsCacheKeyRef) -> bool {
966        self.as_cache_key_ref() == other.as_cache_key_ref()
967    }
968}
969
970impl PartialEq for HashedCacheKey {
971    fn eq(&self, other: &Self) -> bool {
972        self.text_hash == other.text_hash
973            && self.text_len == other.text_len
974            && self.font_size == other.font_size
975            && self.runs.as_slice() == other.runs.as_slice()
976            && self.wrap_width == other.wrap_width
977            && self.force_width == other.force_width
978    }
979}
980
981impl Eq for HashedCacheKey {}
982
983impl Hash for HashedCacheKey {
984    fn hash<H: Hasher>(&self, state: &mut H) {
985        self.text_hash.hash(state);
986        self.text_len.hash(state);
987        self.font_size.hash(state);
988        self.runs.as_slice().hash(state);
989        self.wrap_width.hash(state);
990        self.force_width.hash(state);
991    }
992}
993
994impl PartialEq for HashedCacheKeyRef<'_> {
995    fn eq(&self, other: &Self) -> bool {
996        self.text_hash == other.text_hash
997            && self.text_len == other.text_len
998            && self.font_size == other.font_size
999            && self.runs == other.runs
1000            && self.wrap_width == other.wrap_width
1001            && self.force_width == other.force_width
1002    }
1003}
1004
1005impl Eq for HashedCacheKeyRef<'_> {}
1006
1007impl Hash for HashedCacheKeyRef<'_> {
1008    fn hash<H: Hasher>(&self, state: &mut H) {
1009        self.text_hash.hash(state);
1010        self.text_len.hash(state);
1011        self.font_size.hash(state);
1012        self.runs.hash(state);
1013        self.wrap_width.hash(state);
1014        self.force_width.hash(state);
1015    }
1016}
1017
1018impl Eq for dyn AsCacheKeyRef + '_ {}
1019
1020impl Hash for dyn AsCacheKeyRef + '_ {
1021    fn hash<H: Hasher>(&self, state: &mut H) {
1022        self.as_cache_key_ref().hash(state)
1023    }
1024}
1025
1026impl AsCacheKeyRef for CacheKey {
1027    fn as_cache_key_ref(&self) -> CacheKeyRef<'_> {
1028        CacheKeyRef {
1029            text: &self.text,
1030            font_size: self.font_size,
1031            runs: self.runs.as_slice(),
1032            wrap_width: self.wrap_width,
1033            force_width: self.force_width,
1034        }
1035    }
1036}
1037
1038impl PartialEq for CacheKey {
1039    fn eq(&self, other: &Self) -> bool {
1040        self.as_cache_key_ref().eq(&other.as_cache_key_ref())
1041    }
1042}
1043
1044impl Hash for CacheKey {
1045    fn hash<H: Hasher>(&self, state: &mut H) {
1046        self.as_cache_key_ref().hash(state);
1047    }
1048}
1049
1050impl<'a> Borrow<dyn AsCacheKeyRef + 'a> for Arc<CacheKey> {
1051    fn borrow(&self) -> &(dyn AsCacheKeyRef + 'a) {
1052        self.as_ref() as &dyn AsCacheKeyRef
1053    }
1054}
1055
1056impl AsCacheKeyRef for CacheKeyRef<'_> {
1057    fn as_cache_key_ref(&self) -> CacheKeyRef<'_> {
1058        *self
1059    }
1060}
1061
1062#[cfg(test)]
1063mod tests {
1064    use super::*;
1065    use crate::GlyphId;
1066
1067    fn glyph_at(x: f32, index: usize) -> ShapedGlyph {
1068        ShapedGlyph {
1069            id: GlyphId(0),
1070            position: point(px(x), px(0.)),
1071            index,
1072            is_emoji: false,
1073        }
1074    }
1075
1076    fn make_layout(glyphs: Vec<ShapedGlyph>) -> LineLayout {
1077        LineLayout {
1078            font_size: px(16.),
1079            width: px(100.),
1080            ascent: px(12.),
1081            descent: px(4.),
1082            runs: vec![ShapedRun {
1083                font_id: FontId(0),
1084                glyphs,
1085            }],
1086            len: 0,
1087        }
1088    }
1089
1090    fn glyph_x_positions(layout: &LineLayout) -> Vec<f32> {
1091        layout.runs[0]
1092            .glyphs
1093            .iter()
1094            .map(|g| f32::from(g.position.x))
1095            .collect()
1096    }
1097
1098    #[test]
1099    fn test_force_width_latin_unchanged() {
1100        let cell_width = px(8.);
1101        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(8., 1), glyph_at(16., 2)]);
1102
1103        apply_force_width_to_layout(&mut layout, cell_width);
1104
1105        let positions = glyph_x_positions(&layout);
1106        assert_eq!(positions, vec![0., 8., 16.]);
1107    }
1108
1109    #[test]
1110    fn test_force_width_combining_marks_not_advanced() {
1111        let cell_width = px(8.);
1112        // Simulates Thai "กี" — base consonant at x=0, combining vowel also at x=0
1113        let mut layout = make_layout(vec![
1114            glyph_at(0., 0), // ก (base)
1115            glyph_at(0., 3), // ี (combining mark, same x)
1116        ]);
1117
1118        apply_force_width_to_layout(&mut layout, cell_width);
1119
1120        let positions = glyph_x_positions(&layout);
1121        assert_eq!(positions, vec![0., 0.]);
1122    }
1123
1124    #[test]
1125    fn test_force_width_base_after_combining_mark() {
1126        let cell_width = px(8.);
1127        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(0., 3), glyph_at(8., 6)]);
1128
1129        apply_force_width_to_layout(&mut layout, cell_width);
1130
1131        let positions = glyph_x_positions(&layout);
1132        assert_eq!(positions, vec![0., 0., 8.]);
1133    }
1134
1135    #[test]
1136    fn test_force_width_multiple_combining_marks() {
1137        let cell_width = px(8.);
1138        // Simulates "ก้" — base + vowel + tone mark (two combining marks stacked)
1139        let mut layout = make_layout(vec![
1140            glyph_at(0., 0), // ก (base)
1141            glyph_at(0., 3), // vowel (combining)
1142            glyph_at(0., 6), // tone mark (combining)
1143            glyph_at(8., 9), // next base
1144        ]);
1145
1146        apply_force_width_to_layout(&mut layout, cell_width);
1147
1148        let positions = glyph_x_positions(&layout);
1149        assert_eq!(positions, vec![0., 0., 0., 8.]);
1150    }
1151
1152    #[test]
1153    fn test_force_width_corrects_drifted_base_positions() {
1154        let cell_width = px(8.);
1155        // Font metrics don't perfectly match cell grid — glyphs drift >1px from cell boundary
1156        let mut layout = make_layout(vec![
1157            glyph_at(0.5, 0),  // within 1px tolerance, kept as-is
1158            glyph_at(10.2, 1), // >1px off from 8.0, corrected
1159            glyph_at(19.8, 2), // >1px off from 16.0, corrected
1160        ]);
1161
1162        apply_force_width_to_layout(&mut layout, cell_width);
1163
1164        let positions = glyph_x_positions(&layout);
1165        assert_eq!(positions, vec![0.5, 8., 16.]);
1166    }
1167
1168    #[test]
1169    fn test_force_width_combining_mark_after_within_tolerance_base() {
1170        let cell_width = px(8.);
1171        // Base glyph is within 1px of grid so it keeps its shaped position.
1172        // The combining mark must align to the base's actual position, not the grid slot.
1173        let mut layout = make_layout(vec![glyph_at(0.5, 0), glyph_at(0.5, 3)]);
1174
1175        apply_force_width_to_layout(&mut layout, cell_width);
1176
1177        let positions = glyph_x_positions(&layout);
1178        assert_eq!(positions, vec![0.5, 0.5]);
1179    }
1180}