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