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 .into_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 ellipsis: Option<&str>,
137 runs: &mut Vec<TextRun>,
138 ) -> SharedString {
139 let mut width = px(0.);
140 let mut ellipsis_width = px(0.);
141 if let Some(ellipsis) = ellipsis {
142 for c in ellipsis.chars() {
143 ellipsis_width += self.width_for_char(c);
144 }
145 }
146
147 let mut char_indices = line.char_indices();
148 let mut truncate_ix = 0;
149 for (ix, c) in char_indices {
150 if width + ellipsis_width < truncate_width {
151 truncate_ix = ix;
152 }
153
154 let char_width = self.width_for_char(c);
155 width += char_width;
156
157 if width.floor() > truncate_width {
158 let ellipsis = ellipsis.unwrap_or("");
159 let result = SharedString::from(format!("{}{}", &line[..truncate_ix], ellipsis));
160 update_runs_after_truncation(&result, ellipsis, runs);
161
162 return result;
163 }
164 }
165
166 line
167 }
168
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 // Some other known special characters that should be treated as word characters,
186 // e.g. `a-b`, `var_name`, `I'm`, '@mention`, `#hashtag`, `100%`, `3.1415`, `2^3`, `a~b`, etc.
187 matches!(c, '-' | '_' | '.' | '\'' | '$' | '%' | '@' | '#' | '^' | '~' | ',') ||
188 // Characters that used in URL, e.g. `https://github.com/zed-industries/zed?a=1&b=2` for better wrapping a long URL.
189 matches!(c, '/' | ':' | '?' | '&' | '=') ||
190 // `⋯` character is special used in Zed, to keep this at the end of the line.
191 matches!(c, '⋯')
192 }
193
194 #[inline(always)]
195 fn width_for_char(&mut self, c: char) -> Pixels {
196 if (c as u32) < 128 {
197 if let Some(cached_width) = self.cached_ascii_char_widths[c as usize] {
198 cached_width
199 } else {
200 let width = self.compute_width_for_char(c);
201 self.cached_ascii_char_widths[c as usize] = Some(width);
202 width
203 }
204 } else if let Some(cached_width) = self.cached_other_char_widths.get(&c) {
205 *cached_width
206 } else {
207 let width = self.compute_width_for_char(c);
208 self.cached_other_char_widths.insert(c, width);
209 width
210 }
211 }
212
213 fn compute_width_for_char(&self, c: char) -> Pixels {
214 let mut buffer = [0; 4];
215 let buffer = c.encode_utf8(&mut buffer);
216 self.platform_text_system
217 .layout_line(
218 buffer,
219 self.font_size,
220 &[FontRun {
221 len: buffer.len(),
222 font_id: self.font_id,
223 }],
224 )
225 .width
226 }
227}
228
229fn update_runs_after_truncation(result: &str, ellipsis: &str, runs: &mut Vec<TextRun>) {
230 let mut truncate_at = result.len() - ellipsis.len();
231 let mut run_end = None;
232 for (run_index, run) in runs.iter_mut().enumerate() {
233 if run.len <= truncate_at {
234 truncate_at -= run.len;
235 } else {
236 run.len = truncate_at + ellipsis.len();
237 run_end = Some(run_index + 1);
238 break;
239 }
240 }
241 if let Some(run_end) = run_end {
242 runs.truncate(run_end);
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::{
324 Font, FontFeatures, FontStyle, FontWeight, Hsla, TestAppContext, TestDispatcher, font,
325 };
326 #[cfg(target_os = "macos")]
327 use crate::{TextRun, WindowTextSystem, WrapBoundary};
328 use rand::prelude::*;
329
330 fn build_wrapper() -> LineWrapper {
331 let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
332 let cx = TestAppContext::build(dispatcher, None);
333 let id = cx.text_system().font_id(&font("Zed Plex Mono")).unwrap();
334 LineWrapper::new(id, px(16.), cx.text_system().platform_text_system.clone())
335 }
336
337 fn generate_test_runs(input_run_len: &[usize]) -> Vec<TextRun> {
338 input_run_len
339 .iter()
340 .map(|run_len| TextRun {
341 len: *run_len,
342 font: Font {
343 family: "Dummy".into(),
344 features: FontFeatures::default(),
345 fallbacks: None,
346 weight: FontWeight::default(),
347 style: FontStyle::Normal,
348 },
349 color: Hsla::default(),
350 background_color: None,
351 underline: None,
352 strikethrough: None,
353 })
354 .collect()
355 }
356
357 #[test]
358 fn test_wrap_line() {
359 let mut wrapper = build_wrapper();
360
361 assert_eq!(
362 wrapper
363 .wrap_line(&[LineFragment::text("aa bbb cccc ddddd eeee")], px(72.))
364 .collect::<Vec<_>>(),
365 &[
366 Boundary::new(7, 0),
367 Boundary::new(12, 0),
368 Boundary::new(18, 0)
369 ],
370 );
371 assert_eq!(
372 wrapper
373 .wrap_line(&[LineFragment::text("aaa aaaaaaaaaaaaaaaaaa")], px(72.0))
374 .collect::<Vec<_>>(),
375 &[
376 Boundary::new(4, 0),
377 Boundary::new(11, 0),
378 Boundary::new(18, 0)
379 ],
380 );
381 assert_eq!(
382 wrapper
383 .wrap_line(&[LineFragment::text(" aaaaaaa")], px(72.))
384 .collect::<Vec<_>>(),
385 &[
386 Boundary::new(7, 5),
387 Boundary::new(9, 5),
388 Boundary::new(11, 5),
389 ]
390 );
391 assert_eq!(
392 wrapper
393 .wrap_line(
394 &[LineFragment::text(" ")],
395 px(72.)
396 )
397 .collect::<Vec<_>>(),
398 &[
399 Boundary::new(7, 0),
400 Boundary::new(14, 0),
401 Boundary::new(21, 0)
402 ]
403 );
404 assert_eq!(
405 wrapper
406 .wrap_line(&[LineFragment::text(" aaaaaaaaaaaaaa")], px(72.))
407 .collect::<Vec<_>>(),
408 &[
409 Boundary::new(7, 0),
410 Boundary::new(14, 3),
411 Boundary::new(18, 3),
412 Boundary::new(22, 3),
413 ]
414 );
415
416 // Test wrapping multiple text fragments
417 assert_eq!(
418 wrapper
419 .wrap_line(
420 &[
421 LineFragment::text("aa bbb "),
422 LineFragment::text("cccc ddddd eeee")
423 ],
424 px(72.)
425 )
426 .collect::<Vec<_>>(),
427 &[
428 Boundary::new(7, 0),
429 Boundary::new(12, 0),
430 Boundary::new(18, 0)
431 ],
432 );
433
434 // Test wrapping with a mix of text and element fragments
435 assert_eq!(
436 wrapper
437 .wrap_line(
438 &[
439 LineFragment::text("aa "),
440 LineFragment::element(px(20.), 1),
441 LineFragment::text(" bbb "),
442 LineFragment::element(px(30.), 1),
443 LineFragment::text(" cccc")
444 ],
445 px(72.)
446 )
447 .collect::<Vec<_>>(),
448 &[
449 Boundary::new(5, 0),
450 Boundary::new(9, 0),
451 Boundary::new(11, 0)
452 ],
453 );
454
455 // Test with element at the beginning and text afterward
456 assert_eq!(
457 wrapper
458 .wrap_line(
459 &[
460 LineFragment::element(px(50.), 1),
461 LineFragment::text(" aaaa bbbb cccc dddd")
462 ],
463 px(72.)
464 )
465 .collect::<Vec<_>>(),
466 &[
467 Boundary::new(2, 0),
468 Boundary::new(7, 0),
469 Boundary::new(12, 0),
470 Boundary::new(17, 0)
471 ],
472 );
473
474 // Test with a large element that forces wrapping by itself
475 assert_eq!(
476 wrapper
477 .wrap_line(
478 &[
479 LineFragment::text("short text "),
480 LineFragment::element(px(100.), 1),
481 LineFragment::text(" more text")
482 ],
483 px(72.)
484 )
485 .collect::<Vec<_>>(),
486 &[
487 Boundary::new(6, 0),
488 Boundary::new(11, 0),
489 Boundary::new(12, 0),
490 Boundary::new(18, 0)
491 ],
492 );
493 }
494
495 #[test]
496 fn test_truncate_line() {
497 let mut wrapper = build_wrapper();
498
499 fn perform_test(
500 wrapper: &mut LineWrapper,
501 text: &'static str,
502 result: &'static str,
503 ellipsis: Option<&str>,
504 ) {
505 let dummy_run_lens = vec![text.len()];
506 let mut dummy_runs = generate_test_runs(&dummy_run_lens);
507 assert_eq!(
508 wrapper.truncate_line(text.into(), px(220.), ellipsis, &mut dummy_runs),
509 result
510 );
511 assert_eq!(dummy_runs.first().unwrap().len, result.len());
512 }
513
514 perform_test(
515 &mut wrapper,
516 "aa bbb cccc ddddd eeee ffff gggg",
517 "aa bbb cccc ddddd eeee",
518 None,
519 );
520 perform_test(
521 &mut wrapper,
522 "aa bbb cccc ddddd eeee ffff gggg",
523 "aa bbb cccc ddddd eee…",
524 Some("…"),
525 );
526 perform_test(
527 &mut wrapper,
528 "aa bbb cccc ddddd eeee ffff gggg",
529 "aa bbb cccc dddd......",
530 Some("......"),
531 );
532 }
533
534 #[test]
535 fn test_truncate_multiple_runs() {
536 let mut wrapper = build_wrapper();
537
538 fn perform_test(
539 wrapper: &mut LineWrapper,
540 text: &'static str,
541 result: &str,
542 run_lens: &[usize],
543 result_run_len: &[usize],
544 line_width: Pixels,
545 ) {
546 let mut dummy_runs = generate_test_runs(run_lens);
547 assert_eq!(
548 wrapper.truncate_line(text.into(), line_width, Some("…"), &mut dummy_runs),
549 result
550 );
551 for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
552 assert_eq!(run.len, *result_len);
553 }
554 }
555 // Case 0: Normal
556 // Text: abcdefghijkl
557 // Runs: Run0 { len: 12, ... }
558 //
559 // Truncate res: abcd… (truncate_at = 4)
560 // Run res: Run0 { string: abcd…, len: 7, ... }
561 perform_test(&mut wrapper, "abcdefghijkl", "abcd…", &[12], &[7], px(50.));
562 // Case 1: Drop some runs
563 // Text: abcdefghijkl
564 // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
565 //
566 // Truncate res: abcdef… (truncate_at = 6)
567 // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
568 // 5, ... }
569 perform_test(
570 &mut wrapper,
571 "abcdefghijkl",
572 "abcdef…",
573 &[4, 4, 4],
574 &[4, 5],
575 px(70.),
576 );
577 // Case 2: Truncate at start of some run
578 // Text: abcdefghijkl
579 // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
580 //
581 // Truncate res: abcdefgh… (truncate_at = 8)
582 // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
583 // 4, ... }, Run2 { string: …, len: 3, ... }
584 perform_test(
585 &mut wrapper,
586 "abcdefghijkl",
587 "abcdefgh…",
588 &[4, 4, 4],
589 &[4, 4, 3],
590 px(90.),
591 );
592 }
593
594 #[test]
595 fn test_update_run_after_truncation() {
596 fn perform_test(result: &str, run_lens: &[usize], result_run_lens: &[usize]) {
597 let mut dummy_runs = generate_test_runs(run_lens);
598 update_runs_after_truncation(result, "…", &mut dummy_runs);
599 for (run, result_len) in dummy_runs.iter().zip(result_run_lens) {
600 assert_eq!(run.len, *result_len);
601 }
602 }
603 // Case 0: Normal
604 // Text: abcdefghijkl
605 // Runs: Run0 { len: 12, ... }
606 //
607 // Truncate res: abcd… (truncate_at = 4)
608 // Run res: Run0 { string: abcd…, len: 7, ... }
609 perform_test("abcd…", &[12], &[7]);
610 // Case 1: Drop some runs
611 // Text: abcdefghijkl
612 // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
613 //
614 // Truncate res: abcdef… (truncate_at = 6)
615 // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: ef…, len:
616 // 5, ... }
617 perform_test("abcdef…", &[4, 4, 4], &[4, 5]);
618 // Case 2: Truncate at start of some run
619 // Text: abcdefghijkl
620 // Runs: Run0 { len: 4, ... }, Run1 { len: 4, ... }, Run2 { len: 4, ... }
621 //
622 // Truncate res: abcdefgh… (truncate_at = 8)
623 // Runs res: Run0 { string: abcd, len: 4, ... }, Run1 { string: efgh, len:
624 // 4, ... }, Run2 { string: …, len: 3, ... }
625 perform_test("abcdefgh…", &[4, 4, 4], &[4, 4, 3]);
626 }
627
628 #[test]
629 fn test_is_word_char() {
630 #[track_caller]
631 fn assert_word(word: &str) {
632 for c in word.chars() {
633 assert!(LineWrapper::is_word_char(c), "assertion failed for '{}'", c);
634 }
635 }
636
637 #[track_caller]
638 fn assert_not_word(word: &str) {
639 let found = word.chars().any(|c| !LineWrapper::is_word_char(c));
640 assert!(found, "assertion failed for '{}'", word);
641 }
642
643 assert_word("Hello123");
644 assert_word("non-English");
645 assert_word("var_name");
646 assert_word("123456");
647 assert_word("3.1415");
648 assert_word("10^2");
649 assert_word("1~2");
650 assert_word("100%");
651 assert_word("@mention");
652 assert_word("#hashtag");
653 assert_word("$variable");
654 assert_word("more⋯");
655
656 // Space
657 assert_not_word("foo bar");
658
659 // URL case
660 assert_word("https://github.com/zed-industries/zed/");
661 assert_word("github.com");
662 assert_word("a=1&b=2");
663
664 // Latin-1 Supplement
665 assert_word("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ");
666 // Latin Extended-A
667 assert_word("ĀāĂ㥹ĆćĈĉĊċČčĎď");
668 // Latin Extended-B
669 assert_word("ƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏ");
670 // Cyrillic
671 assert_word("АБВГДЕЖЗИЙКЛМНОП");
672
673 // non-word characters
674 assert_not_word("你好");
675 assert_not_word("안녕하세요");
676 assert_not_word("こんにちは");
677 assert_not_word("😀😁😂");
678 assert_not_word("()[]{}<>");
679 }
680
681 // For compatibility with the test macro
682 #[cfg(target_os = "macos")]
683 use crate as gpui;
684
685 // These seem to vary wildly based on the text system.
686 #[cfg(target_os = "macos")]
687 #[crate::test]
688 fn test_wrap_shaped_line(cx: &mut TestAppContext) {
689 cx.update(|cx| {
690 let text_system = WindowTextSystem::new(cx.text_system().clone());
691
692 let normal = TextRun {
693 len: 0,
694 font: font("Helvetica"),
695 color: Default::default(),
696 underline: Default::default(),
697 strikethrough: None,
698 background_color: None,
699 };
700 let bold = TextRun {
701 len: 0,
702 font: font("Helvetica").bold(),
703 color: Default::default(),
704 underline: Default::default(),
705 strikethrough: None,
706 background_color: None,
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}