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