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