Skip to main content

gpui/text_system/
line_wrapper.rs

1use crate::{FontId, Pixels, SharedString, TextRun, TextSystem, px};
2use collections::HashMap;
3use std::{borrow::Cow, iter, sync::Arc};
4use unicode_segmentation::UnicodeSegmentation;
5
6/// Determines whether to truncate text from the start or end.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum TruncateFrom {
9    /// Truncate text from the start.
10    Start,
11    /// Truncate text from the end.
12    End,
13    /// Truncate text from the middle, preserving the start and end.
14    Middle,
15}
16
17/// Controls how soft-wrapped continuation lines are indented.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum IndentAdjustment {
20    /// No indent - continuation lines start at column 0.
21    NoIndent,
22    /// Match the original line's leading whitespace.
23    #[default]
24    SameIndent,
25    /// Add N extra columns of indent (in space-character widths).
26    ExtraColumns(u32),
27}
28
29/// The GPUI line wrapper, used to wrap lines of text to a given width.
30pub struct LineWrapper {
31    text_system: Arc<TextSystem>,
32    pub(crate) font_id: FontId,
33    pub(crate) font_size: Pixels,
34    char_widths: CharWidthCache,
35    text_buffer: String,
36}
37
38/// Cached character widths for one font and size.
39pub(crate) struct CharWidthCache {
40    ascii: [Option<Pixels>; 128],
41    other: HashMap<char, Pixels>,
42}
43
44impl Default for CharWidthCache {
45    fn default() -> Self {
46        Self {
47            ascii: [None; 128],
48            other: HashMap::default(),
49        }
50    }
51}
52
53impl LineWrapper {
54    /// The maximum indent that can be applied to a line.
55    pub const MAX_INDENT: u32 = 256;
56
57    pub(crate) fn new(
58        font_id: FontId,
59        font_size: Pixels,
60        text_system: Arc<TextSystem>,
61        char_widths: CharWidthCache,
62    ) -> Self {
63        Self {
64            text_system,
65            font_id,
66            font_size,
67            char_widths,
68            text_buffer: String::new(),
69        }
70    }
71
72    pub(crate) fn into_char_widths(self) -> CharWidthCache {
73        self.char_widths
74    }
75
76    /// Wrap a line of text to the given width with this wrapper's font and font size.
77    pub fn wrap_line<'a>(
78        &'a mut self,
79        fragments: &'a [LineFragment],
80        wrap_width: Pixels,
81        indent_adjustment: IndentAdjustment,
82    ) -> impl Iterator<Item = Boundary> + 'a {
83        let mut width = px(0.);
84        let mut first_non_whitespace_ix = None;
85        let mut base_indent = None;
86        let mut last_candidate_ix = 0;
87        let mut last_candidate_width = px(0.);
88        let mut last_wrap_ix = 0;
89        let mut index = 0;
90        let Self {
91            text_buffer: text,
92            char_widths,
93            text_system,
94            font_id,
95            font_size,
96        } = self;
97        text.clear();
98        for fragment in fragments {
99            match fragment {
100                LineFragment::Text {
101                    text: fragment_text,
102                } => text.push_str(fragment_text),
103                // This placeholder keeps inline elements attached to adjacent words
104                LineFragment::Element { len_utf8, .. } => {
105                    text.extend(iter::repeat_n('a', *len_utf8));
106                }
107            }
108        }
109        let mut break_indices = Self::break_indices(text).peekable();
110        let mut grapheme_indices = text
111            .grapheme_indices(true)
112            .map(|(index, _)| index)
113            .peekable();
114        let mut width_for_char = move |character| {
115            width_for_char(char_widths, character, text_system, *font_id, *font_size)
116        };
117        let mut grapheme_index = 0;
118        let mut width_before_grapheme = px(0.);
119        let mut candidates = fragments
120            .iter()
121            .flat_map(move |fragment| fragment.wrap_boundary_candidates());
122        iter::from_fn(move || {
123            for candidate in candidates.by_ref() {
124                let ix = index;
125                index += candidate.len_utf8();
126                while grapheme_indices
127                    .next_if(|position| *position < ix)
128                    .is_some()
129                {}
130                let is_grapheme_boundary = grapheme_indices.next_if_eq(&ix).is_some();
131                if is_grapheme_boundary {
132                    grapheme_index = ix;
133                    width_before_grapheme = width;
134                }
135                if break_indices.next_if_eq(&ix).is_some()
136                    && is_grapheme_boundary
137                    && first_non_whitespace_ix.is_some()
138                {
139                    last_candidate_ix = ix;
140                    last_candidate_width = width;
141                }
142                let item_width = match candidate {
143                    WrapBoundaryCandidate::Char { character: c } => {
144                        if c == '\n' {
145                            continue;
146                        }
147
148                        if c != ' ' && first_non_whitespace_ix.is_none() {
149                            first_non_whitespace_ix = Some(ix);
150                        }
151
152                        width_for_char(c)
153                    }
154                    WrapBoundaryCandidate::Element {
155                        width: element_width,
156                        ..
157                    } => {
158                        if first_non_whitespace_ix.is_none() {
159                            first_non_whitespace_ix = Some(ix);
160                        }
161
162                        element_width
163                    }
164                };
165
166                width += item_width;
167                if width > wrap_width && grapheme_index > last_wrap_ix {
168                    let wrap_at_candidate = last_candidate_ix > last_wrap_ix
169                        && width - last_candidate_width <= wrap_width;
170
171                    let carried_width = if wrap_at_candidate {
172                        width - last_candidate_width
173                    } else {
174                        width - width_before_grapheme
175                    };
176
177                    // Compute base indentation from the first non-whitespace character on the line
178                    // and retain it for all subsequent wrap rows. If the line begins with leading
179                    // whitespace that wraps before any non-whitespace character (or is all whitespace),
180                    // base_indent remains None so continuation rows within the leading whitespace
181                    // do not receive ExtraColumns indentation and degrade into cascading short rows.
182                    if base_indent.is_none() {
183                        if let Some(first_non_whitespace_ix) = first_non_whitespace_ix {
184                            base_indent =
185                                Some(Self::MAX_INDENT.min(
186                                    first_non_whitespace_ix.saturating_sub(last_wrap_ix) as u32,
187                                ));
188                        }
189                    }
190
191                    let next_indent = match indent_adjustment {
192                        IndentAdjustment::NoIndent => 0,
193                        IndentAdjustment::SameIndent => base_indent.unwrap_or(0),
194                        IndentAdjustment::ExtraColumns(extra) => {
195                            if let Some(base_indent) = base_indent {
196                                let candidate = base_indent.saturating_add(extra);
197                                let candidate_indent_width = width_for_char(' ') * candidate as f32;
198                                // Reserve headroom for any carried suffix from an earlier word boundary
199                                // (and at least 2 columns for a full-width character) so the continuation
200                                // line does not immediately exceed wrap width.
201                                let min_headroom = carried_width.max(width_for_char(' ') * 2.0);
202                                if candidate_indent_width + min_headroom > wrap_width {
203                                    0
204                                } else {
205                                    Self::MAX_INDENT.min(candidate)
206                                }
207                            } else {
208                                0
209                            }
210                        }
211                    };
212
213                    if wrap_at_candidate {
214                        last_wrap_ix = last_candidate_ix;
215                        width -= last_candidate_width;
216                        width_before_grapheme -= last_candidate_width;
217                    } else {
218                        // An oversized grapheme stays intact, even if it exceeds the line width.
219                        last_wrap_ix = grapheme_index;
220                        width -= width_before_grapheme;
221                        width_before_grapheme = px(0.);
222                    }
223                    last_candidate_ix = 0;
224
225                    let indent_width = width_for_char(' ') * next_indent as f32;
226                    width += indent_width;
227                    width_before_grapheme += indent_width;
228
229                    return Some(Boundary::new(last_wrap_ix, next_indent));
230                }
231            }
232
233            None
234        })
235    }
236
237    /// Determines if a line should be truncated based on its width.
238    ///
239    /// Returns the truncation index in `line`.
240    pub fn should_truncate_line(
241        &mut self,
242        line: &str,
243        truncate_width: Pixels,
244        truncation_affix: &str,
245        truncate_from: TruncateFrom,
246    ) -> Option<usize> {
247        let mut width = px(0.);
248        let suffix_width = truncation_affix
249            .chars()
250            .map(|c| self.width_for_char(c))
251            .fold(px(0.0), |a, x| a + x);
252        let mut truncate_ix = 0;
253
254        match truncate_from {
255            TruncateFrom::Start => {
256                for (ix, c) in line.char_indices().rev() {
257                    if width + suffix_width < truncate_width {
258                        truncate_ix = ix;
259                    }
260
261                    let char_width = self.width_for_char(c);
262                    width += char_width;
263
264                    if width.floor() > truncate_width {
265                        return Some(truncate_ix);
266                    }
267                }
268            }
269            TruncateFrom::End => {
270                for (ix, c) in line.char_indices() {
271                    if width + suffix_width < truncate_width {
272                        truncate_ix = ix;
273                    }
274
275                    let char_width = self.width_for_char(c);
276                    width += char_width;
277
278                    if width.floor() > truncate_width {
279                        return Some(truncate_ix);
280                    }
281                }
282            }
283            TruncateFrom::Middle => {}
284        }
285
286        None
287    }
288
289    fn should_truncate_line_middle(
290        &mut self,
291        line: &str,
292        truncate_width: Pixels,
293        truncation_affix: &str,
294    ) -> Option<(usize, usize)> {
295        let suffix_width = truncation_affix
296            .chars()
297            .map(|c| self.width_for_char(c))
298            .fold(px(0.0), |a, x| a + x);
299
300        let total_width: Pixels = line
301            .chars()
302            .map(|c| self.width_for_char(c))
303            .fold(px(0.0), |a, x| a + x);
304
305        if total_width <= truncate_width {
306            return None;
307        }
308
309        let content_budget = truncate_width - suffix_width;
310        if content_budget <= px(0.) {
311            return Some((0, line.len()));
312        }
313
314        let front_budget = content_budget * (2.0 / 3.0);
315        let back_budget = content_budget - front_budget;
316
317        let mut front_width = px(0.);
318        let mut front_end_ix = 0usize;
319        for (ix, c) in line.char_indices() {
320            let char_width = self.width_for_char(c);
321            if front_width + char_width > front_budget {
322                break;
323            }
324            front_width += char_width;
325            front_end_ix = ix + c.len_utf8();
326        }
327
328        let mut back_width = px(0.);
329        let mut back_start_ix = line.len();
330        for (ix, c) in line.char_indices().rev() {
331            let char_width = self.width_for_char(c);
332            if back_width + char_width > back_budget {
333                break;
334            }
335            back_width += char_width;
336            back_start_ix = ix;
337        }
338
339        if front_end_ix >= back_start_ix {
340            return Some((0, line.len()));
341        }
342
343        Some((front_end_ix, back_start_ix))
344    }
345
346    /// Truncate a line of text to the given width with this wrapper's font and font size.
347    pub fn truncate_line<'a>(
348        &mut self,
349        line: SharedString,
350        truncate_width: Pixels,
351        truncation_affix: &str,
352        runs: &'a [TextRun],
353        truncate_from: TruncateFrom,
354    ) -> (SharedString, Cow<'a, [TextRun]>) {
355        if truncate_from == TruncateFrom::Middle {
356            if let Some((front_end_ix, back_start_ix)) =
357                self.should_truncate_line_middle(&line, truncate_width, truncation_affix)
358            {
359                let result = SharedString::from(format!(
360                    "{}{truncation_affix}{}",
361                    &line[..front_end_ix],
362                    &line[back_start_ix..]
363                ));
364                let mut runs = runs.to_vec();
365                update_runs_after_middle_truncation(
366                    truncation_affix,
367                    &mut runs,
368                    front_end_ix,
369                    back_start_ix,
370                );
371                return (result, Cow::Owned(runs));
372            } else {
373                return (line, Cow::Borrowed(runs));
374            }
375        }
376
377        if let Some(truncate_ix) =
378            self.should_truncate_line(&line, truncate_width, truncation_affix, truncate_from)
379        {
380            let result = match truncate_from {
381                TruncateFrom::Start => SharedString::from(format!(
382                    "{truncation_affix}{}",
383                    &line[line.ceil_char_boundary(truncate_ix + 1)..]
384                )),
385                TruncateFrom::End => SharedString::from(format!(
386                    "{}{truncation_affix}",
387                    line[..truncate_ix]
388                        .trim_end_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation())
389                )),
390                TruncateFrom::Middle => unreachable!("Middle truncation is handled above"),
391            };
392            let mut runs = runs.to_vec();
393            update_runs_after_truncation(&result, truncation_affix, &mut runs, truncate_from);
394            (result, Cow::Owned(runs))
395        } else {
396            (line, Cow::Borrowed(runs))
397        }
398    }
399
400    /// Truncate text to fit within a given number of wrapped lines.
401    ///
402    /// Unlike `truncate_line` which treats the text as a flat width budget
403    /// (`width * max_lines`), this method accounts for word-boundary wrapping:
404    /// it walks through characters once, tracking wrap boundaries and the
405    /// truncation point simultaneously. When text overflows on the last
406    /// allowed line, it truncates there and appends the affix.
407    ///
408    /// For `max_lines == 1`, this delegates to `truncate_line`.
409    pub fn truncate_wrapped_line<'a>(
410        &mut self,
411        text: SharedString,
412        wrap_width: Pixels,
413        max_lines: usize,
414        truncation_affix: &str,
415        runs: &'a [TextRun],
416        truncate_from: TruncateFrom,
417    ) -> (SharedString, Cow<'a, [TextRun]>) {
418        if max_lines <= 1 || truncate_from == TruncateFrom::Start {
419            return self.truncate_line(
420                text,
421                wrap_width * max_lines,
422                truncation_affix,
423                runs,
424                truncate_from,
425            );
426        }
427        if truncate_from == TruncateFrom::Middle {
428            return self.truncate_line(text, wrap_width, truncation_affix, runs, truncate_from);
429        }
430
431        let affix_width: Pixels = truncation_affix
432            .chars()
433            .map(|c| self.width_for_char(c))
434            .sum();
435
436        let mut width = px(0.);
437        let mut line = 0usize;
438        let mut first_non_whitespace_ix = None;
439        let mut last_candidate_ix = 0usize;
440        let mut last_candidate_width = px(0.);
441        let mut last_wrap_ix = 0usize;
442        let mut indent: Option<u32> = None;
443        let mut truncate_ix = 0usize;
444
445        let mut break_indices = Self::break_indices(&text).peekable();
446        for (ix, c) in text.char_indices() {
447            // Consume boundaries on newlines too, so skipping an empty line does not
448            // leave the iterator stuck before subsequent text.
449            let is_break = break_indices.next_if_eq(&ix).is_some();
450            if c == '\n' {
451                if line >= max_lines - 1 && !text[ix + 1..].trim().is_empty() {
452                    // Newline on the last allowed line with real content
453                    // below. Truncate here.
454                    let truncated = text[..truncate_ix]
455                        .trim_end_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation());
456                    let result = SharedString::from(format!("{truncated}{truncation_affix}"));
457                    let mut runs = runs.to_vec();
458                    update_runs_after_truncation(
459                        &result,
460                        truncation_affix,
461                        &mut runs,
462                        TruncateFrom::End,
463                    );
464                    return (result, Cow::Owned(runs));
465                }
466
467                // Newline before the last line: it consumes a line.
468                line += 1;
469                width = px(0.);
470                first_non_whitespace_ix = None;
471                last_candidate_ix = 0;
472                last_candidate_width = px(0.);
473                last_wrap_ix = ix + 1;
474                indent = None;
475                truncate_ix = ix + 1;
476                continue;
477            }
478
479            let char_width = self.width_for_char(c);
480
481            if is_break && first_non_whitespace_ix.is_some() {
482                last_candidate_ix = ix;
483                last_candidate_width = width;
484            }
485
486            if c != ' ' && first_non_whitespace_ix.is_none() {
487                first_non_whitespace_ix = Some(ix);
488            }
489
490            width += char_width;
491
492            if line < max_lines - 1 {
493                // Before the last line: replicate wrap_line's boundary logic.
494                if width > wrap_width && ix > last_wrap_ix {
495                    if let (None, Some(first_nw)) = (indent, first_non_whitespace_ix) {
496                        indent = Some(Self::MAX_INDENT.min((first_nw - last_wrap_ix) as u32));
497                    }
498
499                    if last_candidate_ix > last_wrap_ix {
500                        last_wrap_ix = last_candidate_ix;
501                        width -= last_candidate_width;
502                        last_candidate_ix = 0;
503                    } else {
504                        last_wrap_ix = ix;
505                        width = char_width;
506                    }
507
508                    if let Some(ind) = indent {
509                        width += self.width_for_char(' ') * ind as f32;
510                    }
511
512                    line += 1;
513                    truncate_ix = last_wrap_ix;
514                }
515            } else {
516                // On the last line: track the furthest point where the affix
517                // still fits, and stop as soon as the line overflows.
518                if width + affix_width <= wrap_width {
519                    truncate_ix = ix + c.len_utf8();
520                }
521
522                if width > wrap_width {
523                    let truncated = text[..truncate_ix]
524                        .trim_end_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation());
525                    let result = SharedString::from(format!("{truncated}{truncation_affix}"));
526                    let mut runs = runs.to_vec();
527                    update_runs_after_truncation(
528                        &result,
529                        truncation_affix,
530                        &mut runs,
531                        TruncateFrom::End,
532                    );
533                    return (result, Cow::Owned(runs));
534                }
535            }
536        }
537
538        // Text fits within max_lines without truncation.
539        drop(break_indices);
540        (text, Cow::Borrowed(runs))
541    }
542
543    /// The byte offsets in `text` at which a line break is allowed.
544    pub(crate) fn break_indices(text: &str) -> impl Iterator<Item = usize> {
545        icu_segmenter::LineSegmenter::new_for_non_complex_scripts(Default::default())
546            .segment_str(text)
547    }
548
549    #[inline(always)]
550    fn width_for_char(&mut self, c: char) -> Pixels {
551        width_for_char(
552            &mut self.char_widths,
553            c,
554            &self.text_system,
555            self.font_id,
556            self.font_size,
557        )
558    }
559}
560
561#[inline(always)]
562fn width_for_char(
563    char_widths: &mut CharWidthCache,
564    c: char,
565    text_system: &TextSystem,
566    font_id: FontId,
567    font_size: Pixels,
568) -> Pixels {
569    if (c as u32) < 128 {
570        if let Some(cached_width) = char_widths.ascii[c as usize] {
571            cached_width
572        } else {
573            let width = text_system.layout_width(font_id, font_size, c);
574            char_widths.ascii[c as usize] = Some(width);
575            width
576        }
577    } else if let Some(cached_width) = char_widths.other.get(&c) {
578        *cached_width
579    } else {
580        let width = text_system.layout_width(font_id, font_size, c);
581        char_widths.other.insert(c, width);
582        width
583    }
584}
585
586fn update_runs_after_truncation(
587    result: &str,
588    ellipsis: &str,
589    runs: &mut Vec<TextRun>,
590    truncate_from: TruncateFrom,
591) {
592    let mut truncate_at = result.len() - ellipsis.len();
593    match truncate_from {
594        TruncateFrom::Start => {
595            for (run_index, run) in runs.iter_mut().enumerate().rev() {
596                if run.len <= truncate_at {
597                    truncate_at -= run.len;
598                } else {
599                    run.len = truncate_at + ellipsis.len();
600                    runs.splice(..run_index, std::iter::empty());
601                    break;
602                }
603            }
604        }
605        TruncateFrom::End => {
606            for (run_index, run) in runs.iter_mut().enumerate() {
607                if run.len <= truncate_at {
608                    truncate_at -= run.len;
609                } else {
610                    run.len = truncate_at + ellipsis.len();
611                    runs.truncate(run_index + 1);
612                    break;
613                }
614            }
615        }
616        TruncateFrom::Middle => {
617            unreachable!("Middle truncation calls this function with TruncateFrom::End directly")
618        }
619    }
620}
621
622fn update_runs_after_middle_truncation(
623    ellipsis: &str,
624    runs: &mut Vec<TextRun>,
625    front_end_ix: usize,
626    back_start_ix: usize,
627) {
628    let original_runs = std::mem::take(runs);
629    let mut result_runs: Vec<TextRun> = Vec::with_capacity(original_runs.len());
630
631    // Front segment [0, front_end_ix) + ellipsis: walk forward until the run
632    // that straddles or ends at front_end_ix, then extend that run's length
633    // to include the ellipsis.
634    let mut front_remaining = front_end_ix;
635    let mut front_done = false;
636    for run in &original_runs {
637        if front_done {
638            break;
639        }
640        if run.len <= front_remaining {
641            result_runs.push(run.clone());
642            front_remaining -= run.len;
643        } else {
644            let mut partial = run.clone();
645            partial.len = front_remaining + ellipsis.len();
646            result_runs.push(partial);
647            front_done = true;
648        }
649    }
650    if !front_done {
651        // front_end_ix landed exactly on a run boundary; append ellipsis to
652        // the last front run (or, if the front is empty, to the first back run).
653        if let Some(last) = result_runs.last_mut() {
654            last.len += ellipsis.len();
655        } else if let Some(first) = original_runs.first() {
656            let mut affix_run = first.clone();
657            affix_run.len = ellipsis.len();
658            result_runs.push(affix_run);
659        }
660    }
661
662    // Back segment [back_start_ix, original.len()): skip runs entirely in the
663    // removed middle, keep the rest.
664    let mut byte_pos = 0usize;
665    for run in &original_runs {
666        let run_end = byte_pos + run.len;
667        if run_end > back_start_ix {
668            if byte_pos < back_start_ix {
669                // Run straddles back_start_ix; keep only the tail.
670                let mut partial = run.clone();
671                partial.len = run_end - back_start_ix;
672                result_runs.push(partial);
673            } else {
674                result_runs.push(run.clone());
675            }
676        }
677        byte_pos = run_end;
678    }
679
680    *runs = result_runs;
681}
682
683/// A fragment of a line that can be wrapped.
684pub enum LineFragment<'a> {
685    /// A text fragment consisting of characters.
686    Text {
687        /// The text content of the fragment.
688        text: &'a str,
689    },
690    /// A non-text element with a fixed width.
691    Element {
692        /// The width of the element in pixels.
693        width: Pixels,
694        /// The UTF-8 encoded length of the element.
695        len_utf8: usize,
696    },
697}
698
699impl<'a> LineFragment<'a> {
700    /// Creates a new text fragment from the given text.
701    pub fn text(text: &'a str) -> Self {
702        LineFragment::Text { text }
703    }
704
705    /// Creates a new non-text element with the given width and UTF-8 encoded length.
706    pub fn element(width: Pixels, len_utf8: usize) -> Self {
707        LineFragment::Element { width, len_utf8 }
708    }
709
710    fn wrap_boundary_candidates(&self) -> impl Iterator<Item = WrapBoundaryCandidate> {
711        let text = match self {
712            LineFragment::Text { text } => text,
713            LineFragment::Element { .. } => "\0",
714        };
715        text.chars().map(move |character| {
716            if let LineFragment::Element { width, len_utf8 } = self {
717                WrapBoundaryCandidate::Element {
718                    width: *width,
719                    len_utf8: *len_utf8,
720                }
721            } else {
722                WrapBoundaryCandidate::Char { character }
723            }
724        })
725    }
726}
727
728enum WrapBoundaryCandidate {
729    Char { character: char },
730    Element { width: Pixels, len_utf8: usize },
731}
732
733impl WrapBoundaryCandidate {
734    pub fn len_utf8(&self) -> usize {
735        match self {
736            WrapBoundaryCandidate::Char { character } => character.len_utf8(),
737            WrapBoundaryCandidate::Element { len_utf8: len, .. } => *len,
738        }
739    }
740}
741
742/// A boundary between two lines of text.
743#[derive(Copy, Clone, Debug, PartialEq, Eq)]
744pub struct Boundary {
745    /// The index of the last character in a line
746    pub ix: usize,
747    /// The indent of the next line.
748    pub next_indent: u32,
749}
750
751impl Boundary {
752    fn new(ix: usize, next_indent: u32) -> Self {
753        Self { ix, next_indent }
754    }
755}
756
757#[cfg(test)]
758mod tests {
759    use super::*;
760    use crate::{Font, FontFeatures, FontStyle, FontWeight, TestAppContext, TestDispatcher, font};
761    #[cfg(target_os = "macos")]
762    use crate::{TextRun, WindowTextSystem, WrapBoundary};
763
764    fn build_wrapper() -> LineWrapper {
765        let dispatcher = TestDispatcher::new(0);
766        let cx = TestAppContext::build(dispatcher, None);
767        let id = cx.text_system().resolve_font(&font(".ZedMono"));
768        LineWrapper::new(
769            id,
770            px(16.),
771            cx.text_system().clone(),
772            CharWidthCache::default(),
773        )
774    }
775
776    fn assert_emergency_wrap_preserves_graphemes(wrapper: &mut LineWrapper) {
777        use unicode_segmentation::UnicodeSegmentation;
778
779        let mut failures = Vec::new();
780        for cluster in ["e\u{301}", "か\u{3099}", "👍🏽", "🇯🇵", "👩\u{200d}💻"] {
781            let cluster_width: Pixels = cluster
782                .chars()
783                .map(|character| wrapper.width_for_char(character))
784                .sum();
785            let first_width = cluster
786                .chars()
787                .next()
788                .map(|character| wrapper.width_for_char(character))
789                .expect("nonempty fixture");
790            for text in [cluster.to_owned(), format!("x{cluster}y")] {
791                let grapheme_boundaries: Vec<_> = text
792                    .grapheme_indices(true)
793                    .map(|(index, _)| index)
794                    .chain(std::iter::once(text.len()))
795                    .collect();
796                assert!(
797                    LineWrapper::break_indices(&text)
798                        .all(|index| grapheme_boundaries.contains(&index)),
799                    "UAX #14 boundary inside {text:?}"
800                );
801                let fragments = [LineFragment::text(&text)];
802                let full_width: Pixels = text
803                    .chars()
804                    .map(|character| wrapper.width_for_char(character))
805                    .sum();
806                assert!(
807                    wrapper
808                        .wrap_line(&fragments, full_width + px(1.), IndentAdjustment::NoIndent)
809                        .next()
810                        .is_none()
811                );
812                for wrap_width in [
813                    first_width - px(0.1),
814                    first_width,
815                    first_width + px(0.1),
816                    cluster_width - px(0.1),
817                    cluster_width,
818                    cluster_width + px(0.1),
819                ] {
820                    let boundaries: Vec<_> = wrapper
821                        .wrap_line(&fragments, wrap_width, IndentAdjustment::NoIndent)
822                        .map(|boundary| boundary.ix)
823                        .collect();
824                    let split_fragments: Vec<_> = text
825                        .split_inclusive(|_: char| true)
826                        .map(LineFragment::text)
827                        .collect();
828                    let split_boundaries: Vec<_> = wrapper
829                        .wrap_line(&split_fragments, wrap_width, IndentAdjustment::NoIndent)
830                        .map(|boundary| boundary.ix)
831                        .collect();
832                    assert_eq!(
833                        boundaries, split_boundaries,
834                        "fragmentation changed {text:?}"
835                    );
836                    let invalid: Vec<_> = boundaries
837                        .iter()
838                        .copied()
839                        .filter(|index| !grapheme_boundaries.contains(index))
840                        .collect();
841                    if !invalid.is_empty() {
842                        failures.push(format!("text={text:?}, width={wrap_width:?}, cluster_width={cluster_width:?}, breaks={boundaries:?}, inside_grapheme={invalid:?}"));
843                    }
844                }
845            }
846        }
847        assert!(failures.is_empty(), "{}", failures.join("\n"));
848    }
849
850    #[test]
851    fn test_emergency_wrap_preserves_graphemes() {
852        assert_emergency_wrap_preserves_graphemes(&mut build_wrapper());
853    }
854
855    #[test]
856    fn test_emergency_wrap_exact_boundaries() {
857        let mut wrapper = build_wrapper();
858        wrapper.char_widths.ascii.fill(Some(px(1.)));
859        wrapper.char_widths.other.insert('\u{301}', px(1.));
860
861        for (text, width, adjustment, expected) in [
862            (
863                "xe\u{301}y",
864                1.,
865                IndentAdjustment::NoIndent,
866                vec![Boundary::new(1, 0), Boundary::new(4, 0)],
867            ),
868            (
869                "  xe\u{301}yze\u{301}q",
870                5.,
871                IndentAdjustment::SameIndent,
872                vec![Boundary::new(6, 2), Boundary::new(8, 2)],
873            ),
874            (
875                "  xe\u{301}yze\u{301}q",
876                5.,
877                IndentAdjustment::ExtraColumns(1),
878                vec![
879                    Boundary::new(6, 3),
880                    Boundary::new(8, 3),
881                    Boundary::new(11, 3),
882                ],
883            ),
884        ] {
885            let fragments = [LineFragment::text(text)];
886            assert_eq!(
887                wrapper
888                    .wrap_line(&fragments, px(width), adjustment)
889                    .collect::<Vec<_>>(),
890                expected,
891                "{text:?}, {adjustment:?}",
892            );
893        }
894    }
895
896    #[test]
897    fn test_emergency_wrap_elements_and_graphemes() {
898        let mut wrapper = build_wrapper();
899        wrapper.char_widths.ascii.fill(Some(px(1.)));
900        wrapper.char_widths.other.insert('\u{301}', px(1.));
901
902        for element_length in [1, 3, 32] {
903            let fragments = [
904                LineFragment::text("xe\u{301}"),
905                LineFragment::element(px(4.), element_length),
906                LineFragment::text("e\u{301}yz"),
907            ];
908            assert_eq!(
909                wrapper
910                    .wrap_line(&fragments, px(2.), IndentAdjustment::NoIndent)
911                    .collect::<Vec<_>>(),
912                vec![
913                    Boundary::new(1, 0),
914                    Boundary::new(4, 0),
915                    Boundary::new(4 + element_length, 0),
916                    Boundary::new(7 + element_length, 0),
917                ],
918                "element_length={element_length}",
919            );
920        }
921    }
922
923    fn generate_test_runs(input_run_len: &[usize]) -> Vec<TextRun> {
924        input_run_len
925            .iter()
926            .map(|run_len| TextRun {
927                len: *run_len,
928                font: Font {
929                    family: "Dummy".into(),
930                    features: FontFeatures::default(),
931                    fallbacks: None,
932                    weight: FontWeight::default(),
933                    style: FontStyle::Normal,
934                },
935                ..Default::default()
936            })
937            .collect()
938    }
939
940    #[test]
941    fn test_wrap_line() {
942        let mut wrapper = build_wrapper();
943
944        assert_eq!(
945            wrapper
946                .wrap_line(
947                    &[LineFragment::text("aa bbb cccc ddddd eeee")],
948                    px(72.),
949                    IndentAdjustment::default()
950                )
951                .collect::<Vec<_>>(),
952            &[
953                Boundary::new(7, 0),
954                Boundary::new(12, 0),
955                Boundary::new(18, 0)
956            ],
957        );
958        assert_eq!(
959            wrapper
960                .wrap_line(
961                    &[LineFragment::text("aaa aaaaaaaaaaaaaaaaaa")],
962                    px(72.0),
963                    IndentAdjustment::default()
964                )
965                .collect::<Vec<_>>(),
966            &[
967                Boundary::new(4, 0),
968                Boundary::new(11, 0),
969                Boundary::new(18, 0)
970            ],
971        );
972        assert_eq!(
973            wrapper
974                .wrap_line(
975                    &[LineFragment::text("     aaaaaaa")],
976                    px(72.),
977                    IndentAdjustment::default()
978                )
979                .collect::<Vec<_>>(),
980            &[
981                Boundary::new(7, 5),
982                Boundary::new(9, 5),
983                Boundary::new(11, 5),
984            ]
985        );
986        assert_eq!(
987            wrapper
988                .wrap_line(
989                    &[LineFragment::text("                            ")],
990                    px(72.),
991                    IndentAdjustment::default()
992                )
993                .collect::<Vec<_>>(),
994            &[
995                Boundary::new(7, 0),
996                Boundary::new(14, 0),
997                Boundary::new(21, 0)
998            ]
999        );
1000        assert_eq!(
1001            wrapper
1002                .wrap_line(
1003                    &[LineFragment::text("          aaaaaaaaaaaaaa")],
1004                    px(72.),
1005                    IndentAdjustment::default()
1006                )
1007                .collect::<Vec<_>>(),
1008            &[
1009                Boundary::new(7, 0),
1010                Boundary::new(14, 3),
1011                Boundary::new(18, 3),
1012                Boundary::new(22, 3),
1013            ]
1014        );
1015
1016        // Test wrapping multiple text fragments
1017        assert_eq!(
1018            wrapper
1019                .wrap_line(
1020                    &[
1021                        LineFragment::text("aa bbb "),
1022                        LineFragment::text("cccc ddddd eeee")
1023                    ],
1024                    px(72.),
1025                    IndentAdjustment::default()
1026                )
1027                .collect::<Vec<_>>(),
1028            &[
1029                Boundary::new(7, 0),
1030                Boundary::new(12, 0),
1031                Boundary::new(18, 0)
1032            ],
1033        );
1034
1035        // Test wrapping with a mix of text and element fragments
1036        assert_eq!(
1037            wrapper
1038                .wrap_line(
1039                    &[
1040                        LineFragment::text("aa "),
1041                        LineFragment::element(px(20.), 1),
1042                        LineFragment::text(" bbb "),
1043                        LineFragment::element(px(30.), 1),
1044                        LineFragment::text(" cccc")
1045                    ],
1046                    px(72.),
1047                    IndentAdjustment::default()
1048                )
1049                .collect::<Vec<_>>(),
1050            &[
1051                Boundary::new(5, 0),
1052                Boundary::new(9, 0),
1053                Boundary::new(11, 0)
1054            ],
1055        );
1056
1057        // Test with element at the beginning and text afterward
1058        assert_eq!(
1059            wrapper
1060                .wrap_line(
1061                    &[
1062                        LineFragment::element(px(50.), 1),
1063                        LineFragment::text(" aaaa bbbb cccc dddd")
1064                    ],
1065                    px(72.),
1066                    IndentAdjustment::default()
1067                )
1068                .collect::<Vec<_>>(),
1069            &[
1070                Boundary::new(2, 0),
1071                Boundary::new(7, 0),
1072                Boundary::new(12, 0),
1073                Boundary::new(17, 0)
1074            ],
1075        );
1076
1077        // Test with a large element that forces wrapping by itself
1078        assert_eq!(
1079            wrapper
1080                .wrap_line(
1081                    &[
1082                        LineFragment::text("short text "),
1083                        LineFragment::element(px(100.), 1),
1084                        LineFragment::text(" more text")
1085                    ],
1086                    px(72.),
1087                    IndentAdjustment::default()
1088                )
1089                .collect::<Vec<_>>(),
1090            &[
1091                Boundary::new(6, 0),
1092                Boundary::new(11, 0),
1093                Boundary::new(12, 0),
1094                Boundary::new(18, 0)
1095            ],
1096        );
1097
1098        // Test with non-breaking glue characters
1099        assert_eq!(
1100            wrapper
1101                .wrap_line(
1102                    &[LineFragment::text("a\u{202F}b\u{00A0}c\u{2011}d e")],
1103                    px(72.0),
1104                    IndentAdjustment::default()
1105                )
1106                .collect::<Vec<_>>(),
1107            &[Boundary::new(12, 0),], // special chars above take up 3, 2 and 3 bytes, so boundary ends up at 12
1108        );
1109    }
1110
1111    #[test]
1112    fn test_wrap_line_break_opportunities() {
1113        let mut wrapper = build_wrapper();
1114        for (text, fitting_prefix, expected_index) in [
1115            ("aaa required!", "aaa required", 4),
1116            ("aaa foo/bar", "aaa foo/", 8),
1117            ("aaa (hello)", "aaa (hello", 4),
1118            ("aaa αβγδε", "aaa αβγδ", 4),
1119            ("aaa a\u{a0}b", "aaa a\u{a0}", 4),
1120            ("aaa 你好!", "aaa 你好", 7),
1121        ] {
1122            let wrap_width = fitting_prefix
1123                .chars()
1124                .map(|character| wrapper.width_for_char(character))
1125                .sum();
1126            assert_eq!(
1127                wrapper
1128                    .wrap_line(
1129                        &[LineFragment::text(text)],
1130                        wrap_width,
1131                        IndentAdjustment::default()
1132                    )
1133                    .collect::<Vec<_>>(),
1134                [Boundary::new(expected_index, 0)],
1135                "{text:?}",
1136            );
1137        }
1138    }
1139
1140    #[test]
1141    fn test_truncate_line_end() {
1142        let mut wrapper = build_wrapper();
1143
1144        fn perform_test(
1145            wrapper: &mut LineWrapper,
1146            text: &'static str,
1147            expected: &'static str,
1148            ellipsis: &str,
1149        ) {
1150            let dummy_run_lens = vec![text.len()];
1151            let dummy_runs = generate_test_runs(&dummy_run_lens);
1152            let (result, dummy_runs) = wrapper.truncate_line(
1153                text.into(),
1154                px(220.),
1155                ellipsis,
1156                &dummy_runs,
1157                TruncateFrom::End,
1158            );
1159            assert_eq!(result, expected);
1160            assert_eq!(dummy_runs.first().unwrap().len, result.len());
1161        }
1162
1163        perform_test(
1164            &mut wrapper,
1165            "aa bbb cccc ddddd eeee ffff gggg",
1166            "aa bbb cccc ddddd eeee",
1167            "",
1168        );
1169        perform_test(
1170            &mut wrapper,
1171            "aa bbb cccc ddddd eeee ffff gggg",
1172            "aa bbb cccc ddddd eee…",
1173            "…",
1174        );
1175        perform_test(
1176            &mut wrapper,
1177            "aa bbb cccc ddddd eeee ffff gggg",
1178            "aa bbb cccc dddd......",
1179            "......",
1180        );
1181        perform_test(
1182            &mut wrapper,
1183            "aa bbb cccc 🦀🦀🦀🦀🦀 eeee ffff gggg",
1184            "aa bbb cccc 🦀🦀🦀🦀…",
1185            "…",
1186        );
1187    }
1188
1189    #[test]
1190    fn test_truncate_line_start() {
1191        let mut wrapper = build_wrapper();
1192
1193        #[track_caller]
1194        fn perform_test(
1195            wrapper: &mut LineWrapper,
1196            text: &'static str,
1197            expected: &'static str,
1198            ellipsis: &str,
1199        ) {
1200            let dummy_run_lens = vec![text.len()];
1201            let dummy_runs = generate_test_runs(&dummy_run_lens);
1202            let (result, dummy_runs) = wrapper.truncate_line(
1203                text.into(),
1204                px(220.),
1205                ellipsis,
1206                &dummy_runs,
1207                TruncateFrom::Start,
1208            );
1209            assert_eq!(result, expected);
1210            assert_eq!(dummy_runs.first().unwrap().len, result.len());
1211        }
1212
1213        perform_test(
1214            &mut wrapper,
1215            "aaaa bbbb cccc ddddd eeee fff gg",
1216            "cccc ddddd eeee fff gg",
1217            "",
1218        );
1219        perform_test(
1220            &mut wrapper,
1221            "aaaa bbbb cccc ddddd eeee fff gg",
1222            "…ccc ddddd eeee fff gg",
1223            "…",
1224        );
1225        perform_test(
1226            &mut wrapper,
1227            "aaaa bbbb cccc ddddd eeee fff gg",
1228            "......dddd eeee fff gg",
1229            "......",
1230        );
1231        perform_test(
1232            &mut wrapper,
1233            "aaaa bbbb cccc 🦀🦀🦀🦀🦀 eeee fff gg",
1234            "…🦀🦀🦀🦀 eeee fff gg",
1235            "…",
1236        );
1237    }
1238
1239    #[test]
1240    fn test_truncate_multiple_runs_end() {
1241        let mut wrapper = build_wrapper();
1242
1243        fn perform_test(
1244            wrapper: &mut LineWrapper,
1245            text: &'static str,
1246            expected: &str,
1247            run_lens: &[usize],
1248            result_run_len: &[usize],
1249            line_width: Pixels,
1250        ) {
1251            let dummy_runs = generate_test_runs(run_lens);
1252            let (result, dummy_runs) =
1253                wrapper.truncate_line(text.into(), line_width, "…", &dummy_runs, TruncateFrom::End);
1254            assert_eq!(result, expected);
1255            for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
1256                assert_eq!(run.len, *result_len);
1257            }
1258        }
1259        // Case 0: Normal
1260        // Text: abcdefghijkl
1261        // Runs: Run0 { len: 12, ... }
1262        //
1263        // Truncate res: abcd… (truncate_at = 4)
1264        // Run res: Run0 { string: abcd…, len: 7, ... }
1265        perform_test(&mut wrapper, "abcdefghijkl", "abcd…", &[12], &[7], px(50.));
1266        // Case 1: Drop some runs
1267        // Text: abcdefghijkl
1268        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1269        //
1270        // Truncate res: abcdef… (truncate_at = 6)
1271        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
1272        // 5, ... }
1273        perform_test(
1274            &mut wrapper,
1275            "abcdefghijkl",
1276            "abcdef…",
1277            &[4, 4, 4],
1278            &[4, 5],
1279            px(70.),
1280        );
1281        // Case 2: Truncate at start of some run
1282        // Text: abcdefghijkl
1283        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1284        //
1285        // Truncate res: abcdefgh… (truncate_at = 8)
1286        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
1287        // 4, ... }, Run2 { string: …, len: 3, ... }
1288        perform_test(
1289            &mut wrapper,
1290            "abcdefghijkl",
1291            "abcdefgh…",
1292            &[4, 4, 4],
1293            &[4, 4, 3],
1294            px(90.),
1295        );
1296    }
1297
1298    #[test]
1299    fn test_truncate_multiple_runs_start() {
1300        let mut wrapper = build_wrapper();
1301
1302        #[track_caller]
1303        fn perform_test(
1304            wrapper: &mut LineWrapper,
1305            text: &'static str,
1306            expected: &str,
1307            run_lens: &[usize],
1308            result_run_len: &[usize],
1309            line_width: Pixels,
1310        ) {
1311            let dummy_runs = generate_test_runs(run_lens);
1312            let (result, dummy_runs) = wrapper.truncate_line(
1313                text.into(),
1314                line_width,
1315                "…",
1316                &dummy_runs,
1317                TruncateFrom::Start,
1318            );
1319            assert_eq!(result, expected);
1320            for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
1321                assert_eq!(run.len, *result_len);
1322            }
1323        }
1324        // Case 0: Normal
1325        // Text: abcdefghijkl
1326        // Runs: Run0 { len: 12, ... }
1327        //
1328        // Truncate res: …ijkl (truncate_at = 9)
1329        // Run res: Run0 { string: …ijkl, len: 7, ... }
1330        perform_test(&mut wrapper, "abcdefghijkl", "…ijkl", &[12], &[7], px(50.));
1331        // Case 1: Drop some runs
1332        // Text: abcdefghijkl
1333        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1334        //
1335        // Truncate res: …ghijkl (truncate_at = 7)
1336        // Runs res: Run0 { string: …gh, len: 5, ... }, Run1 { string: ijkl, len:
1337        // 4, ... }
1338        perform_test(
1339            &mut wrapper,
1340            "abcdefghijkl",
1341            "…ghijkl",
1342            &[4, 4, 4],
1343            &[5, 4],
1344            px(70.),
1345        );
1346        // Case 2: Truncate at start of some run
1347        // Text: abcdefghijkl
1348        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1349        //
1350        // Truncate res: abcdefgh… (truncate_at = 3)
1351        // Runs res: Run0 { string: …, len: 3, ... }, Run1 { string: efgh, len:
1352        // 4, ... }, Run2 { string: ijkl, len: 4, ... }
1353        perform_test(
1354            &mut wrapper,
1355            "abcdefghijkl",
1356            "…efghijkl",
1357            &[4, 4, 4],
1358            &[3, 4, 4],
1359            px(90.),
1360        );
1361    }
1362
1363    #[test]
1364    fn test_update_run_after_truncation_end() {
1365        fn perform_test(result: &str, run_lens: &[usize], result_run_lens: &[usize]) {
1366            let mut dummy_runs = generate_test_runs(run_lens);
1367            update_runs_after_truncation(result, "…", &mut dummy_runs, TruncateFrom::End);
1368            for (run, result_len) in dummy_runs.iter().zip(result_run_lens) {
1369                assert_eq!(run.len, *result_len);
1370            }
1371        }
1372        // Case 0: Normal
1373        // Text: abcdefghijkl
1374        // Runs: Run0 { len: 12, ... }
1375        //
1376        // Truncate res: abcd… (truncate_at = 4)
1377        // Run res: Run0 { string: abcd…, len: 7, ... }
1378        perform_test("abcd…", &[12], &[7]);
1379        // Case 1: Drop some runs
1380        // Text: abcdefghijkl
1381        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1382        //
1383        // Truncate res: abcdef… (truncate_at = 6)
1384        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
1385        // 5, ... }
1386        perform_test("abcdef…", &[4, 4, 4], &[4, 5]);
1387        // Case 2: Truncate at start of some run
1388        // Text: abcdefghijkl
1389        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
1390        //
1391        // Truncate res: abcdefgh… (truncate_at = 8)
1392        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
1393        // 4, ... }, Run2 { string: …, len: 3, ... }
1394        perform_test("abcdefgh…", &[4, 4, 4], &[4, 4, 3]);
1395    }
1396
1397    // For compatibility with the test macro
1398    #[cfg(target_os = "macos")]
1399    use crate as gpui;
1400
1401    // These seem to vary wildly based on the text system.
1402    #[cfg(target_os = "macos")]
1403    #[crate::test]
1404    fn test_wrap_shaped_line(cx: &mut TestAppContext) {
1405        cx.update(|cx| {
1406            let text_system = WindowTextSystem::new(cx.text_system().clone());
1407
1408            let normal = TextRun {
1409                len: 0,
1410                font: font("Helvetica"),
1411                color: Default::default(),
1412                underline: Default::default(),
1413                ..Default::default()
1414            };
1415            let bold = TextRun {
1416                len: 0,
1417                font: font("Helvetica").bold(),
1418                ..Default::default()
1419            };
1420
1421            let text = "aa bbb cccc ddddd eeee".into();
1422            let lines = text_system
1423                .shape_text(
1424                    text,
1425                    px(16.),
1426                    &[
1427                        normal.with_len(4),
1428                        bold.with_len(5),
1429                        normal.with_len(6),
1430                        bold.with_len(1),
1431                        normal.with_len(7),
1432                    ],
1433                    Some(px(72.)),
1434                    None,
1435                )
1436                .unwrap();
1437
1438            assert_eq!(
1439                lines[0].layout.wrap_boundaries(),
1440                &[
1441                    WrapBoundary {
1442                        run_ix: 0,
1443                        glyph_ix: 7
1444                    },
1445                    WrapBoundary {
1446                        run_ix: 0,
1447                        glyph_ix: 12
1448                    },
1449                    WrapBoundary {
1450                        run_ix: 0,
1451                        glyph_ix: 18
1452                    }
1453                ],
1454            );
1455        });
1456    }
1457
1458    #[test]
1459    fn test_multiline_truncation_fits_within_wrapped_lines() {
1460        let mut wrapper = build_wrapper();
1461
1462        // With .ZedMono at 16px, each char is 9.6px wide.
1463        // wrap_width = 72px fits ~7 chars per line.
1464        //
1465        // "aa bbbbbb cccccc dddddd eeee ffff" with wrap_width=72px wraps as:
1466        //   Line 1: "aa "       (28.8px, wraps because "bbbbbb" won't fit)
1467        //   Line 2: "bbbbbb "   (67.2px)
1468        //   Line 3: "cccccc "   (67.2px)
1469        //   ...
1470        //
1471        // truncate_wrapped_line should wrap first to find line 2 starts at
1472        // "bbbbbb...", then truncate only that line to fit with ellipsis.
1473        let text: &str = "aa bbbbbb cccccc dddddd eeee ffff";
1474        let wrap_width = px(72.);
1475        let max_lines: usize = 2;
1476
1477        let runs = generate_test_runs(&[text.len()]);
1478        let (truncated, _) = wrapper.truncate_wrapped_line(
1479            text.into(),
1480            wrap_width,
1481            max_lines,
1482            "\u{2026}",
1483            &runs,
1484            TruncateFrom::End,
1485        );
1486
1487        // The truncated text, when wrapped, must fit within max_lines lines.
1488        let wrap_count = wrapper
1489            .wrap_line(
1490                &[LineFragment::text(&truncated)],
1491                wrap_width,
1492                IndentAdjustment::default(),
1493            )
1494            .count();
1495
1496        assert!(
1497            wrap_count < max_lines,
1498            "Truncated text '{}' wraps into {} visual lines, expected at most {}",
1499            truncated,
1500            wrap_count + 1,
1501            max_lines
1502        );
1503
1504        // The truncated text should end with the ellipsis.
1505        assert!(
1506            truncated.ends_with('\u{2026}'),
1507            "Truncated text '{}' should end with ellipsis",
1508            truncated
1509        );
1510    }
1511
1512    #[test]
1513    fn test_multiline_truncation_no_truncation_needed() {
1514        let mut wrapper = build_wrapper();
1515
1516        // Text that fits in 2 lines shouldn't be truncated.
1517        // Line 1: "aa bbb " (67.2px), Line 2: "cccccc" (57.6px)
1518        let text: &str = "aa bbb cccccc";
1519        let wrap_width = px(72.);
1520        let max_lines: usize = 2;
1521
1522        let runs = generate_test_runs(&[text.len()]);
1523        let (result, _) = wrapper.truncate_wrapped_line(
1524            text.into(),
1525            wrap_width,
1526            max_lines,
1527            "\u{2026}",
1528            &runs,
1529            TruncateFrom::End,
1530        );
1531
1532        assert_eq!(
1533            result.as_ref(),
1534            text,
1535            "Text that fits should not be modified"
1536        );
1537    }
1538
1539    #[test]
1540    fn test_multiline_truncation_three_lines() {
1541        let mut wrapper = build_wrapper();
1542
1543        let text: &str = "aa bbb cccc ddddd eeee ffff gggg hhhh iiii jjjj";
1544        let wrap_width = px(72.);
1545        let max_lines: usize = 3;
1546
1547        let runs = generate_test_runs(&[text.len()]);
1548        let (truncated, _) = wrapper.truncate_wrapped_line(
1549            text.into(),
1550            wrap_width,
1551            max_lines,
1552            "\u{2026}",
1553            &runs,
1554            TruncateFrom::End,
1555        );
1556
1557        let wrap_count = wrapper
1558            .wrap_line(
1559                &[LineFragment::text(&truncated)],
1560                wrap_width,
1561                IndentAdjustment::default(),
1562            )
1563            .count();
1564
1565        assert!(
1566            wrap_count < max_lines,
1567            "Truncated text '{}' wraps into {} visual lines, expected at most {}",
1568            truncated,
1569            wrap_count + 1,
1570            max_lines
1571        );
1572
1573        assert!(
1574            truncated.ends_with('\u{2026}'),
1575            "Truncated text '{}' should end with ellipsis",
1576            truncated
1577        );
1578    }
1579
1580    #[test]
1581    fn test_multiline_truncation_preserves_breaks_after_empty_lines() {
1582        let mut wrapper = build_wrapper();
1583        for prefix in ["", "\n", "\n\n", "hello\n\n"] {
1584            let text = format!("{prefix}aaa required! more words follow");
1585            let runs = generate_test_runs(&[text.len()]);
1586            let max_lines = prefix.bytes().filter(|byte| *byte == b'\n').count() + 2;
1587            let (truncated, _) = wrapper.truncate_wrapped_line(
1588                text.into(),
1589                px(72.),
1590                max_lines,
1591                "…",
1592                &runs,
1593                TruncateFrom::End,
1594            );
1595            assert_eq!(
1596                truncated.as_ref(),
1597                format!("{prefix}aaa {}…", &"required!"[..6]),
1598                "prefix: {prefix:?}",
1599            );
1600        }
1601    }
1602
1603    #[test]
1604    fn test_multiline_truncation_with_newlines() {
1605        let mut wrapper = build_wrapper();
1606
1607        // "hello\nworld foo bar baz" with line_clamp(2):
1608        // shape_text splits on \n, giving physical lines "hello" and
1609        // "world foo bar baz". The newline consumes line 1, so the
1610        // second physical line should be truncated on line 2.
1611        let text: &str = "hello\nworld foo bar baz";
1612        let wrap_width = px(72.);
1613        let max_lines: usize = 2;
1614
1615        let runs = generate_test_runs(&[text.len()]);
1616        let (truncated, _) = wrapper.truncate_wrapped_line(
1617            text.into(),
1618            wrap_width,
1619            max_lines,
1620            "\u{2026}",
1621            &runs,
1622            TruncateFrom::End,
1623        );
1624
1625        // The newline should be preserved.
1626        let parts: Vec<&str> = truncated.splitn(2, '\n').collect();
1627        assert_eq!(
1628            parts.len(),
1629            2,
1630            "Newline should be preserved: '{}'",
1631            truncated
1632        );
1633        assert_eq!(parts[0], "hello");
1634
1635        // The second line should fit within wrap_width and end with ellipsis.
1636        let second_line_width: Pixels = parts[1].chars().map(|c| wrapper.width_for_char(c)).sum();
1637        assert!(
1638            second_line_width <= wrap_width,
1639            "Second line '{}' ({}px) exceeds wrap_width ({}px)",
1640            parts[1],
1641            second_line_width,
1642            wrap_width
1643        );
1644        assert!(
1645            truncated.ends_with('\u{2026}'),
1646            "Should end with ellipsis: '{}'",
1647            truncated
1648        );
1649    }
1650
1651    #[test]
1652    fn test_multiline_truncation_newline_on_last_line() {
1653        let mut wrapper = build_wrapper();
1654
1655        // "hello\nworld\nmore" with line_clamp(2):
1656        // Line 1: "hello", Line 2: "world" — but there's a third line,
1657        // so line 2 should be truncated with ellipsis.
1658        let text: &str = "hello\nworld\nmore";
1659        let wrap_width = px(72.);
1660        let max_lines: usize = 2;
1661
1662        let runs = generate_test_runs(&[text.len()]);
1663        let (truncated, _) = wrapper.truncate_wrapped_line(
1664            text.into(),
1665            wrap_width,
1666            max_lines,
1667            "\u{2026}",
1668            &runs,
1669            TruncateFrom::End,
1670        );
1671
1672        let parts: Vec<&str> = truncated.splitn(2, '\n').collect();
1673        assert_eq!(parts[0], "hello");
1674        assert!(
1675            truncated.ends_with('\u{2026}'),
1676            "Should end with ellipsis since there's more content: '{}'",
1677            truncated
1678        );
1679    }
1680
1681    #[test]
1682    fn test_truncate_line_middle() {
1683        let mut wrapper = build_wrapper();
1684
1685        // No truncation when text fits within a very wide budget.
1686        let short_text = "hello world";
1687        let runs = generate_test_runs(&[short_text.len()]);
1688        let (result, result_runs) = wrapper.truncate_line(
1689            short_text.into(),
1690            px(10000.),
1691            "…",
1692            &runs,
1693            TruncateFrom::Middle,
1694        );
1695        assert_eq!(result.as_ref(), short_text);
1696        assert_eq!(result_runs.len(), 1);
1697        assert_eq!(result_runs[0].len, short_text.len());
1698
1699        // Basic middle truncation: long string with px(100.) budget.
1700        let long_text = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz";
1701        let runs = generate_test_runs(&[long_text.len()]);
1702        let (result, _result_runs) =
1703            wrapper.truncate_line(long_text.into(), px(100.), "…", &runs, TruncateFrom::Middle);
1704        assert!(
1705            result.contains('…'),
1706            "Middle-truncated result should contain '…', got: '{}'",
1707            result
1708        );
1709        assert!(
1710            result.chars().count() < long_text.chars().count(),
1711            "Middle-truncated result should be shorter than original"
1712        );
1713        assert_eq!(
1714            result.chars().next(),
1715            long_text.chars().next(),
1716            "Result should start with the same first character as original"
1717        );
1718        assert_eq!(
1719            result.chars().last(),
1720            long_text.chars().last(),
1721            "Result should end with the same last character as original"
1722        );
1723
1724        // Degenerate case: budget so narrow that middle truncation cannot find a valid split.
1725        // Still show the truncation affix instead of returning the original overflowing text.
1726        let text = "abcdef";
1727        let runs = generate_test_runs(&[text.len()]);
1728        let (result, result_runs) =
1729            wrapper.truncate_line(text.into(), px(1.), "…", &runs, TruncateFrom::Middle);
1730        assert_eq!(result.as_ref(), "…");
1731        assert_eq!(result_runs.len(), 1);
1732        assert_eq!(result_runs[0].len, "…".len());
1733
1734        // Run adjustment correctness: multiple runs across the string.
1735        // Verify that the returned runs' lengths sum to result.len().
1736        let multi_run_text = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz";
1737        let run_lens = [20, 20, multi_run_text.len() - 40];
1738        let runs = generate_test_runs(&run_lens);
1739        let (result, result_runs) = wrapper.truncate_line(
1740            multi_run_text.into(),
1741            px(100.),
1742            "…",
1743            &runs,
1744            TruncateFrom::Middle,
1745        );
1746        let total_run_len: usize = result_runs.iter().map(|r| r.len).sum();
1747        assert_eq!(
1748            total_run_len,
1749            result.len(),
1750            "Sum of run lengths ({}) should equal result byte length ({})",
1751            total_run_len,
1752            result.len()
1753        );
1754    }
1755
1756    #[test]
1757    fn test_multiline_truncation_trailing_newline() {
1758        let mut wrapper = build_wrapper();
1759
1760        // "hello\nworld\n" with line_clamp(2):
1761        // The trailing newline has no content after it, so no ellipsis.
1762        let text: &str = "hello\nworld\n";
1763        let wrap_width = px(72.);
1764        let max_lines: usize = 2;
1765
1766        let runs = generate_test_runs(&[text.len()]);
1767        let (result, _) = wrapper.truncate_wrapped_line(
1768            text.into(),
1769            wrap_width,
1770            max_lines,
1771            "\u{2026}",
1772            &runs,
1773            TruncateFrom::End,
1774        );
1775
1776        assert!(
1777            !result.ends_with('\u{2026}'),
1778            "Trailing newline with no content should not add ellipsis: '{}'",
1779            result
1780        );
1781    }
1782
1783    #[test]
1784    fn test_multiline_truncation_newline_fits_exactly() {
1785        let mut wrapper = build_wrapper();
1786
1787        // "hello\nworld" with line_clamp(2):
1788        // Exactly 2 lines, no truncation needed.
1789        let text: &str = "hello\nworld";
1790        let wrap_width = px(72.);
1791        let max_lines: usize = 2;
1792
1793        let runs = generate_test_runs(&[text.len()]);
1794        let (result, _) = wrapper.truncate_wrapped_line(
1795            text.into(),
1796            wrap_width,
1797            max_lines,
1798            "\u{2026}",
1799            &runs,
1800            TruncateFrom::End,
1801        );
1802
1803        assert_eq!(
1804            result.as_ref(),
1805            text,
1806            "Text that fits exactly should not be modified: '{}'",
1807            result
1808        );
1809    }
1810
1811    #[test]
1812    fn test_extra_columns_overflow_guard() {
1813        let mut wrapper = build_wrapper();
1814        let space_width = wrapper.width_for_char(' ');
1815
1816        // 6 spaces indent, wrap width 10 columns.
1817        let text = "      ab cd ef gh";
1818        let wrap_width = space_width * 10.0;
1819
1820        // When base_indent + extra overflows wrap width (6 + 8 + 2 > 10),
1821        // indent must fall back to 0 instead of degrading to one character per row.
1822        //
1823        // Expected wrapped lines (10 columns):
1824        //   |      ab  |  (row 0: 6 spaces + "ab ", len 9)
1825        //   |cd ef gh  |  (row 1: 0 indent + "cd ef gh", len 8)
1826        assert_eq!(
1827            wrapper
1828                .wrap_line(
1829                    &[LineFragment::text(text)],
1830                    wrap_width,
1831                    IndentAdjustment::ExtraColumns(8),
1832                )
1833                .collect::<Vec<_>>(),
1834            &[Boundary::new(9, 0)]
1835        );
1836
1837        // When base_indent + extra fits within wrap width (6 + 2 + 2 <= 10),
1838        // the extra indent is applied and not clamped.
1839        // Spaces count toward the width, so the separators occupy their own rows
1840        // rather than overflowing the preceding row or splitting the following word.
1841        //
1842        // Expected wrapped lines (10 columns):
1843        //   |      ab  |  (row 0: 6 spaces + "ab ", len 9)
1844        //   |        cd|  (row 1: 8 spaces + "cd", len 10)
1845        //   |          |  (row 2: 8 spaces + " ", len 9)
1846        //   |        ef|  (row 3: 8 spaces + "ef", len 10)
1847        //   |          |  (row 4: 8 spaces + " ", len 9)
1848        //   |        gh|  (row 5: 8 spaces + "gh", len 10)
1849        assert_eq!(
1850            wrapper
1851                .wrap_line(
1852                    &[LineFragment::text(text)],
1853                    wrap_width,
1854                    IndentAdjustment::ExtraColumns(2),
1855                )
1856                .collect::<Vec<_>>(),
1857            &[
1858                Boundary::new(9, 8),
1859                Boundary::new(11, 8),
1860                Boundary::new(12, 8),
1861                Boundary::new(14, 8),
1862                Boundary::new(15, 8),
1863            ]
1864        );
1865
1866        // When text contains full-width (two-column) glyphs, reserving headroom for a
1867        // two-column character (candidate + 2 > wrap_width) ensures that candidate
1868        // indents leaving only 1 column cannot accept the indent and overflow.
1869        //
1870        // 1 space indent, wrap width 10 columns.
1871        // " 🦀🦀🦀🦀🦀🦀🦀🦀" with extra=8 (extra_two with tab_size=4):
1872        // candidate = 1 + 8 = 9.
1873        // With +2 headroom (9 + 2 > 10), indent falls back to 0.
1874        //
1875        // Expected wrapped lines (10 columns):
1876        //   | 🦀🦀🦀🦀 |  (row 0: 1 space + 4 two-column glyphs, 9 cols)
1877        //   |🦀🦀🦀🦀  |  (row 1: 0 indent + 4 two-column glyphs, 8 cols)
1878        let full_width_text = " 🦀🦀🦀🦀🦀🦀🦀🦀";
1879        assert_eq!(
1880            wrapper
1881                .wrap_line(
1882                    &[LineFragment::text(full_width_text)],
1883                    wrap_width,
1884                    IndentAdjustment::ExtraColumns(8),
1885                )
1886                .collect::<Vec<_>>(),
1887            &[Boundary::new(17, 0)]
1888        );
1889
1890        // When the carried suffix fits within wrap width alongside extra indent
1891        // (1 indent + 9 carried suffix = 10 <= 10), the extra indent is applied.
1892        //
1893        // Expected wrapped lines (10 columns):
1894        //   |a         |  (row 0: "a ", len 2)
1895        //   | abcdefghi|  (row 1: 1 indent + "abcdefghi", len 10)
1896        assert_eq!(
1897            wrapper
1898                .wrap_line(
1899                    &[LineFragment::text("a abcdefghi")],
1900                    wrap_width,
1901                    IndentAdjustment::ExtraColumns(1),
1902                )
1903                .collect::<Vec<_>>(),
1904            &[Boundary::new(2, 1)]
1905        );
1906
1907        // When extra indent exceeds wrap width by even 1 column
1908        // (2 indent + 9 carried suffix = 11 > 10), indent falls back to 0.
1909        //
1910        // Expected wrapped lines (10 columns):
1911        //   |a         |  (row 0: "a ", len 2)
1912        //   |abcdefghi |  (row 1: 0 indent + "abcdefghi", len 9)
1913        assert_eq!(
1914            wrapper
1915                .wrap_line(
1916                    &[LineFragment::text("a abcdefghi")],
1917                    wrap_width,
1918                    IndentAdjustment::ExtraColumns(2),
1919                )
1920                .collect::<Vec<_>>(),
1921            &[Boundary::new(2, 0)]
1922        );
1923
1924        // When text wraps at an earlier word boundary, the carried suffix
1925        // must be accounted for so indent + carried_suffix <= wrap_width.
1926        //
1927        // "a abcdefghij" with wrap_width 10 columns, ExtraColumns(8):
1928        // candidate = 0 + 8 = 8.
1929        // carried suffix = "abcdefghi" (9 columns).
1930        // 8 indent + 9 carried suffix = 17 > 10, so indent falls back to 0.
1931        //
1932        // Expected wrapped lines (10 columns):
1933        //   |a         |  (row 0: "a ", len 2)
1934        //   |abcdefghij|  (row 1: 0 indent + "abcdefghij", len 10)
1935        let carried_text = "a abcdefghij";
1936        assert_eq!(
1937            wrapper
1938                .wrap_line(
1939                    &[LineFragment::text(carried_text)],
1940                    wrap_width,
1941                    IndentAdjustment::ExtraColumns(8),
1942                )
1943                .collect::<Vec<_>>(),
1944            &[Boundary::new(2, 0)]
1945        );
1946
1947        // When a wider inline element is encountered after the first wrap,
1948        // the overflow guard must evaluate whether the element fits with the extra indent.
1949        // If text continues after the element row and wraps again, subsequent continuation
1950        // lines resume the extra indent if their carried content fits.
1951        //
1952        // "abcdefghijk " followed by an 8-column element and "z 12":
1953        // Row 0: "abcdefghij" (len 10)
1954        // Row 1: "k " (2 cols) with 8 indent (len 10)
1955        // Row 2: element (8 cols) cannot fit with 8 indent (8 + 8 = 16 > 10),
1956        //        so indent falls back to 0. Element (8 cols) + "z " (2 cols) = len 10.
1957        // Row 3: "12" (2 cols) fits with 8 indent (8 + 2 = 10 <= 10).
1958        //
1959        // Expected wrapped lines (10 columns):
1960        //   |abcdefghij|  (row 0: 10 cols)
1961        //   |        k |  (row 1: 8 indent + "k ", len 10)
1962        //   |[ELEMENT]z|  (row 2: 0 indent + [ELEMENT (8)] + "z ", len 10)
1963        //   |        12|  (row 3: 8 indent + "12", len 10)
1964        let element_fragments = [
1965            LineFragment::text("abcdefghijk "),
1966            LineFragment::element(space_width * 8.0, 1),
1967            LineFragment::text("z 12"),
1968        ];
1969        assert_eq!(
1970            wrapper
1971                .wrap_line(
1972                    &element_fragments,
1973                    wrap_width,
1974                    IndentAdjustment::ExtraColumns(8),
1975                )
1976                .collect::<Vec<_>>(),
1977            &[
1978                Boundary::new(10, 8),
1979                Boundary::new(12, 0),
1980                Boundary::new(15, 8),
1981            ]
1982        );
1983
1984        // A line of only whitespace wrapping before any non-whitespace character
1985        // must not have extra columns added to subsequent rows.
1986        let spaces = "                    "; // 20 spaces
1987        assert_eq!(
1988            wrapper
1989                .wrap_line(
1990                    &[LineFragment::text(spaces)],
1991                    wrap_width,
1992                    IndentAdjustment::ExtraColumns(8),
1993                )
1994                .collect::<Vec<_>>(),
1995            &[Boundary::new(10, 0)]
1996        );
1997
1998        // When leading whitespace wraps before the first non-whitespace character,
1999        // base_indent should reflect the leading whitespace on the row where non-whitespace begins.
2000        // 14 spaces followed by "ab cd ef gh", wrap width 10:
2001        // Row 0: 10 spaces (len 10) -> wraps at ix 10 with indent 0
2002        // Row 1: 4 spaces + "ab cd" (len 9) -> wraps at ix 20
2003        //        base_indent is 14 - 10 = 4.
2004        //        With ExtraColumns(2), candidate = 4 + 2 = 6. 6 + 2 (headroom) = 8 <= 10.
2005        //        Row 2 and subsequent rows get indent 6.
2006        let multiline_indent_text = "              ab cd ef gh";
2007        assert_eq!(
2008            wrapper
2009                .wrap_line(
2010                    &[LineFragment::text(multiline_indent_text)],
2011                    wrap_width,
2012                    IndentAdjustment::ExtraColumns(2),
2013                )
2014                .collect::<Vec<_>>(),
2015            &[
2016                Boundary::new(10, 0),
2017                Boundary::new(20, 6),
2018                Boundary::new(23, 6),
2019            ]
2020        );
2021
2022        // When a word boundary precedes an oversized carried suffix that itself
2023        // exceeds wrap_width (e.g. text followed by an inline element), wrapping
2024        // at the earlier candidate would force the continuation row to immediately
2025        // overflow even with 0 indent. The wrapper must reject the candidate and
2026        // break before the overflowing item instead.
2027        //
2028        // "aaaaaaaaaaaaaaaaaaa a" (21 chars: 19 'a's, space, 'a') followed by 10-column element:
2029        // Row 0: "aaaaaaaaaa" (10 chars, len 10) -> wraps at ix 10
2030        // Row 1: "aaaaaaaa" (8 chars) with 2 indent (len 10) -> wraps at ix 18
2031        // Row 2: "a a" (3 chars) with 2 indent (len 5)
2032        //        candidate boundary at ix 20 (space)
2033        //        Then element (10 cols): width becomes 5 + 10 = 15 > wrap_width (10).
2034        //        Candidate would carry 'a' (1 col) + element (10 cols) = 11 cols > 10.
2035        //        Because carried suffix (11) > wrap_width (10), candidate is rejected.
2036        //        Wrapper breaks at ix 21 (before element) with indent 0.
2037        // Row 3: element (10 cols, len 10)
2038        let oversized_suffix_fragments = [
2039            LineFragment::text("aaaaaaaaaaaaaaaaaaa a"),
2040            LineFragment::element(space_width * 10.0, 1),
2041        ];
2042        assert_eq!(
2043            wrapper
2044                .wrap_line(
2045                    &oversized_suffix_fragments,
2046                    wrap_width,
2047                    IndentAdjustment::ExtraColumns(2),
2048                )
2049                .collect::<Vec<_>>(),
2050            &[
2051                Boundary::new(10, 2),
2052                Boundary::new(18, 2),
2053                Boundary::new(21, 0),
2054            ]
2055        );
2056
2057        assert_eq!(
2058            wrapper
2059                .wrap_line(
2060                    &[LineFragment::text("  aaaaaaaa")],
2061                    space_width * 4.0,
2062                    IndentAdjustment::ExtraColumns(u32::MAX),
2063                )
2064                .collect::<Vec<_>>(),
2065            &[Boundary::new(4, 0), Boundary::new(8, 0)]
2066        );
2067    }
2068}