1use super::{
2 fold_map,
3 tab_map::{self, Edit as TabEdit, Snapshot as TabSnapshot, TabPoint, TextSummary},
4};
5use buffer::{HighlightId, Point};
6use gpui::{fonts::FontId, text_layout::LineWrapper, Entity, ModelContext, Task};
7use lazy_static::lazy_static;
8use smol::future::yield_now;
9use std::{collections::VecDeque, ops::Range, time::Duration};
10use sum_tree::{Bias, Cursor, SumTree};
11
12pub struct WrapMap {
13 snapshot: Snapshot,
14 pending_edits: VecDeque<(TabSnapshot, Vec<TabEdit>)>,
15 wrap_width: Option<f32>,
16 background_task: Option<Task<()>>,
17 font: (FontId, f32),
18}
19
20impl Entity for WrapMap {
21 type Event = ();
22}
23
24#[derive(Clone)]
25pub struct Snapshot {
26 tab_snapshot: TabSnapshot,
27 transforms: SumTree<Transform>,
28 interpolated: bool,
29}
30
31#[derive(Clone, Debug, Default, Eq, PartialEq)]
32struct Transform {
33 summary: TransformSummary,
34 display_text: Option<&'static str>,
35}
36
37#[derive(Clone, Debug, Default, Eq, PartialEq)]
38struct TransformSummary {
39 input: TextSummary,
40 output: TextSummary,
41}
42
43#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
44pub struct WrapPoint(super::Point);
45
46pub struct Chunks<'a> {
47 input_chunks: tab_map::Chunks<'a>,
48 input_chunk: &'a str,
49 output_position: WrapPoint,
50 transforms: Cursor<'a, Transform, (WrapPoint, TabPoint)>,
51}
52
53pub struct HighlightedChunks<'a> {
54 input_chunks: tab_map::HighlightedChunks<'a>,
55 input_chunk: &'a str,
56 style_id: HighlightId,
57 output_position: WrapPoint,
58 max_output_row: u32,
59 transforms: Cursor<'a, Transform, (WrapPoint, TabPoint)>,
60}
61
62pub struct BufferRows<'a> {
63 input_buffer_rows: fold_map::BufferRows<'a>,
64 input_buffer_row: u32,
65 output_row: u32,
66 soft_wrapped: bool,
67 max_output_row: u32,
68 transforms: Cursor<'a, Transform, (WrapPoint, TabPoint)>,
69}
70
71impl WrapMap {
72 pub fn new(
73 tab_snapshot: TabSnapshot,
74 font_id: FontId,
75 font_size: f32,
76 wrap_width: Option<f32>,
77 cx: &mut ModelContext<Self>,
78 ) -> Self {
79 let mut this = Self {
80 font: (font_id, font_size),
81 wrap_width: None,
82 pending_edits: Default::default(),
83 snapshot: Snapshot::new(tab_snapshot),
84 background_task: None,
85 };
86 this.set_wrap_width(wrap_width, cx);
87
88 this
89 }
90
91 #[cfg(test)]
92 pub fn is_rewrapping(&self) -> bool {
93 self.background_task.is_some()
94 }
95
96 pub fn sync(
97 &mut self,
98 tab_snapshot: TabSnapshot,
99 edits: Vec<TabEdit>,
100 cx: &mut ModelContext<Self>,
101 ) -> Snapshot {
102 self.pending_edits.push_back((tab_snapshot, edits));
103 self.flush_edits(cx);
104 self.snapshot.clone()
105 }
106
107 pub fn set_font(&mut self, font_id: FontId, font_size: f32, cx: &mut ModelContext<Self>) {
108 if (font_id, font_size) != self.font {
109 self.font = (font_id, font_size);
110 self.rewrap(cx)
111 }
112 }
113
114 pub fn set_wrap_width(&mut self, wrap_width: Option<f32>, cx: &mut ModelContext<Self>) -> bool {
115 if wrap_width == self.wrap_width {
116 return false;
117 }
118
119 self.wrap_width = wrap_width;
120 self.rewrap(cx);
121 true
122 }
123
124 fn rewrap(&mut self, cx: &mut ModelContext<Self>) {
125 self.background_task.take();
126
127 if let Some(wrap_width) = self.wrap_width {
128 let mut new_snapshot = self.snapshot.clone();
129 let font_cache = cx.font_cache().clone();
130 let (font_id, font_size) = self.font;
131 let task = cx.background().spawn(async move {
132 let mut line_wrapper = font_cache.line_wrapper(font_id, font_size);
133 let tab_snapshot = new_snapshot.tab_snapshot.clone();
134 let range = TabPoint::zero()..tab_snapshot.max_point();
135 new_snapshot
136 .update(
137 tab_snapshot,
138 &[TabEdit {
139 old_lines: range.clone(),
140 new_lines: range.clone(),
141 }],
142 wrap_width,
143 &mut line_wrapper,
144 )
145 .await;
146 new_snapshot
147 });
148
149 match cx
150 .background()
151 .block_with_timeout(Duration::from_millis(5), task)
152 {
153 Ok(snapshot) => {
154 self.snapshot = snapshot;
155 cx.notify();
156 }
157 Err(wrap_task) => {
158 self.background_task = Some(cx.spawn(|this, mut cx| async move {
159 let snapshot = wrap_task.await;
160 this.update(&mut cx, |this, cx| {
161 this.snapshot = snapshot;
162 this.background_task = None;
163 this.flush_edits(cx);
164 cx.notify();
165 });
166 }));
167 }
168 }
169 } else {
170 self.snapshot.transforms = SumTree::new();
171 let summary = self.snapshot.tab_snapshot.text_summary();
172 if !summary.lines.is_zero() {
173 self.snapshot
174 .transforms
175 .push(Transform::isomorphic(summary), &());
176 }
177 }
178 }
179
180 fn flush_edits(&mut self, cx: &mut ModelContext<Self>) {
181 if !self.snapshot.interpolated {
182 let mut to_remove_len = 0;
183 for (tab_snapshot, _) in &self.pending_edits {
184 if tab_snapshot.version() <= self.snapshot.tab_snapshot.version() {
185 to_remove_len += 1;
186 } else {
187 break;
188 }
189 }
190 self.pending_edits.drain(..to_remove_len);
191 }
192
193 if self.pending_edits.is_empty() {
194 return;
195 }
196
197 if let Some(wrap_width) = self.wrap_width {
198 if self.background_task.is_none() {
199 let pending_edits = self.pending_edits.clone();
200 let mut snapshot = self.snapshot.clone();
201 let font_cache = cx.font_cache().clone();
202 let (font_id, font_size) = self.font;
203 let update_task = cx.background().spawn(async move {
204 let mut line_wrapper = font_cache.line_wrapper(font_id, font_size);
205
206 for (tab_snapshot, edits) in pending_edits {
207 snapshot
208 .update(tab_snapshot, &edits, wrap_width, &mut line_wrapper)
209 .await;
210 }
211 snapshot
212 });
213
214 match cx
215 .background()
216 .block_with_timeout(Duration::from_millis(1), update_task)
217 {
218 Ok(snapshot) => {
219 self.snapshot = snapshot;
220 }
221 Err(update_task) => {
222 self.background_task = Some(cx.spawn(|this, mut cx| async move {
223 let snapshot = update_task.await;
224 this.update(&mut cx, |this, cx| {
225 this.snapshot = snapshot;
226 this.background_task = None;
227 this.flush_edits(cx);
228 cx.notify();
229 });
230 }));
231 }
232 }
233 }
234 }
235
236 let was_interpolated = self.snapshot.interpolated;
237 let mut to_remove_len = 0;
238 for (tab_snapshot, edits) in &self.pending_edits {
239 if tab_snapshot.version() <= self.snapshot.tab_snapshot.version() {
240 to_remove_len += 1;
241 } else {
242 self.snapshot.interpolate(tab_snapshot.clone(), &edits);
243 }
244 }
245
246 if !was_interpolated {
247 self.pending_edits.drain(..to_remove_len);
248 }
249 }
250}
251
252impl Snapshot {
253 fn new(tab_snapshot: TabSnapshot) -> Self {
254 let mut transforms = SumTree::new();
255 let extent = tab_snapshot.text_summary();
256 if !extent.lines.is_zero() {
257 transforms.push(Transform::isomorphic(extent), &());
258 }
259 Self {
260 transforms,
261 tab_snapshot,
262 interpolated: true,
263 }
264 }
265
266 fn interpolate(&mut self, new_tab_snapshot: TabSnapshot, edits: &[TabEdit]) {
267 let mut new_transforms;
268 if edits.is_empty() {
269 new_transforms = self.transforms.clone();
270 } else {
271 let mut old_cursor = self.transforms.cursor::<TabPoint>();
272 let mut edits = edits.into_iter().peekable();
273 new_transforms =
274 old_cursor.slice(&edits.peek().unwrap().old_lines.start, Bias::Right, &());
275
276 while let Some(edit) = edits.next() {
277 if edit.new_lines.start > TabPoint::from(new_transforms.summary().input.lines) {
278 let summary = new_tab_snapshot.text_summary_for_range(
279 TabPoint::from(new_transforms.summary().input.lines)..edit.new_lines.start,
280 );
281 new_transforms.push_or_extend(Transform::isomorphic(summary));
282 }
283
284 if !edit.new_lines.is_empty() {
285 new_transforms.push_or_extend(Transform::isomorphic(
286 new_tab_snapshot.text_summary_for_range(edit.new_lines.clone()),
287 ));
288 }
289
290 old_cursor.seek_forward(&edit.old_lines.end, Bias::Right, &());
291 if let Some(next_edit) = edits.peek() {
292 if next_edit.old_lines.start > old_cursor.end(&()) {
293 if old_cursor.end(&()) > edit.old_lines.end {
294 let summary = self
295 .tab_snapshot
296 .text_summary_for_range(edit.old_lines.end..old_cursor.end(&()));
297 new_transforms.push_or_extend(Transform::isomorphic(summary));
298 }
299 old_cursor.next(&());
300 new_transforms.push_tree(
301 old_cursor.slice(&next_edit.old_lines.start, Bias::Right, &()),
302 &(),
303 );
304 }
305 } else {
306 if old_cursor.end(&()) > edit.old_lines.end {
307 let summary = self
308 .tab_snapshot
309 .text_summary_for_range(edit.old_lines.end..old_cursor.end(&()));
310 new_transforms.push_or_extend(Transform::isomorphic(summary));
311 }
312 old_cursor.next(&());
313 new_transforms.push_tree(old_cursor.suffix(&()), &());
314 }
315 }
316 }
317
318 self.transforms = new_transforms;
319 self.tab_snapshot = new_tab_snapshot;
320 self.interpolated = true;
321 self.check_invariants();
322 }
323
324 async fn update(
325 &mut self,
326 new_tab_snapshot: TabSnapshot,
327 edits: &[TabEdit],
328 wrap_width: f32,
329 line_wrapper: &mut LineWrapper,
330 ) {
331 #[derive(Debug)]
332 struct RowEdit {
333 old_rows: Range<u32>,
334 new_rows: Range<u32>,
335 }
336
337 let mut edits = edits.into_iter().peekable();
338 let mut row_edits = Vec::new();
339 while let Some(edit) = edits.next() {
340 let mut row_edit = RowEdit {
341 old_rows: edit.old_lines.start.row()..edit.old_lines.end.row() + 1,
342 new_rows: edit.new_lines.start.row()..edit.new_lines.end.row() + 1,
343 };
344
345 while let Some(next_edit) = edits.peek() {
346 if next_edit.old_lines.start.row() <= row_edit.old_rows.end {
347 row_edit.old_rows.end = next_edit.old_lines.end.row() + 1;
348 row_edit.new_rows.end = next_edit.new_lines.end.row() + 1;
349 edits.next();
350 } else {
351 break;
352 }
353 }
354
355 row_edits.push(row_edit);
356 }
357
358 let mut new_transforms;
359 if row_edits.is_empty() {
360 new_transforms = self.transforms.clone();
361 } else {
362 let mut row_edits = row_edits.into_iter().peekable();
363 let mut old_cursor = self.transforms.cursor::<TabPoint>();
364
365 new_transforms = old_cursor.slice(
366 &TabPoint::new(row_edits.peek().unwrap().old_rows.start, 0),
367 Bias::Right,
368 &(),
369 );
370
371 while let Some(edit) = row_edits.next() {
372 if edit.new_rows.start > new_transforms.summary().input.lines.row {
373 let summary = new_tab_snapshot.text_summary_for_range(
374 TabPoint::new(new_transforms.summary().input.lines.row, 0)
375 ..TabPoint::new(edit.new_rows.start, 0),
376 );
377 new_transforms.push_or_extend(Transform::isomorphic(summary));
378 }
379
380 let mut line = String::new();
381 let mut remaining = None;
382 let mut chunks = new_tab_snapshot.chunks_at(TabPoint::new(edit.new_rows.start, 0));
383 let mut edit_transforms = Vec::<Transform>::new();
384 for _ in edit.new_rows.start..edit.new_rows.end {
385 while let Some(chunk) = remaining.take().or_else(|| chunks.next()) {
386 if let Some(ix) = chunk.find('\n') {
387 line.push_str(&chunk[..ix + 1]);
388 remaining = Some(&chunk[ix + 1..]);
389 break;
390 } else {
391 line.push_str(chunk)
392 }
393 }
394
395 if line.is_empty() {
396 break;
397 }
398
399 let mut prev_boundary_ix = 0;
400 for boundary in line_wrapper.wrap_line(&line, wrap_width) {
401 let wrapped = &line[prev_boundary_ix..boundary.ix];
402 push_isomorphic(&mut edit_transforms, TextSummary::from(wrapped));
403 edit_transforms.push(Transform::wrap(boundary.next_indent));
404 prev_boundary_ix = boundary.ix;
405 }
406
407 if prev_boundary_ix < line.len() {
408 push_isomorphic(
409 &mut edit_transforms,
410 TextSummary::from(&line[prev_boundary_ix..]),
411 );
412 }
413
414 line.clear();
415 yield_now().await;
416 }
417
418 let mut edit_transforms = edit_transforms.into_iter();
419 if let Some(transform) = edit_transforms.next() {
420 new_transforms.push_or_extend(transform);
421 }
422 new_transforms.extend(edit_transforms, &());
423
424 old_cursor.seek_forward(&TabPoint::new(edit.old_rows.end, 0), Bias::Right, &());
425 if let Some(next_edit) = row_edits.peek() {
426 if next_edit.old_rows.start > old_cursor.end(&()).row() {
427 if old_cursor.end(&()) > TabPoint::new(edit.old_rows.end, 0) {
428 let summary = self.tab_snapshot.text_summary_for_range(
429 TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(&()),
430 );
431 new_transforms.push_or_extend(Transform::isomorphic(summary));
432 }
433 old_cursor.next(&());
434 new_transforms.push_tree(
435 old_cursor.slice(
436 &TabPoint::new(next_edit.old_rows.start, 0),
437 Bias::Right,
438 &(),
439 ),
440 &(),
441 );
442 }
443 } else {
444 if old_cursor.end(&()) > TabPoint::new(edit.old_rows.end, 0) {
445 let summary = self.tab_snapshot.text_summary_for_range(
446 TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(&()),
447 );
448 new_transforms.push_or_extend(Transform::isomorphic(summary));
449 }
450 old_cursor.next(&());
451 new_transforms.push_tree(old_cursor.suffix(&()), &());
452 }
453 }
454 }
455
456 self.transforms = new_transforms;
457 self.tab_snapshot = new_tab_snapshot;
458 self.interpolated = false;
459 self.check_invariants();
460 }
461
462 pub fn chunks_at(&self, wrap_row: u32) -> Chunks {
463 let point = WrapPoint::new(wrap_row, 0);
464 let mut transforms = self.transforms.cursor::<(WrapPoint, TabPoint)>();
465 transforms.seek(&point, Bias::Right, &());
466 let mut input_position = TabPoint(transforms.start().1 .0);
467 if transforms.item().map_or(false, |t| t.is_isomorphic()) {
468 input_position.0 += point.0 - transforms.start().0 .0;
469 }
470 let input_chunks = self.tab_snapshot.chunks_at(input_position);
471 Chunks {
472 input_chunks,
473 transforms,
474 output_position: point,
475 input_chunk: "",
476 }
477 }
478
479 pub fn highlighted_chunks_for_rows(&mut self, rows: Range<u32>) -> HighlightedChunks {
480 let output_start = WrapPoint::new(rows.start, 0);
481 let output_end = WrapPoint::new(rows.end, 0);
482 let mut transforms = self.transforms.cursor::<(WrapPoint, TabPoint)>();
483 transforms.seek(&output_start, Bias::Right, &());
484 let mut input_start = TabPoint(transforms.start().1 .0);
485 if transforms.item().map_or(false, |t| t.is_isomorphic()) {
486 input_start.0 += output_start.0 - transforms.start().0 .0;
487 }
488 let input_end = self
489 .to_tab_point(output_end)
490 .min(self.tab_snapshot.max_point());
491 HighlightedChunks {
492 input_chunks: self.tab_snapshot.highlighted_chunks(input_start..input_end),
493 input_chunk: "",
494 style_id: HighlightId::default(),
495 output_position: output_start,
496 max_output_row: rows.end,
497 transforms,
498 }
499 }
500
501 pub fn max_point(&self) -> WrapPoint {
502 self.to_wrap_point(self.tab_snapshot.max_point())
503 }
504
505 pub fn line_len(&self, row: u32) -> u32 {
506 let mut len = 0;
507 for chunk in self.chunks_at(row) {
508 if let Some(newline_ix) = chunk.find('\n') {
509 len += newline_ix;
510 break;
511 } else {
512 len += chunk.len();
513 }
514 }
515 len as u32
516 }
517
518 pub fn soft_wrap_indent(&self, row: u32) -> Option<u32> {
519 let mut cursor = self.transforms.cursor::<WrapPoint>();
520 cursor.seek(&WrapPoint::new(row + 1, 0), Bias::Right, &());
521 cursor.item().and_then(|transform| {
522 if transform.is_isomorphic() {
523 None
524 } else {
525 Some(transform.summary.output.lines.column)
526 }
527 })
528 }
529
530 pub fn longest_row(&self) -> u32 {
531 self.transforms.summary().output.longest_row
532 }
533
534 pub fn buffer_rows(&self, start_row: u32) -> BufferRows {
535 let mut transforms = self.transforms.cursor::<(WrapPoint, TabPoint)>();
536 transforms.seek(&WrapPoint::new(start_row, 0), Bias::Left, &());
537 let mut input_row = transforms.start().1.row();
538 if transforms.item().map_or(false, |t| t.is_isomorphic()) {
539 input_row += start_row - transforms.start().0.row();
540 }
541 let soft_wrapped = transforms.item().map_or(false, |t| !t.is_isomorphic());
542 let mut input_buffer_rows = self.tab_snapshot.buffer_rows(input_row);
543 let input_buffer_row = input_buffer_rows.next().unwrap();
544 BufferRows {
545 transforms,
546 input_buffer_row,
547 input_buffer_rows,
548 output_row: start_row,
549 soft_wrapped,
550 max_output_row: self.max_point().row(),
551 }
552 }
553
554 pub fn to_tab_point(&self, point: WrapPoint) -> TabPoint {
555 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>();
556 cursor.seek(&point, Bias::Right, &());
557 let mut tab_point = cursor.start().1 .0;
558 if cursor.item().map_or(false, |t| t.is_isomorphic()) {
559 tab_point += point.0 - cursor.start().0 .0;
560 }
561 TabPoint(tab_point)
562 }
563
564 pub fn to_wrap_point(&self, point: TabPoint) -> WrapPoint {
565 let mut cursor = self.transforms.cursor::<(TabPoint, WrapPoint)>();
566 cursor.seek(&point, Bias::Right, &());
567 WrapPoint(cursor.start().1 .0 + (point.0 - cursor.start().0 .0))
568 }
569
570 pub fn clip_point(&self, mut point: WrapPoint, bias: Bias) -> WrapPoint {
571 if bias == Bias::Left {
572 let mut cursor = self.transforms.cursor::<WrapPoint>();
573 cursor.seek(&point, Bias::Right, &());
574 if cursor.item().map_or(false, |t| !t.is_isomorphic()) {
575 point = *cursor.start();
576 *point.column_mut() -= 1;
577 }
578 }
579
580 self.to_wrap_point(self.tab_snapshot.clip_point(self.to_tab_point(point), bias))
581 }
582
583 fn check_invariants(&self) {
584 #[cfg(test)]
585 {
586 assert_eq!(
587 TabPoint::from(self.transforms.summary().input.lines),
588 self.tab_snapshot.max_point()
589 );
590
591 {
592 let mut transforms = self.transforms.cursor::<()>().peekable();
593 while let Some(transform) = transforms.next() {
594 if let Some(next_transform) = transforms.peek() {
595 assert!(transform.is_isomorphic() != next_transform.is_isomorphic());
596 }
597 }
598 }
599
600 let mut expected_buffer_rows = Vec::new();
601 let mut buffer_row = 0;
602 let mut prev_tab_row = 0;
603 for display_row in 0..=self.max_point().row() {
604 let tab_point = self.to_tab_point(WrapPoint::new(display_row, 0));
605 let soft_wrapped;
606 if tab_point.row() == prev_tab_row {
607 soft_wrapped = display_row != 0;
608 } else {
609 let fold_point = self.tab_snapshot.to_fold_point(tab_point, Bias::Left).0;
610 let buffer_point = fold_point.to_buffer_point(&self.tab_snapshot.fold_snapshot);
611 buffer_row = buffer_point.row;
612 prev_tab_row = tab_point.row();
613 soft_wrapped = false;
614 }
615 expected_buffer_rows.push((buffer_row, soft_wrapped));
616 }
617
618 for start_display_row in 0..expected_buffer_rows.len() {
619 assert_eq!(
620 self.buffer_rows(start_display_row as u32)
621 .collect::<Vec<_>>(),
622 &expected_buffer_rows[start_display_row..],
623 "invalid buffer_rows({}..)",
624 start_display_row
625 );
626 }
627 }
628 }
629}
630
631impl<'a> Iterator for Chunks<'a> {
632 type Item = &'a str;
633
634 fn next(&mut self) -> Option<Self::Item> {
635 let transform = self.transforms.item()?;
636 if let Some(display_text) = transform.display_text {
637 if self.output_position > self.transforms.start().0 {
638 self.output_position.0.column += transform.summary.output.lines.column;
639 self.transforms.next(&());
640 return Some(&display_text[1..]);
641 } else {
642 self.output_position.0 += transform.summary.output.lines;
643 self.transforms.next(&());
644 return Some(display_text);
645 }
646 }
647
648 if self.input_chunk.is_empty() {
649 self.input_chunk = self.input_chunks.next().unwrap();
650 }
651
652 let mut input_len = 0;
653 let transform_end = self.transforms.end(&()).0;
654 for c in self.input_chunk.chars() {
655 let char_len = c.len_utf8();
656 input_len += char_len;
657 if c == '\n' {
658 *self.output_position.row_mut() += 1;
659 *self.output_position.column_mut() = 0;
660 } else {
661 *self.output_position.column_mut() += char_len as u32;
662 }
663
664 if self.output_position >= transform_end {
665 self.transforms.next(&());
666 break;
667 }
668 }
669
670 let (prefix, suffix) = self.input_chunk.split_at(input_len);
671 self.input_chunk = suffix;
672 Some(prefix)
673 }
674}
675
676impl<'a> Iterator for HighlightedChunks<'a> {
677 type Item = (&'a str, HighlightId);
678
679 fn next(&mut self) -> Option<Self::Item> {
680 if self.output_position.row() >= self.max_output_row {
681 return None;
682 }
683
684 let transform = self.transforms.item()?;
685 if let Some(display_text) = transform.display_text {
686 let mut start_ix = 0;
687 let mut end_ix = display_text.len();
688 let mut summary = transform.summary.output.lines;
689
690 if self.output_position > self.transforms.start().0 {
691 // Exclude newline starting prior to the desired row.
692 start_ix = 1;
693 summary.row = 0;
694 } else if self.output_position.row() + 1 >= self.max_output_row {
695 // Exclude soft indentation ending after the desired row.
696 end_ix = 1;
697 summary.column = 0;
698 }
699
700 self.output_position.0 += summary;
701 self.transforms.next(&());
702 return Some((&display_text[start_ix..end_ix], self.style_id));
703 }
704
705 if self.input_chunk.is_empty() {
706 let (chunk, style_id) = self.input_chunks.next().unwrap();
707 self.input_chunk = chunk;
708 self.style_id = style_id;
709 }
710
711 let mut input_len = 0;
712 let transform_end = self.transforms.end(&()).0;
713 for c in self.input_chunk.chars() {
714 let char_len = c.len_utf8();
715 input_len += char_len;
716 if c == '\n' {
717 *self.output_position.row_mut() += 1;
718 *self.output_position.column_mut() = 0;
719 } else {
720 *self.output_position.column_mut() += char_len as u32;
721 }
722
723 if self.output_position >= transform_end {
724 self.transforms.next(&());
725 break;
726 }
727 }
728
729 let (prefix, suffix) = self.input_chunk.split_at(input_len);
730 self.input_chunk = suffix;
731 Some((prefix, self.style_id))
732 }
733}
734
735impl<'a> Iterator for BufferRows<'a> {
736 type Item = (u32, bool);
737
738 fn next(&mut self) -> Option<Self::Item> {
739 if self.output_row > self.max_output_row {
740 return None;
741 }
742
743 let buffer_row = self.input_buffer_row;
744 let soft_wrapped = self.soft_wrapped;
745
746 self.output_row += 1;
747 self.transforms
748 .seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left, &());
749 if self.transforms.item().map_or(false, |t| t.is_isomorphic()) {
750 self.input_buffer_row = self.input_buffer_rows.next().unwrap();
751 self.soft_wrapped = false;
752 } else {
753 self.soft_wrapped = true;
754 }
755
756 Some((buffer_row, soft_wrapped))
757 }
758}
759
760impl Transform {
761 fn isomorphic(summary: TextSummary) -> Self {
762 #[cfg(test)]
763 assert!(!summary.lines.is_zero());
764
765 Self {
766 summary: TransformSummary {
767 input: summary.clone(),
768 output: summary,
769 },
770 display_text: None,
771 }
772 }
773
774 fn wrap(indent: u32) -> Self {
775 lazy_static! {
776 static ref WRAP_TEXT: String = {
777 let mut wrap_text = String::new();
778 wrap_text.push('\n');
779 wrap_text.extend((0..LineWrapper::MAX_INDENT as usize).map(|_| ' '));
780 wrap_text
781 };
782 }
783
784 Self {
785 summary: TransformSummary {
786 input: TextSummary::default(),
787 output: TextSummary {
788 lines: Point::new(1, indent),
789 first_line_chars: 0,
790 last_line_chars: indent,
791 longest_row: 1,
792 longest_row_chars: indent,
793 },
794 },
795 display_text: Some(&WRAP_TEXT[..1 + indent as usize]),
796 }
797 }
798
799 fn is_isomorphic(&self) -> bool {
800 self.display_text.is_none()
801 }
802}
803
804impl sum_tree::Item for Transform {
805 type Summary = TransformSummary;
806
807 fn summary(&self) -> Self::Summary {
808 self.summary.clone()
809 }
810}
811
812fn push_isomorphic(transforms: &mut Vec<Transform>, summary: TextSummary) {
813 if let Some(last_transform) = transforms.last_mut() {
814 if last_transform.is_isomorphic() {
815 last_transform.summary.input += &summary;
816 last_transform.summary.output += &summary;
817 return;
818 }
819 }
820 transforms.push(Transform::isomorphic(summary));
821}
822
823trait SumTreeExt {
824 fn push_or_extend(&mut self, transform: Transform);
825}
826
827impl SumTreeExt for SumTree<Transform> {
828 fn push_or_extend(&mut self, transform: Transform) {
829 let mut transform = Some(transform);
830 self.update_last(
831 |last_transform| {
832 if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
833 let transform = transform.take().unwrap();
834 last_transform.summary.input += &transform.summary.input;
835 last_transform.summary.output += &transform.summary.output;
836 }
837 },
838 &(),
839 );
840
841 if let Some(transform) = transform {
842 self.push(transform, &());
843 }
844 }
845}
846
847impl WrapPoint {
848 pub fn new(row: u32, column: u32) -> Self {
849 Self(super::Point::new(row, column))
850 }
851
852 #[cfg(test)]
853 pub fn is_zero(&self) -> bool {
854 self.0.is_zero()
855 }
856
857 pub fn row(self) -> u32 {
858 self.0.row
859 }
860
861 pub fn column(self) -> u32 {
862 self.0.column
863 }
864
865 pub fn row_mut(&mut self) -> &mut u32 {
866 &mut self.0.row
867 }
868
869 pub fn column_mut(&mut self) -> &mut u32 {
870 &mut self.0.column
871 }
872}
873
874impl sum_tree::Summary for TransformSummary {
875 type Context = ();
876
877 fn add_summary(&mut self, other: &Self, _: &()) {
878 self.input += &other.input;
879 self.output += &other.output;
880 }
881}
882
883impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
884 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
885 self.0 += summary.input.lines;
886 }
887}
888
889impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
890 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
891 self.0 += summary.output.lines;
892 }
893}
894
895#[cfg(test)]
896mod tests {
897 use super::*;
898 use crate::{
899 display_map::{fold_map::FoldMap, tab_map::TabMap},
900 test::Observer,
901 };
902 use buffer::{Buffer, RandomCharIter};
903 use rand::prelude::*;
904 use std::env;
905
906 #[gpui::test(iterations = 100)]
907 async fn test_random_wraps(mut cx: gpui::TestAppContext, mut rng: StdRng) {
908 cx.foreground().set_block_on_ticks(0..=50);
909 cx.foreground().forbid_parking();
910 let operations = env::var("OPERATIONS")
911 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
912 .unwrap_or(10);
913
914 let font_cache = cx.font_cache().clone();
915 let font_system = cx.platform().fonts();
916 let mut wrap_width = if rng.gen_bool(0.1) {
917 None
918 } else {
919 Some(rng.gen_range(0.0..=1000.0))
920 };
921 let tab_size = rng.gen_range(1..=4);
922 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
923 let font_id = font_cache
924 .select_font(family_id, &Default::default())
925 .unwrap();
926 let font_size = 14.0;
927
928 log::info!("Tab size: {}", tab_size);
929 log::info!("Wrap width: {:?}", wrap_width);
930
931 let buffer = cx.add_model(|cx| {
932 let len = rng.gen_range(0..10);
933 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
934 Buffer::new(0, text, cx)
935 });
936 let (mut fold_map, folds_snapshot) = cx.read(|cx| FoldMap::new(buffer.clone(), cx));
937 let (tab_map, tabs_snapshot) = TabMap::new(folds_snapshot.clone(), tab_size);
938 log::info!(
939 "Unwrapped text (no folds): {:?}",
940 buffer.read_with(&cx, |buf, _| buf.text())
941 );
942 log::info!(
943 "Unwrapped text (unexpanded tabs): {:?}",
944 folds_snapshot.text()
945 );
946 log::info!("Unwrapped text (expanded tabs): {:?}", tabs_snapshot.text());
947
948 let mut line_wrapper = LineWrapper::new(font_id, font_size, font_system);
949 let unwrapped_text = tabs_snapshot.text();
950 let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
951
952 let wrap_map = cx.add_model(|cx| {
953 WrapMap::new(tabs_snapshot.clone(), font_id, font_size, wrap_width, cx)
954 });
955 let (_observer, notifications) = Observer::new(&wrap_map, &mut cx);
956
957 if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
958 notifications.recv().await.unwrap();
959 }
960
961 let snapshot = wrap_map.update(&mut cx, |map, cx| map.sync(tabs_snapshot, Vec::new(), cx));
962 let actual_text = snapshot.text();
963 assert_eq!(
964 actual_text, expected_text,
965 "unwrapped text is: {:?}",
966 unwrapped_text
967 );
968 log::info!("Wrapped text: {:?}", actual_text);
969
970 for _i in 0..operations {
971 match rng.gen_range(0..=100) {
972 0..=19 => {
973 wrap_width = if rng.gen_bool(0.2) {
974 None
975 } else {
976 Some(rng.gen_range(0.0..=1000.0))
977 };
978 log::info!("Setting wrap width to {:?}", wrap_width);
979 wrap_map.update(&mut cx, |map, cx| map.set_wrap_width(wrap_width, cx));
980 }
981 20..=39 => {
982 for (folds_snapshot, edits) in
983 cx.read(|cx| fold_map.randomly_mutate(&mut rng, cx))
984 {
985 let (tabs_snapshot, edits) = tab_map.sync(folds_snapshot, edits);
986 let mut snapshot =
987 wrap_map.update(&mut cx, |map, cx| map.sync(tabs_snapshot, edits, cx));
988 snapshot.check_invariants();
989 snapshot.verify_chunks(&mut rng);
990 }
991 }
992 _ => {
993 buffer.update(&mut cx, |buffer, cx| buffer.randomly_mutate(&mut rng, cx));
994 }
995 }
996
997 log::info!(
998 "Unwrapped text (no folds): {:?}",
999 buffer.read_with(&cx, |buf, _| buf.text())
1000 );
1001 let (folds_snapshot, edits) = cx.read(|cx| fold_map.read(cx));
1002 log::info!(
1003 "Unwrapped text (unexpanded tabs): {:?}",
1004 folds_snapshot.text()
1005 );
1006 let (tabs_snapshot, edits) = tab_map.sync(folds_snapshot, edits);
1007 log::info!("Unwrapped text (expanded tabs): {:?}", tabs_snapshot.text());
1008
1009 let unwrapped_text = tabs_snapshot.text();
1010 let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1011 let mut snapshot = wrap_map.update(&mut cx, |map, cx| {
1012 map.sync(tabs_snapshot.clone(), edits, cx)
1013 });
1014 snapshot.check_invariants();
1015 snapshot.verify_chunks(&mut rng);
1016
1017 if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) && rng.gen_bool(0.4) {
1018 log::info!("Waiting for wrapping to finish");
1019 while wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1020 notifications.recv().await.unwrap();
1021 }
1022 }
1023
1024 if !wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1025 let mut wrapped_snapshot =
1026 wrap_map.update(&mut cx, |map, cx| map.sync(tabs_snapshot, Vec::new(), cx));
1027 let actual_text = wrapped_snapshot.text();
1028 log::info!("Wrapping finished: {:?}", actual_text);
1029 wrapped_snapshot.check_invariants();
1030 wrapped_snapshot.verify_chunks(&mut rng);
1031 assert_eq!(
1032 actual_text, expected_text,
1033 "unwrapped text is: {:?}",
1034 unwrapped_text
1035 );
1036 }
1037 }
1038 }
1039
1040 fn wrap_text(
1041 unwrapped_text: &str,
1042 wrap_width: Option<f32>,
1043 line_wrapper: &mut LineWrapper,
1044 ) -> String {
1045 if let Some(wrap_width) = wrap_width {
1046 let mut wrapped_text = String::new();
1047 for (row, line) in unwrapped_text.split('\n').enumerate() {
1048 if row > 0 {
1049 wrapped_text.push('\n')
1050 }
1051
1052 let mut prev_ix = 0;
1053 for boundary in line_wrapper.wrap_line(line, wrap_width) {
1054 wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1055 wrapped_text.push('\n');
1056 wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1057 prev_ix = boundary.ix;
1058 }
1059 wrapped_text.push_str(&line[prev_ix..]);
1060 }
1061 wrapped_text
1062 } else {
1063 unwrapped_text.to_string()
1064 }
1065 }
1066
1067 impl Snapshot {
1068 fn text(&self) -> String {
1069 self.chunks_at(0).collect()
1070 }
1071
1072 fn verify_chunks(&mut self, rng: &mut impl Rng) {
1073 for _ in 0..5 {
1074 let mut end_row = rng.gen_range(0..=self.max_point().row());
1075 let start_row = rng.gen_range(0..=end_row);
1076 end_row += 1;
1077
1078 let mut expected_text = self.chunks_at(start_row).collect::<String>();
1079 if expected_text.ends_with("\n") {
1080 expected_text.push('\n');
1081 }
1082 let mut expected_text = expected_text
1083 .lines()
1084 .take((end_row - start_row) as usize)
1085 .collect::<Vec<_>>()
1086 .join("\n");
1087 if end_row <= self.max_point().row() {
1088 expected_text.push('\n');
1089 }
1090
1091 let actual_text = self
1092 .highlighted_chunks_for_rows(start_row..end_row)
1093 .map(|c| c.0)
1094 .collect::<String>();
1095 assert_eq!(
1096 expected_text,
1097 actual_text,
1098 "chunks != highlighted_chunks for rows {:?}",
1099 start_row..end_row
1100 );
1101 }
1102 }
1103 }
1104}