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
437 .chunks(TabPoint::new(edit.new_rows.start, 0)..new_tab_snapshot.max_point());
438 let mut edit_transforms = Vec::<Transform>::new();
439 for _ in edit.new_rows.start..edit.new_rows.end {
440 while let Some(chunk) =
441 remaining.take().or_else(|| chunks.next().map(|c| c.text))
442 {
443 if let Some(ix) = chunk.find('\n') {
444 line.push_str(&chunk[..ix + 1]);
445 remaining = Some(&chunk[ix + 1..]);
446 break;
447 } else {
448 line.push_str(chunk)
449 }
450 }
451
452 if line.is_empty() {
453 break;
454 }
455
456 let mut prev_boundary_ix = 0;
457 for boundary in line_wrapper.wrap_line(&line, wrap_width) {
458 let wrapped = &line[prev_boundary_ix..boundary.ix];
459 push_isomorphic(&mut edit_transforms, TextSummary::from(wrapped));
460 edit_transforms.push(Transform::wrap(boundary.next_indent));
461 prev_boundary_ix = boundary.ix;
462 }
463
464 if prev_boundary_ix < line.len() {
465 push_isomorphic(
466 &mut edit_transforms,
467 TextSummary::from(&line[prev_boundary_ix..]),
468 );
469 }
470
471 line.clear();
472 yield_now().await;
473 }
474
475 let mut edit_transforms = edit_transforms.into_iter();
476 if let Some(transform) = edit_transforms.next() {
477 new_transforms.push_or_extend(transform);
478 }
479 new_transforms.extend(edit_transforms, &());
480
481 old_cursor.seek_forward(&TabPoint::new(edit.old_rows.end, 0), Bias::Right, &());
482 if let Some(next_edit) = row_edits.peek() {
483 if next_edit.old_rows.start > old_cursor.end(&()).row() {
484 if old_cursor.end(&()) > TabPoint::new(edit.old_rows.end, 0) {
485 let summary = self.tab_snapshot.text_summary_for_range(
486 TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(&()),
487 );
488 new_transforms.push_or_extend(Transform::isomorphic(summary));
489 }
490 old_cursor.next(&());
491 new_transforms.push_tree(
492 old_cursor.slice(
493 &TabPoint::new(next_edit.old_rows.start, 0),
494 Bias::Right,
495 &(),
496 ),
497 &(),
498 );
499 }
500 } else {
501 if old_cursor.end(&()) > TabPoint::new(edit.old_rows.end, 0) {
502 let summary = self.tab_snapshot.text_summary_for_range(
503 TabPoint::new(edit.old_rows.end, 0)..old_cursor.end(&()),
504 );
505 new_transforms.push_or_extend(Transform::isomorphic(summary));
506 }
507 old_cursor.next(&());
508 new_transforms.push_tree(old_cursor.suffix(&()), &());
509 }
510 }
511 }
512
513 let old_snapshot = mem::replace(
514 self,
515 WrapSnapshot {
516 tab_snapshot: new_tab_snapshot,
517 transforms: new_transforms,
518 interpolated: false,
519 },
520 );
521 self.check_invariants();
522 old_snapshot.compute_edits(tab_edits, self)
523 }
524
525 fn compute_edits(&self, tab_edits: &[TabEdit], new_snapshot: &WrapSnapshot) -> Patch<u32> {
526 let mut wrap_edits = Vec::new();
527 let mut old_cursor = self.transforms.cursor::<TransformSummary>();
528 let mut new_cursor = new_snapshot.transforms.cursor::<TransformSummary>();
529 for mut tab_edit in tab_edits.iter().cloned() {
530 tab_edit.old.start.0.column = 0;
531 tab_edit.old.end.0 += Point::new(1, 0);
532 tab_edit.new.start.0.column = 0;
533 tab_edit.new.end.0 += Point::new(1, 0);
534
535 old_cursor.seek(&tab_edit.old.start, Bias::Right, &());
536 let mut old_start = old_cursor.start().output.lines;
537 old_start += tab_edit.old.start.0 - old_cursor.start().input.lines;
538
539 old_cursor.seek(&tab_edit.old.end, Bias::Right, &());
540 let mut old_end = old_cursor.start().output.lines;
541 old_end += tab_edit.old.end.0 - old_cursor.start().input.lines;
542
543 new_cursor.seek(&tab_edit.new.start, Bias::Right, &());
544 let mut new_start = new_cursor.start().output.lines;
545 new_start += tab_edit.new.start.0 - new_cursor.start().input.lines;
546
547 new_cursor.seek(&tab_edit.new.end, Bias::Right, &());
548 let mut new_end = new_cursor.start().output.lines;
549 new_end += tab_edit.new.end.0 - new_cursor.start().input.lines;
550
551 wrap_edits.push(WrapEdit {
552 old: old_start.row..old_end.row,
553 new: new_start.row..new_end.row,
554 });
555 }
556
557 consolidate_wrap_edits(&mut wrap_edits);
558 Patch::new(wrap_edits)
559 }
560
561 pub fn text_chunks(&self, wrap_row: u32) -> impl Iterator<Item = &str> {
562 self.chunks(wrap_row..self.max_point().row() + 1)
563 .map(|h| h.text)
564 }
565
566 pub fn chunks<'a>(&'a self, rows: Range<u32>) -> WrapChunks<'a> {
567 let output_start = WrapPoint::new(rows.start, 0);
568 let output_end = WrapPoint::new(rows.end, 0);
569 let mut transforms = self.transforms.cursor::<(WrapPoint, TabPoint)>();
570 transforms.seek(&output_start, Bias::Right, &());
571 let mut input_start = TabPoint(transforms.start().1 .0);
572 if transforms.item().map_or(false, |t| t.is_isomorphic()) {
573 input_start.0 += output_start.0 - transforms.start().0 .0;
574 }
575 let input_end = self
576 .to_tab_point(output_end)
577 .min(self.tab_snapshot.max_point());
578 WrapChunks {
579 input_chunks: self.tab_snapshot.chunks(input_start..input_end),
580 input_chunk: Default::default(),
581 output_position: output_start,
582 max_output_row: rows.end,
583 transforms,
584 }
585 }
586
587 pub fn text_summary(&self) -> TextSummary {
588 self.transforms.summary().output
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(&self) -> u32 {
955 self.0.column
956 }
957
958 pub fn column_mut(&mut self) -> &mut u32 {
959 &mut self.0.column
960 }
961}
962
963impl sum_tree::Summary for TransformSummary {
964 type Context = ();
965
966 fn add_summary(&mut self, other: &Self, _: &()) {
967 self.input += &other.input;
968 self.output += &other.output;
969 }
970}
971
972impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
973 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
974 self.0 += summary.input.lines;
975 }
976}
977
978impl<'a> sum_tree::SeekTarget<'a, TransformSummary, TransformSummary> for TabPoint {
979 fn cmp(&self, cursor_location: &TransformSummary, _: &()) -> std::cmp::Ordering {
980 Ord::cmp(&self.0, &cursor_location.input.lines)
981 }
982}
983
984impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
985 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
986 self.0 += summary.output.lines;
987 }
988}
989
990fn consolidate_wrap_edits(edits: &mut Vec<WrapEdit>) {
991 let mut i = 1;
992 while i < edits.len() {
993 let edit = edits[i].clone();
994 let prev_edit = &mut edits[i - 1];
995 if prev_edit.old.end >= edit.old.start {
996 prev_edit.old.end = edit.old.end;
997 prev_edit.new.end = edit.new.end;
998 edits.remove(i);
999 continue;
1000 }
1001 i += 1;
1002 }
1003}
1004
1005#[cfg(test)]
1006mod tests {
1007 use super::*;
1008 use crate::{
1009 display_map::{fold_map::FoldMap, tab_map::TabMap},
1010 MultiBuffer,
1011 };
1012 use gpui::test::observe;
1013 use language::RandomCharIter;
1014 use rand::prelude::*;
1015 use smol::stream::StreamExt;
1016 use std::{cmp, env};
1017 use text::Rope;
1018
1019 #[gpui::test(iterations = 100)]
1020 async fn test_random_wraps(mut cx: gpui::TestAppContext, mut rng: StdRng) {
1021 cx.foreground().set_block_on_ticks(0..=50);
1022 cx.foreground().forbid_parking();
1023 let operations = env::var("OPERATIONS")
1024 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1025 .unwrap_or(10);
1026
1027 let font_cache = cx.font_cache().clone();
1028 let font_system = cx.platform().fonts();
1029 let mut wrap_width = if rng.gen_bool(0.1) {
1030 None
1031 } else {
1032 Some(rng.gen_range(0.0..=1000.0))
1033 };
1034 let tab_size = rng.gen_range(1..=4);
1035 let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1036 let font_id = font_cache
1037 .select_font(family_id, &Default::default())
1038 .unwrap();
1039 let font_size = 14.0;
1040
1041 log::info!("Tab size: {}", tab_size);
1042 log::info!("Wrap width: {:?}", wrap_width);
1043
1044 let buffer = cx.update(|cx| {
1045 if rng.gen() {
1046 MultiBuffer::build_random(&mut rng, cx)
1047 } else {
1048 let len = rng.gen_range(0..10);
1049 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1050 MultiBuffer::build_simple(&text, cx)
1051 }
1052 });
1053 let mut buffer_snapshot = buffer.read_with(&cx, |buffer, cx| buffer.snapshot(cx));
1054 let (mut fold_map, folds_snapshot) = FoldMap::new(buffer_snapshot.clone());
1055 let (tab_map, tabs_snapshot) = TabMap::new(folds_snapshot.clone(), tab_size);
1056 log::info!("Unwrapped text (no folds): {:?}", buffer_snapshot.text());
1057 log::info!(
1058 "Unwrapped text (unexpanded tabs): {:?}",
1059 folds_snapshot.text()
1060 );
1061 log::info!("Unwrapped text (expanded tabs): {:?}", tabs_snapshot.text());
1062
1063 let mut line_wrapper = LineWrapper::new(font_id, font_size, font_system);
1064 let unwrapped_text = tabs_snapshot.text();
1065 let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1066
1067 let (wrap_map, _) =
1068 cx.update(|cx| WrapMap::new(tabs_snapshot.clone(), font_id, font_size, wrap_width, cx));
1069 let mut notifications = observe(&wrap_map, &mut cx);
1070
1071 if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1072 notifications.next().await.unwrap();
1073 }
1074
1075 let (initial_snapshot, _) = wrap_map.update(&mut cx, |map, cx| {
1076 assert!(!map.is_rewrapping());
1077 map.sync(tabs_snapshot.clone(), Vec::new(), cx)
1078 });
1079
1080 let actual_text = initial_snapshot.text();
1081 assert_eq!(
1082 actual_text, expected_text,
1083 "unwrapped text is: {:?}",
1084 unwrapped_text
1085 );
1086 log::info!("Wrapped text: {:?}", actual_text);
1087
1088 let mut edits = Vec::new();
1089 for _i in 0..operations {
1090 log::info!("{} ==============================================", _i);
1091
1092 let mut buffer_edits = Vec::new();
1093 match rng.gen_range(0..=100) {
1094 0..=19 => {
1095 wrap_width = if rng.gen_bool(0.2) {
1096 None
1097 } else {
1098 Some(rng.gen_range(0.0..=1000.0))
1099 };
1100 log::info!("Setting wrap width to {:?}", wrap_width);
1101 wrap_map.update(&mut cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1102 }
1103 20..=39 => {
1104 for (folds_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
1105 let (tabs_snapshot, tab_edits) = tab_map.sync(folds_snapshot, fold_edits);
1106 let (mut snapshot, wrap_edits) = wrap_map
1107 .update(&mut cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
1108 snapshot.check_invariants();
1109 snapshot.verify_chunks(&mut rng);
1110 edits.push((snapshot, wrap_edits));
1111 }
1112 }
1113 _ => {
1114 buffer.update(&mut cx, |buffer, cx| {
1115 let subscription = buffer.subscribe();
1116 let edit_count = rng.gen_range(1..=5);
1117 buffer.randomly_edit(&mut rng, edit_count, cx);
1118 buffer_snapshot = buffer.snapshot(cx);
1119 buffer_edits.extend(subscription.consume());
1120 });
1121 }
1122 }
1123
1124 log::info!("Unwrapped text (no folds): {:?}", buffer_snapshot.text());
1125 let (folds_snapshot, fold_edits) = fold_map.read(buffer_snapshot.clone(), buffer_edits);
1126 log::info!(
1127 "Unwrapped text (unexpanded tabs): {:?}",
1128 folds_snapshot.text()
1129 );
1130 let (tabs_snapshot, tab_edits) = tab_map.sync(folds_snapshot, fold_edits);
1131 log::info!("Unwrapped text (expanded tabs): {:?}", tabs_snapshot.text());
1132
1133 let unwrapped_text = tabs_snapshot.text();
1134 let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
1135 let (mut snapshot, wrap_edits) = wrap_map.update(&mut cx, |map, cx| {
1136 map.sync(tabs_snapshot.clone(), tab_edits, cx)
1137 });
1138 snapshot.check_invariants();
1139 snapshot.verify_chunks(&mut rng);
1140 edits.push((snapshot, wrap_edits));
1141
1142 if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) && rng.gen_bool(0.4) {
1143 log::info!("Waiting for wrapping to finish");
1144 while wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1145 notifications.next().await.unwrap();
1146 }
1147 wrap_map.read_with(&cx, |map, _| assert!(map.pending_edits.is_empty()));
1148 }
1149
1150 if !wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1151 let (mut wrapped_snapshot, wrap_edits) =
1152 wrap_map.update(&mut cx, |map, cx| map.sync(tabs_snapshot, Vec::new(), cx));
1153 let actual_text = wrapped_snapshot.text();
1154 let actual_longest_row = wrapped_snapshot.longest_row();
1155 log::info!("Wrapping finished: {:?}", actual_text);
1156 wrapped_snapshot.check_invariants();
1157 wrapped_snapshot.verify_chunks(&mut rng);
1158 edits.push((wrapped_snapshot.clone(), wrap_edits));
1159 assert_eq!(
1160 actual_text, expected_text,
1161 "unwrapped text is: {:?}",
1162 unwrapped_text
1163 );
1164
1165 let mut summary = TextSummary::default();
1166 for (ix, item) in wrapped_snapshot
1167 .transforms
1168 .items(&())
1169 .into_iter()
1170 .enumerate()
1171 {
1172 summary += &item.summary.output;
1173 log::info!("{} summary: {:?}", ix, item.summary.output,);
1174 }
1175
1176 if tab_size == 1
1177 || !wrapped_snapshot
1178 .tab_snapshot
1179 .fold_snapshot
1180 .text()
1181 .contains('\t')
1182 {
1183 let mut expected_longest_rows = Vec::new();
1184 let mut longest_line_len = -1;
1185 for (row, line) in expected_text.split('\n').enumerate() {
1186 let line_char_count = line.chars().count() as isize;
1187 if line_char_count > longest_line_len {
1188 expected_longest_rows.clear();
1189 longest_line_len = line_char_count;
1190 }
1191 if line_char_count >= longest_line_len {
1192 expected_longest_rows.push(row as u32);
1193 }
1194 }
1195
1196 assert!(
1197 expected_longest_rows.contains(&actual_longest_row),
1198 "incorrect longest row {}. expected {:?} with length {}",
1199 actual_longest_row,
1200 expected_longest_rows,
1201 longest_line_len,
1202 )
1203 }
1204 }
1205 }
1206
1207 let mut initial_text = Rope::from(initial_snapshot.text().as_str());
1208 for (snapshot, patch) in edits {
1209 let snapshot_text = Rope::from(snapshot.text().as_str());
1210 for edit in &patch {
1211 let old_start = initial_text.point_to_offset(Point::new(edit.new.start, 0));
1212 let old_end = initial_text.point_to_offset(cmp::min(
1213 Point::new(edit.new.start + edit.old.len() as u32, 0),
1214 initial_text.max_point(),
1215 ));
1216 let new_start = snapshot_text.point_to_offset(Point::new(edit.new.start, 0));
1217 let new_end = snapshot_text.point_to_offset(cmp::min(
1218 Point::new(edit.new.end, 0),
1219 snapshot_text.max_point(),
1220 ));
1221 let new_text = snapshot_text
1222 .chunks_in_range(new_start..new_end)
1223 .collect::<String>();
1224
1225 initial_text.replace(old_start..old_end, &new_text);
1226 }
1227 assert_eq!(initial_text.to_string(), snapshot_text.to_string());
1228 }
1229
1230 if wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1231 log::info!("Waiting for wrapping to finish");
1232 while wrap_map.read_with(&cx, |map, _| map.is_rewrapping()) {
1233 notifications.next().await.unwrap();
1234 }
1235 }
1236 wrap_map.read_with(&cx, |map, _| assert!(map.pending_edits.is_empty()));
1237 }
1238
1239 fn wrap_text(
1240 unwrapped_text: &str,
1241 wrap_width: Option<f32>,
1242 line_wrapper: &mut LineWrapper,
1243 ) -> String {
1244 if let Some(wrap_width) = wrap_width {
1245 let mut wrapped_text = String::new();
1246 for (row, line) in unwrapped_text.split('\n').enumerate() {
1247 if row > 0 {
1248 wrapped_text.push('\n')
1249 }
1250
1251 let mut prev_ix = 0;
1252 for boundary in line_wrapper.wrap_line(line, wrap_width) {
1253 wrapped_text.push_str(&line[prev_ix..boundary.ix]);
1254 wrapped_text.push('\n');
1255 wrapped_text.push_str(&" ".repeat(boundary.next_indent as usize));
1256 prev_ix = boundary.ix;
1257 }
1258 wrapped_text.push_str(&line[prev_ix..]);
1259 }
1260 wrapped_text
1261 } else {
1262 unwrapped_text.to_string()
1263 }
1264 }
1265
1266 impl WrapSnapshot {
1267 pub fn text(&self) -> String {
1268 self.text_chunks(0).collect()
1269 }
1270
1271 fn verify_chunks(&mut self, rng: &mut impl Rng) {
1272 for _ in 0..5 {
1273 let mut end_row = rng.gen_range(0..=self.max_point().row());
1274 let start_row = rng.gen_range(0..=end_row);
1275 end_row += 1;
1276
1277 let mut expected_text = self.text_chunks(start_row).collect::<String>();
1278 if expected_text.ends_with("\n") {
1279 expected_text.push('\n');
1280 }
1281 let mut expected_text = expected_text
1282 .lines()
1283 .take((end_row - start_row) as usize)
1284 .collect::<Vec<_>>()
1285 .join("\n");
1286 if end_row <= self.max_point().row() {
1287 expected_text.push('\n');
1288 }
1289
1290 let actual_text = self
1291 .chunks(start_row..end_row)
1292 .map(|c| c.text)
1293 .collect::<String>();
1294 assert_eq!(
1295 expected_text,
1296 actual_text,
1297 "chunks != highlighted_chunks for rows {:?}",
1298 start_row..end_row
1299 );
1300 }
1301 }
1302 }
1303}