1use crate::{FontId, FontRun, Pixels, PlatformTextSystem, SharedString, TextRun, px};
2use collections::HashMap;
3use std::{borrow::Cow, 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<'a>(
133 &mut self,
134 line: SharedString,
135 truncate_width: Pixels,
136 truncation_suffix: &str,
137 runs: &'a [TextRun],
138 ) -> (SharedString, Cow<'a, [TextRun]>) {
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 let mut runs = runs.to_vec();
158 update_runs_after_truncation(&result, truncation_suffix, &mut runs);
159
160 return (result, Cow::Owned(runs));
161 }
162 }
163
164 (line, Cow::Borrowed(runs))
165 }
166
167 /// Any character in this list should be treated as a word character,
168 /// meaning it can be part of a word that should not be wrapped.
169 pub(crate) fn is_word_char(c: char) -> bool {
170 // ASCII alphanumeric characters, for English, numbers: `Hello123`, etc.
171 c.is_ascii_alphanumeric() ||
172 // Latin script in Unicode for French, German, Spanish, etc.
173 // Latin-1 Supplement
174 // https://en.wikipedia.org/wiki/Latin-1_Supplement
175 matches!(c, '\u{00C0}'..='\u{00FF}') ||
176 // Latin Extended-A
177 // https://en.wikipedia.org/wiki/Latin_Extended-A
178 matches!(c, '\u{0100}'..='\u{017F}') ||
179 // Latin Extended-B
180 // https://en.wikipedia.org/wiki/Latin_Extended-B
181 matches!(c, '\u{0180}'..='\u{024F}') ||
182 // Cyrillic for Russian, Ukrainian, etc.
183 // https://en.wikipedia.org/wiki/Cyrillic_script_in_Unicode
184 matches!(c, '\u{0400}'..='\u{04FF}') ||
185
186 // Vietnamese (https://vietunicode.sourceforge.net/charset/)
187 matches!(c, '\u{1E00}'..='\u{1EFF}') || // Latin Extended Additional
188 matches!(c, '\u{0300}'..='\u{036F}') || // Combining Diacritical Marks
189
190 // Some other known special characters that should be treated as word characters,
191 // e.g. `a-b`, `var_name`, `I'm`, '@mention`, `#hashtag`, `100%`, `3.1415`,
192 // `2^3`, `a~b`, `a=1`, `Self::new`, etc.
193 matches!(c, '-' | '_' | '.' | '\'' | '$' | '%' | '@' | '#' | '^' | '~' | ',' | '=' | ':') ||
194 // `⋯` character is special used in Zed, to keep this at the end of the line.
195 matches!(c, '⋯')
196 }
197
198 #[inline(always)]
199 fn width_for_char(&mut self, c: char) -> Pixels {
200 if (c as u32) < 128 {
201 if let Some(cached_width) = self.cached_ascii_char_widths[c as usize] {
202 cached_width
203 } else {
204 let width = self.compute_width_for_char(c);
205 self.cached_ascii_char_widths[c as usize] = Some(width);
206 width
207 }
208 } else if let Some(cached_width) = self.cached_other_char_widths.get(&c) {
209 *cached_width
210 } else {
211 let width = self.compute_width_for_char(c);
212 self.cached_other_char_widths.insert(c, width);
213 width
214 }
215 }
216
217 fn compute_width_for_char(&self, c: char) -> Pixels {
218 let mut buffer = [0; 4];
219 let buffer = c.encode_utf8(&mut buffer);
220 self.platform_text_system
221 .layout_line(
222 buffer,
223 self.font_size,
224 &[FontRun {
225 len: buffer.len(),
226 font_id: self.font_id,
227 }],
228 )
229 .width
230 }
231}
232
233fn update_runs_after_truncation(result: &str, ellipsis: &str, runs: &mut Vec<TextRun>) {
234 let mut truncate_at = result.len() - ellipsis.len();
235 for (run_index, run) in runs.iter_mut().enumerate() {
236 if run.len <= truncate_at {
237 truncate_at -= run.len;
238 } else {
239 run.len = truncate_at + ellipsis.len();
240 runs.truncate(run_index + 1);
241 break;
242 }
243 }
244}
245
246/// A fragment of a line that can be wrapped.
247pub enum LineFragment<'a> {
248 /// A text fragment consisting of characters.
249 Text {
250 /// The text content of the fragment.
251 text: &'a str,
252 },
253 /// A non-text element with a fixed width.
254 Element {
255 /// The width of the element in pixels.
256 width: Pixels,
257 /// The UTF-8 encoded length of the element.
258 len_utf8: usize,
259 },
260}
261
262impl<'a> LineFragment<'a> {
263 /// Creates a new text fragment from the given text.
264 pub fn text(text: &'a str) -> Self {
265 LineFragment::Text { text }
266 }
267
268 /// Creates a new non-text element with the given width and UTF-8 encoded length.
269 pub fn element(width: Pixels, len_utf8: usize) -> Self {
270 LineFragment::Element { width, len_utf8 }
271 }
272
273 fn wrap_boundary_candidates(&self) -> impl Iterator<Item = WrapBoundaryCandidate> {
274 let text = match self {
275 LineFragment::Text { text } => text,
276 LineFragment::Element { .. } => "\0",
277 };
278 text.chars().map(move |character| {
279 if let LineFragment::Element { width, len_utf8 } = self {
280 WrapBoundaryCandidate::Element {
281 width: *width,
282 len_utf8: *len_utf8,
283 }
284 } else {
285 WrapBoundaryCandidate::Char { character }
286 }
287 })
288 }
289}
290
291enum WrapBoundaryCandidate {
292 Char { character: char },
293 Element { width: Pixels, len_utf8: usize },
294}
295
296impl WrapBoundaryCandidate {
297 pub fn len_utf8(&self) -> usize {
298 match self {
299 WrapBoundaryCandidate::Char { character } => character.len_utf8(),
300 WrapBoundaryCandidate::Element { len_utf8: len, .. } => *len,
301 }
302 }
303}
304
305/// A boundary between two lines of text.
306#[derive(Copy, Clone, Debug, PartialEq, Eq)]
307pub struct Boundary {
308 /// The index of the last character in a line
309 pub ix: usize,
310 /// The indent of the next line.
311 pub next_indent: u32,
312}
313
314impl Boundary {
315 fn new(ix: usize, next_indent: u32) -> Self {
316 Self { ix, next_indent }
317 }
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323 use crate::{Font, FontFeatures, FontStyle, FontWeight, TestAppContext, TestDispatcher, font};
324 #[cfg(target_os = "macos")]
325 use crate::{TextRun, WindowTextSystem, WrapBoundary};
326 use rand::prelude::*;
327
328 fn build_wrapper() -> LineWrapper {
329 let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
330 let cx = TestAppContext::build(dispatcher, None);
331 let id = cx.text_system().resolve_font(&font(".ZedMono"));
332 LineWrapper::new(id, px(16.), cx.text_system().platform_text_system.clone())
333 }
334
335 fn generate_test_runs(input_run_len: &[usize]) -> Vec<TextRun> {
336 input_run_len
337 .iter()
338 .map(|run_len| TextRun {
339 len: *run_len,
340 font: Font {
341 family: "Dummy".into(),
342 features: FontFeatures::default(),
343 fallbacks: None,
344 weight: FontWeight::default(),
345 style: FontStyle::Normal,
346 },
347 ..Default::default()
348 })
349 .collect()
350 }
351
352 #[test]
353 fn test_wrap_line() {
354 let mut wrapper = build_wrapper();
355
356 assert_eq!(
357 wrapper
358 .wrap_line(&[LineFragment::text("aa bbb cccc ddddd eeee")], px(72.))
359 .collect::<Vec<_>>(),
360 &[
361 Boundary::new(7, 0),
362 Boundary::new(12, 0),
363 Boundary::new(18, 0)
364 ],
365 );
366 assert_eq!(
367 wrapper
368 .wrap_line(&[LineFragment::text("aaa aaaaaaaaaaaaaaaaaa")], px(72.0))
369 .collect::<Vec<_>>(),
370 &[
371 Boundary::new(4, 0),
372 Boundary::new(11, 0),
373 Boundary::new(18, 0)
374 ],
375 );
376 assert_eq!(
377 wrapper
378 .wrap_line(&[LineFragment::text(" aaaaaaa")], px(72.))
379 .collect::<Vec<_>>(),
380 &[
381 Boundary::new(7, 5),
382 Boundary::new(9, 5),
383 Boundary::new(11, 5),
384 ]
385 );
386 assert_eq!(
387 wrapper
388 .wrap_line(
389 &[LineFragment::text(" ")],
390 px(72.)
391 )
392 .collect::<Vec<_>>(),
393 &[
394 Boundary::new(7, 0),
395 Boundary::new(14, 0),
396 Boundary::new(21, 0)
397 ]
398 );
399 assert_eq!(
400 wrapper
401 .wrap_line(&[LineFragment::text(" aaaaaaaaaaaaaa")], px(72.))
402 .collect::<Vec<_>>(),
403 &[
404 Boundary::new(7, 0),
405 Boundary::new(14, 3),
406 Boundary::new(18, 3),
407 Boundary::new(22, 3),
408 ]
409 );
410
411 // Test wrapping multiple text fragments
412 assert_eq!(
413 wrapper
414 .wrap_line(
415 &[
416 LineFragment::text("aa bbb "),
417 LineFragment::text("cccc ddddd eeee")
418 ],
419 px(72.)
420 )
421 .collect::<Vec<_>>(),
422 &[
423 Boundary::new(7, 0),
424 Boundary::new(12, 0),
425 Boundary::new(18, 0)
426 ],
427 );
428
429 // Test wrapping with a mix of text and element fragments
430 assert_eq!(
431 wrapper
432 .wrap_line(
433 &[
434 LineFragment::text("aa "),
435 LineFragment::element(px(20.), 1),
436 LineFragment::text(" bbb "),
437 LineFragment::element(px(30.), 1),
438 LineFragment::text(" cccc")
439 ],
440 px(72.)
441 )
442 .collect::<Vec<_>>(),
443 &[
444 Boundary::new(5, 0),
445 Boundary::new(9, 0),
446 Boundary::new(11, 0)
447 ],
448 );
449
450 // Test with element at the beginning and text afterward
451 assert_eq!(
452 wrapper
453 .wrap_line(
454 &[
455 LineFragment::element(px(50.), 1),
456 LineFragment::text(" aaaa bbbb cccc dddd")
457 ],
458 px(72.)
459 )
460 .collect::<Vec<_>>(),
461 &[
462 Boundary::new(2, 0),
463 Boundary::new(7, 0),
464 Boundary::new(12, 0),
465 Boundary::new(17, 0)
466 ],
467 );
468
469 // Test with a large element that forces wrapping by itself
470 assert_eq!(
471 wrapper
472 .wrap_line(
473 &[
474 LineFragment::text("short text "),
475 LineFragment::element(px(100.), 1),
476 LineFragment::text(" more text")
477 ],
478 px(72.)
479 )
480 .collect::<Vec<_>>(),
481 &[
482 Boundary::new(6, 0),
483 Boundary::new(11, 0),
484 Boundary::new(12, 0),
485 Boundary::new(18, 0)
486 ],
487 );
488 }
489
490 #[test]
491 fn test_truncate_line() {
492 let mut wrapper = build_wrapper();
493
494 fn perform_test(
495 wrapper: &mut LineWrapper,
496 text: &'static str,
497 expected: &'static str,
498 ellipsis: &str,
499 ) {
500 let dummy_run_lens = vec![text.len()];
501 let dummy_runs = generate_test_runs(&dummy_run_lens);
502 let (result, dummy_runs) =
503 wrapper.truncate_line(text.into(), px(220.), ellipsis, &dummy_runs);
504 assert_eq!(result, expected);
505 assert_eq!(dummy_runs.first().unwrap().len, result.len());
506 }
507
508 perform_test(
509 &mut wrapper,
510 "aa bbb cccc ddddd eeee ffff gggg",
511 "aa bbb cccc ddddd eeee",
512 "",
513 );
514 perform_test(
515 &mut wrapper,
516 "aa bbb cccc ddddd eeee ffff gggg",
517 "aa bbb cccc ddddd eee…",
518 "…",
519 );
520 perform_test(
521 &mut wrapper,
522 "aa bbb cccc ddddd eeee ffff gggg",
523 "aa bbb cccc dddd......",
524 "......",
525 );
526 }
527
528 #[test]
529 fn test_truncate_multiple_runs() {
530 let mut wrapper = build_wrapper();
531
532 fn perform_test(
533 wrapper: &mut LineWrapper,
534 text: &'static str,
535 expected: &str,
536 run_lens: &[usize],
537 result_run_len: &[usize],
538 line_width: Pixels,
539 ) {
540 let dummy_runs = generate_test_runs(run_lens);
541 let (result, dummy_runs) =
542 wrapper.truncate_line(text.into(), line_width, "…", &dummy_runs);
543 assert_eq!(result, expected);
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!(
627 LineWrapper::is_word_char(c),
628 "assertion failed for '{}' (unicode 0x{:x})",
629 c,
630 c as u32
631 );
632 }
633 }
634
635 #[track_caller]
636 fn assert_not_word(word: &str) {
637 let found = word.chars().any(|c| !LineWrapper::is_word_char(c));
638 assert!(found, "assertion failed for '{}'", word);
639 }
640
641 assert_word("Hello123");
642 assert_word("non-English");
643 assert_word("var_name");
644 assert_word("123456");
645 assert_word("3.1415");
646 assert_word("10^2");
647 assert_word("1~2");
648 assert_word("100%");
649 assert_word("@mention");
650 assert_word("#hashtag");
651 assert_word("$variable");
652 assert_word("a=1");
653 assert_word("Self::is_word_char");
654 assert_word("more⋯");
655
656 // Space
657 assert_not_word("foo bar");
658
659 // URL case
660 assert_word("github.com");
661 assert_not_word("zed-industries/zed");
662 assert_not_word("zed-industries\\zed");
663 assert_not_word("a=1&b=2");
664 assert_not_word("foo?b=2");
665
666 // Latin-1 Supplement
667 assert_word("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ");
668 // Latin Extended-A
669 assert_word("ĀāĂ㥹ĆćĈĉĊċČčĎď");
670 // Latin Extended-B
671 assert_word("ƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏ");
672 // Cyrillic
673 assert_word("АБВГДЕЖЗИЙКЛМНОП");
674 // Vietnamese (https://github.com/zed-industries/zed/issues/23245)
675 assert_word("ThậmchíđếnkhithuachạychúngcònnhẫntâmgiếtnốtsốđôngtùchínhtrịởYênBáivàCaoBằng");
676
677 // non-word characters
678 assert_not_word("你好");
679 assert_not_word("안녕하세요");
680 assert_not_word("こんにちは");
681 assert_not_word("😀😁😂");
682 assert_not_word("()[]{}<>");
683 }
684
685 // For compatibility with the test macro
686 #[cfg(target_os = "macos")]
687 use crate as gpui;
688
689 // These seem to vary wildly based on the text system.
690 #[cfg(target_os = "macos")]
691 #[crate::test]
692 fn test_wrap_shaped_line(cx: &mut TestAppContext) {
693 cx.update(|cx| {
694 let text_system = WindowTextSystem::new(cx.text_system().clone());
695
696 let normal = TextRun {
697 len: 0,
698 font: font("Helvetica"),
699 color: Default::default(),
700 underline: Default::default(),
701 ..Default::default()
702 };
703 let bold = TextRun {
704 len: 0,
705 font: font("Helvetica").bold(),
706 ..Default::default()
707 };
708
709 let text = "aa bbb cccc ddddd eeee".into();
710 let lines = text_system
711 .shape_text(
712 text,
713 px(16.),
714 &[
715 normal.with_len(4),
716 bold.with_len(5),
717 normal.with_len(6),
718 bold.with_len(1),
719 normal.with_len(7),
720 ],
721 Some(px(72.)),
722 None,
723 )
724 .unwrap();
725
726 assert_eq!(
727 lines[0].layout.wrap_boundaries(),
728 &[
729 WrapBoundary {
730 run_ix: 0,
731 glyph_ix: 7
732 },
733 WrapBoundary {
734 run_ix: 0,
735 glyph_ix: 12
736 },
737 WrapBoundary {
738 run_ix: 0,
739 glyph_ix: 18
740 }
741 ],
742 );
743 });
744 }
745}