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 // 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`,
187 // `2^3`, `a~b`, `a=1`, `Self::new`, etc.
188 matches!(c, '-' | '_' | '.' | '\'' | '$' | '%' | '@' | '#' | '^' | '~' | ',' | '=' | ':') ||
189 // `⋯` character is special used in Zed, to keep this at the end of the line.
190 matches!(c, '⋯')
191 }
192
193 #[inline(always)]
194 fn width_for_char(&mut self, c: char) -> Pixels {
195 if (c as u32) < 128 {
196 if let Some(cached_width) = self.cached_ascii_char_widths[c as usize] {
197 cached_width
198 } else {
199 let width = self.compute_width_for_char(c);
200 self.cached_ascii_char_widths[c as usize] = Some(width);
201 width
202 }
203 } else if let Some(cached_width) = self.cached_other_char_widths.get(&c) {
204 *cached_width
205 } else {
206 let width = self.compute_width_for_char(c);
207 self.cached_other_char_widths.insert(c, width);
208 width
209 }
210 }
211
212 fn compute_width_for_char(&self, c: char) -> Pixels {
213 let mut buffer = [0; 4];
214 let buffer = c.encode_utf8(&mut buffer);
215 self.platform_text_system
216 .layout_line(
217 buffer,
218 self.font_size,
219 &[FontRun {
220 len: buffer.len(),
221 font_id: self.font_id,
222 }],
223 )
224 .width
225 }
226}
227
228fn update_runs_after_truncation(result: &str, ellipsis: &str, runs: &mut Vec<TextRun>) {
229 let mut truncate_at = result.len() - ellipsis.len();
230 for (run_index, run) in runs.iter_mut().enumerate() {
231 if run.len <= truncate_at {
232 truncate_at -= run.len;
233 } else {
234 run.len = truncate_at + ellipsis.len();
235 runs.truncate(run_index + 1);
236 break;
237 }
238 }
239}
240
241/// A fragment of a line that can be wrapped.
242pub enum LineFragment<'a> {
243 /// A text fragment consisting of characters.
244 Text {
245 /// The text content of the fragment.
246 text: &'a str,
247 },
248 /// A non-text element with a fixed width.
249 Element {
250 /// The width of the element in pixels.
251 width: Pixels,
252 /// The UTF-8 encoded length of the element.
253 len_utf8: usize,
254 },
255}
256
257impl<'a> LineFragment<'a> {
258 /// Creates a new text fragment from the given text.
259 pub fn text(text: &'a str) -> Self {
260 LineFragment::Text { text }
261 }
262
263 /// Creates a new non-text element with the given width and UTF-8 encoded length.
264 pub fn element(width: Pixels, len_utf8: usize) -> Self {
265 LineFragment::Element { width, len_utf8 }
266 }
267
268 fn wrap_boundary_candidates(&self) -> impl Iterator<Item = WrapBoundaryCandidate> {
269 let text = match self {
270 LineFragment::Text { text } => text,
271 LineFragment::Element { .. } => "\0",
272 };
273 text.chars().map(move |character| {
274 if let LineFragment::Element { width, len_utf8 } = self {
275 WrapBoundaryCandidate::Element {
276 width: *width,
277 len_utf8: *len_utf8,
278 }
279 } else {
280 WrapBoundaryCandidate::Char { character }
281 }
282 })
283 }
284}
285
286enum WrapBoundaryCandidate {
287 Char { character: char },
288 Element { width: Pixels, len_utf8: usize },
289}
290
291impl WrapBoundaryCandidate {
292 pub fn len_utf8(&self) -> usize {
293 match self {
294 WrapBoundaryCandidate::Char { character } => character.len_utf8(),
295 WrapBoundaryCandidate::Element { len_utf8: len, .. } => *len,
296 }
297 }
298}
299
300/// A boundary between two lines of text.
301#[derive(Copy, Clone, Debug, PartialEq, Eq)]
302pub struct Boundary {
303 /// The index of the last character in a line
304 pub ix: usize,
305 /// The indent of the next line.
306 pub next_indent: u32,
307}
308
309impl Boundary {
310 fn new(ix: usize, next_indent: u32) -> Self {
311 Self { ix, next_indent }
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318 use crate::{
319 Font, FontFeatures, FontStyle, FontWeight, Hsla, TestAppContext, TestDispatcher, font,
320 };
321 #[cfg(target_os = "macos")]
322 use crate::{TextRun, WindowTextSystem, WrapBoundary};
323 use rand::prelude::*;
324
325 fn build_wrapper() -> LineWrapper {
326 let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
327 let cx = TestAppContext::build(dispatcher, 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 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!(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("a=1");
648 assert_word("Self::is_word_char");
649 assert_word("more⋯");
650
651 // Space
652 assert_not_word("foo bar");
653
654 // URL case
655 assert_word("github.com");
656 assert_not_word("zed-industries/zed");
657 assert_not_word("zed-industries\\zed");
658 assert_not_word("a=1&b=2");
659 assert_not_word("foo?b=2");
660
661 // Latin-1 Supplement
662 assert_word("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ");
663 // Latin Extended-A
664 assert_word("ĀāĂ㥹ĆćĈĉĊċČčĎď");
665 // Latin Extended-B
666 assert_word("ƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏ");
667 // Cyrillic
668 assert_word("АБВГДЕЖЗИЙКЛМНОП");
669
670 // non-word characters
671 assert_not_word("你好");
672 assert_not_word("안녕하세요");
673 assert_not_word("こんにちは");
674 assert_not_word("😀😁😂");
675 assert_not_word("()[]{}<>");
676 }
677
678 // For compatibility with the test macro
679 #[cfg(target_os = "macos")]
680 use crate as gpui;
681
682 // These seem to vary wildly based on the text system.
683 #[cfg(target_os = "macos")]
684 #[crate::test]
685 fn test_wrap_shaped_line(cx: &mut TestAppContext) {
686 cx.update(|cx| {
687 let text_system = WindowTextSystem::new(cx.text_system().clone());
688
689 let normal = TextRun {
690 len: 0,
691 font: font("Helvetica"),
692 color: Default::default(),
693 underline: Default::default(),
694 strikethrough: None,
695 background_color: None,
696 };
697 let bold = TextRun {
698 len: 0,
699 font: font("Helvetica").bold(),
700 color: Default::default(),
701 underline: Default::default(),
702 strikethrough: None,
703 background_color: None,
704 };
705
706 let text = "aa bbb cccc ddddd eeee".into();
707 let lines = text_system
708 .shape_text(
709 text,
710 px(16.),
711 &[
712 normal.with_len(4),
713 bold.with_len(5),
714 normal.with_len(6),
715 bold.with_len(1),
716 normal.with_len(7),
717 ],
718 Some(px(72.)),
719 None,
720 )
721 .unwrap();
722
723 assert_eq!(
724 lines[0].layout.wrap_boundaries(),
725 &[
726 WrapBoundary {
727 run_ix: 0,
728 glyph_ix: 7
729 },
730 WrapBoundary {
731 run_ix: 0,
732 glyph_ix: 12
733 },
734 WrapBoundary {
735 run_ix: 0,
736 glyph_ix: 18
737 }
738 ],
739 );
740 });
741 }
742}