Skip to main content

gpui/text_system/
line_layout.rs

1use crate::{
2    FontId, GlyphId, Hyphens, Pixels, PlatformTextSystem, Point, SharedString, Size, TextWrap,
3    WordBreak, point, px,
4};
5use collections::{FxHashMap, FxHashSet};
6use icu_segmenter::{
7    LineSegmenter,
8    options::{LineBreakOptions, LineBreakWordOption},
9};
10use itertools::Itertools;
11use smallvec::SmallVec;
12use std::{
13    borrow::Borrow,
14    cell::RefCell,
15    hash::{Hash, Hasher},
16    ops::Range,
17    sync::{
18        Arc,
19        atomic::{AtomicUsize, Ordering},
20    },
21};
22
23use super::LineWrapper;
24
25/// vue-native fork: line lookups and the shaping they missed into, process-wide.
26/// One relaxed add per lookup and a clock pair per shape, so an embedder's
27/// frame trace can say how much of a frame went to text shaping.
28static LINE_LOOKUPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
29static LINE_SHAPES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
30static LINE_SHAPE_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
31
32/// vue-native fork: `(lookups, shapes, nanoseconds spent shaping)` since the
33/// process started, over every window's line layout cache. A lookup that is
34/// not a shape was answered from this frame's or the previous frame's cache.
35pub fn line_layout_counters() -> (u64, u64, u64) {
36    (
37        LINE_LOOKUPS.load(Ordering::Relaxed),
38        LINE_SHAPES.load(Ordering::Relaxed),
39        LINE_SHAPE_NANOS.load(Ordering::Relaxed),
40    )
41}
42
43fn count_lookup() {
44    LINE_LOOKUPS.fetch_add(1, Ordering::Relaxed);
45}
46
47fn count_shape(started: std::time::Instant) {
48    LINE_SHAPES.fetch_add(1, Ordering::Relaxed);
49    LINE_SHAPE_NANOS.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
50}
51
52/// A laid out and styled line of text
53#[derive(Default, Debug)]
54pub struct LineLayout {
55    /// The font size for this line
56    pub font_size: Pixels,
57    /// The width of the line
58    pub width: Pixels,
59    /// The ascent of the line
60    pub ascent: Pixels,
61    /// The descent of the line
62    pub descent: Pixels,
63    /// The shaped runs that make up this line
64    pub runs: Vec<ShapedRun>,
65    /// The length of the line in utf-8 bytes
66    pub len: usize,
67}
68
69/// A run of text that has been shaped .
70#[derive(Debug, Clone)]
71pub struct ShapedRun {
72    /// The font id for this run
73    pub font_id: FontId,
74    /// The glyphs that make up this run
75    pub glyphs: Vec<ShapedGlyph>,
76}
77
78/// A single glyph, ready to paint.
79#[derive(Clone, Debug)]
80pub struct ShapedGlyph {
81    /// The ID for this glyph, as determined by the text system.
82    pub id: GlyphId,
83
84    /// The position of this glyph in its containing line.
85    pub position: Point<Pixels>,
86
87    /// The index of this glyph in the original text.
88    pub index: usize,
89
90    /// Whether this glyph is an emoji
91    pub is_emoji: bool,
92}
93
94impl LineLayout {
95    /// The index for the character at the given x coordinate
96    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
97        if x >= self.width {
98            None
99        } else {
100            for run in self.runs.iter().rev() {
101                for glyph in run.glyphs.iter().rev() {
102                    if glyph.position.x <= x {
103                        return Some(glyph.index);
104                    }
105                }
106            }
107            Some(0)
108        }
109    }
110
111    /// closest_index_for_x returns the character boundary closest to the given x coordinate
112    /// (e.g. to handle aligning up/down arrow keys)
113    pub fn closest_index_for_x(&self, x: Pixels) -> usize {
114        let mut prev_index = 0;
115        let mut prev_x = px(0.);
116
117        for run in self.runs.iter() {
118            for glyph in run.glyphs.iter() {
119                if glyph.position.x >= x {
120                    if glyph.position.x - x < x - prev_x {
121                        return glyph.index;
122                    } else {
123                        return prev_index;
124                    }
125                }
126                prev_index = glyph.index;
127                prev_x = glyph.position.x;
128            }
129        }
130
131        if self.len == 1 {
132            if x > self.width / 2. {
133                return 1;
134            } else {
135                return 0;
136            }
137        }
138
139        self.len
140    }
141
142    /// The x position of the character at the given index
143    pub fn x_for_index(&self, index: usize) -> Pixels {
144        for run in &self.runs {
145            for glyph in &run.glyphs {
146                if glyph.index >= index {
147                    return glyph.position.x;
148                }
149            }
150        }
151        self.width
152    }
153
154    /// The corresponding Font at the given index
155    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
156        for run in &self.runs {
157            for glyph in &run.glyphs {
158                if glyph.index >= index {
159                    return Some(run.font_id);
160                }
161            }
162        }
163        None
164    }
165
166    /// Split this layout at a byte index, returning `(prefix, suffix)`.
167    ///
168    /// - `prefix` contains glyphs for bytes `[0, byte_index)` with original positions.
169    ///   Its width equals the x-advance up to the split point.
170    /// - `suffix` contains glyphs for bytes `[byte_index, len)` with positions
171    ///   shifted left so the first glyph starts at x=0, and byte indices rebased to 0.
172    /// - `font_size`, `ascent`, and `descent` are copied to both halves.
173    pub fn split_at(&self, byte_index: usize) -> (LineLayout, LineLayout) {
174        let x_offset = self.x_for_index(byte_index);
175
176        // Partition glyph runs. A single run may contribute glyphs to both halves.
177        let mut left_runs = Vec::new();
178        let mut right_runs = Vec::new();
179
180        for run in &self.runs {
181            let split_pos = run.glyphs.partition_point(|g| g.index < byte_index);
182
183            if split_pos > 0 {
184                left_runs.push(ShapedRun {
185                    font_id: run.font_id,
186                    glyphs: run.glyphs[..split_pos].to_vec(),
187                });
188            }
189
190            if split_pos < run.glyphs.len() {
191                let right_glyphs = run.glyphs[split_pos..]
192                    .iter()
193                    .map(|g| ShapedGlyph {
194                        id: g.id,
195                        position: point(g.position.x - x_offset, g.position.y),
196                        index: g.index - byte_index,
197                        is_emoji: g.is_emoji,
198                    })
199                    .collect();
200                right_runs.push(ShapedRun {
201                    font_id: run.font_id,
202                    glyphs: right_glyphs,
203                });
204            }
205        }
206
207        let left = LineLayout {
208            font_size: self.font_size,
209            width: x_offset,
210            ascent: self.ascent,
211            descent: self.descent,
212            runs: left_runs,
213            len: byte_index,
214        };
215
216        let right = LineLayout {
217            font_size: self.font_size,
218            width: self.width - x_offset,
219            ascent: self.ascent,
220            descent: self.descent,
221            runs: right_runs,
222            len: self.len - byte_index,
223        };
224
225        (left, right)
226    }
227
228    /// vue-native fork: where the line breaks when wrapped at `wrap_width`
229    /// under `rules` (CSS Text 3 §5). A line breaks at its last soft wrap
230    /// opportunity that fits ([`LineLayout::wrap_glyphs`]). A word that fits
231    /// nowhere is broken where it overflows when `rules` allow that
232    /// (`overflow-wrap: break-word | anywhere`, `word-break: break-word`), and
233    /// otherwise overflows its line, which then breaks at the next opportunity.
234    /// `hyphen_width` is the width of the hyphen a soft-hyphen break shows: a
235    /// line that ends in one must fit it.
236    pub(crate) fn wrap(
237        &self,
238        text: &str,
239        wrap_width: Pixels,
240        max_lines: Option<usize>,
241        rules: TextWrap,
242        hyphen_width: Pixels,
243        scratch: &mut WrapScratch,
244    ) -> Wrapping {
245        let mut out = Wrapping::default();
246        // The last opportunity on the current line: the glyph the next line
247        // would start at, its x, where the line's content ends before it
248        // (trailing spaces hang; a hyphen counts), and whether it shows a
249        // hyphen.
250        let mut candidate: Option<(WrapBoundary, Pixels, Pixels, bool)> = None;
251        let mut last_boundary = WrapBoundary {
252            run_ix: 0,
253            glyph_ix: 0,
254        };
255        let mut last_boundary_x = px(0.);
256        // The end of the current line's last glyph that is not a space.
257        let mut content_end = px(0.);
258        // The current line holds a word that may not break and is past the
259        // edge: it breaks at the next opportunity, wherever that is.
260        let mut overflowing = false;
261        let mut widest = px(0.);
262        let full = |out: &Wrapping| {
263            max_lines.is_some_and(|max| out.boundaries.len() >= max.saturating_sub(1))
264        };
265
266        'glyphs: for WrapGlyph {
267            boundary,
268            prev_ch,
269            ch,
270            x,
271            next_x,
272            opportunity,
273        } in self.wrap_glyphs(text, rules, scratch)
274        {
275            if let Some(hyphen) = opportunity {
276                let end = if hyphen {
277                    content_end + hyphen_width
278                } else {
279                    content_end
280                };
281                if overflowing && boundary > last_boundary {
282                    // The overflowing word ends here: so does its line.
283                    if full(&out) {
284                        break 'glyphs;
285                    }
286                    widest = widest.max(end - last_boundary_x);
287                    out.push(boundary, hyphen);
288                    last_boundary = boundary;
289                    last_boundary_x = x;
290                    overflowing = false;
291                    candidate = None;
292                } else if !hyphen || end - last_boundary_x <= wrap_width {
293                    candidate = Some((boundary, x, end, hyphen));
294                }
295            }
296
297            // A space that crosses the edge hangs (CSS Text 3 §4.1.3): the
298            // line breaks before the next word, not before the space, which
299            // would start the next line with it.
300            while !overflowing
301                && next_x - last_boundary_x > wrap_width
302                && boundary > last_boundary
303                && ch != ' '
304            {
305                // When used line_clamp, we should limit the number of lines.
306                if full(&out) {
307                    break 'glyphs;
308                }
309                if let Some((at, at_x, end, hyphen)) = candidate.take() {
310                    widest = widest.max(end - last_boundary_x);
311                    out.push(at, hyphen);
312                    last_boundary = at;
313                    last_boundary_x = at_x;
314                    // The rest of the word may still not fit on the new
315                    // line: looked at again.
316                } else if rules.breaks_words() && !continues_cluster(prev_ch, ch) {
317                    widest = widest.max(x - last_boundary_x);
318                    out.push(boundary, false);
319                    last_boundary = boundary;
320                    last_boundary_x = x;
321                } else {
322                    overflowing = true;
323                }
324            }
325            if ch != ' ' {
326                content_end = next_x;
327            }
328        }
329        widest = widest.max(content_end - last_boundary_x);
330        if widest > wrap_width {
331            out.overflow = widest;
332        }
333        out
334    }
335
336    /// The line's min-content width (CSS Sizing 3 §5.1): its widest stretch
337    /// between two of the soft wrap opportunities [`Self::wrap`] breaks at,
338    /// without the spaces that end it, which hang. Under `overflow-wrap:
339    /// anywhere` (and `word-break: break-word`) a break inside a word counts
340    /// too, so the widest stretch is one character. Wrapped at this width,
341    /// the line breaks at every opportunity it counted.
342    pub(crate) fn min_content_width(
343        &self,
344        text: &str,
345        rules: TextWrap,
346        hyphen_width: Pixels,
347    ) -> Pixels {
348        let mut widest = px(0.);
349        let mut start_x = px(0.);
350        let mut end_x = px(0.);
351        let mut seen_non_whitespace = false;
352        let mut scratch = WrapScratch::default();
353        for WrapGlyph {
354            prev_ch,
355            ch,
356            x,
357            next_x,
358            opportunity,
359            ..
360        } in self.wrap_glyphs(text, rules, &mut scratch)
361        {
362            let opportunity = opportunity.or_else(|| {
363                (rules.min_content_breaks_words()
364                    && seen_non_whitespace
365                    && ch != ' '
366                    && !continues_cluster(prev_ch, ch))
367                .then_some(false)
368            });
369            if let Some(hyphen) = opportunity {
370                let hyphen = if hyphen { hyphen_width } else { px(0.) };
371                widest = widest.max(end_x - start_x + hyphen);
372                start_x = x;
373            }
374            if ch != ' ' {
375                seen_non_whitespace = true;
376                end_x = next_x;
377            }
378        }
379        widest.max(end_x - start_x)
380    }
381
382    /// vue-native fork: the line's glyphs in visual order, one per shaped
383    /// cluster, newlines skipped, each with the soft wrap opportunity before
384    /// it under `rules`.
385    ///
386    /// The opportunities are UAX #14's ([`css_break_indices`], tailored by
387    /// `word-break` and `hyphens`), less those inside a shaped cluster.
388    /// Transitions between line-break segments are detected rather than
389    /// glyph indices matched directly, to accommodate RTL text (a workaround
390    /// for the lack of complete UAX #9 support). The first segment that is
391    /// not a space opens no opportunity: a line never breaks before its first
392    /// word.
393    fn wrap_glyphs<'a>(
394        &'a self,
395        text: &'a str,
396        rules: TextWrap,
397        scratch: &'a mut WrapScratch,
398    ) -> impl Iterator<Item = WrapGlyph> + 'a {
399        // Shaping can combine characters across a line break opportunity, so we ignore those
400        // break opportunities that would separate them.
401        let WrapScratch {
402            glyph_indices,
403            break_indices,
404        } = scratch;
405        glyph_indices.clear();
406        glyph_indices.extend(
407            self.runs
408                .iter()
409                .flat_map(|run| run.glyphs.iter().map(|glyph| glyph.index)),
410        );
411        break_indices.clear();
412        break_indices
413            .extend(css_break_indices(text, rules).filter(|index| glyph_indices.contains(index)));
414        let break_indices = &*break_indices;
415        let mut glyphs = self
416            .runs
417            .iter()
418            .enumerate()
419            .flat_map(move |(run_ix, run)| {
420                run.glyphs.iter().enumerate().map(move |(glyph_ix, glyph)| {
421                    (
422                        WrapBoundary { run_ix, glyph_ix },
423                        glyph.index,
424                        glyph.position.x,
425                    )
426                })
427            })
428            .dedup_by(|(_, previous_index, ..), (_, index, ..)| previous_index == index)
429            .peekable();
430        let mut current_segment: Option<Range<usize>> = None;
431        let mut prev_ch = '\0';
432        std::iter::from_fn(move || {
433            loop {
434                let (boundary, index, x) = glyphs.next()?;
435                let next_x = glyphs.peek().map_or(self.width, |(_, _, x)| *x);
436                let ch = text[index..].chars().next().unwrap_or(' ');
437                if ch == '\n' {
438                    continue;
439                }
440                let mut opportunity = None;
441                if ch != ' '
442                    && current_segment
443                        .as_ref()
444                        .is_none_or(|segment| !segment.contains(&index))
445                {
446                    let segment =
447                        break_indices.partition_point(|break_index| *break_index <= index);
448                    let start = segment
449                        .checked_sub(1)
450                        .and_then(|previous| break_indices.get(previous))
451                        .copied()
452                        .unwrap_or(0);
453                    let end = break_indices.get(segment).copied().unwrap_or(text.len());
454                    if current_segment.is_some() {
455                        // A break after a soft hyphen shows a hyphen; under
456                        // `hyphens: none` there is no such break.
457                        opportunity = Some(text[..start].ends_with('\u{AD}'));
458                    }
459                    current_segment = Some(start..end);
460                }
461                let glyph = WrapGlyph {
462                    boundary,
463                    prev_ch,
464                    ch,
465                    x,
466                    next_x,
467                    opportunity,
468                };
469                prev_ch = ch;
470                return Some(glyph);
471            }
472        })
473    }
474}
475
476/// vue-native fork: one glyph of [`LineLayout::wrap_glyphs`].
477struct WrapGlyph {
478    boundary: WrapBoundary,
479    /// The character of the glyph before, `'\0'` for the first.
480    prev_ch: char,
481    ch: char,
482    x: Pixels,
483    /// Where the next glyph starts, or the line's width after the last.
484    next_x: Pixels,
485    /// A soft wrap opportunity before this glyph: `Some(true)` when the
486    /// break shows a hyphen.
487    opportunity: Option<bool>,
488}
489
490/// vue-native fork: what [`LineLayout::wrap`] decided for one line of text.
491#[derive(Clone, Debug, Default)]
492pub(crate) struct Wrapping {
493    pub(crate) boundaries: SmallVec<[WrapBoundary; 1]>,
494    /// The boundaries a soft hyphen made, as indices into `boundaries`: the
495    /// line before each one ends with a visible hyphen.
496    pub(crate) hyphens: SmallVec<[usize; 1]>,
497    /// The widest line, trailing spaces not counted, when one is wider than
498    /// the wrap width (a word that may not break). Zero otherwise.
499    pub(crate) overflow: Pixels,
500}
501
502impl Wrapping {
503    fn push(&mut self, at: WrapBoundary, hyphen: bool) {
504        if hyphen {
505            self.hyphens.push(self.boundaries.len());
506        }
507        self.boundaries.push(at);
508    }
509}
510
511/// vue-native fork: the byte offsets in `text` a line may break before under
512/// `rules`: UAX #14's opportunities ([`LineWrapper::break_indices`]), tailored
513/// by CSS Text 3:
514/// - `word-break: break-all`: between any two letters, though not before
515///   punctuation that never starts a line; `keep-all`: no break between two
516///   CJK letters (UAX #14's own tailorings, the same as CSS's);
517/// - after a soft hyphen (U+00AD) only under `hyphens: manual`;
518/// - after a zero width space (U+200B), as UAX #14 has it.
519///
520/// No opportunity splits a grapheme cluster.
521fn css_break_indices(text: &str, rules: TextWrap) -> impl Iterator<Item = usize> + '_ {
522    let word_option = match rules.word_break {
523        WordBreak::BreakAll => Some(LineBreakWordOption::BreakAll),
524        WordBreak::KeepAll => Some(LineBreakWordOption::KeepAll),
525        WordBreak::Normal | WordBreak::BreakWord => None,
526    };
527    let indices: Box<dyn Iterator<Item = usize> + '_> = match word_option {
528        None => Box::new(LineWrapper::break_indices(text)),
529        Some(word_option) => {
530            let mut options = LineBreakOptions::default();
531            options.word_option = Some(word_option);
532            Box::new(LineSegmenter::new_for_non_complex_scripts(options).segment_str(text))
533        }
534    };
535    indices.filter(move |index| {
536        rules.hyphens == Hyphens::Manual || !text[..*index].ends_with('\u{AD}')
537    })
538}
539
540/// Does `ch` belong to the grapheme cluster `prev` is in? A combining mark,
541/// a joiner, a variation selector, an emoji modifier or tag, or anything
542/// after a zero width joiner. A shaper usually gives a cluster one glyph, but
543/// not always; a break between two of its glyphs would split a character.
544/// Used where a line breaks inside a word (`overflow-wrap`), which UAX #14's
545/// opportunities say nothing about.
546fn continues_cluster(prev: char, ch: char) -> bool {
547    prev == '\u{200D}'
548        || matches!(
549            ch,
550            '\u{0300}'..='\u{036F}'
551                | '\u{0483}'..='\u{0489}'
552                | '\u{0591}'..='\u{05BD}'
553                | '\u{0610}'..='\u{061A}'
554                | '\u{064B}'..='\u{065F}'
555                | '\u{0900}'..='\u{0903}'
556                | '\u{093A}'..='\u{094F}'
557                | '\u{1AB0}'..='\u{1AFF}'
558                | '\u{1DC0}'..='\u{1DFF}'
559                | '\u{200C}'..='\u{200D}'
560                | '\u{20D0}'..='\u{20FF}'
561                | '\u{FE00}'..='\u{FE0F}'
562                | '\u{FE20}'..='\u{FE2F}'
563                | '\u{1F3FB}'..='\u{1F3FF}'
564                | '\u{E0020}'..='\u{E007F}'
565                | '\u{E0100}'..='\u{E01EF}'
566        )
567}
568
569/// A line of text that has been wrapped to fit a given width
570#[derive(Default, Debug)]
571pub struct WrappedLineLayout {
572    /// The line layout, pre-wrapping.
573    pub unwrapped_layout: Arc<LineLayout>,
574
575    /// The boundaries at which the line was wrapped
576    pub wrap_boundaries: SmallVec<[WrapBoundary; 1]>,
577
578    /// The width of the line, if it was wrapped
579    pub wrap_width: Option<Pixels>,
580
581    /// vue-native fork: the wrap boundaries a soft hyphen made, as indices
582    /// into `wrap_boundaries`. The line before each ends with a hyphen.
583    pub(crate) hyphen_breaks: SmallVec<[usize; 1]>,
584
585    /// vue-native fork: the widest line, when a word that may not break made
586    /// it wider than the wrap width. Zero otherwise.
587    pub(crate) overflow_width: Pixels,
588}
589
590/// A boundary at which a line was wrapped
591#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
592pub struct WrapBoundary {
593    /// The index in the run just before the line was wrapped
594    pub run_ix: usize,
595    /// The index of the glyph just before the line was wrapped
596    pub glyph_ix: usize,
597}
598
599impl WrappedLineLayout {
600    /// The length of the underlying text, in utf8 bytes.
601    #[allow(clippy::len_without_is_empty)]
602    pub fn len(&self) -> usize {
603        self.unwrapped_layout.len
604    }
605
606    /// The width of this line, in pixels, whether or not it was wrapped.
607    pub fn width(&self) -> Pixels {
608        self.wrap_width
609            .unwrap_or(Pixels::MAX)
610            .min(self.unwrapped_layout.width)
611            // A line that overflows the wrap width is as wide as it is.
612            .max(self.overflow_width)
613    }
614
615    /// The size of the whole wrapped text, for the given line_height.
616    /// can span multiple lines if there are multiple wrap boundaries.
617    pub fn size(&self, line_height: Pixels) -> Size<Pixels> {
618        Size {
619            width: self.width(),
620            height: line_height * (self.wrap_boundaries.len() + 1),
621        }
622    }
623
624    /// The ascent of a line in this layout
625    pub fn ascent(&self) -> Pixels {
626        self.unwrapped_layout.ascent
627    }
628
629    /// The descent of a line in this layout
630    pub fn descent(&self) -> Pixels {
631        self.unwrapped_layout.descent
632    }
633
634    /// The wrap boundaries in this layout
635    pub fn wrap_boundaries(&self) -> &[WrapBoundary] {
636        &self.wrap_boundaries
637    }
638
639    /// The font size of this layout
640    pub fn font_size(&self) -> Pixels {
641        self.unwrapped_layout.font_size
642    }
643
644    /// The runs in this layout, sans wrapping
645    pub fn runs(&self) -> &[ShapedRun] {
646        &self.unwrapped_layout.runs
647    }
648
649    /// The index corresponding to a given position in this layout for the given line height.
650    ///
651    /// See also [`Self::closest_index_for_position`].
652    pub fn index_for_position(
653        &self,
654        position: Point<Pixels>,
655        line_height: Pixels,
656    ) -> Result<usize, usize> {
657        self._index_for_position(position, line_height, false)
658    }
659
660    /// The closest index to a given position in this layout for the given line height.
661    ///
662    /// Closest means the character boundary closest to the given position.
663    ///
664    /// See also [`LineLayout::closest_index_for_x`].
665    pub fn closest_index_for_position(
666        &self,
667        position: Point<Pixels>,
668        line_height: Pixels,
669    ) -> Result<usize, usize> {
670        self._index_for_position(position, line_height, true)
671    }
672
673    fn _index_for_position(
674        &self,
675        position: Point<Pixels>,
676        line_height: Pixels,
677        closest: bool,
678    ) -> Result<usize, usize> {
679        let wrapped_line_ix = (position.y / line_height) as usize;
680
681        let wrapped_line_start_index;
682        let wrapped_line_start_x;
683        if wrapped_line_ix > 0 {
684            let Some(line_start_boundary) = self.wrap_boundaries.get(wrapped_line_ix - 1) else {
685                return Err(0);
686            };
687            let run = &self.unwrapped_layout.runs[line_start_boundary.run_ix];
688            let glyph = &run.glyphs[line_start_boundary.glyph_ix];
689            wrapped_line_start_index = glyph.index;
690            wrapped_line_start_x = glyph.position.x;
691        } else {
692            wrapped_line_start_index = 0;
693            wrapped_line_start_x = Pixels::ZERO;
694        };
695
696        let wrapped_line_end_index;
697        let wrapped_line_end_x;
698        if wrapped_line_ix < self.wrap_boundaries.len() {
699            let next_wrap_boundary_ix = wrapped_line_ix;
700            let next_wrap_boundary = self.wrap_boundaries[next_wrap_boundary_ix];
701            let run = &self.unwrapped_layout.runs[next_wrap_boundary.run_ix];
702            let glyph = &run.glyphs[next_wrap_boundary.glyph_ix];
703            wrapped_line_end_index = glyph.index;
704            wrapped_line_end_x = glyph.position.x;
705        } else {
706            wrapped_line_end_index = self.unwrapped_layout.len;
707            wrapped_line_end_x = self.unwrapped_layout.width;
708        };
709
710        let mut position_in_unwrapped_line = position;
711        position_in_unwrapped_line.x += wrapped_line_start_x;
712        if position_in_unwrapped_line.x < wrapped_line_start_x {
713            Err(wrapped_line_start_index)
714        } else if position_in_unwrapped_line.x >= wrapped_line_end_x {
715            Err(wrapped_line_end_index)
716        } else {
717            if closest {
718                Ok(self
719                    .unwrapped_layout
720                    .closest_index_for_x(position_in_unwrapped_line.x))
721            } else {
722                // The shaper can place a trailing zero-width wrap boundary glyph slightly past
723                // the line's width, so the row can extend past where `index_for_x` has glyphs.
724                self.unwrapped_layout
725                    .index_for_x(position_in_unwrapped_line.x)
726                    .ok_or(wrapped_line_end_index)
727            }
728        }
729    }
730
731    /// Returns the pixel position for the given byte index.
732    pub fn position_for_index(&self, index: usize, line_height: Pixels) -> Option<Point<Pixels>> {
733        let mut line_start_ix = 0;
734        let line_end_indices = self
735            .wrap_boundaries
736            .iter()
737            .map(|wrap_boundary| {
738                let run = &self.unwrapped_layout.runs[wrap_boundary.run_ix];
739                let glyph = &run.glyphs[wrap_boundary.glyph_ix];
740                glyph.index
741            })
742            .chain([self.len()])
743            .enumerate();
744        for (ix, line_end_ix) in line_end_indices {
745            let line_y = ix as f32 * line_height;
746            if index < line_start_ix {
747                break;
748            } else if index > line_end_ix {
749                line_start_ix = line_end_ix;
750                continue;
751            } else {
752                let line_start_x = self.unwrapped_layout.x_for_index(line_start_ix);
753                let x = self.unwrapped_layout.x_for_index(index) - line_start_x;
754                return Some(point(x, line_y));
755            }
756        }
757
758        None
759    }
760}
761
762pub(crate) struct LineLayoutCache {
763    state: RefCell<LineLayoutCacheState>,
764    wrap_scratch: RefCell<WrapScratch>,
765    platform_text_system: Arc<dyn PlatformTextSystem>,
766    /// Advances when [`TextSystem::add_fonts`] successfully changes the font database.
767    font_generation: Arc<AtomicUsize>,
768    /// Records the generation represented by both frame caches.
769    cached_font_generation: AtomicUsize,
770}
771
772#[derive(Default)]
773pub(crate) struct WrapScratch {
774    glyph_indices: FxHashSet<usize>,
775    break_indices: Vec<usize>,
776}
777
778#[derive(Default)]
779struct LineLayoutCacheState {
780    previous_frame: FrameCache,
781    current_frame: FrameCache,
782}
783
784#[derive(Default)]
785struct FrameCache {
786    lines: FxHashMap<Arc<CacheKey>, Arc<LineLayout>>,
787    wrapped_lines: FxHashMap<Arc<CacheKey>, Arc<WrappedLineLayout>>,
788    used_lines: Vec<Arc<CacheKey>>,
789    used_wrapped_lines: Vec<Arc<CacheKey>>,
790}
791
792#[derive(Clone, Default)]
793pub(crate) struct LineLayoutIndex {
794    font_generation: usize,
795    lines_index: usize,
796    wrapped_lines_index: usize,
797}
798
799impl LineLayoutCache {
800    pub fn new(
801        platform_text_system: Arc<dyn PlatformTextSystem>,
802        font_generation: Arc<AtomicUsize>,
803    ) -> Self {
804        let cached_font_generation = font_generation.load(Ordering::Acquire);
805        Self {
806            state: RefCell::default(),
807            wrap_scratch: RefCell::default(),
808            platform_text_system,
809            font_generation,
810            cached_font_generation: AtomicUsize::new(cached_font_generation),
811        }
812    }
813
814    pub fn layout_index(&self) -> LineLayoutIndex {
815        let font_generation = self.clear_if_font_generation_changed();
816        let state = self.state.borrow();
817        let frame = &state.current_frame;
818        LineLayoutIndex {
819            font_generation,
820            lines_index: frame.used_lines.len(),
821            wrapped_lines_index: frame.used_wrapped_lines.len(),
822        }
823    }
824
825    pub fn reuse_layouts(&self, range: Range<LineLayoutIndex>) {
826        let font_generation = self.clear_if_font_generation_changed();
827        if range.start.font_generation != font_generation
828            || range.end.font_generation != font_generation
829        {
830            return;
831        }
832        let mut state = self.state.borrow_mut();
833        let LineLayoutCacheState {
834            previous_frame,
835            current_frame,
836        } = &mut *state;
837
838        for key in &previous_frame.used_lines[range.start.lines_index..range.end.lines_index] {
839            if let Some((key, line)) = previous_frame.lines.remove_entry(key) {
840                current_frame.lines.insert(key, line);
841            }
842            current_frame.used_lines.push(key.clone());
843        }
844
845        for key in &previous_frame.used_wrapped_lines
846            [range.start.wrapped_lines_index..range.end.wrapped_lines_index]
847        {
848            if let Some((key, line)) = previous_frame.wrapped_lines.remove_entry(key) {
849                current_frame.wrapped_lines.insert(key, line);
850            }
851            current_frame.used_wrapped_lines.push(key.clone());
852        }
853    }
854
855    pub fn truncate_layouts(&self, index: LineLayoutIndex) {
856        let font_generation = self.clear_if_font_generation_changed();
857        if index.font_generation != font_generation {
858            return;
859        }
860        let mut state = self.state.borrow_mut();
861        let current_frame = &mut state.current_frame;
862        current_frame.used_lines.truncate(index.lines_index);
863        current_frame
864            .used_wrapped_lines
865            .truncate(index.wrapped_lines_index);
866    }
867
868    pub fn finish_frame(&self) {
869        let _font_generation = self.clear_if_font_generation_changed();
870        let LineLayoutCacheState {
871            previous_frame,
872            current_frame,
873        } = &mut *self.state.borrow_mut();
874        std::mem::swap(previous_frame, current_frame);
875        current_frame.lines.clear();
876        current_frame.wrapped_lines.clear();
877        current_frame.used_lines.clear();
878        current_frame.used_wrapped_lines.clear();
879    }
880
881    /// vue-native fork: the width of the hyphen a soft-hyphen break shows,
882    /// in the first run's font. Zero when no break can show one.
883    fn hyphen_width(
884        &self,
885        text: &str,
886        font_size: Pixels,
887        runs: &[FontRun],
888        rules: TextWrap,
889    ) -> Pixels {
890        if rules.hyphens != Hyphens::Manual || !text.contains('\u{AD}') {
891            return px(0.);
892        }
893        let Some(font_id) = runs.first().map(|run| run.font_id) else {
894            return px(0.);
895        };
896        let Some(glyph) = self.platform_text_system.glyph_for_char(font_id, '-') else {
897            return px(0.);
898        };
899        let Ok(advance) = self.platform_text_system.advance(font_id, glyph) else {
900            return px(0.);
901        };
902        let units_per_em = self.platform_text_system.font_metrics(font_id).units_per_em as f32;
903        px(advance.width / units_per_em * font_size.0)
904    }
905
906    pub fn layout_wrapped_line<Text>(
907        &self,
908        text: Text,
909        font_size: Pixels,
910        runs: &[FontRun],
911        wrap_width: Option<Pixels>,
912        max_lines: Option<usize>,
913        rules: TextWrap,
914    ) -> Arc<WrappedLineLayout>
915    where
916        Text: AsRef<str>,
917        SharedString: From<Text>,
918    {
919        let _font_generation = self.clear_if_font_generation_changed();
920        let key = &CacheKeyRef {
921            text: text.as_ref(),
922            font_size,
923            runs,
924            wrap_width,
925            force_width: None,
926            wrap: rules,
927        } as &dyn AsCacheKeyRef;
928
929        let state = self.state.borrow();
930        if let Some(layout) = state.current_frame.wrapped_lines.get(key) {
931            return layout.clone();
932        }
933        drop(state);
934
935        let mut state = self.state.borrow_mut();
936        let previous_frame_entry = state.previous_frame.wrapped_lines.remove_entry(key);
937        if let Some((key, layout)) = previous_frame_entry {
938            state
939                .current_frame
940                .wrapped_lines
941                .insert(key.clone(), layout.clone());
942            state.current_frame.used_wrapped_lines.push(key);
943            layout
944        } else {
945            drop(state);
946            let text = SharedString::from(text);
947            let unwrapped_layout = self.layout_line::<&SharedString>(&text, font_size, runs, None);
948            let wrapping = if let Some(wrap_width) = wrap_width {
949                let hyphen_width = self.hyphen_width(&text, font_size, runs, rules);
950                unwrapped_layout.wrap(
951                    text.as_ref(),
952                    wrap_width,
953                    max_lines,
954                    rules,
955                    hyphen_width,
956                    &mut self.wrap_scratch.borrow_mut(),
957                )
958            } else {
959                Wrapping::default()
960            };
961            let layout = Arc::new(WrappedLineLayout {
962                unwrapped_layout,
963                wrap_boundaries: wrapping.boundaries,
964                wrap_width,
965                hyphen_breaks: wrapping.hyphens,
966                overflow_width: wrapping.overflow,
967            });
968            let key = Arc::new(CacheKey {
969                text,
970                font_size,
971                runs: SmallVec::from(runs),
972                wrap_width,
973                force_width: None,
974                wrap: rules,
975            });
976
977            let mut state = self.state.borrow_mut();
978            state
979                .current_frame
980                .wrapped_lines
981                .insert(key.clone(), layout.clone());
982            state.current_frame.used_wrapped_lines.push(key);
983
984            layout
985        }
986    }
987
988    pub fn layout_line<Text>(
989        &self,
990        text: Text,
991        font_size: Pixels,
992        runs: &[FontRun],
993        force_width: Option<Pixels>,
994    ) -> Arc<LineLayout>
995    where
996        Text: AsRef<str>,
997        SharedString: From<Text>,
998    {
999        let _font_generation = self.clear_if_font_generation_changed();
1000        let key = &CacheKeyRef {
1001            text: text.as_ref(),
1002            font_size,
1003            runs,
1004            wrap_width: None,
1005            force_width,
1006            wrap: TextWrap::default(),
1007        } as &dyn AsCacheKeyRef;
1008
1009        count_lookup();
1010        let state = self.state.borrow();
1011        if let Some(layout) = state.current_frame.lines.get(key) {
1012            return layout.clone();
1013        }
1014        drop(state);
1015
1016        let mut state = self.state.borrow_mut();
1017        let LineLayoutCacheState {
1018            previous_frame,
1019            current_frame,
1020        } = &mut *state;
1021        if let Some((key, layout)) = previous_frame.lines.remove_entry(key) {
1022            current_frame.lines.insert(key.clone(), layout.clone());
1023            current_frame.used_lines.push(key);
1024            layout
1025        } else {
1026            let text = SharedString::from(text);
1027            let shaping = std::time::Instant::now();
1028            let mut layout = self
1029                .platform_text_system
1030                .layout_line(&text, font_size, runs);
1031            count_shape(shaping);
1032
1033            // Spacing first: `force_width` assigns each cluster an ABSOLUTE
1034            // cell, so it has to see the positions it is going to overwrite,
1035            // not ones already widened by tracking.
1036            apply_spacing_to_layout(&mut layout, &text, runs);
1037            if let Some(force_width) = force_width {
1038                apply_force_width_to_layout(&mut layout, force_width);
1039            }
1040
1041            let key = Arc::new(CacheKey {
1042                text,
1043                font_size,
1044                runs: SmallVec::from(runs),
1045                wrap_width: None,
1046                force_width,
1047                wrap: TextWrap::default(),
1048            });
1049            let layout = Arc::new(layout);
1050            current_frame.lines.insert(key.clone(), layout.clone());
1051            current_frame.used_lines.push(key);
1052            layout
1053        }
1054    }
1055
1056    fn clear_if_font_generation_changed(&self) -> usize {
1057        let font_generation = self.font_generation.load(Ordering::Acquire);
1058        if self.cached_font_generation.load(Ordering::Acquire) == font_generation {
1059            return font_generation;
1060        }
1061
1062        let mut state = self.state.borrow_mut();
1063        if self.cached_font_generation.load(Ordering::Acquire) == font_generation {
1064            return font_generation;
1065        }
1066
1067        *state = LineLayoutCacheState::default();
1068        self.cached_font_generation
1069            .store(font_generation, Ordering::Release);
1070        font_generation
1071    }
1072}
1073
1074/// CSS `letter-spacing` and `word-spacing`, applied to an already-shaped line.
1075///
1076/// A post-pass rather than a shaper feature, and deliberately so: every
1077/// platform text system gpui has (DirectWrite, CoreText, cosmic-text) hands
1078/// back absolute glyph POSITIONS, so widening the gaps between them is the same
1079/// arithmetic on all three and needs no per-backend work at all. Painting,
1080/// hit-testing, alignment, `split_at` and `compute_wrap_boundaries` read those
1081/// same positions and `LineLayout::width`, so they all follow for free.
1082///
1083/// The unit CSS spaces is the *typographic character unit*, not the glyph: a
1084/// combining mark or a ligature component must not be pushed away from what it
1085/// belongs to. `ShapedGlyph::index` is the cluster's start offset and every
1086/// glyph in a cluster shares it, so a change of `index` IS a cluster boundary.
1087///
1088/// Tracking is added AFTER each unit, including the last, which is what Chrome
1089/// does and what makes a tracked run measure `n * tracking` wider.
1090fn apply_spacing_to_layout(layout: &mut LineLayout, text: &str, runs: &[FontRun]) {
1091    if runs
1092        .iter()
1093        .all(|run| run.tracking == px(0.) && run.word_spacing == px(0.))
1094    {
1095        return;
1096    }
1097
1098    // `runs` are byte spans over `text`, and a shaped run is not necessarily
1099    // the same span (the platform may split one on a font fallback), so the
1100    // spacing in force is looked up by the glyph's own byte offset.
1101    let spacing_at = |offset: usize| {
1102        let mut start = 0;
1103        for run in runs {
1104            if offset < start + run.len {
1105                return (run.tracking, run.word_spacing);
1106            }
1107            start += run.len;
1108        }
1109        runs.last()
1110            .map(|run| (run.tracking, run.word_spacing))
1111            .unwrap_or((px(0.), px(0.)))
1112    };
1113
1114    let mut extra = px(0.);
1115    let mut previous_index: Option<usize> = None;
1116    for run in layout.runs.iter_mut() {
1117        for glyph in run.glyphs.iter_mut() {
1118            if previous_index != Some(glyph.index) {
1119                if let Some(previous) = previous_index {
1120                    let (tracking, word_spacing) = spacing_at(previous);
1121                    extra += tracking;
1122                    // CSS adds word spacing at each word-separator character,
1123                    // which for every script gpui shapes is U+0020.
1124                    if text[previous..].starts_with(' ') {
1125                        extra += word_spacing;
1126                    }
1127                }
1128                previous_index = Some(glyph.index);
1129            }
1130            glyph.position.x += extra;
1131        }
1132    }
1133
1134    if let Some(previous) = previous_index {
1135        let (tracking, word_spacing) = spacing_at(previous);
1136        extra += tracking;
1137        if text[previous..].starts_with(' ') {
1138            extra += word_spacing;
1139        }
1140    }
1141    layout.width += extra;
1142}
1143
1144// Combining marks (e.g. Thai vowel signs, Arabic diacritics) are shaped by
1145// HarfBuzz at the same x position as their base character. The force-width
1146// loop must not advance the cell counter for these zero-advance glyphs,
1147// otherwise they get displaced into the next cell. We detect them by checking
1148// whether shaped x has advanced by at least half a cell beyond the last base.
1149fn apply_force_width_to_layout(layout: &mut LineLayout, force_width: Pixels) {
1150    let mut glyph_pos: usize = 0;
1151    // NEG_INFINITY ensures the first glyph is always classified as a base.
1152    let mut last_base_shaped_x = px(f32::NEG_INFINITY);
1153    let mut last_base_actual_x = px(0.);
1154
1155    for run in layout.runs.iter_mut() {
1156        for glyph in run.glyphs.iter_mut() {
1157            let shaped_x = glyph.position.x;
1158
1159            if shaped_x > last_base_shaped_x + force_width * 0.5 {
1160                let forced_x = glyph_pos * force_width;
1161                if (shaped_x - forced_x).abs() > px(1.) {
1162                    glyph.position.x = forced_x;
1163                }
1164                last_base_shaped_x = shaped_x;
1165                last_base_actual_x = glyph.position.x;
1166                glyph_pos += 1;
1167            } else {
1168                glyph.position.x = last_base_actual_x + (shaped_x - last_base_shaped_x);
1169            }
1170        }
1171    }
1172}
1173
1174/// A run of text with a single font.
1175#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
1176#[expect(missing_docs)]
1177pub struct FontRun {
1178    pub len: usize,
1179    pub font_id: FontId,
1180    /// Extra space after each typographic character unit — CSS
1181    /// `letter-spacing`. Part of the run, and therefore part of every layout
1182    /// CACHE KEY, because two runs that differ only in tracking are two
1183    /// different layouts.
1184    pub tracking: Pixels,
1185    /// Extra space after each word separator — CSS `word-spacing`.
1186    pub word_spacing: Pixels,
1187}
1188
1189trait AsCacheKeyRef {
1190    fn as_cache_key_ref(&self) -> CacheKeyRef<'_>;
1191}
1192
1193#[derive(Clone, Debug, Eq)]
1194struct CacheKey {
1195    text: SharedString,
1196    font_size: Pixels,
1197    runs: SmallVec<[FontRun; 1]>,
1198    wrap_width: Option<Pixels>,
1199    force_width: Option<Pixels>,
1200    /// vue-native fork: the same text wraps differently under other rules.
1201    wrap: TextWrap,
1202}
1203
1204#[derive(Copy, Clone, PartialEq, Eq, Hash)]
1205struct CacheKeyRef<'a> {
1206    text: &'a str,
1207    font_size: Pixels,
1208    runs: &'a [FontRun],
1209    wrap_width: Option<Pixels>,
1210    force_width: Option<Pixels>,
1211    wrap: TextWrap,
1212}
1213
1214impl PartialEq for dyn AsCacheKeyRef + '_ {
1215    fn eq(&self, other: &dyn AsCacheKeyRef) -> bool {
1216        self.as_cache_key_ref() == other.as_cache_key_ref()
1217    }
1218}
1219
1220impl Eq for dyn AsCacheKeyRef + '_ {}
1221
1222impl Hash for dyn AsCacheKeyRef + '_ {
1223    fn hash<H: Hasher>(&self, state: &mut H) {
1224        self.as_cache_key_ref().hash(state)
1225    }
1226}
1227
1228impl AsCacheKeyRef for CacheKey {
1229    fn as_cache_key_ref(&self) -> CacheKeyRef<'_> {
1230        CacheKeyRef {
1231            text: &self.text,
1232            font_size: self.font_size,
1233            runs: self.runs.as_slice(),
1234            wrap_width: self.wrap_width,
1235            force_width: self.force_width,
1236            wrap: self.wrap,
1237        }
1238    }
1239}
1240
1241impl PartialEq for CacheKey {
1242    fn eq(&self, other: &Self) -> bool {
1243        self.as_cache_key_ref().eq(&other.as_cache_key_ref())
1244    }
1245}
1246
1247impl Hash for CacheKey {
1248    fn hash<H: Hasher>(&self, state: &mut H) {
1249        self.as_cache_key_ref().hash(state);
1250    }
1251}
1252
1253impl<'a> Borrow<dyn AsCacheKeyRef + 'a> for Arc<CacheKey> {
1254    fn borrow(&self) -> &(dyn AsCacheKeyRef + 'a) {
1255        self.as_ref() as &dyn AsCacheKeyRef
1256    }
1257}
1258
1259impl AsCacheKeyRef for CacheKeyRef<'_> {
1260    fn as_cache_key_ref(&self) -> CacheKeyRef<'_> {
1261        *self
1262    }
1263}
1264
1265#[cfg(test)]
1266mod tests {
1267    use super::*;
1268    use crate::{
1269        GlyphId, NoopTextSystem, OverflowWrap, TextRun, TextSystem, WindowTextSystem, font,
1270    };
1271
1272    impl LineLayout {
1273        /// Upstream's wrapping entry point, as these tests call it: gpui's
1274        /// own rules ([`TextWrap::BREAK_WORD`]), no soft hyphens shown.
1275        fn compute_wrap_boundaries(
1276            &self,
1277            text: &str,
1278            wrap_width: Pixels,
1279            max_lines: Option<usize>,
1280            scratch: &mut WrapScratch,
1281        ) -> SmallVec<[WrapBoundary; 1]> {
1282            self.wrap(
1283                text,
1284                wrap_width,
1285                max_lines,
1286                TextWrap::BREAK_WORD,
1287                px(0.),
1288                scratch,
1289            )
1290            .boundaries
1291        }
1292    }
1293
1294    #[test]
1295    fn shape_line_shares_its_text_with_the_layout_cache() {
1296        let text_system =
1297            WindowTextSystem::new(Arc::new(TextSystem::new(Arc::new(NoopTextSystem::new()))));
1298        // Long enough to be stored on the heap rather than inline.
1299        let text = SharedString::from("let value = compute_something(argument_one, argument_two);");
1300        let runs = [TextRun {
1301            len: text.len(),
1302            font: font(".ZedMono"),
1303            ..Default::default()
1304        }];
1305
1306        text_system.shape_line(text.clone(), px(14.), &runs, None);
1307        let state = text_system.line_layout_cache.state.borrow();
1308        let (key, _) = state.current_frame.lines.iter().next().unwrap();
1309        assert_eq!(key.text.as_ptr(), text.as_ptr());
1310    }
1311
1312    fn glyph_at(x: f32, index: usize) -> ShapedGlyph {
1313        ShapedGlyph {
1314            id: GlyphId(0),
1315            position: point(px(x), px(0.)),
1316            index,
1317            is_emoji: false,
1318        }
1319    }
1320
1321    fn make_layout(glyphs: Vec<ShapedGlyph>) -> LineLayout {
1322        LineLayout {
1323            font_size: px(16.),
1324            width: px(100.),
1325            ascent: px(12.),
1326            descent: px(4.),
1327            runs: vec![ShapedRun {
1328                font_id: FontId(0),
1329                glyphs,
1330            }],
1331            len: 0,
1332        }
1333    }
1334
1335    fn glyph_x_positions(layout: &LineLayout) -> Vec<f32> {
1336        layout.runs[0]
1337            .glyphs
1338            .iter()
1339            .map(|g| f32::from(g.position.x))
1340            .collect()
1341    }
1342
1343    #[test]
1344    fn test_wrap_preserves_shaped_clusters() {
1345        let mut layout = make_layout(vec![
1346            glyph_at(0., 0),
1347            glyph_at(5., 0),
1348            glyph_at(10., 3),
1349            glyph_at(15., 3),
1350        ]);
1351        layout.width = px(20.);
1352        layout.len = "你好".len();
1353        assert_eq!(
1354            layout
1355                .compute_wrap_boundaries("你好", px(15.), None, &mut WrapScratch::default())
1356                .as_slice(),
1357            &[WrapBoundary {
1358                run_ix: 0,
1359                glyph_ix: 2
1360            }],
1361        );
1362
1363        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(10., 0)]);
1364        layout.width = px(20.);
1365        layout.len = 1;
1366        assert!(
1367            layout
1368                .compute_wrap_boundaries("a", px(10.), None, &mut WrapScratch::default())
1369                .is_empty()
1370        );
1371    }
1372
1373    #[test]
1374    fn test_wrap_right_to_left_text() {
1375        for (text, indices, expected_boundaries) in [
1376            ("אבג דהו", vec![11, 9, 7, 6, 4, 2, 0], vec![4]),
1377            ("a אבג b", vec![0, 1, 6, 4, 2, 8, 9], vec![2, 6]),
1378        ] {
1379            let mut layout = make_layout(
1380                indices
1381                    .iter()
1382                    .enumerate()
1383                    .map(|(position, index)| glyph_at(position as f32 * 10., *index))
1384                    .collect(),
1385            );
1386            layout.width = px(indices.len() as f32 * 10.);
1387            layout.len = text.len();
1388            assert_eq!(
1389                layout.compute_wrap_boundaries(text, px(40.), None, &mut WrapScratch::default()),
1390                expected_boundaries
1391                    .into_iter()
1392                    .map(|glyph_ix| WrapBoundary {
1393                        run_ix: 0,
1394                        glyph_ix
1395                    })
1396                    .collect::<SmallVec<[WrapBoundary; 1]>>(),
1397                "{text:?}",
1398            );
1399        }
1400    }
1401
1402    #[test]
1403    fn test_wrap_ignores_breaks_inside_shaped_clusters() {
1404        let text = "x a-bcde";
1405        let mut layout = make_layout(
1406            [0, 1, 2, 5, 6, 7]
1407                .into_iter()
1408                .map(|index| glyph_at(index as f32 * 10., index))
1409                .collect(),
1410        );
1411        layout.width = px(80.);
1412        layout.len = text.len();
1413        assert_eq!(
1414            layout
1415                .compute_wrap_boundaries(text, px(60.), None, &mut WrapScratch::default())
1416                .as_slice(),
1417            &[WrapBoundary {
1418                run_ix: 0,
1419                glyph_ix: 2
1420            }],
1421        );
1422    }
1423
1424    #[test]
1425    fn test_force_width_latin_unchanged() {
1426        let cell_width = px(8.);
1427        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(8., 1), glyph_at(16., 2)]);
1428
1429        apply_force_width_to_layout(&mut layout, cell_width);
1430
1431        let positions = glyph_x_positions(&layout);
1432        assert_eq!(positions, vec![0., 8., 16.]);
1433    }
1434
1435    #[test]
1436    fn test_force_width_combining_marks_not_advanced() {
1437        let cell_width = px(8.);
1438        // Simulates Thai "กี" — base consonant at x=0, combining vowel also at x=0
1439        let mut layout = make_layout(vec![
1440            glyph_at(0., 0), // ก (base)
1441            glyph_at(0., 3), // ี (combining mark, same x)
1442        ]);
1443
1444        apply_force_width_to_layout(&mut layout, cell_width);
1445
1446        let positions = glyph_x_positions(&layout);
1447        assert_eq!(positions, vec![0., 0.]);
1448    }
1449
1450    #[test]
1451    fn test_force_width_base_after_combining_mark() {
1452        let cell_width = px(8.);
1453        let mut layout = make_layout(vec![glyph_at(0., 0), glyph_at(0., 3), glyph_at(8., 6)]);
1454
1455        apply_force_width_to_layout(&mut layout, cell_width);
1456
1457        let positions = glyph_x_positions(&layout);
1458        assert_eq!(positions, vec![0., 0., 8.]);
1459    }
1460
1461    #[test]
1462    fn test_force_width_multiple_combining_marks() {
1463        let cell_width = px(8.);
1464        // Simulates "ก้" — base + vowel + tone mark (two combining marks stacked)
1465        let mut layout = make_layout(vec![
1466            glyph_at(0., 0), // ก (base)
1467            glyph_at(0., 3), // vowel (combining)
1468            glyph_at(0., 6), // tone mark (combining)
1469            glyph_at(8., 9), // next base
1470        ]);
1471
1472        apply_force_width_to_layout(&mut layout, cell_width);
1473
1474        let positions = glyph_x_positions(&layout);
1475        assert_eq!(positions, vec![0., 0., 0., 8.]);
1476    }
1477
1478    #[test]
1479    fn test_force_width_corrects_drifted_base_positions() {
1480        let cell_width = px(8.);
1481        // Font metrics don't perfectly match cell grid — glyphs drift >1px from cell boundary
1482        let mut layout = make_layout(vec![
1483            glyph_at(0.5, 0),  // within 1px tolerance, kept as-is
1484            glyph_at(10.2, 1), // >1px off from 8.0, corrected
1485            glyph_at(19.8, 2), // >1px off from 16.0, corrected
1486        ]);
1487
1488        apply_force_width_to_layout(&mut layout, cell_width);
1489
1490        let positions = glyph_x_positions(&layout);
1491        assert_eq!(positions, vec![0.5, 8., 16.]);
1492    }
1493
1494    #[test]
1495    fn test_force_width_combining_mark_after_within_tolerance_base() {
1496        let cell_width = px(8.);
1497        // Base glyph is within 1px of grid so it keeps its shaped position.
1498        // The combining mark must align to the base's actual position, not the grid slot.
1499        let mut layout = make_layout(vec![glyph_at(0.5, 0), glyph_at(0.5, 3)]);
1500
1501        apply_force_width_to_layout(&mut layout, cell_width);
1502
1503        let positions = glyph_x_positions(&layout);
1504        assert_eq!(positions, vec![0.5, 0.5]);
1505    }
1506
1507    /// One 10 px glyph per character of `text`; a soft hyphen and a zero
1508    /// width space take no room, as a shaper gives them.
1509    fn monospaced(text: &str) -> LineLayout {
1510        let mut x = 0.;
1511        let glyphs = text
1512            .char_indices()
1513            .map(|(i, ch)| {
1514                let glyph = glyph_at(x, i);
1515                if ch != '\u{AD}' && ch != '\u{200B}' {
1516                    x += 10.;
1517                }
1518                glyph
1519            })
1520            .collect();
1521        LineLayout {
1522            width: px(x),
1523            len: text.len(),
1524            ..make_layout(glyphs)
1525        }
1526    }
1527
1528    fn boundary(glyph_ix: usize) -> WrapBoundary {
1529        WrapBoundary {
1530            run_ix: 0,
1531            glyph_ix,
1532        }
1533    }
1534
1535    const HYPHEN: Pixels = px(10.);
1536
1537    fn rules(overflow_wrap: OverflowWrap, word_break: WordBreak, hyphens: Hyphens) -> TextWrap {
1538        TextWrap {
1539            overflow_wrap,
1540            word_break,
1541            hyphens,
1542        }
1543    }
1544
1545    const NORMAL: TextWrap = TextWrap {
1546        overflow_wrap: OverflowWrap::Normal,
1547        word_break: WordBreak::Normal,
1548        hyphens: Hyphens::Manual,
1549    };
1550
1551    /// Where `text` breaks at `width`, and how wide its widest overflowing line is.
1552    fn wrap(text: &str, width: f32, rules: TextWrap) -> (Vec<usize>, Vec<usize>, Pixels) {
1553        let w = monospaced(text).wrap(
1554            text,
1555            px(width),
1556            None,
1557            rules,
1558            HYPHEN,
1559            &mut WrapScratch::default(),
1560        );
1561        (
1562            w.boundaries.iter().map(|b| b.glyph_ix).collect(),
1563            w.hyphens.to_vec(),
1564            w.overflow,
1565        )
1566    }
1567
1568    fn min_content(text: &str, rules: TextWrap) -> Pixels {
1569        monospaced(text).min_content_width(text, rules, HYPHEN)
1570    }
1571
1572    #[test]
1573    fn min_content_width_is_the_widest_word() {
1574        assert_eq!(min_content("ab cd efg", NORMAL), px(30.));
1575        // Spaces end a stretch and hang: they never count.
1576        assert_eq!(min_content("abc   de ", NORMAL), px(30.));
1577        // UAX #14: a break after a solidus, never before it ("a/" + "bcd").
1578        assert_eq!(min_content("a/bcd", NORMAL), px(30.));
1579        // One word: all of it.
1580        assert_eq!(min_content("abcdef", NORMAL), px(60.));
1581        assert_eq!(min_content("   ", NORMAL), px(0.));
1582    }
1583
1584    #[test]
1585    fn wrapped_at_min_content_it_breaks_at_every_opportunity_and_in_no_word() {
1586        let text = "ab cd efg";
1587        let width = min_content(text, NORMAL);
1588        assert_eq!(wrap(text, width.0, NORMAL).0, vec![3, 6]);
1589    }
1590
1591    #[test]
1592    fn a_space_at_the_edge_hangs_instead_of_starting_the_next_line() {
1593        // "ab" fills the 20 px line; the space after it crosses the edge. The
1594        // break goes before "cd", not before the space.
1595        assert_eq!(wrap("ab cd", 20., NORMAL).0, vec![3]);
1596    }
1597
1598    /// CSS Text 3 §5.5. `normal`: a word wider than the line overflows it,
1599    /// and the line breaks at the next opportunity. `break-word` and
1600    /// `anywhere`: the word is broken where it overflows.
1601    #[test]
1602    fn overflow_wrap_decides_whether_a_long_word_breaks() {
1603        let text = "aaaaaaaa bb";
1604        assert_eq!(wrap(text, 30., NORMAL), (vec![9], vec![], px(80.)));
1605        let break_word = rules(OverflowWrap::BreakWord, WordBreak::Normal, Hyphens::Manual);
1606        assert_eq!(wrap(text, 30., break_word), (vec![3, 6, 9], vec![], px(0.)));
1607        let anywhere = rules(OverflowWrap::Anywhere, WordBreak::Normal, Hyphens::Manual);
1608        assert_eq!(wrap(text, 30., anywhere).0, vec![3, 6, 9]);
1609        // The legacy `word-break: break-word` is `overflow-wrap: anywhere`.
1610        let legacy = rules(OverflowWrap::Normal, WordBreak::BreakWord, Hyphens::Manual);
1611        assert_eq!(wrap(text, 30., legacy).0, vec![3, 6, 9]);
1612        // gpui's own callers keep breaking.
1613        assert_eq!(wrap(text, 30., TextWrap::BREAK_WORD).0, vec![3, 6, 9]);
1614        // A word that fits is never broken, under any of them.
1615        assert_eq!(wrap("ab cd", 30., anywhere).0, vec![3]);
1616    }
1617
1618    /// `anywhere` lowers the min-content size to one character; `break-word`
1619    /// does not (CSS Text 3 §5.5).
1620    #[test]
1621    fn only_anywhere_counts_its_breaks_for_min_content() {
1622        let anywhere = rules(OverflowWrap::Anywhere, WordBreak::Normal, Hyphens::Manual);
1623        let break_word = rules(OverflowWrap::BreakWord, WordBreak::Normal, Hyphens::Manual);
1624        let legacy = rules(OverflowWrap::Normal, WordBreak::BreakWord, Hyphens::Manual);
1625        assert_eq!(min_content("abcdef gh", anywhere), px(10.));
1626        assert_eq!(min_content("abcdef gh", legacy), px(10.));
1627        assert_eq!(min_content("abcdef gh", break_word), px(60.));
1628        // Never inside a grapheme cluster: e + a combining acute is one.
1629        assert_eq!(min_content("ae\u{301}b", anywhere), px(20.));
1630    }
1631
1632    /// `word-break: break-all` breaks between any two letters, so a line
1633    /// fills up instead of wrapping at its last space; `keep-all` keeps CJK
1634    /// letters together (CSS Text 3 §5.2).
1635    #[test]
1636    fn word_break_moves_the_opportunities() {
1637        let break_all = rules(OverflowWrap::Normal, WordBreak::BreakAll, Hyphens::Manual);
1638        assert_eq!(wrap("ab cdefgh", 50., break_all).0, vec![5]);
1639        let break_word = rules(OverflowWrap::BreakWord, WordBreak::Normal, Hyphens::Manual);
1640        assert_eq!(wrap("ab cdefgh", 50., break_word).0, vec![3, 8]);
1641        assert_eq!(min_content("abc", break_all), px(10.));
1642        // Not before punctuation that never starts a line.
1643        assert_eq!(min_content("a,b", break_all), px(20.));
1644
1645        let keep_all = rules(OverflowWrap::Normal, WordBreak::KeepAll, Hyphens::Manual);
1646        assert_eq!(min_content("日本語", NORMAL), px(10.));
1647        assert_eq!(min_content("日本語", keep_all), px(30.));
1648        assert_eq!(min_content("日本 語", keep_all), px(20.));
1649    }
1650
1651    /// A soft hyphen is a break opportunity under `hyphens: manual`, after
1652    /// it, with a hyphen shown that the line must fit; never under `none`
1653    /// (CSS Text 3 §6.1).
1654    #[test]
1655    fn a_soft_hyphen_breaks_with_a_hyphen() {
1656        let text = "ab\u{AD}cd";
1657        // "ab" and its hyphen fill the 30 px line.
1658        assert_eq!(wrap(text, 30., NORMAL), (vec![3], vec![0], px(0.)));
1659        assert_eq!(min_content(text, NORMAL), px(30.));
1660        // Without room for the hyphen, the break does not happen there.
1661        assert_eq!(wrap(text, 25., NORMAL).0, Vec::<usize>::new());
1662        let none = rules(OverflowWrap::Normal, WordBreak::Normal, Hyphens::None);
1663        assert_eq!(wrap(text, 30., none), (vec![], vec![], px(40.)));
1664        assert_eq!(min_content(text, none), px(40.));
1665    }
1666
1667    #[test]
1668    fn a_zero_width_space_is_a_break_opportunity() {
1669        assert_eq!(wrap("aaa\u{200B}bbb", 30., NORMAL).0, vec![4]);
1670        assert_eq!(min_content("aaa\u{200B}bbb", NORMAL), px(30.));
1671    }
1672}