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