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