line_wrapper.rs

  1use crate::{FontId, FontRun, Pixels, PlatformTextSystem, SharedString, TextRun, px};
  2use collections::HashMap;
  3use std::{iter, sync::Arc};
  4
  5/// The GPUI line wrapper, used to wrap lines of text to a given width.
  6pub struct LineWrapper {
  7    platform_text_system: Arc<dyn PlatformTextSystem>,
  8    pub(crate) font_id: FontId,
  9    pub(crate) font_size: Pixels,
 10    cached_ascii_char_widths: [Option<Pixels>; 128],
 11    cached_other_char_widths: HashMap<char, Pixels>,
 12}
 13
 14impl LineWrapper {
 15    /// The maximum indent that can be applied to a line.
 16    pub const MAX_INDENT: u32 = 256;
 17
 18    pub(crate) fn new(
 19        font_id: FontId,
 20        font_size: Pixels,
 21        text_system: Arc<dyn PlatformTextSystem>,
 22    ) -> Self {
 23        Self {
 24            platform_text_system: text_system,
 25            font_id,
 26            font_size,
 27            cached_ascii_char_widths: [None; 128],
 28            cached_other_char_widths: HashMap::default(),
 29        }
 30    }
 31
 32    /// Wrap a line of text to the given width with this wrapper's font and font size.
 33    pub fn wrap_line<'a>(
 34        &'a mut self,
 35        fragments: &'a [LineFragment],
 36        wrap_width: Pixels,
 37    ) -> impl Iterator<Item = Boundary> + 'a {
 38        let mut width = px(0.);
 39        let mut first_non_whitespace_ix = None;
 40        let mut indent = None;
 41        let mut last_candidate_ix = 0;
 42        let mut last_candidate_width = px(0.);
 43        let mut last_wrap_ix = 0;
 44        let mut prev_c = '\0';
 45        let mut index = 0;
 46        let mut candidates = fragments
 47            .iter()
 48            .flat_map(move |fragment| fragment.wrap_boundary_candidates())
 49            .peekable();
 50        iter::from_fn(move || {
 51            for candidate in candidates.by_ref() {
 52                let ix = index;
 53                index += candidate.len_utf8();
 54                let mut new_prev_c = prev_c;
 55                let item_width = match candidate {
 56                    WrapBoundaryCandidate::Char { character: c } => {
 57                        if c == '\n' {
 58                            continue;
 59                        }
 60
 61                        if Self::is_word_char(c) {
 62                            if prev_c == ' ' && c != ' ' && first_non_whitespace_ix.is_some() {
 63                                last_candidate_ix = ix;
 64                                last_candidate_width = width;
 65                            }
 66                        } else {
 67                            // CJK may not be space separated, e.g.: `Hello world你好世界`
 68                            if c != ' ' && first_non_whitespace_ix.is_some() {
 69                                last_candidate_ix = ix;
 70                                last_candidate_width = width;
 71                            }
 72                        }
 73
 74                        if c != ' ' && first_non_whitespace_ix.is_none() {
 75                            first_non_whitespace_ix = Some(ix);
 76                        }
 77
 78                        new_prev_c = c;
 79
 80                        self.width_for_char(c)
 81                    }
 82                    WrapBoundaryCandidate::Element {
 83                        width: element_width,
 84                        ..
 85                    } => {
 86                        if prev_c == ' ' && first_non_whitespace_ix.is_some() {
 87                            last_candidate_ix = ix;
 88                            last_candidate_width = width;
 89                        }
 90
 91                        if first_non_whitespace_ix.is_none() {
 92                            first_non_whitespace_ix = Some(ix);
 93                        }
 94
 95                        element_width
 96                    }
 97                };
 98
 99                width += item_width;
100                if width > wrap_width && ix > last_wrap_ix {
101                    if let (None, Some(first_non_whitespace_ix)) = (indent, first_non_whitespace_ix)
102                    {
103                        indent = Some(
104                            Self::MAX_INDENT.min((first_non_whitespace_ix - last_wrap_ix) as u32),
105                        );
106                    }
107
108                    if last_candidate_ix > 0 {
109                        last_wrap_ix = last_candidate_ix;
110                        width -= last_candidate_width;
111                        last_candidate_ix = 0;
112                    } else {
113                        last_wrap_ix = ix;
114                        width = item_width;
115                    }
116
117                    if let Some(indent) = indent {
118                        width += self.width_for_char(' ') * indent as f32;
119                    }
120
121                    return Some(Boundary::new(last_wrap_ix, indent.unwrap_or(0)));
122                }
123
124                prev_c = new_prev_c;
125            }
126
127            None
128        })
129    }
130
131    /// Truncate a line of text to the given width with this wrapper's font and font size.
132    pub fn truncate_line(
133        &mut self,
134        line: SharedString,
135        truncate_width: Pixels,
136        truncation_suffix: &str,
137        runs: &mut Vec<TextRun>,
138    ) -> SharedString {
139        let mut width = px(0.);
140        let mut suffix_width = truncation_suffix
141            .chars()
142            .map(|c| self.width_for_char(c))
143            .fold(px(0.0), |a, x| a + x);
144        let mut char_indices = line.char_indices();
145        let mut truncate_ix = 0;
146        for (ix, c) in char_indices {
147            if width + suffix_width < truncate_width {
148                truncate_ix = ix;
149            }
150
151            let char_width = self.width_for_char(c);
152            width += char_width;
153
154            if width.floor() > truncate_width {
155                let result =
156                    SharedString::from(format!("{}{}", &line[..truncate_ix], truncation_suffix));
157                update_runs_after_truncation(&result, truncation_suffix, runs);
158
159                return result;
160            }
161        }
162
163        line
164    }
165
166    pub(crate) fn is_word_char(c: char) -> bool {
167        // ASCII alphanumeric characters, for English, numbers: `Hello123`, etc.
168        c.is_ascii_alphanumeric() ||
169        // Latin script in Unicode for French, German, Spanish, etc.
170        // Latin-1 Supplement
171        // https://en.wikipedia.org/wiki/Latin-1_Supplement
172        matches!(c, '\u{00C0}'..='\u{00FF}') ||
173        // Latin Extended-A
174        // https://en.wikipedia.org/wiki/Latin_Extended-A
175        matches!(c, '\u{0100}'..='\u{017F}') ||
176        // Latin Extended-B
177        // https://en.wikipedia.org/wiki/Latin_Extended-B
178        matches!(c, '\u{0180}'..='\u{024F}') ||
179        // Cyrillic for Russian, Ukrainian, etc.
180        // https://en.wikipedia.org/wiki/Cyrillic_script_in_Unicode
181        matches!(c, '\u{0400}'..='\u{04FF}') ||
182        // Some other known special characters that should be treated as word characters,
183        // e.g. `a-b`, `var_name`, `I'm`, '@mention`, `#hashtag`, `100%`, `3.1415`, `2^3`, `a~b`, etc.
184        matches!(c, '-' | '_' | '.' | '\'' | '$' | '%' | '@' | '#' | '^' | '~' | ',' | '!' | ';' | '*') ||
185        // Characters that used in URL, e.g. `https://github.com/zed-industries/zed?a=1&b=2` for better wrapping a long URL.
186        matches!(c,  '/' | ':' | '?' | '&' | '=') ||
187        // `⋯` character is special used in Zed, to keep this at the end of the line.
188        matches!(c, '⋯')
189    }
190
191    #[inline(always)]
192    fn width_for_char(&mut self, c: char) -> Pixels {
193        if (c as u32) < 128 {
194            if let Some(cached_width) = self.cached_ascii_char_widths[c as usize] {
195                cached_width
196            } else {
197                let width = self.compute_width_for_char(c);
198                self.cached_ascii_char_widths[c as usize] = Some(width);
199                width
200            }
201        } else if let Some(cached_width) = self.cached_other_char_widths.get(&c) {
202            *cached_width
203        } else {
204            let width = self.compute_width_for_char(c);
205            self.cached_other_char_widths.insert(c, width);
206            width
207        }
208    }
209
210    fn compute_width_for_char(&self, c: char) -> Pixels {
211        let mut buffer = [0; 4];
212        let buffer = c.encode_utf8(&mut buffer);
213        self.platform_text_system
214            .layout_line(
215                buffer,
216                self.font_size,
217                &[FontRun {
218                    len: buffer.len(),
219                    font_id: self.font_id,
220                }],
221            )
222            .width
223    }
224}
225
226fn update_runs_after_truncation(result: &str, ellipsis: &str, runs: &mut Vec<TextRun>) {
227    let mut truncate_at = result.len() - ellipsis.len();
228    for (run_index, run) in runs.iter_mut().enumerate() {
229        if run.len <= truncate_at {
230            truncate_at -= run.len;
231        } else {
232            run.len = truncate_at + ellipsis.len();
233            runs.truncate(run_index + 1);
234            break;
235        }
236    }
237}
238
239/// A fragment of a line that can be wrapped.
240pub enum LineFragment<'a> {
241    /// A text fragment consisting of characters.
242    Text {
243        /// The text content of the fragment.
244        text: &'a str,
245    },
246    /// A non-text element with a fixed width.
247    Element {
248        /// The width of the element in pixels.
249        width: Pixels,
250        /// The UTF-8 encoded length of the element.
251        len_utf8: usize,
252    },
253}
254
255impl<'a> LineFragment<'a> {
256    /// Creates a new text fragment from the given text.
257    pub fn text(text: &'a str) -> Self {
258        LineFragment::Text { text }
259    }
260
261    /// Creates a new non-text element with the given width and UTF-8 encoded length.
262    pub fn element(width: Pixels, len_utf8: usize) -> Self {
263        LineFragment::Element { width, len_utf8 }
264    }
265
266    fn wrap_boundary_candidates(&self) -> impl Iterator<Item = WrapBoundaryCandidate> {
267        let text = match self {
268            LineFragment::Text { text } => text,
269            LineFragment::Element { .. } => "\0",
270        };
271        text.chars().map(move |character| {
272            if let LineFragment::Element { width, len_utf8 } = self {
273                WrapBoundaryCandidate::Element {
274                    width: *width,
275                    len_utf8: *len_utf8,
276                }
277            } else {
278                WrapBoundaryCandidate::Char { character }
279            }
280        })
281    }
282}
283
284enum WrapBoundaryCandidate {
285    Char { character: char },
286    Element { width: Pixels, len_utf8: usize },
287}
288
289impl WrapBoundaryCandidate {
290    pub fn len_utf8(&self) -> usize {
291        match self {
292            WrapBoundaryCandidate::Char { character } => character.len_utf8(),
293            WrapBoundaryCandidate::Element { len_utf8: len, .. } => *len,
294        }
295    }
296}
297
298/// A boundary between two lines of text.
299#[derive(Copy, Clone, Debug, PartialEq, Eq)]
300pub struct Boundary {
301    /// The index of the last character in a line
302    pub ix: usize,
303    /// The indent of the next line.
304    pub next_indent: u32,
305}
306
307impl Boundary {
308    fn new(ix: usize, next_indent: u32) -> Self {
309        Self { ix, next_indent }
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316    use crate::{
317        Font, FontFeatures, FontStyle, FontWeight, Hsla, TestAppContext, TestDispatcher, font,
318    };
319    #[cfg(target_os = "macos")]
320    use crate::{TextRun, WindowTextSystem, WrapBoundary};
321    use rand::prelude::*;
322
323    fn build_wrapper() -> LineWrapper {
324        let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
325        let cx = TestAppContext::build(dispatcher, None);
326        let id = cx.text_system().resolve_font(&font(".ZedMono"));
327        LineWrapper::new(id, px(16.), cx.text_system().platform_text_system.clone())
328    }
329
330    fn generate_test_runs(input_run_len: &[usize]) -> Vec<TextRun> {
331        input_run_len
332            .iter()
333            .map(|run_len| TextRun {
334                len: *run_len,
335                font: Font {
336                    family: "Dummy".into(),
337                    features: FontFeatures::default(),
338                    fallbacks: None,
339                    weight: FontWeight::default(),
340                    style: FontStyle::Normal,
341                },
342                color: Hsla::default(),
343                background_color: None,
344                underline: None,
345                strikethrough: None,
346            })
347            .collect()
348    }
349
350    #[test]
351    fn test_wrap_line() {
352        let mut wrapper = build_wrapper();
353
354        assert_eq!(
355            wrapper
356                .wrap_line(&[LineFragment::text("aa bbb cccc ddddd eeee")], px(72.))
357                .collect::<Vec<_>>(),
358            &[
359                Boundary::new(7, 0),
360                Boundary::new(12, 0),
361                Boundary::new(18, 0)
362            ],
363        );
364        assert_eq!(
365            wrapper
366                .wrap_line(&[LineFragment::text("aaa aaaaaaaaaaaaaaaaaa")], px(72.0))
367                .collect::<Vec<_>>(),
368            &[
369                Boundary::new(4, 0),
370                Boundary::new(11, 0),
371                Boundary::new(18, 0)
372            ],
373        );
374        assert_eq!(
375            wrapper
376                .wrap_line(&[LineFragment::text("     aaaaaaa")], px(72.))
377                .collect::<Vec<_>>(),
378            &[
379                Boundary::new(7, 5),
380                Boundary::new(9, 5),
381                Boundary::new(11, 5),
382            ]
383        );
384        assert_eq!(
385            wrapper
386                .wrap_line(
387                    &[LineFragment::text("                            ")],
388                    px(72.)
389                )
390                .collect::<Vec<_>>(),
391            &[
392                Boundary::new(7, 0),
393                Boundary::new(14, 0),
394                Boundary::new(21, 0)
395            ]
396        );
397        assert_eq!(
398            wrapper
399                .wrap_line(&[LineFragment::text("          aaaaaaaaaaaaaa")], px(72.))
400                .collect::<Vec<_>>(),
401            &[
402                Boundary::new(7, 0),
403                Boundary::new(14, 3),
404                Boundary::new(18, 3),
405                Boundary::new(22, 3),
406            ]
407        );
408
409        // Test wrapping multiple text fragments
410        assert_eq!(
411            wrapper
412                .wrap_line(
413                    &[
414                        LineFragment::text("aa bbb "),
415                        LineFragment::text("cccc ddddd eeee")
416                    ],
417                    px(72.)
418                )
419                .collect::<Vec<_>>(),
420            &[
421                Boundary::new(7, 0),
422                Boundary::new(12, 0),
423                Boundary::new(18, 0)
424            ],
425        );
426
427        // Test wrapping with a mix of text and element fragments
428        assert_eq!(
429            wrapper
430                .wrap_line(
431                    &[
432                        LineFragment::text("aa "),
433                        LineFragment::element(px(20.), 1),
434                        LineFragment::text(" bbb "),
435                        LineFragment::element(px(30.), 1),
436                        LineFragment::text(" cccc")
437                    ],
438                    px(72.)
439                )
440                .collect::<Vec<_>>(),
441            &[
442                Boundary::new(5, 0),
443                Boundary::new(9, 0),
444                Boundary::new(11, 0)
445            ],
446        );
447
448        // Test with element at the beginning and text afterward
449        assert_eq!(
450            wrapper
451                .wrap_line(
452                    &[
453                        LineFragment::element(px(50.), 1),
454                        LineFragment::text(" aaaa bbbb cccc dddd")
455                    ],
456                    px(72.)
457                )
458                .collect::<Vec<_>>(),
459            &[
460                Boundary::new(2, 0),
461                Boundary::new(7, 0),
462                Boundary::new(12, 0),
463                Boundary::new(17, 0)
464            ],
465        );
466
467        // Test with a large element that forces wrapping by itself
468        assert_eq!(
469            wrapper
470                .wrap_line(
471                    &[
472                        LineFragment::text("short text "),
473                        LineFragment::element(px(100.), 1),
474                        LineFragment::text(" more text")
475                    ],
476                    px(72.)
477                )
478                .collect::<Vec<_>>(),
479            &[
480                Boundary::new(6, 0),
481                Boundary::new(11, 0),
482                Boundary::new(12, 0),
483                Boundary::new(18, 0)
484            ],
485        );
486    }
487
488    #[test]
489    fn test_truncate_line() {
490        let mut wrapper = build_wrapper();
491
492        fn perform_test(
493            wrapper: &mut LineWrapper,
494            text: &'static str,
495            result: &'static str,
496            ellipsis: &str,
497        ) {
498            let dummy_run_lens = vec![text.len()];
499            let mut dummy_runs = generate_test_runs(&dummy_run_lens);
500            assert_eq!(
501                wrapper.truncate_line(text.into(), px(220.), ellipsis, &mut dummy_runs),
502                result
503            );
504            assert_eq!(dummy_runs.first().unwrap().len, result.len());
505        }
506
507        perform_test(
508            &mut wrapper,
509            "aa bbb cccc ddddd eeee ffff gggg",
510            "aa bbb cccc ddddd eeee",
511            "",
512        );
513        perform_test(
514            &mut wrapper,
515            "aa bbb cccc ddddd eeee ffff gggg",
516            "aa bbb cccc ddddd eee…",
517            "",
518        );
519        perform_test(
520            &mut wrapper,
521            "aa bbb cccc ddddd eeee ffff gggg",
522            "aa bbb cccc dddd......",
523            "......",
524        );
525    }
526
527    #[test]
528    fn test_truncate_multiple_runs() {
529        let mut wrapper = build_wrapper();
530
531        fn perform_test(
532            wrapper: &mut LineWrapper,
533            text: &'static str,
534            result: &str,
535            run_lens: &[usize],
536            result_run_len: &[usize],
537            line_width: Pixels,
538        ) {
539            let mut dummy_runs = generate_test_runs(run_lens);
540            assert_eq!(
541                wrapper.truncate_line(text.into(), line_width, "", &mut dummy_runs),
542                result
543            );
544            for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
545                assert_eq!(run.len, *result_len);
546            }
547        }
548        // Case 0: Normal
549        // Text: abcdefghijkl
550        // Runs: Run0 { len: 12, ... }
551        //
552        // Truncate res: abcd… (truncate_at = 4)
553        // Run res: Run0 { string: abcd…, len: 7, ... }
554        perform_test(&mut wrapper, "abcdefghijkl", "abcd…", &[12], &[7], px(50.));
555        // Case 1: Drop some runs
556        // Text: abcdefghijkl
557        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
558        //
559        // Truncate res: abcdef… (truncate_at = 6)
560        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
561        // 5, ... }
562        perform_test(
563            &mut wrapper,
564            "abcdefghijkl",
565            "abcdef…",
566            &[4, 4, 4],
567            &[4, 5],
568            px(70.),
569        );
570        // Case 2: Truncate at start of some run
571        // Text: abcdefghijkl
572        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
573        //
574        // Truncate res: abcdefgh… (truncate_at = 8)
575        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
576        // 4, ... }, Run2 { string: …, len: 3, ... }
577        perform_test(
578            &mut wrapper,
579            "abcdefghijkl",
580            "abcdefgh…",
581            &[4, 4, 4],
582            &[4, 4, 3],
583            px(90.),
584        );
585    }
586
587    #[test]
588    fn test_update_run_after_truncation() {
589        fn perform_test(result: &str, run_lens: &[usize], result_run_lens: &[usize]) {
590            let mut dummy_runs = generate_test_runs(run_lens);
591            update_runs_after_truncation(result, "", &mut dummy_runs);
592            for (run, result_len) in dummy_runs.iter().zip(result_run_lens) {
593                assert_eq!(run.len, *result_len);
594            }
595        }
596        // Case 0: Normal
597        // Text: abcdefghijkl
598        // Runs: Run0 { len: 12, ... }
599        //
600        // Truncate res: abcd… (truncate_at = 4)
601        // Run res: Run0 { string: abcd…, len: 7, ... }
602        perform_test("abcd…", &[12], &[7]);
603        // Case 1: Drop some runs
604        // Text: abcdefghijkl
605        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
606        //
607        // Truncate res: abcdef… (truncate_at = 6)
608        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
609        // 5, ... }
610        perform_test("abcdef…", &[4, 4, 4], &[4, 5]);
611        // Case 2: Truncate at start of some run
612        // Text: abcdefghijkl
613        // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
614        //
615        // Truncate res: abcdefgh… (truncate_at = 8)
616        // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
617        // 4, ... }, Run2 { string: …, len: 3, ... }
618        perform_test("abcdefgh…", &[4, 4, 4], &[4, 4, 3]);
619    }
620
621    #[test]
622    fn test_is_word_char() {
623        #[track_caller]
624        fn assert_word(word: &str) {
625            for c in word.chars() {
626                assert!(LineWrapper::is_word_char(c), "assertion failed for '{}'", c);
627            }
628        }
629
630        #[track_caller]
631        fn assert_not_word(word: &str) {
632            let found = word.chars().any(|c| !LineWrapper::is_word_char(c));
633            assert!(found, "assertion failed for '{}'", word);
634        }
635
636        assert_word("Hello123");
637        assert_word("non-English");
638        assert_word("var_name");
639        assert_word("123456");
640        assert_word("3.1415");
641        assert_word("10^2");
642        assert_word("1~2");
643        assert_word("100%");
644        assert_word("@mention");
645        assert_word("#hashtag");
646        assert_word("$variable");
647        assert_word("more⋯");
648
649        // Space
650        assert_not_word("foo bar");
651
652        // URL case
653        assert_word("https://github.com/zed-industries/zed/");
654        assert_word("github.com");
655        assert_word("a=1&b=2");
656
657        // Latin-1 Supplement
658        assert_word("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ");
659        // Latin Extended-A
660        assert_word("ĀāĂ㥹ĆćĈĉĊċČčĎď");
661        // Latin Extended-B
662        assert_word("ƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏ");
663        // Cyrillic
664        assert_word("АБВГДЕЖЗИЙКЛМНОП");
665
666        // non-word characters
667        assert_not_word("你好");
668        assert_not_word("안녕하세요");
669        assert_not_word("こんにちは");
670        assert_not_word("😀😁😂");
671        assert_not_word("()[]{}<>");
672    }
673
674    // For compatibility with the test macro
675    #[cfg(target_os = "macos")]
676    use crate as gpui;
677
678    // These seem to vary wildly based on the text system.
679    #[cfg(target_os = "macos")]
680    #[crate::test]
681    fn test_wrap_shaped_line(cx: &mut TestAppContext) {
682        cx.update(|cx| {
683            let text_system = WindowTextSystem::new(cx.text_system().clone());
684
685            let normal = TextRun {
686                len: 0,
687                font: font("Helvetica"),
688                color: Default::default(),
689                underline: Default::default(),
690                strikethrough: None,
691                background_color: None,
692            };
693            let bold = TextRun {
694                len: 0,
695                font: font("Helvetica").bold(),
696                color: Default::default(),
697                underline: Default::default(),
698                strikethrough: None,
699                background_color: None,
700            };
701
702            let text = "aa bbb cccc ddddd eeee".into();
703            let lines = text_system
704                .shape_text(
705                    text,
706                    px(16.),
707                    &[
708                        normal.with_len(4),
709                        bold.with_len(5),
710                        normal.with_len(6),
711                        bold.with_len(1),
712                        normal.with_len(7),
713                    ],
714                    Some(px(72.)),
715                    None,
716                )
717                .unwrap();
718
719            assert_eq!(
720                lines[0].layout.wrap_boundaries(),
721                &[
722                    WrapBoundary {
723                        run_ix: 0,
724                        glyph_ix: 7
725                    },
726                    WrapBoundary {
727                        run_ix: 0,
728                        glyph_ix: 12
729                    },
730                    WrapBoundary {
731                        run_ix: 0,
732                        glyph_ix: 18
733                    }
734                ],
735            );
736        });
737    }
738}