1use crate::{FontId, Pixels, SharedString, TextRun, TextSystem, px};
2use collections::HashMap;
3use std::{borrow::Cow, iter, sync::Arc};
4use unicode_segmentation::UnicodeSegmentation;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum TruncateFrom {
9 Start,
11 End,
13 Middle,
15}
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum IndentAdjustment {
20 NoIndent,
22 #[default]
24 SameIndent,
25 ExtraColumns(u32),
27}
28
29pub struct LineWrapper {
31 text_system: Arc<TextSystem>,
32 pub(crate) font_id: FontId,
33 pub(crate) font_size: Pixels,
34 pub(crate) tracking: Pixels,
40 char_widths: CharWidthCache,
41 text_buffer: String,
42}
43
44pub(crate) struct CharWidthCache {
46 ascii: [Option<Pixels>; 128],
47 other: HashMap<char, Pixels>,
48}
49
50impl Default for CharWidthCache {
51 fn default() -> Self {
52 Self {
53 ascii: [None; 128],
54 other: HashMap::default(),
55 }
56 }
57}
58
59impl LineWrapper {
60 pub const MAX_INDENT: u32 = 256;
62
63 pub(crate) fn new(
64 font_id: FontId,
65 font_size: Pixels,
66 tracking: Pixels,
67 text_system: Arc<TextSystem>,
68 char_widths: CharWidthCache,
69 ) -> Self {
70 Self {
71 text_system,
72 font_id,
73 font_size,
74 tracking,
75 char_widths,
76 text_buffer: String::new(),
77 }
78 }
79
80 pub(crate) fn into_char_widths(self) -> CharWidthCache {
81 self.char_widths
82 }
83
84 pub fn wrap_line<'a>(
86 &'a mut self,
87 fragments: &'a [LineFragment],
88 wrap_width: Pixels,
89 indent_adjustment: IndentAdjustment,
90 ) -> impl Iterator<Item = Boundary> + 'a {
91 let mut width = px(0.);
92 let mut first_non_whitespace_ix = None;
93 let mut base_indent = None;
94 let mut last_candidate_ix = 0;
95 let mut last_candidate_width = px(0.);
96 let mut last_wrap_ix = 0;
97 let mut index = 0;
98 let Self {
99 text_buffer: text,
100 char_widths,
101 text_system,
102 font_id,
103 font_size,
104 tracking,
105 } = self;
106 let tracking = *tracking;
107 text.clear();
108 for fragment in fragments {
109 match fragment {
110 LineFragment::Text {
111 text: fragment_text,
112 } => text.push_str(fragment_text),
113 LineFragment::Element { len_utf8, .. } => {
115 text.extend(iter::repeat_n('a', *len_utf8));
116 }
117 }
118 }
119 let mut break_indices = Self::break_indices(text).peekable();
120 let mut grapheme_indices = text
121 .grapheme_indices(true)
122 .map(|(index, _)| index)
123 .peekable();
124 let mut width_for_char = move |character| {
125 width_for_char(char_widths, character, text_system, *font_id, *font_size) + tracking
126 };
127 let mut grapheme_index = 0;
128 let mut width_before_grapheme = px(0.);
129 let mut candidates = fragments
130 .iter()
131 .flat_map(move |fragment| fragment.wrap_boundary_candidates())
132 .peekable();
133 iter::from_fn(move || {
134 for candidate in candidates.by_ref() {
135 let ix = index;
136 index += candidate.len_utf8();
137 while grapheme_indices
138 .next_if(|position| *position < ix)
139 .is_some()
140 {}
141 let is_grapheme_boundary = grapheme_indices.next_if_eq(&ix).is_some();
142 if is_grapheme_boundary {
143 grapheme_index = ix;
144 width_before_grapheme = width;
145 }
146 if break_indices.next_if_eq(&ix).is_some()
147 && is_grapheme_boundary
148 && first_non_whitespace_ix.is_some()
149 {
150 last_candidate_ix = ix;
151 last_candidate_width = width;
152 }
153 let item_width = match candidate {
154 WrapBoundaryCandidate::Char { character: c } => {
155 if c == '\n' {
156 continue;
157 }
158
159 if c != ' ' && first_non_whitespace_ix.is_none() {
160 first_non_whitespace_ix = Some(ix);
161 }
162
163 width_for_char(c)
164 }
165 WrapBoundaryCandidate::Element {
166 width: element_width,
167 ..
168 } => {
169 if first_non_whitespace_ix.is_none() {
170 first_non_whitespace_ix = Some(ix);
171 }
172
173 element_width
174 }
175 };
176
177 width += item_width;
178 if width > wrap_width && grapheme_index > last_wrap_ix {
179 let wrap_at_candidate = last_candidate_ix > last_wrap_ix
180 && width - last_candidate_width <= wrap_width;
181
182 let carried_width = if wrap_at_candidate {
183 width - last_candidate_width
184 } else {
185 width - width_before_grapheme
186 };
187
188 if base_indent.is_none() {
194 if let Some(first_non_whitespace_ix) = first_non_whitespace_ix {
195 base_indent =
196 Some(Self::MAX_INDENT.min(
197 first_non_whitespace_ix.saturating_sub(last_wrap_ix) as u32,
198 ));
199 }
200 }
201
202 let next_indent = match indent_adjustment {
203 IndentAdjustment::NoIndent => 0,
204 IndentAdjustment::SameIndent => base_indent.unwrap_or(0),
205 IndentAdjustment::ExtraColumns(extra) => {
206 if let Some(base_indent) = base_indent {
207 let candidate = base_indent.saturating_add(extra);
208 let candidate_indent_width = width_for_char(' ') * candidate as f32;
209 let min_headroom = carried_width.max(width_for_char(' ') * 2.0);
213 if candidate_indent_width + min_headroom > wrap_width {
214 0
215 } else {
216 Self::MAX_INDENT.min(candidate)
217 }
218 } else {
219 0
220 }
221 }
222 };
223
224 if wrap_at_candidate {
225 last_wrap_ix = last_candidate_ix;
226 width -= last_candidate_width;
227 width_before_grapheme -= last_candidate_width;
228 } else {
229 last_wrap_ix = grapheme_index;
231 width -= width_before_grapheme;
232 width_before_grapheme = px(0.);
233 }
234 last_candidate_ix = 0;
235
236 let indent_width = width_for_char(' ') * next_indent as f32;
237 width += indent_width;
238 width_before_grapheme += indent_width;
239
240 return Some(Boundary::new(last_wrap_ix, next_indent));
241 }
242 }
243
244 None
245 })
246 }
247
248 pub fn should_truncate_line(
252 &mut self,
253 line: &str,
254 truncate_width: Pixels,
255 truncation_affix: &str,
256 truncate_from: TruncateFrom,
257 ) -> Option<usize> {
258 let mut width = px(0.);
259 let suffix_width = truncation_affix
260 .chars()
261 .map(|c| self.width_for_char(c))
262 .fold(px(0.0), |a, x| a + x);
263 let mut truncate_ix = 0;
264
265 match truncate_from {
266 TruncateFrom::Start => {
267 for (ix, c) in line.char_indices().rev() {
268 if width + suffix_width < truncate_width {
269 truncate_ix = ix;
270 }
271
272 let char_width = self.width_for_char(c);
273 width += char_width;
274
275 if width.floor() > truncate_width {
276 return Some(truncate_ix);
277 }
278 }
279 }
280 TruncateFrom::End => {
281 for (ix, c) in line.char_indices() {
282 if width + suffix_width < truncate_width {
283 truncate_ix = ix;
284 }
285
286 let char_width = self.width_for_char(c);
287 width += char_width;
288
289 if width.floor() > truncate_width {
290 return Some(truncate_ix);
291 }
292 }
293 }
294 TruncateFrom::Middle => {}
295 }
296
297 None
298 }
299
300 fn should_truncate_line_middle(
301 &mut self,
302 line: &str,
303 truncate_width: Pixels,
304 truncation_affix: &str,
305 ) -> Option<(usize, usize)> {
306 let suffix_width = truncation_affix
307 .chars()
308 .map(|c| self.width_for_char(c))
309 .fold(px(0.0), |a, x| a + x);
310
311 let total_width: Pixels = line
312 .chars()
313 .map(|c| self.width_for_char(c))
314 .fold(px(0.0), |a, x| a + x);
315
316 if total_width <= truncate_width {
317 return None;
318 }
319
320 let content_budget = truncate_width - suffix_width;
321 if content_budget <= px(0.) {
322 return Some((0, line.len()));
323 }
324
325 let front_budget = content_budget * (2.0 / 3.0);
326 let back_budget = content_budget - front_budget;
327
328 let mut front_width = px(0.);
329 let mut front_end_ix = 0usize;
330 for (ix, c) in line.char_indices() {
331 let char_width = self.width_for_char(c);
332 if front_width + char_width > front_budget {
333 break;
334 }
335 front_width += char_width;
336 front_end_ix = ix + c.len_utf8();
337 }
338
339 let mut back_width = px(0.);
340 let mut back_start_ix = line.len();
341 for (ix, c) in line.char_indices().rev() {
342 let char_width = self.width_for_char(c);
343 if back_width + char_width > back_budget {
344 break;
345 }
346 back_width += char_width;
347 back_start_ix = ix;
348 }
349
350 if front_end_ix >= back_start_ix {
351 return Some((0, line.len()));
352 }
353
354 Some((front_end_ix, back_start_ix))
355 }
356
357 pub fn truncate_line<'a>(
359 &mut self,
360 line: SharedString,
361 truncate_width: Pixels,
362 truncation_affix: &str,
363 runs: &'a [TextRun],
364 truncate_from: TruncateFrom,
365 ) -> (SharedString, Cow<'a, [TextRun]>) {
366 if truncate_from == TruncateFrom::Middle {
367 if let Some((front_end_ix, back_start_ix)) =
368 self.should_truncate_line_middle(&line, truncate_width, truncation_affix)
369 {
370 let result = SharedString::from(format!(
371 "{}{truncation_affix}{}",
372 &line[..front_end_ix],
373 &line[back_start_ix..]
374 ));
375 let mut runs = runs.to_vec();
376 update_runs_after_middle_truncation(
377 truncation_affix,
378 &mut runs,
379 front_end_ix,
380 back_start_ix,
381 );
382 return (result, Cow::Owned(runs));
383 } else {
384 return (line, Cow::Borrowed(runs));
385 }
386 }
387
388 if let Some(truncate_ix) =
389 self.should_truncate_line(&line, truncate_width, truncation_affix, truncate_from)
390 {
391 let result = match truncate_from {
392 TruncateFrom::Start => SharedString::from(format!(
393 "{truncation_affix}{}",
394 &line[line.ceil_char_boundary(truncate_ix + 1)..]
395 )),
396 TruncateFrom::End => SharedString::from(format!(
397 "{}{truncation_affix}",
398 line[..truncate_ix]
399 .trim_end_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation())
400 )),
401 TruncateFrom::Middle => unreachable!("Middle truncation is handled above"),
402 };
403 let mut runs = runs.to_vec();
404 update_runs_after_truncation(&result, truncation_affix, &mut runs, truncate_from);
405 (result, Cow::Owned(runs))
406 } else {
407 (line, Cow::Borrowed(runs))
408 }
409 }
410
411 pub fn truncate_wrapped_line<'a>(
421 &mut self,
422 text: SharedString,
423 wrap_width: Pixels,
424 max_lines: usize,
425 truncation_affix: &str,
426 runs: &'a [TextRun],
427 truncate_from: TruncateFrom,
428 ) -> (SharedString, Cow<'a, [TextRun]>) {
429 if max_lines <= 1 || truncate_from == TruncateFrom::Start {
430 return self.truncate_line(
431 text,
432 wrap_width * max_lines,
433 truncation_affix,
434 runs,
435 truncate_from,
436 );
437 }
438 if truncate_from == TruncateFrom::Middle {
439 return self.truncate_line(text, wrap_width, truncation_affix, runs, truncate_from);
440 }
441
442 let affix_width: Pixels = truncation_affix
443 .chars()
444 .map(|c| self.width_for_char(c))
445 .sum();
446
447 let mut width = px(0.);
448 let mut line = 0usize;
449 let mut first_non_whitespace_ix = None;
450 let mut last_candidate_ix = 0usize;
451 let mut last_candidate_width = px(0.);
452 let mut last_wrap_ix = 0usize;
453 let mut indent: Option<u32> = None;
454 let mut truncate_ix = 0usize;
455
456 let mut break_indices = Self::break_indices(&text).peekable();
457 for (ix, c) in text.char_indices() {
458 let is_break = break_indices.next_if_eq(&ix).is_some();
461 if c == '\n' {
462 if line >= max_lines - 1 && !text[ix + 1..].trim().is_empty() {
463 let truncated = text[..truncate_ix]
466 .trim_end_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation());
467 let result = SharedString::from(format!("{truncated}{truncation_affix}"));
468 let mut runs = runs.to_vec();
469 update_runs_after_truncation(
470 &result,
471 truncation_affix,
472 &mut runs,
473 TruncateFrom::End,
474 );
475 return (result, Cow::Owned(runs));
476 }
477
478 line += 1;
480 width = px(0.);
481 first_non_whitespace_ix = None;
482 last_candidate_ix = 0;
483 last_candidate_width = px(0.);
484 last_wrap_ix = ix + 1;
485 indent = None;
486 truncate_ix = ix + 1;
487 continue;
488 }
489
490 let char_width = self.width_for_char(c);
491
492 if is_break && first_non_whitespace_ix.is_some() {
493 last_candidate_ix = ix;
494 last_candidate_width = width;
495 }
496
497 if c != ' ' && first_non_whitespace_ix.is_none() {
498 first_non_whitespace_ix = Some(ix);
499 }
500
501 width += char_width;
502
503 if line < max_lines - 1 {
504 if width > wrap_width && ix > last_wrap_ix {
506 if let (None, Some(first_nw)) = (indent, first_non_whitespace_ix) {
507 indent = Some(Self::MAX_INDENT.min((first_nw - last_wrap_ix) as u32));
508 }
509
510 if last_candidate_ix > last_wrap_ix {
511 last_wrap_ix = last_candidate_ix;
512 width -= last_candidate_width;
513 last_candidate_ix = 0;
514 } else {
515 last_wrap_ix = ix;
516 width = char_width;
517 }
518
519 if let Some(ind) = indent {
520 width += self.width_for_char(' ') * ind as f32;
521 }
522
523 line += 1;
524 truncate_ix = last_wrap_ix;
525 }
526 } else {
527 if width + affix_width <= wrap_width {
530 truncate_ix = ix + c.len_utf8();
531 }
532
533 if width > wrap_width {
534 let truncated = text[..truncate_ix]
535 .trim_end_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation());
536 let result = SharedString::from(format!("{truncated}{truncation_affix}"));
537 let mut runs = runs.to_vec();
538 update_runs_after_truncation(
539 &result,
540 truncation_affix,
541 &mut runs,
542 TruncateFrom::End,
543 );
544 return (result, Cow::Owned(runs));
545 }
546 }
547 }
548
549 drop(break_indices);
551 (text, Cow::Borrowed(runs))
552 }
553
554 pub(crate) fn break_indices(text: &str) -> impl Iterator<Item = usize> {
556 icu_segmenter::LineSegmenter::new_for_non_complex_scripts(Default::default())
557 .segment_str(text)
558 }
559
560 #[inline(always)]
561 fn width_for_char(&mut self, c: char) -> Pixels {
562 width_for_char(
563 &mut self.char_widths,
564 c,
565 &self.text_system,
566 self.font_id,
567 self.font_size,
568 ) + self.tracking
569 }
570}
571
572#[inline(always)]
575fn width_for_char(
576 char_widths: &mut CharWidthCache,
577 c: char,
578 text_system: &TextSystem,
579 font_id: FontId,
580 font_size: Pixels,
581) -> Pixels {
582 if (c as u32) < 128 {
583 if let Some(cached_width) = char_widths.ascii[c as usize] {
584 cached_width
585 } else {
586 let width = text_system.layout_width(font_id, font_size, c);
587 char_widths.ascii[c as usize] = Some(width);
588 width
589 }
590 } else if let Some(cached_width) = char_widths.other.get(&c) {
591 *cached_width
592 } else {
593 let width = text_system.layout_width(font_id, font_size, c);
594 char_widths.other.insert(c, width);
595 width
596 }
597}
598
599fn update_runs_after_truncation(
600 result: &str,
601 ellipsis: &str,
602 runs: &mut Vec<TextRun>,
603 truncate_from: TruncateFrom,
604) {
605 let mut truncate_at = result.len() - ellipsis.len();
606 match truncate_from {
607 TruncateFrom::Start => {
608 for (run_index, run) in runs.iter_mut().enumerate().rev() {
609 if run.len <= truncate_at {
610 truncate_at -= run.len;
611 } else {
612 run.len = truncate_at + ellipsis.len();
613 runs.splice(..run_index, std::iter::empty());
614 break;
615 }
616 }
617 }
618 TruncateFrom::End => {
619 for (run_index, run) in runs.iter_mut().enumerate() {
620 if run.len <= truncate_at {
621 truncate_at -= run.len;
622 } else {
623 run.len = truncate_at + ellipsis.len();
624 runs.truncate(run_index + 1);
625 break;
626 }
627 }
628 }
629 TruncateFrom::Middle => {
630 unreachable!("Middle truncation calls this function with TruncateFrom::End directly")
631 }
632 }
633}
634
635fn update_runs_after_middle_truncation(
636 ellipsis: &str,
637 runs: &mut Vec<TextRun>,
638 front_end_ix: usize,
639 back_start_ix: usize,
640) {
641 let original_runs = std::mem::take(runs);
642 let mut result_runs: Vec<TextRun> = Vec::with_capacity(original_runs.len());
643
644 let mut front_remaining = front_end_ix;
648 let mut front_done = false;
649 for run in &original_runs {
650 if front_done {
651 break;
652 }
653 if run.len <= front_remaining {
654 result_runs.push(run.clone());
655 front_remaining -= run.len;
656 } else {
657 let mut partial = run.clone();
658 partial.len = front_remaining + ellipsis.len();
659 result_runs.push(partial);
660 front_done = true;
661 }
662 }
663 if !front_done {
664 if let Some(last) = result_runs.last_mut() {
667 last.len += ellipsis.len();
668 } else if let Some(first) = original_runs.first() {
669 let mut affix_run = first.clone();
670 affix_run.len = ellipsis.len();
671 result_runs.push(affix_run);
672 }
673 }
674
675 let mut byte_pos = 0usize;
678 for run in &original_runs {
679 let run_end = byte_pos + run.len;
680 if run_end > back_start_ix {
681 if byte_pos < back_start_ix {
682 let mut partial = run.clone();
684 partial.len = run_end - back_start_ix;
685 result_runs.push(partial);
686 } else {
687 result_runs.push(run.clone());
688 }
689 }
690 byte_pos = run_end;
691 }
692
693 *runs = result_runs;
694}
695
696pub enum LineFragment<'a> {
698 Text {
700 text: &'a str,
702 },
703 Element {
705 width: Pixels,
707 len_utf8: usize,
709 },
710}
711
712impl<'a> LineFragment<'a> {
713 pub fn text(text: &'a str) -> Self {
715 LineFragment::Text { text }
716 }
717
718 pub fn element(width: Pixels, len_utf8: usize) -> Self {
720 LineFragment::Element { width, len_utf8 }
721 }
722
723 fn wrap_boundary_candidates(&self) -> impl Iterator<Item = WrapBoundaryCandidate> {
724 let text = match self {
725 LineFragment::Text { text } => text,
726 LineFragment::Element { .. } => "\0",
727 };
728 text.chars().map(move |character| {
729 if let LineFragment::Element { width, len_utf8 } = self {
730 WrapBoundaryCandidate::Element {
731 width: *width,
732 len_utf8: *len_utf8,
733 }
734 } else {
735 WrapBoundaryCandidate::Char { character }
736 }
737 })
738 }
739}
740
741enum WrapBoundaryCandidate {
742 Char { character: char },
743 Element { width: Pixels, len_utf8: usize },
744}
745
746impl WrapBoundaryCandidate {
747 pub fn len_utf8(&self) -> usize {
748 match self {
749 WrapBoundaryCandidate::Char { character } => character.len_utf8(),
750 WrapBoundaryCandidate::Element { len_utf8: len, .. } => *len,
751 }
752 }
753}
754
755#[derive(Copy, Clone, Debug, PartialEq, Eq)]
757pub struct Boundary {
758 pub ix: usize,
760 pub next_indent: u32,
762}
763
764impl Boundary {
765 fn new(ix: usize, next_indent: u32) -> Self {
766 Self { ix, next_indent }
767 }
768}
769
770#[cfg(test)]
771mod tests {
772 use super::*;
773 use crate::{Font, FontFeatures, FontStyle, FontWeight, TestAppContext, TestDispatcher, font};
774 #[cfg(target_os = "macos")]
775 use crate::{TextRun, WindowTextSystem, WrapBoundary};
776
777 fn build_wrapper() -> LineWrapper {
778 let dispatcher = TestDispatcher::new(0);
779 let cx = TestAppContext::build(dispatcher, None);
780 let id = cx.text_system().resolve_font(&font(".ZedMono"));
781 LineWrapper::new(
782 id,
783 px(16.),
784 px(0.),
785 cx.text_system().clone(),
786 CharWidthCache::default(),
787 )
788 }
789
790 fn assert_emergency_wrap_preserves_graphemes(wrapper: &mut LineWrapper) {
791 use unicode_segmentation::UnicodeSegmentation;
792
793 let mut failures = Vec::new();
794 for cluster in ["e\u{301}", "か\u{3099}", "👍🏽", "🇯🇵", "👩\u{200d}💻"] {
795 let cluster_width: Pixels = cluster
796 .chars()
797 .map(|character| wrapper.width_for_char(character))
798 .sum();
799 let first_width = cluster
800 .chars()
801 .next()
802 .map(|character| wrapper.width_for_char(character))
803 .expect("nonempty fixture");
804 for text in [cluster.to_owned(), format!("x{cluster}y")] {
805 let grapheme_boundaries: Vec<_> = text
806 .grapheme_indices(true)
807 .map(|(index, _)| index)
808 .chain(std::iter::once(text.len()))
809 .collect();
810 assert!(
811 LineWrapper::break_indices(&text)
812 .all(|index| grapheme_boundaries.contains(&index)),
813 "UAX #14 boundary inside {text:?}"
814 );
815 let fragments = [LineFragment::text(&text)];
816 let full_width: Pixels = text
817 .chars()
818 .map(|character| wrapper.width_for_char(character))
819 .sum();
820 assert!(
821 wrapper
822 .wrap_line(&fragments, full_width + px(1.), IndentAdjustment::NoIndent)
823 .next()
824 .is_none()
825 );
826 for wrap_width in [
827 first_width - px(0.1),
828 first_width,
829 first_width + px(0.1),
830 cluster_width - px(0.1),
831 cluster_width,
832 cluster_width + px(0.1),
833 ] {
834 let boundaries: Vec<_> = wrapper
835 .wrap_line(&fragments, wrap_width, IndentAdjustment::NoIndent)
836 .map(|boundary| boundary.ix)
837 .collect();
838 let split_fragments: Vec<_> = text
839 .split_inclusive(|_: char| true)
840 .map(LineFragment::text)
841 .collect();
842 let split_boundaries: Vec<_> = wrapper
843 .wrap_line(&split_fragments, wrap_width, IndentAdjustment::NoIndent)
844 .map(|boundary| boundary.ix)
845 .collect();
846 assert_eq!(
847 boundaries, split_boundaries,
848 "fragmentation changed {text:?}"
849 );
850 let invalid: Vec<_> = boundaries
851 .iter()
852 .copied()
853 .filter(|index| !grapheme_boundaries.contains(index))
854 .collect();
855 if !invalid.is_empty() {
856 failures.push(format!("text={text:?}, width={wrap_width:?}, cluster_width={cluster_width:?}, breaks={boundaries:?}, inside_grapheme={invalid:?}"));
857 }
858 }
859 }
860 }
861 assert!(failures.is_empty(), "{}", failures.join("\n"));
862 }
863
864 #[test]
865 fn test_emergency_wrap_preserves_graphemes() {
866 assert_emergency_wrap_preserves_graphemes(&mut build_wrapper());
867 }
868
869 #[test]
870 fn test_emergency_wrap_exact_boundaries() {
871 let mut wrapper = build_wrapper();
872 wrapper.char_widths.ascii.fill(Some(px(1.)));
873 wrapper.char_widths.other.insert('\u{301}', px(1.));
874
875 for (text, width, adjustment, expected) in [
876 (
877 "xe\u{301}y",
878 1.,
879 IndentAdjustment::NoIndent,
880 vec![Boundary::new(1, 0), Boundary::new(4, 0)],
881 ),
882 (
883 " xe\u{301}yze\u{301}q",
884 5.,
885 IndentAdjustment::SameIndent,
886 vec![Boundary::new(6, 2), Boundary::new(8, 2)],
887 ),
888 (
889 " xe\u{301}yze\u{301}q",
890 5.,
891 IndentAdjustment::ExtraColumns(1),
892 vec![
893 Boundary::new(6, 3),
894 Boundary::new(8, 3),
895 Boundary::new(11, 3),
896 ],
897 ),
898 ] {
899 let fragments = [LineFragment::text(text)];
900 assert_eq!(
901 wrapper
902 .wrap_line(&fragments, px(width), adjustment)
903 .collect::<Vec<_>>(),
904 expected,
905 "{text:?}, {adjustment:?}",
906 );
907 }
908 }
909
910 #[test]
911 fn test_emergency_wrap_elements_and_graphemes() {
912 let mut wrapper = build_wrapper();
913 wrapper.char_widths.ascii.fill(Some(px(1.)));
914 wrapper.char_widths.other.insert('\u{301}', px(1.));
915
916 for element_length in [1, 3, 32] {
917 let fragments = [
918 LineFragment::text("xe\u{301}"),
919 LineFragment::element(px(4.), element_length),
920 LineFragment::text("e\u{301}yz"),
921 ];
922 assert_eq!(
923 wrapper
924 .wrap_line(&fragments, px(2.), IndentAdjustment::NoIndent)
925 .collect::<Vec<_>>(),
926 vec![
927 Boundary::new(1, 0),
928 Boundary::new(4, 0),
929 Boundary::new(4 + element_length, 0),
930 Boundary::new(7 + element_length, 0),
931 ],
932 "element_length={element_length}",
933 );
934 }
935 }
936
937 fn generate_test_runs(input_run_len: &[usize]) -> Vec<TextRun> {
938 input_run_len
939 .iter()
940 .map(|run_len| TextRun {
941 len: *run_len,
942 font: Font {
943 family: "Dummy".into(),
944 features: FontFeatures::default(),
945 fallbacks: None,
946 weight: FontWeight::default(),
947 style: FontStyle::Normal,
948 },
949 ..Default::default()
950 })
951 .collect()
952 }
953
954 #[test]
955 fn test_wrap_line() {
956 let mut wrapper = build_wrapper();
957
958 assert_eq!(
959 wrapper
960 .wrap_line(
961 &[LineFragment::text("aa bbb cccc ddddd eeee")],
962 px(72.),
963 IndentAdjustment::default()
964 )
965 .collect::<Vec<_>>(),
966 &[
967 Boundary::new(7, 0),
968 Boundary::new(12, 0),
969 Boundary::new(18, 0)
970 ],
971 );
972 assert_eq!(
973 wrapper
974 .wrap_line(
975 &[LineFragment::text("aaa aaaaaaaaaaaaaaaaaa")],
976 px(72.0),
977 IndentAdjustment::default()
978 )
979 .collect::<Vec<_>>(),
980 &[
981 Boundary::new(4, 0),
982 Boundary::new(11, 0),
983 Boundary::new(18, 0)
984 ],
985 );
986 assert_eq!(
987 wrapper
988 .wrap_line(
989 &[LineFragment::text(" aaaaaaa")],
990 px(72.),
991 IndentAdjustment::default()
992 )
993 .collect::<Vec<_>>(),
994 &[
995 Boundary::new(7, 5),
996 Boundary::new(9, 5),
997 Boundary::new(11, 5),
998 ]
999 );
1000 assert_eq!(
1001 wrapper
1002 .wrap_line(
1003 &[LineFragment::text(" ")],
1004 px(72.),
1005 IndentAdjustment::default()
1006 )
1007 .collect::<Vec<_>>(),
1008 &[
1009 Boundary::new(7, 0),
1010 Boundary::new(14, 0),
1011 Boundary::new(21, 0)
1012 ]
1013 );
1014 assert_eq!(
1015 wrapper
1016 .wrap_line(
1017 &[LineFragment::text(" aaaaaaaaaaaaaa")],
1018 px(72.),
1019 IndentAdjustment::default()
1020 )
1021 .collect::<Vec<_>>(),
1022 &[
1023 Boundary::new(7, 0),
1024 Boundary::new(14, 3),
1025 Boundary::new(18, 3),
1026 Boundary::new(22, 3),
1027 ]
1028 );
1029
1030 assert_eq!(
1032 wrapper
1033 .wrap_line(
1034 &[
1035 LineFragment::text("aa bbb "),
1036 LineFragment::text("cccc ddddd eeee")
1037 ],
1038 px(72.),
1039 IndentAdjustment::default()
1040 )
1041 .collect::<Vec<_>>(),
1042 &[
1043 Boundary::new(7, 0),
1044 Boundary::new(12, 0),
1045 Boundary::new(18, 0)
1046 ],
1047 );
1048
1049 assert_eq!(
1051 wrapper
1052 .wrap_line(
1053 &[
1054 LineFragment::text("aa "),
1055 LineFragment::element(px(20.), 1),
1056 LineFragment::text(" bbb "),
1057 LineFragment::element(px(30.), 1),
1058 LineFragment::text(" cccc")
1059 ],
1060 px(72.),
1061 IndentAdjustment::default()
1062 )
1063 .collect::<Vec<_>>(),
1064 &[
1065 Boundary::new(5, 0),
1066 Boundary::new(9, 0),
1067 Boundary::new(11, 0)
1068 ],
1069 );
1070
1071 assert_eq!(
1073 wrapper
1074 .wrap_line(
1075 &[
1076 LineFragment::element(px(50.), 1),
1077 LineFragment::text(" aaaa bbbb cccc dddd")
1078 ],
1079 px(72.),
1080 IndentAdjustment::default()
1081 )
1082 .collect::<Vec<_>>(),
1083 &[
1084 Boundary::new(2, 0),
1085 Boundary::new(7, 0),
1086 Boundary::new(12, 0),
1087 Boundary::new(17, 0)
1088 ],
1089 );
1090
1091 assert_eq!(
1093 wrapper
1094 .wrap_line(
1095 &[
1096 LineFragment::text("short text "),
1097 LineFragment::element(px(100.), 1),
1098 LineFragment::text(" more text")
1099 ],
1100 px(72.),
1101 IndentAdjustment::default()
1102 )
1103 .collect::<Vec<_>>(),
1104 &[
1105 Boundary::new(6, 0),
1106 Boundary::new(11, 0),
1107 Boundary::new(12, 0),
1108 Boundary::new(18, 0)
1109 ],
1110 );
1111
1112 assert_eq!(
1114 wrapper
1115 .wrap_line(
1116 &[LineFragment::text("a\u{202F}b\u{00A0}c\u{2011}d e")],
1117 px(72.0),
1118 IndentAdjustment::default()
1119 )
1120 .collect::<Vec<_>>(),
1121 &[Boundary::new(12, 0),], );
1123 }
1124
1125 #[test]
1126 fn test_wrap_line_break_opportunities() {
1127 let mut wrapper = build_wrapper();
1128 for (text, fitting_prefix, expected_index) in [
1129 ("aaa required!", "aaa required", 4),
1130 ("aaa foo/bar", "aaa foo/", 8),
1131 ("aaa (hello)", "aaa (hello", 4),
1132 ("aaa αβγδε", "aaa αβγδ", 4),
1133 ("aaa a\u{a0}b", "aaa a\u{a0}", 4),
1134 ("aaa 你好!", "aaa 你好", 7),
1135 ] {
1136 let wrap_width = fitting_prefix
1137 .chars()
1138 .map(|character| wrapper.width_for_char(character))
1139 .sum();
1140 assert_eq!(
1141 wrapper
1142 .wrap_line(
1143 &[LineFragment::text(text)],
1144 wrap_width,
1145 IndentAdjustment::default()
1146 )
1147 .collect::<Vec<_>>(),
1148 [Boundary::new(expected_index, 0)],
1149 "{text:?}",
1150 );
1151 }
1152 }
1153
1154 #[test]
1155 fn test_truncate_line_end() {
1156 let mut wrapper = build_wrapper();
1157
1158 fn perform_test(
1159 wrapper: &mut LineWrapper,
1160 text: &'static str,
1161 expected: &'static str,
1162 ellipsis: &str,
1163 ) {
1164 let dummy_run_lens = vec![text.len()];
1165 let dummy_runs = generate_test_runs(&dummy_run_lens);
1166 let (result, dummy_runs) = wrapper.truncate_line(
1167 text.into(),
1168 px(220.),
1169 ellipsis,
1170 &dummy_runs,
1171 TruncateFrom::End,
1172 );
1173 assert_eq!(result, expected);
1174 assert_eq!(dummy_runs.first().unwrap().len, result.len());
1175 }
1176
1177 perform_test(
1178 &mut wrapper,
1179 "aa bbb cccc ddddd eeee ffff gggg",
1180 "aa bbb cccc ddddd eeee",
1181 "",
1182 );
1183 perform_test(
1184 &mut wrapper,
1185 "aa bbb cccc ddddd eeee ffff gggg",
1186 "aa bbb cccc ddddd eee…",
1187 "…",
1188 );
1189 perform_test(
1190 &mut wrapper,
1191 "aa bbb cccc ddddd eeee ffff gggg",
1192 "aa bbb cccc dddd......",
1193 "......",
1194 );
1195 perform_test(
1196 &mut wrapper,
1197 "aa bbb cccc 🦀🦀🦀🦀🦀 eeee ffff gggg",
1198 "aa bbb cccc 🦀🦀🦀🦀…",
1199 "…",
1200 );
1201 }
1202
1203 #[test]
1204 fn test_truncate_line_start() {
1205 let mut wrapper = build_wrapper();
1206
1207 #[track_caller]
1208 fn perform_test(
1209 wrapper: &mut LineWrapper,
1210 text: &'static str,
1211 expected: &'static str,
1212 ellipsis: &str,
1213 ) {
1214 let dummy_run_lens = vec![text.len()];
1215 let dummy_runs = generate_test_runs(&dummy_run_lens);
1216 let (result, dummy_runs) = wrapper.truncate_line(
1217 text.into(),
1218 px(220.),
1219 ellipsis,
1220 &dummy_runs,
1221 TruncateFrom::Start,
1222 );
1223 assert_eq!(result, expected);
1224 assert_eq!(dummy_runs.first().unwrap().len, result.len());
1225 }
1226
1227 perform_test(
1228 &mut wrapper,
1229 "aaaa bbbb cccc ddddd eeee fff gg",
1230 "cccc ddddd eeee fff gg",
1231 "",
1232 );
1233 perform_test(
1234 &mut wrapper,
1235 "aaaa bbbb cccc ddddd eeee fff gg",
1236 "…ccc ddddd eeee fff gg",
1237 "…",
1238 );
1239 perform_test(
1240 &mut wrapper,
1241 "aaaa bbbb cccc ddddd eeee fff gg",
1242 "......dddd eeee fff gg",
1243 "......",
1244 );
1245 perform_test(
1246 &mut wrapper,
1247 "aaaa bbbb cccc 🦀🦀🦀🦀🦀 eeee fff gg",
1248 "…🦀🦀🦀🦀 eeee fff gg",
1249 "…",
1250 );
1251 }
1252
1253 #[test]
1254 fn test_truncate_multiple_runs_end() {
1255 let mut wrapper = build_wrapper();
1256
1257 fn perform_test(
1258 wrapper: &mut LineWrapper,
1259 text: &'static str,
1260 expected: &str,
1261 run_lens: &[usize],
1262 result_run_len: &[usize],
1263 line_width: Pixels,
1264 ) {
1265 let dummy_runs = generate_test_runs(run_lens);
1266 let (result, dummy_runs) =
1267 wrapper.truncate_line(text.into(), line_width, "…", &dummy_runs, TruncateFrom::End);
1268 assert_eq!(result, expected);
1269 for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
1270 assert_eq!(run.len, *result_len);
1271 }
1272 }
1273 perform_test(&mut wrapper, "abcdefghijkl", "abcd…", &[12], &[7], px(50.));
1280 perform_test(
1288 &mut wrapper,
1289 "abcdefghijkl",
1290 "abcdef…",
1291 &[4, 4, 4],
1292 &[4, 5],
1293 px(70.),
1294 );
1295 perform_test(
1303 &mut wrapper,
1304 "abcdefghijkl",
1305 "abcdefgh…",
1306 &[4, 4, 4],
1307 &[4, 4, 3],
1308 px(90.),
1309 );
1310 }
1311
1312 #[test]
1313 fn test_truncate_multiple_runs_start() {
1314 let mut wrapper = build_wrapper();
1315
1316 #[track_caller]
1317 fn perform_test(
1318 wrapper: &mut LineWrapper,
1319 text: &'static str,
1320 expected: &str,
1321 run_lens: &[usize],
1322 result_run_len: &[usize],
1323 line_width: Pixels,
1324 ) {
1325 let dummy_runs = generate_test_runs(run_lens);
1326 let (result, dummy_runs) = wrapper.truncate_line(
1327 text.into(),
1328 line_width,
1329 "…",
1330 &dummy_runs,
1331 TruncateFrom::Start,
1332 );
1333 assert_eq!(result, expected);
1334 for (run, result_len) in dummy_runs.iter().zip(result_run_len) {
1335 assert_eq!(run.len, *result_len);
1336 }
1337 }
1338 perform_test(&mut wrapper, "abcdefghijkl", "…ijkl", &[12], &[7], px(50.));
1345 perform_test(
1353 &mut wrapper,
1354 "abcdefghijkl",
1355 "…ghijkl",
1356 &[4, 4, 4],
1357 &[5, 4],
1358 px(70.),
1359 );
1360 perform_test(
1368 &mut wrapper,
1369 "abcdefghijkl",
1370 "…efghijkl",
1371 &[4, 4, 4],
1372 &[3, 4, 4],
1373 px(90.),
1374 );
1375 }
1376
1377 #[test]
1378 fn test_update_run_after_truncation_end() {
1379 fn perform_test(result: &str, run_lens: &[usize], result_run_lens: &[usize]) {
1380 let mut dummy_runs = generate_test_runs(run_lens);
1381 update_runs_after_truncation(result, "…", &mut dummy_runs, TruncateFrom::End);
1382 for (run, result_len) in dummy_runs.iter().zip(result_run_lens) {
1383 assert_eq!(run.len, *result_len);
1384 }
1385 }
1386 perform_test("abcd…", &[12], &[7]);
1393 perform_test("abcdef…", &[4, 4, 4], &[4, 5]);
1401 perform_test("abcdefgh…", &[4, 4, 4], &[4, 4, 3]);
1409 }
1410
1411 #[cfg(target_os = "macos")]
1413 use crate as gpui;
1414
1415 #[cfg(target_os = "macos")]
1417 #[crate::test]
1418 fn test_wrap_shaped_line(cx: &mut TestAppContext) {
1419 cx.update(|cx| {
1420 let text_system = WindowTextSystem::new(cx.text_system().clone());
1421
1422 let normal = TextRun {
1423 len: 0,
1424 font: font("Helvetica"),
1425 color: Default::default(),
1426 underline: Default::default(),
1427 ..Default::default()
1428 };
1429 let bold = TextRun {
1430 len: 0,
1431 font: font("Helvetica").bold(),
1432 ..Default::default()
1433 };
1434
1435 let text = "aa bbb cccc ddddd eeee".into();
1436 let lines = text_system
1437 .shape_text(
1438 text,
1439 px(16.),
1440 &[
1441 normal.with_len(4),
1442 bold.with_len(5),
1443 normal.with_len(6),
1444 bold.with_len(1),
1445 normal.with_len(7),
1446 ],
1447 Some(px(72.)),
1448 None,
1449 )
1450 .unwrap();
1451
1452 assert_eq!(
1453 lines[0].layout.wrap_boundaries(),
1454 &[
1455 WrapBoundary {
1456 run_ix: 0,
1457 glyph_ix: 7
1458 },
1459 WrapBoundary {
1460 run_ix: 0,
1461 glyph_ix: 12
1462 },
1463 WrapBoundary {
1464 run_ix: 0,
1465 glyph_ix: 18
1466 }
1467 ],
1468 );
1469 });
1470 }
1471
1472 #[test]
1473 fn test_multiline_truncation_fits_within_wrapped_lines() {
1474 let mut wrapper = build_wrapper();
1475
1476 let text: &str = "aa bbbbbb cccccc dddddd eeee ffff";
1488 let wrap_width = px(72.);
1489 let max_lines: usize = 2;
1490
1491 let runs = generate_test_runs(&[text.len()]);
1492 let (truncated, _) = wrapper.truncate_wrapped_line(
1493 text.into(),
1494 wrap_width,
1495 max_lines,
1496 "\u{2026}",
1497 &runs,
1498 TruncateFrom::End,
1499 );
1500
1501 let wrap_count = wrapper
1503 .wrap_line(
1504 &[LineFragment::text(&truncated)],
1505 wrap_width,
1506 IndentAdjustment::default(),
1507 )
1508 .count();
1509
1510 assert!(
1511 wrap_count < max_lines,
1512 "Truncated text '{}' wraps into {} visual lines, expected at most {}",
1513 truncated,
1514 wrap_count + 1,
1515 max_lines
1516 );
1517
1518 assert!(
1520 truncated.ends_with('\u{2026}'),
1521 "Truncated text '{}' should end with ellipsis",
1522 truncated
1523 );
1524 }
1525
1526 #[test]
1527 fn test_multiline_truncation_no_truncation_needed() {
1528 let mut wrapper = build_wrapper();
1529
1530 let text: &str = "aa bbb cccccc";
1533 let wrap_width = px(72.);
1534 let max_lines: usize = 2;
1535
1536 let runs = generate_test_runs(&[text.len()]);
1537 let (result, _) = wrapper.truncate_wrapped_line(
1538 text.into(),
1539 wrap_width,
1540 max_lines,
1541 "\u{2026}",
1542 &runs,
1543 TruncateFrom::End,
1544 );
1545
1546 assert_eq!(
1547 result.as_ref(),
1548 text,
1549 "Text that fits should not be modified"
1550 );
1551 }
1552
1553 #[test]
1554 fn test_multiline_truncation_three_lines() {
1555 let mut wrapper = build_wrapper();
1556
1557 let text: &str = "aa bbb cccc ddddd eeee ffff gggg hhhh iiii jjjj";
1558 let wrap_width = px(72.);
1559 let max_lines: usize = 3;
1560
1561 let runs = generate_test_runs(&[text.len()]);
1562 let (truncated, _) = wrapper.truncate_wrapped_line(
1563 text.into(),
1564 wrap_width,
1565 max_lines,
1566 "\u{2026}",
1567 &runs,
1568 TruncateFrom::End,
1569 );
1570
1571 let wrap_count = wrapper
1572 .wrap_line(
1573 &[LineFragment::text(&truncated)],
1574 wrap_width,
1575 IndentAdjustment::default(),
1576 )
1577 .count();
1578
1579 assert!(
1580 wrap_count < max_lines,
1581 "Truncated text '{}' wraps into {} visual lines, expected at most {}",
1582 truncated,
1583 wrap_count + 1,
1584 max_lines
1585 );
1586
1587 assert!(
1588 truncated.ends_with('\u{2026}'),
1589 "Truncated text '{}' should end with ellipsis",
1590 truncated
1591 );
1592 }
1593
1594 #[test]
1595 fn test_multiline_truncation_preserves_breaks_after_empty_lines() {
1596 let mut wrapper = build_wrapper();
1597 for prefix in ["", "\n", "\n\n", "hello\n\n"] {
1598 let text = format!("{prefix}aaa required! more words follow");
1599 let runs = generate_test_runs(&[text.len()]);
1600 let max_lines = prefix.bytes().filter(|byte| *byte == b'\n').count() + 2;
1601 let (truncated, _) = wrapper.truncate_wrapped_line(
1602 text.into(),
1603 px(72.),
1604 max_lines,
1605 "…",
1606 &runs,
1607 TruncateFrom::End,
1608 );
1609 assert_eq!(
1610 truncated.as_ref(),
1611 format!("{prefix}aaa {}…", &"required!"[..6]),
1612 "prefix: {prefix:?}",
1613 );
1614 }
1615 }
1616
1617 #[test]
1618 fn test_multiline_truncation_with_newlines() {
1619 let mut wrapper = build_wrapper();
1620
1621 let text: &str = "hello\nworld foo bar baz";
1626 let wrap_width = px(72.);
1627 let max_lines: usize = 2;
1628
1629 let runs = generate_test_runs(&[text.len()]);
1630 let (truncated, _) = wrapper.truncate_wrapped_line(
1631 text.into(),
1632 wrap_width,
1633 max_lines,
1634 "\u{2026}",
1635 &runs,
1636 TruncateFrom::End,
1637 );
1638
1639 let parts: Vec<&str> = truncated.splitn(2, '\n').collect();
1641 assert_eq!(
1642 parts.len(),
1643 2,
1644 "Newline should be preserved: '{}'",
1645 truncated
1646 );
1647 assert_eq!(parts[0], "hello");
1648
1649 let second_line_width: Pixels = parts[1].chars().map(|c| wrapper.width_for_char(c)).sum();
1651 assert!(
1652 second_line_width <= wrap_width,
1653 "Second line '{}' ({}px) exceeds wrap_width ({}px)",
1654 parts[1],
1655 second_line_width,
1656 wrap_width
1657 );
1658 assert!(
1659 truncated.ends_with('\u{2026}'),
1660 "Should end with ellipsis: '{}'",
1661 truncated
1662 );
1663 }
1664
1665 #[test]
1666 fn test_multiline_truncation_newline_on_last_line() {
1667 let mut wrapper = build_wrapper();
1668
1669 let text: &str = "hello\nworld\nmore";
1673 let wrap_width = px(72.);
1674 let max_lines: usize = 2;
1675
1676 let runs = generate_test_runs(&[text.len()]);
1677 let (truncated, _) = wrapper.truncate_wrapped_line(
1678 text.into(),
1679 wrap_width,
1680 max_lines,
1681 "\u{2026}",
1682 &runs,
1683 TruncateFrom::End,
1684 );
1685
1686 let parts: Vec<&str> = truncated.splitn(2, '\n').collect();
1687 assert_eq!(parts[0], "hello");
1688 assert!(
1689 truncated.ends_with('\u{2026}'),
1690 "Should end with ellipsis since there's more content: '{}'",
1691 truncated
1692 );
1693 }
1694
1695 #[test]
1696 fn test_truncate_line_middle() {
1697 let mut wrapper = build_wrapper();
1698
1699 let short_text = "hello world";
1701 let runs = generate_test_runs(&[short_text.len()]);
1702 let (result, result_runs) = wrapper.truncate_line(
1703 short_text.into(),
1704 px(10000.),
1705 "…",
1706 &runs,
1707 TruncateFrom::Middle,
1708 );
1709 assert_eq!(result.as_ref(), short_text);
1710 assert_eq!(result_runs.len(), 1);
1711 assert_eq!(result_runs[0].len, short_text.len());
1712
1713 let long_text = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz";
1715 let runs = generate_test_runs(&[long_text.len()]);
1716 let (result, _result_runs) =
1717 wrapper.truncate_line(long_text.into(), px(100.), "…", &runs, TruncateFrom::Middle);
1718 assert!(
1719 result.contains('…'),
1720 "Middle-truncated result should contain '…', got: '{}'",
1721 result
1722 );
1723 assert!(
1724 result.chars().count() < long_text.chars().count(),
1725 "Middle-truncated result should be shorter than original"
1726 );
1727 assert_eq!(
1728 result.chars().next(),
1729 long_text.chars().next(),
1730 "Result should start with the same first character as original"
1731 );
1732 assert_eq!(
1733 result.chars().last(),
1734 long_text.chars().last(),
1735 "Result should end with the same last character as original"
1736 );
1737
1738 let text = "abcdef";
1741 let runs = generate_test_runs(&[text.len()]);
1742 let (result, result_runs) =
1743 wrapper.truncate_line(text.into(), px(1.), "…", &runs, TruncateFrom::Middle);
1744 assert_eq!(result.as_ref(), "…");
1745 assert_eq!(result_runs.len(), 1);
1746 assert_eq!(result_runs[0].len, "…".len());
1747
1748 let multi_run_text = "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz";
1751 let run_lens = [20, 20, multi_run_text.len() - 40];
1752 let runs = generate_test_runs(&run_lens);
1753 let (result, result_runs) = wrapper.truncate_line(
1754 multi_run_text.into(),
1755 px(100.),
1756 "…",
1757 &runs,
1758 TruncateFrom::Middle,
1759 );
1760 let total_run_len: usize = result_runs.iter().map(|r| r.len).sum();
1761 assert_eq!(
1762 total_run_len,
1763 result.len(),
1764 "Sum of run lengths ({}) should equal result byte length ({})",
1765 total_run_len,
1766 result.len()
1767 );
1768 }
1769
1770 #[test]
1771 fn test_multiline_truncation_trailing_newline() {
1772 let mut wrapper = build_wrapper();
1773
1774 let text: &str = "hello\nworld\n";
1777 let wrap_width = px(72.);
1778 let max_lines: usize = 2;
1779
1780 let runs = generate_test_runs(&[text.len()]);
1781 let (result, _) = wrapper.truncate_wrapped_line(
1782 text.into(),
1783 wrap_width,
1784 max_lines,
1785 "\u{2026}",
1786 &runs,
1787 TruncateFrom::End,
1788 );
1789
1790 assert!(
1791 !result.ends_with('\u{2026}'),
1792 "Trailing newline with no content should not add ellipsis: '{}'",
1793 result
1794 );
1795 }
1796
1797 #[test]
1798 fn test_multiline_truncation_newline_fits_exactly() {
1799 let mut wrapper = build_wrapper();
1800
1801 let text: &str = "hello\nworld";
1804 let wrap_width = px(72.);
1805 let max_lines: usize = 2;
1806
1807 let runs = generate_test_runs(&[text.len()]);
1808 let (result, _) = wrapper.truncate_wrapped_line(
1809 text.into(),
1810 wrap_width,
1811 max_lines,
1812 "\u{2026}",
1813 &runs,
1814 TruncateFrom::End,
1815 );
1816
1817 assert_eq!(
1818 result.as_ref(),
1819 text,
1820 "Text that fits exactly should not be modified: '{}'",
1821 result
1822 );
1823 }
1824
1825 #[test]
1826 fn test_extra_columns_overflow_guard() {
1827 let mut wrapper = build_wrapper();
1828 let space_width = wrapper.width_for_char(' ');
1829
1830 let text = " ab cd ef gh";
1832 let wrap_width = space_width * 10.0;
1833
1834 assert_eq!(
1841 wrapper
1842 .wrap_line(
1843 &[LineFragment::text(text)],
1844 wrap_width,
1845 IndentAdjustment::ExtraColumns(8),
1846 )
1847 .collect::<Vec<_>>(),
1848 &[Boundary::new(9, 0)]
1849 );
1850
1851 assert_eq!(
1864 wrapper
1865 .wrap_line(
1866 &[LineFragment::text(text)],
1867 wrap_width,
1868 IndentAdjustment::ExtraColumns(2),
1869 )
1870 .collect::<Vec<_>>(),
1871 &[
1872 Boundary::new(9, 8),
1873 Boundary::new(11, 8),
1874 Boundary::new(12, 8),
1875 Boundary::new(14, 8),
1876 Boundary::new(15, 8),
1877 ]
1878 );
1879
1880 let full_width_text = " 🦀🦀🦀🦀🦀🦀🦀🦀";
1893 assert_eq!(
1894 wrapper
1895 .wrap_line(
1896 &[LineFragment::text(full_width_text)],
1897 wrap_width,
1898 IndentAdjustment::ExtraColumns(8),
1899 )
1900 .collect::<Vec<_>>(),
1901 &[Boundary::new(17, 0)]
1902 );
1903
1904 assert_eq!(
1911 wrapper
1912 .wrap_line(
1913 &[LineFragment::text("a abcdefghi")],
1914 wrap_width,
1915 IndentAdjustment::ExtraColumns(1),
1916 )
1917 .collect::<Vec<_>>(),
1918 &[Boundary::new(2, 1)]
1919 );
1920
1921 assert_eq!(
1928 wrapper
1929 .wrap_line(
1930 &[LineFragment::text("a abcdefghi")],
1931 wrap_width,
1932 IndentAdjustment::ExtraColumns(2),
1933 )
1934 .collect::<Vec<_>>(),
1935 &[Boundary::new(2, 0)]
1936 );
1937
1938 let carried_text = "a abcdefghij";
1950 assert_eq!(
1951 wrapper
1952 .wrap_line(
1953 &[LineFragment::text(carried_text)],
1954 wrap_width,
1955 IndentAdjustment::ExtraColumns(8),
1956 )
1957 .collect::<Vec<_>>(),
1958 &[Boundary::new(2, 0)]
1959 );
1960
1961 let element_fragments = [
1979 LineFragment::text("abcdefghijk "),
1980 LineFragment::element(space_width * 8.0, 1),
1981 LineFragment::text("z 12"),
1982 ];
1983 assert_eq!(
1984 wrapper
1985 .wrap_line(
1986 &element_fragments,
1987 wrap_width,
1988 IndentAdjustment::ExtraColumns(8),
1989 )
1990 .collect::<Vec<_>>(),
1991 &[
1992 Boundary::new(10, 8),
1993 Boundary::new(12, 0),
1994 Boundary::new(15, 8),
1995 ]
1996 );
1997
1998 let spaces = " "; assert_eq!(
2002 wrapper
2003 .wrap_line(
2004 &[LineFragment::text(spaces)],
2005 wrap_width,
2006 IndentAdjustment::ExtraColumns(8),
2007 )
2008 .collect::<Vec<_>>(),
2009 &[Boundary::new(10, 0)]
2010 );
2011
2012 let multiline_indent_text = " ab cd ef gh";
2021 assert_eq!(
2022 wrapper
2023 .wrap_line(
2024 &[LineFragment::text(multiline_indent_text)],
2025 wrap_width,
2026 IndentAdjustment::ExtraColumns(2),
2027 )
2028 .collect::<Vec<_>>(),
2029 &[
2030 Boundary::new(10, 0),
2031 Boundary::new(20, 6),
2032 Boundary::new(23, 6),
2033 ]
2034 );
2035
2036 let oversized_suffix_fragments = [
2053 LineFragment::text("aaaaaaaaaaaaaaaaaaa a"),
2054 LineFragment::element(space_width * 10.0, 1),
2055 ];
2056 assert_eq!(
2057 wrapper
2058 .wrap_line(
2059 &oversized_suffix_fragments,
2060 wrap_width,
2061 IndentAdjustment::ExtraColumns(2),
2062 )
2063 .collect::<Vec<_>>(),
2064 &[
2065 Boundary::new(10, 2),
2066 Boundary::new(18, 2),
2067 Boundary::new(21, 0),
2068 ]
2069 );
2070
2071 assert_eq!(
2072 wrapper
2073 .wrap_line(
2074 &[LineFragment::text(" aaaaaaaa")],
2075 space_width * 4.0,
2076 IndentAdjustment::ExtraColumns(u32::MAX),
2077 )
2078 .collect::<Vec<_>>(),
2079 &[Boundary::new(4, 0), Boundary::new(8, 0)]
2080 );
2081 }
2082}