1use super::{
2 fold_map,
3 tab_map::{self, TabEdit, TabPoint, TabSnapshot},
4};
5use gpui::{
6 fonts::FontId, text_layout::LineWrapper, Entity, ModelContext, ModelHandle, MutableAppContext,
7 Task,
8};
9use language::{multi_buffer::MultiBufferSnapshot, Chunk, Point};
10use lazy_static::lazy_static;
11use smol::future::yield_now;
12use std::{collections::VecDeque, mem, ops::Range, time::Duration};
13use sum_tree::{Bias, Cursor, SumTree};
14use text::Patch;
15use theme::SyntaxTheme;
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: 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 None,
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, None)
565 .map(|h| h.text)
566 }
567
568 pub fn chunks<'a>(
569 &'a self,
570 rows: Range<u32>,
571 theme: Option<&'a SyntaxTheme>,
572 ) -> WrapChunks<'a> {
573 let output_start = WrapPoint::new(rows.start, 0);
574 let output_end = WrapPoint::new(rows.end, 0);
575 let mut transforms = self.transforms.cursor::<(WrapPoint, TabPoint)>();
576 transforms.seek(&output_start, Bias::Right, &());
577 let mut input_start = TabPoint(transforms.start().1 .0);
578 if transforms.item().map_or(false, |t| t.is_isomorphic()) {
579 input_start.0 += output_start.0 - transforms.start().0 .0;
580 }
581 let input_end = self
582 .to_tab_point(output_end)
583 .min(self.tab_snapshot.max_point());
584 WrapChunks {
585 input_chunks: self.tab_snapshot.chunks(input_start..input_end, theme),
586 input_chunk: Default::default(),
587 output_position: output_start,
588 max_output_row: rows.end,
589 transforms,
590 }
591 }
592
593 pub fn text_summary(&self) -> TextSummary {
594 self.transforms.summary().output
595 }
596
597 pub fn max_point(&self) -> WrapPoint {
598 WrapPoint(self.transforms.summary().output.lines)
599 }
600
601 pub fn line_len(&self, row: u32) -> u32 {
602 let mut len = 0;
603 for chunk in self.text_chunks(row) {
604 if let Some(newline_ix) = chunk.find('\n') {
605 len += newline_ix;
606 break;
607 } else {
608 len += chunk.len();
609 }
610 }
611 len as u32
612 }
613
614 pub fn soft_wrap_indent(&self, row: u32) -> Option<u32> {
615 let mut cursor = self.transforms.cursor::<WrapPoint>();
616 cursor.seek(&WrapPoint::new(row + 1, 0), Bias::Right, &());
617 cursor.item().and_then(|transform| {
618 if transform.is_isomorphic() {
619 None
620 } else {
621 Some(transform.summary.output.lines.column)
622 }
623 })
624 }
625
626 pub fn longest_row(&self) -> u32 {
627 self.transforms.summary().output.longest_row
628 }
629
630 pub fn buffer_rows(&self, start_row: u32) -> WrapBufferRows {
631 let mut transforms = self.transforms.cursor::<(WrapPoint, TabPoint)>();
632 transforms.seek(&WrapPoint::new(start_row, 0), Bias::Left, &());
633 let mut input_row = transforms.start().1.row();
634 if transforms.item().map_or(false, |t| t.is_isomorphic()) {
635 input_row += start_row - transforms.start().0.row();
636 }
637 let soft_wrapped = transforms.item().map_or(false, |t| !t.is_isomorphic());
638 let mut input_buffer_rows = self.tab_snapshot.buffer_rows(input_row);
639 let input_buffer_row = input_buffer_rows.next().unwrap();
640 WrapBufferRows {
641 transforms,
642 input_buffer_row,
643 input_buffer_rows,
644 output_row: start_row,
645 soft_wrapped,
646 max_output_row: self.max_point().row(),
647 }
648 }
649
650 pub fn to_tab_point(&self, point: WrapPoint) -> TabPoint {
651 let mut cursor = self.transforms.cursor::<(WrapPoint, TabPoint)>();
652 cursor.seek(&point, Bias::Right, &());
653 let mut tab_point = cursor.start().1 .0;
654 if cursor.item().map_or(false, |t| t.is_isomorphic()) {
655 tab_point += point.0 - cursor.start().0 .0;
656 }
657 TabPoint(tab_point)
658 }
659
660 pub fn to_point(&self, point: WrapPoint, bias: Bias) -> Point {
661 self.tab_snapshot.to_point(self.to_tab_point(point), bias)
662 }
663
664 pub fn from_point(&self, point: Point, bias: Bias) -> WrapPoint {
665 self.from_tab_point(self.tab_snapshot.from_point(point, bias))
666 }
667
668 pub fn from_tab_point(&self, point: TabPoint) -> WrapPoint {
669 let mut cursor = self.transforms.cursor::<(TabPoint, WrapPoint)>();
670 cursor.seek(&point, Bias::Right, &());
671 WrapPoint(cursor.start().1 .0 + (point.0 - cursor.start().0 .0))
672 }
673
674 pub fn clip_point(&self, mut point: WrapPoint, bias: Bias) -> WrapPoint {
675 if bias == Bias::Left {
676 let mut cursor = self.transforms.cursor::<WrapPoint>();
677 cursor.seek(&point, Bias::Right, &());
678 if cursor.item().map_or(false, |t| !t.is_isomorphic()) {
679 point = *cursor.start();
680 *point.column_mut() -= 1;
681 }
682 }
683
684 self.from_tab_point(self.tab_snapshot.clip_point(self.to_tab_point(point), bias))
685 }
686
687 fn check_invariants(&self) {
688 #[cfg(test)]
689 {
690 assert_eq!(
691 TabPoint::from(self.transforms.summary().input.lines),
692 self.tab_snapshot.max_point()
693 );
694
695 {
696 let mut transforms = self.transforms.cursor::<()>().peekable();
697 while let Some(transform) = transforms.next() {
698 if let Some(next_transform) = transforms.peek() {
699 assert!(transform.is_isomorphic() != next_transform.is_isomorphic());
700 }
701 }
702 }
703
704 let mut expected_buffer_rows = Vec::new();
705 let mut buffer_row = 0;
706 let mut prev_tab_row = 0;
707 for display_row in 0..=self.max_point().row() {
708 let tab_point = self.to_tab_point(WrapPoint::new(display_row, 0));
709 let soft_wrapped;
710 if tab_point.row() == prev_tab_row {
711 soft_wrapped = display_row != 0;
712 } else {
713 let fold_point = self.tab_snapshot.to_fold_point(tab_point, Bias::Left).0;
714 let buffer_point = fold_point.to_buffer_point(&self.tab_snapshot.fold_snapshot);
715 buffer_row = buffer_point.row;
716 prev_tab_row = tab_point.row();
717 soft_wrapped = false;
718 }
719 expected_buffer_rows.push(if soft_wrapped { None } else { Some(buffer_row) });
720 }
721
722 for start_display_row in 0..expected_buffer_rows.len() {
723 assert_eq!(
724 self.buffer_rows(start_display_row as u32)
725 .collect::<Vec<_>>(),
726 &expected_buffer_rows[start_display_row..],
727 "invalid buffer_rows({}..)",
728 start_display_row
729 );
730 }
731 }
732 }
733}
734
735impl<'a> Iterator for WrapChunks<'a> {
736 type Item = Chunk<'a>;
737
738 fn next(&mut self) -> Option<Self::Item> {
739 if self.output_position.row() >= self.max_output_row {
740 return None;
741 }
742
743 let transform = self.transforms.item()?;
744 if let Some(display_text) = transform.display_text {
745 let mut start_ix = 0;
746 let mut end_ix = display_text.len();
747 let mut summary = transform.summary.output.lines;
748
749 if self.output_position > self.transforms.start().0 {
750 // Exclude newline starting prior to the desired row.
751 start_ix = 1;
752 summary.row = 0;
753 } else if self.output_position.row() + 1 >= self.max_output_row {
754 // Exclude soft indentation ending after the desired row.
755 end_ix = 1;
756 summary.column = 0;
757 }
758
759 self.output_position.0 += summary;
760 self.transforms.next(&());
761 return Some(Chunk {
762 text: &display_text[start_ix..end_ix],
763 ..self.input_chunk
764 });
765 }
766
767 if self.input_chunk.text.is_empty() {
768 self.input_chunk = self.input_chunks.next().unwrap();
769 }
770
771 let mut input_len = 0;
772 let transform_end = self.transforms.end(&()).0;
773 for c in self.input_chunk.text.chars() {
774 let char_len = c.len_utf8();
775 input_len += char_len;
776 if c == '\n' {
777 *self.output_position.row_mut() += 1;
778 *self.output_position.column_mut() = 0;
779 } else {
780 *self.output_position.column_mut() += char_len as u32;
781 }
782
783 if self.output_position >= transform_end {
784 self.transforms.next(&());
785 break;
786 }
787 }
788
789 let (prefix, suffix) = self.input_chunk.text.split_at(input_len);
790 self.input_chunk.text = suffix;
791 Some(Chunk {
792 text: prefix,
793 ..self.input_chunk
794 })
795 }
796}
797
798impl<'a> Iterator for WrapBufferRows<'a> {
799 type Item = Option<u32>;
800
801 fn next(&mut self) -> Option<Self::Item> {
802 if self.output_row > self.max_output_row {
803 return None;
804 }
805
806 let buffer_row = self.input_buffer_row;
807 let soft_wrapped = self.soft_wrapped;
808
809 self.output_row += 1;
810 self.transforms
811 .seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left, &());
812 if self.transforms.item().map_or(false, |t| t.is_isomorphic()) {
813 self.input_buffer_row = self.input_buffer_rows.next().unwrap();
814 self.soft_wrapped = false;
815 } else {
816 self.soft_wrapped = true;
817 }
818
819 Some(if soft_wrapped { None } else { Some(buffer_row) })
820 }
821}
822
823impl Transform {
824 fn isomorphic(summary: TextSummary) -> Self {
825 #[cfg(test)]
826 assert!(!summary.lines.is_zero());
827
828 Self {
829 summary: TransformSummary {
830 input: summary.clone(),
831 output: summary,
832 },
833 display_text: None,
834 }
835 }
836
837 fn wrap(indent: u32) -> Self {
838 lazy_static! {
839 static ref WRAP_TEXT: String = {
840 let mut wrap_text = String::new();
841 wrap_text.push('\n');
842 wrap_text.extend((0..LineWrapper::MAX_INDENT as usize).map(|_| ' '));
843 wrap_text
844 };
845 }
846
847 Self {
848 summary: TransformSummary {
849 input: TextSummary::default(),
850 output: TextSummary {
851 lines: Point::new(1, indent),
852 first_line_chars: 0,
853 last_line_chars: indent,
854 longest_row: 1,
855 longest_row_chars: indent,
856 },
857 },
858 display_text: Some(&WRAP_TEXT[..1 + indent as usize]),
859 }
860 }
861
862 fn is_isomorphic(&self) -> bool {
863 self.display_text.is_none()
864 }
865}
866
867impl sum_tree::Item for Transform {
868 type Summary = TransformSummary;
869
870 fn summary(&self) -> Self::Summary {
871 self.summary.clone()
872 }
873}
874
875fn push_isomorphic(transforms: &mut Vec<Transform>, summary: TextSummary) {
876 if let Some(last_transform) = transforms.last_mut() {
877 if last_transform.is_isomorphic() {
878 last_transform.summary.input += &summary;
879 last_transform.summary.output += &summary;
880 return;
881 }
882 }
883 transforms.push(Transform::isomorphic(summary));
884}
885
886trait SumTreeExt {
887 fn push_or_extend(&mut self, transform: Transform);
888}
889
890impl SumTreeExt for SumTree<Transform> {
891 fn push_or_extend(&mut self, transform: Transform) {
892 let mut transform = Some(transform);
893 self.update_last(
894 |last_transform| {
895 if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
896 let transform = transform.take().unwrap();
897 last_transform.summary.input += &transform.summary.input;
898 last_transform.summary.output += &transform.summary.output;
899 }
900 },
901 &(),
902 );
903
904 if let Some(transform) = transform {
905 self.push(transform, &());
906 }
907 }
908}
909
910impl WrapPoint {
911 pub fn new(row: u32, column: u32) -> Self {
912 Self(super::Point::new(row, column))
913 }
914
915 pub fn row(self) -> u32 {
916 self.0.row
917 }
918
919 pub fn row_mut(&mut self) -> &mut u32 {
920 &mut self.0.row
921 }
922
923 pub fn column(&self) -> u32 {
924 self.0.column
925 }
926
927 pub fn column_mut(&mut self) -> &mut u32 {
928 &mut self.0.column
929 }
930}
931
932impl sum_tree::Summary for TransformSummary {
933 type Context = ();
934
935 fn add_summary(&mut self, other: &Self, _: &()) {
936 self.input += &other.input;
937 self.output += &other.output;
938 }
939}
940
941impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
942 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
943 self.0 += summary.input.lines;
944 }
945}
946
947impl<'a> sum_tree::SeekTarget<'a, TransformSummary, TransformSummary> for TabPoint {
948 fn cmp(&self, cursor_location: &TransformSummary, _: &()) -> std::cmp::Ordering {
949 Ord::cmp(&self.0, &cursor_location.input.lines)
950 }
951}
952
953impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
954 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
955 self.0 += summary.output.lines;
956 }
957}
958
959fn consolidate_wrap_edits(edits: &mut Vec<WrapEdit>) {
960 let mut i = 1;
961 while i < edits.len() {
962 let edit = edits[i].clone();
963 let prev_edit = &mut edits[i - 1];
964 if prev_edit.old.end >= edit.old.start {
965 prev_edit.old.end = edit.old.end;
966 prev_edit.new.end = edit.new.end;
967 edits.remove(i);
968 continue;
969 }
970 i += 1;
971 }
972}
973
974#[cfg(test)]
975mod tests {
976 use super::*;
977 use crate::{
978 display_map::{fold_map::FoldMap, tab_map::TabMap},
979 test::Observer,
980 };
981 use language::{multi_buffer::MultiBuffer, RandomCharIter};
982 use rand::prelude::*;
983 use std::{cmp, env};
984 use text::Rope;
985
986 #[gpui::test(iterations = 100)]
987 async fn test_random_wraps(mut cx: gpui::TestAppContext, mut rng: StdRng) {
988 cx.foreground().set_block_on_ticks(0..=50);
989 cx.foreground().forbid_parking();
990 let operations = env::var("OPERATIONS")
991 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
992 .unwrap_or(10);
993
994 let font_cache = cx.font_cache().clone();
995 let font_system = cx.platform().fonts();
996 let mut wrap_width = if rng.gen_bool(0.1) {
997 None
998 } else {
999 Some(rng.gen_range(0.0..=1000.0))
1000 };
1001 let tab_size = rng.gen_range(1..=4);
1002 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1003 let font_id = font_cache
1004 .select_font(family_id, &Default::default())
1005 .unwrap();
1006 let font_size = 14.0;
1007
1008 log::info!("Tab size: {}", tab_size);
1009 log::info!("Wrap width: {:?}", wrap_width);
1010
1011 let buffer = cx.update(|cx| {
1012 let len = rng.gen_range(0..10);
1013 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1014 MultiBuffer::build_simple(&text, cx)
1015 });
1016 let buffer_snapshot = buffer.read_with(&cx, |buffer, cx| buffer.snapshot(cx));
1017 let (mut fold_map, folds_snapshot) = FoldMap::new(buffer_snapshot.clone());
1018 let (tab_map, tabs_snapshot) = TabMap::new(folds_snapshot.clone(), tab_size);
1019 log::info!("Unwrapped text (no folds): {:?}", buffer_snapshot.text());
1020 log::info!(
1021 "Unwrapped text (unexpanded tabs): {:?}",
1022 folds_snapshot.text()
1023 );
1024 log::info!("Unwrapped text (expanded tabs): {:?}", tabs_snapshot.text());
1025
1026 let mut line_wrapper = LineWrapper::new(font_id, font_size, font_system);
1027 let unwrapped_text = tabs_snapshot.text();
1028 let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1029
1030 let (wrap_map, _) =
1031 cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font_id, font_size, wrap_width, cx));
1032 let (_observer, notifications) = Observer::new(&wrap_map, &mut cx);
1033
1034 if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1035 notifications.recv().await.unwrap();
1036 }
1037
1038 let (initial_snapshot, _) = wrap_map.update(&mut cx, |map, cx| {
1039 assert!(!map.is_rewrapping());
1040 map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1041 });
1042
1043 let actual_text = initial_snapshot.text();
1044 assert_eq!(
1045 actual_text, expected_text,
1046 "unwrapped text is: {:?}",
1047 unwrapped_text
1048 );
1049 log::info!("Wrapped text: {:?}", actual_text);
1050
1051 let mut edits = Vec::new();
1052 for _i in 0..operations {
1053 log::info!("{} ==============================================", _i);
1054
1055 let mut buffer_edits = Vec::new();
1056 match rng.gen_range(0..=100) {
1057 0..=19 => {
1058 wrap_width = if rng.gen_bool(0.2) {
1059 None
1060 } else {
1061 Some(rng.gen_range(0.0..=1000.0))
1062 };
1063 log::info!("Setting wrap width to {:?}", wrap_width);
1064 wrap_map.update(&mut cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1065 }
1066 20..=39 => {
1067 for (folds_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
1068 let (tabs_snapshot, tab_edits) = tab_map.sync(folds_snapshot, fold_edits);
1069 let (mut snapshot, wrap_edits) = wrap_map
1070 .update(&mut cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1071 snapshot.check_invariants();
1072 snapshot.verify_chunks(&mut rng);
1073 edits.push((snapshot, wrap_edits));
1074 }
1075 }
1076 _ => {
1077 buffer.update(&mut cx, |buffer, cx| {
1078 let subscription = buffer.subscribe();
1079 let edit_count = rng.gen_range(1..=5);
1080 buffer.randomly_edit(&mut rng, edit_count, cx);
1081 buffer_edits.extend(subscription.consume());
1082 });
1083 }
1084 }
1085
1086 let buffer_snapshot = buffer.read_with(&cx, |buffer, cx| buffer.snapshot(cx));
1087 log::info!("Unwrapped text (no folds): {:?}", buffer_snapshot.text());
1088 let (folds_snapshot, fold_edits) = fold_map.read(buffer_snapshot, buffer_edits);
1089 log::info!(
1090 "Unwrapped text (unexpanded tabs): {:?}",
1091 folds_snapshot.text()
1092 );
1093 let (tabs_snapshot, tab_edits) = tab_map.sync(folds_snapshot, fold_edits);
1094 log::info!("Unwrapped text (expanded tabs): {:?}", tabs_snapshot.text());
1095
1096 let unwrapped_text = tabs_snapshot.text();
1097 let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1098 let (mut snapshot, wrap_edits) = wrap_map.update(&mut cx, |map, cx| {
1099 map.sync(tabs_snapshot.clone(), tab_edits, cx)
1100 });
1101 snapshot.check_invariants();
1102 snapshot.verify_chunks(&mut rng);
1103 edits.push((snapshot, wrap_edits));
1104
1105 if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) && rng.gen_bool(0.4) {
1106 log::info!("Waiting for wrapping to finish");
1107 while wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1108 notifications.recv().await.unwrap();
1109 }
1110 wrap_map.read_with(&cx, |map, _| assert!(map.pending_edits.is_empty()));
1111 }
1112
1113 if !wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1114 let (mut wrapped_snapshot, wrap_edits) =
1115 wrap_map.update(&mut cx, |map, cx| map.sync(tabs_snapshot, Vec::new(), cx));
1116 let actual_text = wrapped_snapshot.text();
1117 let actual_longest_row = wrapped_snapshot.longest_row();
1118 log::info!("Wrapping finished: {:?}", actual_text);
1119 wrapped_snapshot.check_invariants();
1120 wrapped_snapshot.verify_chunks(&mut rng);
1121 edits.push((wrapped_snapshot.clone(), wrap_edits));
1122 assert_eq!(
1123 actual_text, expected_text,
1124 "unwrapped text is: {:?}",
1125 unwrapped_text
1126 );
1127
1128 let mut summary = TextSummary::default();
1129 for (ix, item) in wrapped_snapshot
1130 .transforms
1131 .items(&())
1132 .into_iter()
1133 .enumerate()
1134 {
1135 summary += &item.summary.output;
1136 log::info!("{} summary: {:?}", ix, item.summary.output,);
1137 }
1138
1139 if tab_size == 1
1140 || !wrapped_snapshot
1141 .tab_snapshot
1142 .fold_snapshot
1143 .text()
1144 .contains('\t')
1145 {
1146 let mut expected_longest_rows = Vec::new();
1147 let mut longest_line_len = -1;
1148 for (row, line) in expected_text.split('\n').enumerate() {
1149 let line_char_count = line.chars().count() as isize;
1150 if line_char_count > longest_line_len {
1151 expected_longest_rows.clear();
1152 longest_line_len = line_char_count;
1153 }
1154 if line_char_count >= longest_line_len {
1155 expected_longest_rows.push(row as u32);
1156 }
1157 }
1158
1159 assert!(
1160 expected_longest_rows.contains(&actual_longest_row),
1161 "incorrect longest row {}. expected {:?} with length {}",
1162 actual_longest_row,
1163 expected_longest_rows,
1164 longest_line_len,
1165 )
1166 }
1167 }
1168 }
1169
1170 let mut initial_text = Rope::from(initial_snapshot.text().as_str());
1171 for (snapshot, patch) in edits {
1172 let snapshot_text = Rope::from(snapshot.text().as_str());
1173 for edit in &patch {
1174 let old_start = initial_text.point_to_offset(Point::new(edit.new.start, 0));
1175 let old_end = initial_text.point_to_offset(cmp::min(
1176 Point::new(edit.new.start + edit.old.len() as u32, 0),
1177 initial_text.max_point(),
1178 ));
1179 let new_start = snapshot_text.point_to_offset(Point::new(edit.new.start, 0));
1180 let new_end = snapshot_text.point_to_offset(cmp::min(
1181 Point::new(edit.new.end, 0),
1182 snapshot_text.max_point(),
1183 ));
1184 let new_text = snapshot_text
1185 .chunks_in_range(new_start..new_end)
1186 .collect::<String>();
1187
1188 initial_text.replace(old_start..old_end, &new_text);
1189 }
1190 assert_eq!(initial_text.to_string(), snapshot_text.to_string());
1191 }
1192
1193 if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1194 log::info!("Waiting for wrapping to finish");
1195 while wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1196 notifications.recv().await.unwrap();
1197 }
1198 }
1199 wrap_map.read_with(&cx, |map, _| assert!(map.pending_edits.is_empty()));
1200 }
1201
1202 fn wrap_text(
1203 unwrapped_text: &str,
1204 wrap_width: Option<f32>,
1205 line_wrapper: &mut LineWrapper,
1206 ) -> String {
1207 if let Some(wrap_width) = wrap_width {
1208 let mut wrapped_text = String::new();
1209 for (row, line) in unwrapped_text.split('\n').enumerate() {
1210 if row > 0 {
1211 wrapped_text.push('\n')
1212 }
1213
1214 let mut prev_ix = 0;
1215 for boundary in line_wrapper.wrap_line(line, wrap_width) {
1216 wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1217 wrapped_text.push('\n');
1218 wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1219 prev_ix = boundary.ix;
1220 }
1221 wrapped_text.push_str(&line[prev_ix..]);
1222 }
1223 wrapped_text
1224 } else {
1225 unwrapped_text.to_string()
1226 }
1227 }
1228
1229 impl WrapSnapshot {
1230 pub fn text(&self) -> String {
1231 self.text_chunks(0).collect()
1232 }
1233
1234 fn verify_chunks(&mut self, rng: &mut impl Rng) {
1235 for _ in 0..5 {
1236 let mut end_row = rng.gen_range(0..=self.max_point().row());
1237 let start_row = rng.gen_range(0..=end_row);
1238 end_row += 1;
1239
1240 let mut expected_text = self.text_chunks(start_row).collect::<String>();
1241 if expected_text.ends_with("\n") {
1242 expected_text.push('\n');
1243 }
1244 let mut expected_text = expected_text
1245 .lines()
1246 .take((end_row - start_row) as usize)
1247 .collect::<Vec<_>>()
1248 .join("\n");
1249 if end_row <= self.max_point().row() {
1250 expected_text.push('\n');
1251 }
1252
1253 let actual_text = self
1254 .chunks(start_row..end_row, None)
1255 .map(|c| c.text)
1256 .collect::<String>();
1257 assert_eq!(
1258 expected_text,
1259 actual_text,
1260 "chunks != highlighted_chunks for rows {:?}",
1261 start_row..end_row
1262 );
1263 }
1264 }
1265 }
1266}