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