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