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    pub fn len(&self) -> usize {
321        self.unwrapped_layout.len
322    }
323
324    /// The width of this line, in pixels, whether or not it was wrapped.
325    pub fn width(&self) -> Pixels {
326        self.wrap_width
327            .unwrap_or(Pixels::MAX)
328            .min(self.unwrapped_layout.width)
329    }
330
331    /// The size of the whole wrapped text, for the given line_height.
332    /// can span multiple lines if there are multiple wrap boundaries.
333    pub fn size(&self, line_height: Pixels) -> Size<Pixels> {
334        Size {
335            width: self.width(),
336            height: line_height * (self.wrap_boundaries.len() + 1),
337        }
338    }
339
340    /// The ascent of a line in this layout
341    pub fn ascent(&self) -> Pixels {
342        self.unwrapped_layout.ascent
343    }
344
345    /// The descent of a line in this layout
346    pub fn descent(&self) -> Pixels {
347        self.unwrapped_layout.descent
348    }
349
350    /// The wrap boundaries in this layout
351    pub fn wrap_boundaries(&self) -> &[WrapBoundary] {
352        &self.wrap_boundaries
353    }
354
355    /// The font size of this layout
356    pub fn font_size(&self) -> Pixels {
357        self.unwrapped_layout.font_size
358    }
359
360    /// The runs in this layout, sans wrapping
361    pub fn runs(&self) -> &[ShapedRun] {
362        &self.unwrapped_layout.runs
363    }
364
365    /// The index corresponding to a given position in this layout for the given line height.
366    ///
367    /// See also [`Self::closest_index_for_position`].
368    pub fn index_for_position(
369        &self,
370        position: Point<Pixels>,
371        line_height: Pixels,
372    ) -> Result<usize, usize> {
373        self._index_for_position(position, line_height, false)
374    }
375
376    /// The closest index to a given position in this layout for the given line height.
377    ///
378    /// Closest means the character boundary closest to the given position.
379    ///
380    /// See also [`LineLayout::closest_index_for_x`].
381    pub fn closest_index_for_position(
382        &self,
383        position: Point<Pixels>,
384        line_height: Pixels,
385    ) -> Result<usize, usize> {
386        self._index_for_position(position, line_height, true)
387    }
388
389    fn _index_for_position(
390        &self,
391        position: Point<Pixels>,
392        line_height: Pixels,
393        closest: bool,
394    ) -> Result<usize, usize> {
395        let wrapped_line_ix = (position.y / line_height) as usize;
396
397        let wrapped_line_start_index;
398        let wrapped_line_start_x;
399        if wrapped_line_ix > 0 {
400            let Some(line_start_boundary) = self.wrap_boundaries.get(wrapped_line_ix - 1) else {
401                return Err(0);
402            };
403            let run = &self.unwrapped_layout.runs[line_start_boundary.run_ix];
404            let glyph = &run.glyphs[line_start_boundary.glyph_ix];
405            wrapped_line_start_index = glyph.index;
406            wrapped_line_start_x = glyph.position.x;
407        } else {
408            wrapped_line_start_index = 0;
409            wrapped_line_start_x = Pixels::ZERO;
410        };
411
412        let wrapped_line_end_index;
413        let wrapped_line_end_x;
414        if wrapped_line_ix < self.wrap_boundaries.len() {
415            let next_wrap_boundary_ix = wrapped_line_ix;
416            let next_wrap_boundary = self.wrap_boundaries[next_wrap_boundary_ix];
417            let run = &self.unwrapped_layout.runs[next_wrap_boundary.run_ix];
418            let glyph = &run.glyphs[next_wrap_boundary.glyph_ix];
419            wrapped_line_end_index = glyph.index;
420            wrapped_line_end_x = glyph.position.x;
421        } else {
422            wrapped_line_end_index = self.unwrapped_layout.len;
423            wrapped_line_end_x = self.unwrapped_layout.width;
424        };
425
426        let mut position_in_unwrapped_line = position;
427        position_in_unwrapped_line.x += wrapped_line_start_x;
428        if position_in_unwrapped_line.x < wrapped_line_start_x {
429            Err(wrapped_line_start_index)
430        } else if position_in_unwrapped_line.x >= wrapped_line_end_x {
431            Err(wrapped_line_end_index)
432        } else {
433            if closest {
434                Ok(self
435                    .unwrapped_layout
436                    .closest_index_for_x(position_in_unwrapped_line.x))
437            } else {
438                // The shaper can place a trailing zero-width wrap boundary glyph slightly past
439                // the line's width, so the row can extend past where `index_for_x` has glyphs.
440                self.unwrapped_layout
441                    .index_for_x(position_in_unwrapped_line.x)
442                    .ok_or(wrapped_line_end_index)
443            }
444        }
445    }
446
447    /// Returns the pixel position for the given byte index.
448    pub fn position_for_index(&self, index: usize, line_height: Pixels) -> Option<Point<Pixels>> {
449        let mut line_start_ix = 0;
450        let line_end_indices = self
451            .wrap_boundaries
452            .iter()
453            .map(|wrap_boundary| {
454                let run = &self.unwrapped_layout.runs[wrap_boundary.run_ix];
455                let glyph = &run.glyphs[wrap_boundary.glyph_ix];
456                glyph.index
457            })
458            .chain([self.len()])
459            .enumerate();
460        for (ix, line_end_ix) in line_end_indices {
461            let line_y = ix as f32 * line_height;
462            if index < line_start_ix {
463                break;
464            } else if index > line_end_ix {
465                line_start_ix = line_end_ix;
466                continue;
467            } else {
468                let line_start_x = self.unwrapped_layout.x_for_index(line_start_ix);
469                let x = self.unwrapped_layout.x_for_index(index) - line_start_x;
470                return Some(point(x, line_y));
471            }
472        }
473
474        None
475    }
476}
477
478pub(crate) struct LineLayoutCache {
479    state: RefCell<LineLayoutCacheState>,
480    wrap_scratch: RefCell<WrapScratch>,
481    pub(crate) platform_text_system: Arc<dyn PlatformTextSystem>,
482    /// Advances when [`TextSystem::add_fonts`] successfully changes the font database.
483    font_generation: Arc<AtomicUsize>,
484    /// Records the generation represented by both frame caches.
485    cached_font_generation: AtomicUsize,
486    pub(crate) shaping: crate::fast::text::LineShaping,
487}
488
489#[derive(Default)]
490pub(crate) struct WrapScratch {
491    glyph_indices: FxHashSet<usize>,
492    break_indices: Vec<usize>,
493}
494
495#[derive(Default)]
496struct LineLayoutCacheState {
497    previous_frame: FrameCache,
498    current_frame: FrameCache,
499}
500
501#[derive(Default)]
502pub(crate) struct FrameCache {
503    pub(crate) lines: FxHashMap<Arc<CacheKey>, Arc<LineLayout>>,
504    pub(crate) wrapped_lines: FxHashMap<Arc<CacheKey>, Arc<WrappedLineLayout>>,
505    pub(crate) used_lines: Vec<Arc<CacheKey>>,
506    pub(crate) used_wrapped_lines: Vec<Arc<CacheKey>>,
507}
508
509#[derive(Clone, Default)]
510pub(crate) struct LineLayoutIndex {
511    pub(crate) font_generation: usize,
512    pub(crate) lines_index: usize,
513    pub(crate) wrapped_lines_index: usize,
514}
515
516impl LineLayoutCache {
517    pub fn new(
518        platform_text_system: Arc<dyn PlatformTextSystem>,
519        font_generation: Arc<AtomicUsize>,
520    ) -> Self {
521        let cached_font_generation = font_generation.load(Ordering::Acquire);
522        Self {
523            state: RefCell::default(),
524            wrap_scratch: RefCell::default(),
525            platform_text_system,
526            font_generation,
527            cached_font_generation: AtomicUsize::new(cached_font_generation),
528            shaping: crate::fast::text::LineShaping::default(),
529        }
530    }
531
532    pub fn layout_index(&self) -> LineLayoutIndex {
533        let font_generation = self.clear_if_font_generation_changed();
534        let state = self.state.borrow();
535        let frame = &state.current_frame;
536        LineLayoutIndex {
537            font_generation,
538            lines_index: frame.used_lines.len(),
539            wrapped_lines_index: frame.used_wrapped_lines.len(),
540        }
541    }
542
543    pub fn reuse_layouts(&self, range: Range<LineLayoutIndex>) {
544        let font_generation = self.clear_if_font_generation_changed();
545        if range.start.font_generation != font_generation
546            || range.end.font_generation != font_generation
547        {
548            return;
549        }
550        let mut state = self.state.borrow_mut();
551        let LineLayoutCacheState {
552            previous_frame,
553            current_frame,
554        } = &mut *state;
555
556        for key in &previous_frame.used_lines[range.start.lines_index..range.end.lines_index] {
557            if let Some((key, line)) = previous_frame.lines.remove_entry(key) {
558                current_frame.lines.insert(key, line);
559            }
560            current_frame.used_lines.push(key.clone());
561        }
562
563        for key in &previous_frame.used_wrapped_lines
564            [range.start.wrapped_lines_index..range.end.wrapped_lines_index]
565        {
566            if let Some((key, line)) = previous_frame.wrapped_lines.remove_entry(key) {
567                current_frame.wrapped_lines.insert(key, line);
568            }
569            current_frame.used_wrapped_lines.push(key.clone());
570        }
571    }
572
573    pub fn truncate_layouts(&self, index: LineLayoutIndex) {
574        let font_generation = self.clear_if_font_generation_changed();
575        if index.font_generation != font_generation {
576            return;
577        }
578        let mut state = self.state.borrow_mut();
579        let current_frame = &mut state.current_frame;
580        current_frame.used_lines.truncate(index.lines_index);
581        current_frame
582            .used_wrapped_lines
583            .truncate(index.wrapped_lines_index);
584    }
585
586    pub fn finish_frame(&self) {
587        let _font_generation = self.clear_if_font_generation_changed();
588        let LineLayoutCacheState {
589            previous_frame,
590            current_frame,
591        } = &mut *self.state.borrow_mut();
592        crate::fast::text::carry_over_line_layouts(previous_frame, current_frame);
593    }
594
595    pub fn layout_wrapped_line<Text>(
596        &self,
597        text: Text,
598        font_size: Pixels,
599        runs: &[FontRun],
600        wrap_width: Option<Pixels>,
601        max_lines: Option<usize>,
602    ) -> Arc<WrappedLineLayout>
603    where
604        Text: AsRef<str>,
605        SharedString: From<Text>,
606    {
607        let _font_generation = self.clear_if_font_generation_changed();
608        let key = &CacheKeyRef {
609            text: text.as_ref(),
610            font_size,
611            runs,
612            wrap_width,
613            max_lines,
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                max_lines,
657                force_width: None,
658            });
659
660            let mut state = self.state.borrow_mut();
661            state
662                .current_frame
663                .wrapped_lines
664                .insert(key.clone(), layout.clone());
665            state.current_frame.used_wrapped_lines.push(key);
666
667            layout
668        }
669    }
670
671    pub fn layout_line<Text>(
672        &self,
673        text: Text,
674        font_size: Pixels,
675        runs: &[FontRun],
676        force_width: Option<Pixels>,
677    ) -> Arc<LineLayout>
678    where
679        Text: AsRef<str>,
680        SharedString: From<Text>,
681    {
682        let _font_generation = self.clear_if_font_generation_changed();
683        let key = &CacheKeyRef {
684            text: text.as_ref(),
685            font_size,
686            runs,
687            wrap_width: None,
688            max_lines: None,
689            force_width,
690        } as &dyn AsCacheKeyRef;
691
692        let state = self.state.borrow();
693        if let Some(layout) = state.current_frame.lines.get(key) {
694            return layout.clone();
695        }
696        drop(state);
697
698        let mut state = self.state.borrow_mut();
699        let LineLayoutCacheState {
700            previous_frame,
701            current_frame,
702        } = &mut *state;
703        if let Some((key, layout)) = previous_frame.lines.remove_entry(key) {
704            current_frame.lines.insert(key.clone(), layout.clone());
705            current_frame.used_lines.push(key);
706            layout
707        } else {
708            let text = SharedString::from(text);
709            let mut layout = crate::fast::text::shape_line(self, &text, font_size, runs);
710
711            if let Some(force_width) = force_width {
712                apply_force_width_to_layout(&mut layout, force_width);
713            }
714
715            let key = Arc::new(CacheKey {
716                text,
717                font_size,
718                runs: SmallVec::from(runs),
719                wrap_width: None,
720                max_lines: None,
721                force_width,
722            });
723            let layout = Arc::new(layout);
724            current_frame.lines.insert(key.clone(), layout.clone());
725            current_frame.used_lines.push(key);
726            layout
727        }
728    }
729
730    fn clear_if_font_generation_changed(&self) -> usize {
731        let font_generation = self.font_generation.load(Ordering::Acquire);
732        if self.cached_font_generation.load(Ordering::Acquire) == font_generation {
733            return font_generation;
734        }
735
736        let mut state = self.state.borrow_mut();
737        if self.cached_font_generation.load(Ordering::Acquire) == font_generation {
738            return font_generation;
739        }
740
741        *state = LineLayoutCacheState::default();
742        self.cached_font_generation
743            .store(font_generation, Ordering::Release);
744        font_generation
745    }
746}
747
748// Combining marks (e.g. Thai vowel signs, Arabic diacritics) are shaped by
749// HarfBuzz at the same x position as their base character. The force-width
750// loop must not advance the cell counter for these zero-advance glyphs,
751// otherwise they get displaced into the next cell. We detect them by checking
752// whether shaped x has advanced by at least half a cell beyond the last base.
753fn apply_force_width_to_layout(layout: &mut LineLayout, force_width: Pixels) {
754    let mut glyph_pos: usize = 0;
755    // NEG_INFINITY ensures the first glyph is always classified as a base.
756    let mut last_base_shaped_x = px(f32::NEG_INFINITY);
757    let mut last_base_actual_x = px(0.);
758
759    for run in layout.runs.iter_mut() {
760        for glyph in run.glyphs.iter_mut() {
761            let shaped_x = glyph.position.x;
762
763            if shaped_x > last_base_shaped_x + force_width * 0.5 {
764                let forced_x = glyph_pos * force_width;
765                if (shaped_x - forced_x).abs() > px(1.) {
766                    glyph.position.x = forced_x;
767                }
768                last_base_shaped_x = shaped_x;
769                last_base_actual_x = glyph.position.x;
770                glyph_pos += 1;
771            } else {
772                glyph.position.x = last_base_actual_x + (shaped_x - last_base_shaped_x);
773            }
774        }
775    }
776}
777
778/// A run of text with a single font.
779#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
780#[expect(missing_docs)]
781pub struct FontRun {
782    pub len: usize,
783    pub font_id: FontId,
784}
785
786trait AsCacheKeyRef {
787    fn as_cache_key_ref(&self) -> CacheKeyRef<'_>;
788}
789
790#[derive(Clone, Debug, Eq)]
791pub(crate) struct CacheKey {
792    text: SharedString,
793    font_size: Pixels,
794    runs: SmallVec<[FontRun; 1]>,
795    wrap_width: Option<Pixels>,
796    max_lines: Option<usize>,
797    force_width: Option<Pixels>,
798}
799
800#[derive(Copy, Clone, PartialEq, Eq, Hash)]
801struct CacheKeyRef<'a> {
802    text: &'a str,
803    font_size: Pixels,
804    runs: &'a [FontRun],
805    wrap_width: Option<Pixels>,
806    max_lines: Option<usize>,
807    force_width: Option<Pixels>,
808}
809
810impl PartialEq for dyn AsCacheKeyRef + '_ {
811    fn eq(&self, other: &dyn AsCacheKeyRef) -> bool {
812        self.as_cache_key_ref() == other.as_cache_key_ref()
813    }
814}
815
816impl Eq for dyn AsCacheKeyRef + '_ {}
817
818impl Hash for dyn AsCacheKeyRef + '_ {
819    fn hash<H: Hasher>(&self, state: &mut H) {
820        self.as_cache_key_ref().hash(state)
821    }
822}
823
824impl AsCacheKeyRef for CacheKey {
825    fn as_cache_key_ref(&self) -> CacheKeyRef<'_> {
826        CacheKeyRef {
827            text: &self.text,
828            font_size: self.font_size,
829            runs: self.runs.as_slice(),
830            wrap_width: self.wrap_width,
831            max_lines: self.max_lines,
832            force_width: self.force_width,
833        }
834    }
835}
836
837impl PartialEq for CacheKey {
838    fn eq(&self, other: &Self) -> bool {
839        self.as_cache_key_ref().eq(&other.as_cache_key_ref())
840    }
841}
842
843impl Hash for CacheKey {
844    fn hash<H: Hasher>(&self, state: &mut H) {
845        self.as_cache_key_ref().hash(state);
846    }
847}
848
849impl<'a> Borrow<dyn AsCacheKeyRef + 'a> for Arc<CacheKey> {
850    fn borrow(&self) -> &(dyn AsCacheKeyRef + 'a) {
851        self.as_ref() as &dyn AsCacheKeyRef
852    }
853}
854
855impl AsCacheKeyRef for CacheKeyRef<'_> {
856    fn as_cache_key_ref(&self) -> CacheKeyRef<'_> {
857        *self
858    }
859}
860
861#[cfg(test)]
862mod tests {
863    use super::*;
864    use crate::{GlyphId, NoopTextSystem, TextRun, TextSystem, WindowTextSystem, font};
865
866    #[test]
867    fn shape_line_shares_its_text_with_the_layout_cache() {
868        let text_system =
869            WindowTextSystem::new(Arc::new(TextSystem::new(Arc::new(NoopTextSystem::new()))));
870        // Long enough to be stored on the heap rather than inline.
871        let text = SharedString::from("let value = compute_something(argument_one, argument_two);");
872        let runs = [TextRun {
873            len: text.len(),
874            font: font(".ZedMono"),
875            ..Default::default()
876        }];
877
878        text_system.shape_line(text.clone(), px(14.), &runs, None);
879        let state = text_system.line_layout_cache.state.borrow();
880        let (key, _) = state.current_frame.lines.iter().next().unwrap();
881        assert_eq!(key.text.as_ptr(), text.as_ptr());
882    }
883
884    #[test]
885    fn layouts_held_outside_the_cache_outlive_frames_that_dont_use_them() {
886        let text_system =
887            WindowTextSystem::new(Arc::new(TextSystem::new(Arc::new(NoopTextSystem::new()))));
888        let shape = |text: &'static str| {
889            let runs = [TextRun {
890                len: text.len(),
891                font: font(".ZedMono"),
892                ..Default::default()
893            }];
894            text_system
895                .shape_text(text.into(), px(14.), &runs, Some(px(100.)), None)
896                .unwrap()
897                .remove(0)
898                .layout
899        };
900
901        let held = shape("held");
902        let dropped = Arc::downgrade(&shape("dropped").unwrapped_layout);
903        for _ in 0..3 {
904            text_system.finish_frame();
905        }
906
907        assert!(Arc::ptr_eq(&shape("held"), &held));
908        assert!(dropped.upgrade().is_none());
909    }
910
911    fn glyph_at(x: f32, index: usize) -> ShapedGlyph {
912        ShapedGlyph {
913            id: GlyphId(0),
914            position: point(px(x), px(0.)),
915            index,
916            is_emoji: false,
917        }
918    }
919
920    fn make_layout(glyphs: Vec<ShapedGlyph>) -> LineLayout {
921        LineLayout {
922            font_size: px(16.),
923            width: px(100.),
924            ascent: px(12.),
925            descent: px(4.),
926            runs: vec![ShapedRun {
927                font_id: FontId(0),
928                glyphs,
929            }],
930            len: 0,
931        }
932    }
933
934    fn glyph_x_positions(layout: &LineLayout) -> Vec<f32> {
935        layout.runs[0]
936            .glyphs
937            .iter()
938            .map(|g| f32::from(g.position.x))
939            .collect()
940    }
941
942    #[test]
943    fn test_wrap_preserves_shaped_clusters() {
944        let mut layout = make_layout(vec![
945            glyph_at(0., 0),
946            glyph_at(5., 0),
947            glyph_at(10., 3),
948            glyph_at(15., 3),
949        ]);
950        layout.width = px(20.);
951        layout.len = "你好".len();
952        assert_eq!(
953            layout
954                .compute_wrap_boundaries("你好", px(15.), None, &mut WrapScratch::default())
955                .as_slice(),
956            &[WrapBoundary {
957                run_ix: 0,
958                glyph_ix: 2
959            }],
960        );
961
962        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(10., 0)]);
963        layout.width = px(20.);
964        layout.len = 1;
965        assert!(
966            layout
967                .compute_wrap_boundaries("a", px(10.), None, &mut WrapScratch::default())
968                .is_empty()
969        );
970    }
971
972    #[test]
973    fn test_wrap_right_to_left_text() {
974        for (text, indices, expected_boundaries) in [
975            ("אבג דהו", vec![11, 9, 7, 6, 4, 2, 0], vec![4]),
976            ("a אבג b", vec![0, 1, 6, 4, 2, 8, 9], vec![2, 6]),
977        ] {
978            let mut layout = make_layout(
979                indices
980                    .iter()
981                    .enumerate()
982                    .map(|(position, index)| glyph_at(position as f32 * 10., *index))
983                    .collect(),
984            );
985            layout.width = px(indices.len() as f32 * 10.);
986            layout.len = text.len();
987            assert_eq!(
988                layout.compute_wrap_boundaries(text, px(40.), None, &mut WrapScratch::default()),
989                expected_boundaries
990                    .into_iter()
991                    .map(|glyph_ix| WrapBoundary {
992                        run_ix: 0,
993                        glyph_ix
994                    })
995                    .collect::<SmallVec<[WrapBoundary; 1]>>(),
996                "{text:?}",
997            );
998        }
999    }
1000
1001    #[test]
1002    fn test_wrap_ignores_breaks_inside_shaped_clusters() {
1003        let text = "x a-bcde";
1004        let mut layout = make_layout(
1005            [0, 1, 2, 5, 6, 7]
1006                .into_iter()
1007                .map(|index| glyph_at(index as f32 * 10., index))
1008                .collect(),
1009        );
1010        layout.width = px(80.);
1011        layout.len = text.len();
1012        assert_eq!(
1013            layout
1014                .compute_wrap_boundaries(text, px(60.), None, &mut WrapScratch::default())
1015                .as_slice(),
1016            &[WrapBoundary {
1017                run_ix: 0,
1018                glyph_ix: 2
1019            }],
1020        );
1021    }
1022
1023    #[test]
1024    fn test_force_width_latin_unchanged() {
1025        let cell_width = px(8.);
1026        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(8., 1), glyph_at(16., 2)]);
1027
1028        apply_force_width_to_layout(&mut layout, cell_width);
1029
1030        let positions = glyph_x_positions(&layout);
1031        assert_eq!(positions, vec![0., 8., 16.]);
1032    }
1033
1034    #[test]
1035    fn test_force_width_combining_marks_not_advanced() {
1036        let cell_width = px(8.);
1037        // Simulates Thai "กี" — base consonant at x=0, combining vowel also at x=0
1038        let mut layout = make_layout(vec![
1039            glyph_at(0., 0), // ก (base)
1040            glyph_at(0., 3), // ี (combining mark, same x)
1041        ]);
1042
1043        apply_force_width_to_layout(&mut layout, cell_width);
1044
1045        let positions = glyph_x_positions(&layout);
1046        assert_eq!(positions, vec![0., 0.]);
1047    }
1048
1049    #[test]
1050    fn test_force_width_base_after_combining_mark() {
1051        let cell_width = px(8.);
1052        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(0., 3), glyph_at(8., 6)]);
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., 0., 8.]);
1058    }
1059
1060    #[test]
1061    fn test_force_width_multiple_combining_marks() {
1062        let cell_width = px(8.);
1063        // Simulates "ก้" — base + vowel + tone mark (two combining marks stacked)
1064        let mut layout = make_layout(vec![
1065            glyph_at(0., 0), // ก (base)
1066            glyph_at(0., 3), // vowel (combining)
1067            glyph_at(0., 6), // tone mark (combining)
1068            glyph_at(8., 9), // next base
1069        ]);
1070
1071        apply_force_width_to_layout(&mut layout, cell_width);
1072
1073        let positions = glyph_x_positions(&layout);
1074        assert_eq!(positions, vec![0., 0., 0., 8.]);
1075    }
1076
1077    #[test]
1078    fn test_force_width_corrects_drifted_base_positions() {
1079        let cell_width = px(8.);
1080        // Font metrics don't perfectly match cell grid — glyphs drift >1px from cell boundary
1081        let mut layout = make_layout(vec![
1082            glyph_at(0.5, 0),  // within 1px tolerance, kept as-is
1083            glyph_at(10.2, 1), // >1px off from 8.0, corrected
1084            glyph_at(19.8, 2), // >1px off from 16.0, corrected
1085        ]);
1086
1087        apply_force_width_to_layout(&mut layout, cell_width);
1088
1089        let positions = glyph_x_positions(&layout);
1090        assert_eq!(positions, vec![0.5, 8., 16.]);
1091    }
1092
1093    #[test]
1094    fn test_force_width_combining_mark_after_within_tolerance_base() {
1095        let cell_width = px(8.);
1096        // Base glyph is within 1px of grid so it keeps its shaped position.
1097        // The combining mark must align to the base's actual position, not the grid slot.
1098        let mut layout = make_layout(vec![glyph_at(0.5, 0), glyph_at(0.5, 3)]);
1099
1100        apply_force_width_to_layout(&mut layout, cell_width);
1101
1102        let positions = glyph_x_positions(&layout);
1103        assert_eq!(positions, vec![0.5, 0.5]);
1104    }
1105
1106    #[test]
1107    fn test_wrap_ignores_the_sign_of_a_zero_wrap_width_in_the_cache() {
1108        let runs = [FontRun {
1109            len: 2,
1110            font_id: FontId(1),
1111        }];
1112
1113        let cold_cache = LineLayoutCache::new(Arc::new(NoopTextSystem::new()), Arc::default());
1114        let cold = cold_cache.layout_wrapped_line("ab", px(0.), &runs, Some(px(0.)), None);
1115
1116        let warm_cache = LineLayoutCache::new(Arc::new(NoopTextSystem::new()), Arc::default());
1117        warm_cache.layout_wrapped_line("ab", px(0.), &runs, Some(-px(0.)), None);
1118        let warm = warm_cache.layout_wrapped_line("ab", px(0.), &runs, Some(px(0.)), None);
1119
1120        assert_eq!(warm.wrap_boundaries, cold.wrap_boundaries);
1121    }
1122
1123    #[test]
1124    fn test_wrap_cache_distinguishes_max_lines() {
1125        let text = "one two three four five six";
1126        let runs = [FontRun {
1127            len: text.len(),
1128            font_id: FontId(1),
1129        }];
1130        let cache = LineLayoutCache::new(Arc::new(NoopTextSystem::new()), Arc::default());
1131
1132        let unclamped = cache.layout_wrapped_line(text, px(14.), &runs, Some(px(50.)), None);
1133        assert!(unclamped.wrap_boundaries.len() > 1);
1134
1135        let clamped = cache.layout_wrapped_line(text, px(14.), &runs, Some(px(50.)), Some(1));
1136        assert!(clamped.wrap_boundaries.is_empty());
1137    }
1138}