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