Skip to main content

gpui/text_system/
line_wrapper.rs

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