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 let mut run_end = None;
229 for (run_index, run) in runs.iter_mut().enumerate() {
230 if run.len <= truncate_at {
231 truncate_at -= run.len;
232 } else {
233 run.len = truncate_at + ellipsis.len();
234 run_end = Some(run_index + 1);
235 break;
236 }
237 }
238 if let Some(run_end) = run_end {
239 runs.truncate(run_end);
240 }
241}
242
243/// A fragment of a line that can be wrapped.
244pub enum LineFragment<'a> {
245 /// A text fragment consisting of characters.
246 Text {
247 /// The text content of the fragment.
248 text: &'a str,
249 },
250 /// A non-text element with a fixed width.
251 Element {
252 /// The width of the element in pixels.
253 width: Pixels,
254 /// The UTF-8 encoded length of the element.
255 len_utf8: usize,
256 },
257}
258
259impl<'a> LineFragment<'a> {
260 /// Creates a new text fragment from the given text.
261 pub fn text(text: &'a str) -> Self {
262 LineFragment::Text { text }
263 }
264
265 /// Creates a new non-text element with the given width and UTF-8 encoded length.
266 pub fn element(width: Pixels, len_utf8: usize) -> Self {
267 LineFragment::Element { width, len_utf8 }
268 }
269
270 fn wrap_boundary_candidates(&self) -> impl Iterator<Item = WrapBoundaryCandidate> {
271 let text = match self {
272 LineFragment::Text { text } => text,
273 LineFragment::Element { .. } => "\0",
274 };
275 text.chars().map(move |character| {
276 if let LineFragment::Element { width, len_utf8 } = self {
277 WrapBoundaryCandidate::Element {
278 width: *width,
279 len_utf8: *len_utf8,
280 }
281 } else {
282 WrapBoundaryCandidate::Char { character }
283 }
284 })
285 }
286}
287
288enum WrapBoundaryCandidate {
289 Char { character: char },
290 Element { width: Pixels, len_utf8: usize },
291}
292
293impl WrapBoundaryCandidate {
294 pub fn len_utf8(&self) -> usize {
295 match self {
296 WrapBoundaryCandidate::Char { character } => character.len_utf8(),
297 WrapBoundaryCandidate::Element { len_utf8: len, .. } => *len,
298 }
299 }
300}
301
302/// A boundary between two lines of text.
303#[derive(Copy, Clone, Debug, PartialEq, Eq)]
304pub struct Boundary {
305 /// The index of the last character in a line
306 pub ix: usize,
307 /// The indent of the next line.
308 pub next_indent: u32,
309}
310
311impl Boundary {
312 fn new(ix: usize, next_indent: u32) -> Self {
313 Self { ix, next_indent }
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320 use crate::{Font, FontFeatures, FontStyle, FontWeight, Hsla, TestAppContext, font};
321 #[cfg(target_os = "macos")]
322 use crate::{TextRun, WindowTextSystem, WrapBoundary};
323 use scheduler::{TestScheduler, TestSchedulerConfig};
324
325 fn build_wrapper() -> LineWrapper {
326 let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::with_seed(0)));
327 let cx = TestAppContext::build(scheduler, None);
328 let id = cx.text_system().resolve_font(&font(".ZedMono"));
329 LineWrapper::new(id, px(16.), cx.text_system().platform_text_system.clone())
330 }
331
332 fn generate_test_runs(input_run_len: &[usize]) -> Vec<TextRun> {
333 input_run_len
334 .iter()
335 .map(|run_len| TextRun {
336 len: *run_len,
337 font: Font {
338 family: "Dummy".into(),
339 features: FontFeatures::default(),
340 fallbacks: None,
341 weight: FontWeight::default(),
342 style: FontStyle::Normal,
343 },
344 color: Hsla::default(),
345 background_color: None,
346 underline: None,
347 strikethrough: None,
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 result: &'static str,
498 ellipsis: &str,
499 ) {
500 let dummy_run_lens = vec![text.len()];
501 let mut dummy_runs = generate_test_runs(&dummy_run_lens);
502 assert_eq!(
503 wrapper.truncate_line(text.into(), px(220.), ellipsis, &mut dummy_runs),
504 result
505 );
506 assert_eq!(dummy_runs.first().unwrap().len, result.len());
507 }
508
509 perform_test(
510 &mut wrapper,
511 "aa bbb cccc ddddd eeee ffff gggg",
512 "aa bbb cccc ddddd eeee",
513 "",
514 );
515 perform_test(
516 &mut wrapper,
517 "aa bbb cccc ddddd eeee ffff gggg",
518 "aa bbb cccc ddddd eee…",
519 "…",
520 );
521 perform_test(
522 &mut wrapper,
523 "aa bbb cccc ddddd eeee ffff gggg",
524 "aa bbb cccc dddd......",
525 "......",
526 );
527 }
528
529 #[test]
530 fn test_truncate_multiple_runs() {
531 let mut wrapper = build_wrapper();
532
533 fn perform_test(
534 wrapper: &mut LineWrapper,
535 text: &'static str,
536 result: &str,
537 run_lens: &[usize],
538 result_run_len: &[usize],
539 line_width: Pixels,
540 ) {
541 let mut dummy_runs = generate_test_runs(run_lens);
542 assert_eq!(
543 wrapper.truncate_line(text.into(), line_width, "…", &mut dummy_runs),
544 result
545 );
546 for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
547 assert_eq!(run.len, *result_len);
548 }
549 }
550 // Case 0: Normal
551 // Text: abcdefghijkl
552 // Runs: Run0 { len: 12, ... }
553 //
554 // Truncate res: abcd… (truncate_at = 4)
555 // Run res: Run0 { string: abcd…, len: 7, ... }
556 perform_test(&mut wrapper, "abcdefghijkl", "abcd…", &[12], &[7], px(50.));
557 // Case 1: Drop some runs
558 // Text: abcdefghijkl
559 // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
560 //
561 // Truncate res: abcdef… (truncate_at = 6)
562 // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
563 // 5, ... }
564 perform_test(
565 &mut wrapper,
566 "abcdefghijkl",
567 "abcdef…",
568 &[4, 4, 4],
569 &[4, 5],
570 px(70.),
571 );
572 // Case 2: Truncate at start of some run
573 // Text: abcdefghijkl
574 // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
575 //
576 // Truncate res: abcdefgh… (truncate_at = 8)
577 // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
578 // 4, ... }, Run2 { string: …, len: 3, ... }
579 perform_test(
580 &mut wrapper,
581 "abcdefghijkl",
582 "abcdefgh…",
583 &[4, 4, 4],
584 &[4, 4, 3],
585 px(90.),
586 );
587 }
588
589 #[test]
590 fn test_update_run_after_truncation() {
591 fn perform_test(result: &str, run_lens: &[usize], result_run_lens: &[usize]) {
592 let mut dummy_runs = generate_test_runs(run_lens);
593 update_runs_after_truncation(result, "…", &mut dummy_runs);
594 for (run, result_len) in dummy_runs.iter().zip(result_run_lens) {
595 assert_eq!(run.len, *result_len);
596 }
597 }
598 // Case 0: Normal
599 // Text: abcdefghijkl
600 // Runs: Run0 { len: 12, ... }
601 //
602 // Truncate res: abcd… (truncate_at = 4)
603 // Run res: Run0 { string: abcd…, len: 7, ... }
604 perform_test("abcd…", &[12], &[7]);
605 // Case 1: Drop some runs
606 // Text: abcdefghijkl
607 // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
608 //
609 // Truncate res: abcdef… (truncate_at = 6)
610 // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
611 // 5, ... }
612 perform_test("abcdef…", &[4, 4, 4], &[4, 5]);
613 // Case 2: Truncate at start of some run
614 // Text: abcdefghijkl
615 // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
616 //
617 // Truncate res: abcdefgh… (truncate_at = 8)
618 // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
619 // 4, ... }, Run2 { string: …, len: 3, ... }
620 perform_test("abcdefgh…", &[4, 4, 4], &[4, 4, 3]);
621 }
622
623 #[test]
624 fn test_is_word_char() {
625 #[track_caller]
626 fn assert_word(word: &str) {
627 for c in word.chars() {
628 assert!(LineWrapper::is_word_char(c), "assertion failed for '{}'", c);
629 }
630 }
631
632 #[track_caller]
633 fn assert_not_word(word: &str) {
634 let found = word.chars().any(|c| !LineWrapper::is_word_char(c));
635 assert!(found, "assertion failed for '{}'", word);
636 }
637
638 assert_word("Hello123");
639 assert_word("non-English");
640 assert_word("var_name");
641 assert_word("123456");
642 assert_word("3.1415");
643 assert_word("10^2");
644 assert_word("1~2");
645 assert_word("100%");
646 assert_word("@mention");
647 assert_word("#hashtag");
648 assert_word("$variable");
649 assert_word("more⋯");
650
651 // Space
652 assert_not_word("foo bar");
653
654 // URL case
655 assert_word("https://github.com/zed-industries/zed/");
656 assert_word("github.com");
657 assert_word("a=1&b=2");
658
659 // Latin-1 Supplement
660 assert_word("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ");
661 // Latin Extended-A
662 assert_word("ĀāĂ㥹ĆćĈĉĊċČčĎď");
663 // Latin Extended-B
664 assert_word("ƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏ");
665 // Cyrillic
666 assert_word("АБВГДЕЖЗИЙКЛМНОП");
667
668 // non-word characters
669 assert_not_word("你好");
670 assert_not_word("안녕하세요");
671 assert_not_word("こんにちは");
672 assert_not_word("😀😁😂");
673 assert_not_word("()[]{}<>");
674 }
675
676 // For compatibility with the test macro
677 #[cfg(target_os = "macos")]
678 use crate as gpui;
679
680 // These seem to vary wildly based on the text system.
681 #[cfg(target_os = "macos")]
682 #[crate::test]
683 fn test_wrap_shaped_line(cx: &mut TestAppContext) {
684 cx.update(|cx| {
685 let text_system = WindowTextSystem::new(cx.text_system().clone());
686
687 let normal = TextRun {
688 len: 0,
689 font: font("Helvetica"),
690 color: Default::default(),
691 underline: Default::default(),
692 strikethrough: None,
693 background_color: None,
694 };
695 let bold = TextRun {
696 len: 0,
697 font: font("Helvetica").bold(),
698 color: Default::default(),
699 underline: Default::default(),
700 strikethrough: None,
701 background_color: None,
702 };
703
704 let text = "aa bbb cccc ddddd eeee".into();
705 let lines = text_system
706 .shape_text(
707 text,
708 px(16.),
709 &[
710 normal.with_len(4),
711 bold.with_len(5),
712 normal.with_len(6),
713 bold.with_len(1),
714 normal.with_len(7),
715 ],
716 Some(px(72.)),
717 None,
718 )
719 .unwrap();
720
721 assert_eq!(
722 lines[0].layout.wrap_boundaries(),
723 &[
724 WrapBoundary {
725 run_ix: 0,
726 glyph_ix: 7
727 },
728 WrapBoundary {
729 run_ix: 0,
730 glyph_ix: 12
731 },
732 WrapBoundary {
733 run_ix: 0,
734 glyph_ix: 18
735 }
736 ],
737 );
738 });
739 }
740}