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