wrap_map.rs

  1use super::{
  2    fold_map,
  3    line_wrapper::LineWrapper,
  4    tab_map::{
  5        self, Edit as TabEdit, OutputPoint as TabPoint, Snapshot as TabSnapshot, TextSummary,
  6    },
  7};
  8use crate::{
  9    editor::Point,
 10    settings::StyleId,
 11    sum_tree::{self, Cursor, SumTree},
 12    util::Bias,
 13    Settings,
 14};
 15use gpui::{executor::Background, MutableAppContext, Task};
 16use parking_lot::Mutex;
 17use postage::{prelude::Stream, sink::Sink, watch};
 18use smol::future::yield_now;
 19use std::{collections::VecDeque, ops::Range, sync::Arc, time::Duration};
 20
 21#[derive(Clone)]
 22pub struct WrapMap(Arc<Mutex<WrapMapState>>);
 23
 24struct WrapMapState {
 25    snapshot: Snapshot,
 26    pending_edits: VecDeque<(TabSnapshot, Vec<TabEdit>)>,
 27    wrap_width: Option<f32>,
 28    background_task: Option<Task<()>>,
 29    updates: (watch::Sender<()>, watch::Receiver<()>),
 30    line_wrapper: Arc<LineWrapper>,
 31}
 32
 33#[derive(Clone)]
 34pub struct Snapshot {
 35    tab_snapshot: TabSnapshot,
 36    transforms: SumTree<Transform>,
 37}
 38
 39#[derive(Clone, Debug, Default, Eq, PartialEq)]
 40struct Transform {
 41    summary: TransformSummary,
 42    display_text: Option<&'static str>,
 43}
 44
 45#[derive(Clone, Debug, Default, Eq, PartialEq)]
 46struct TransformSummary {
 47    input: TextSummary,
 48    output: TextSummary,
 49}
 50
 51#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 52pub struct WrapPoint(super::Point);
 53
 54pub struct Chunks<'a> {
 55    input_chunks: tab_map::Chunks<'a>,
 56    input_chunk: &'a str,
 57    output_position: WrapPoint,
 58    transforms: Cursor<'a, Transform, WrapPoint, TabPoint>,
 59}
 60
 61pub struct HighlightedChunks<'a> {
 62    input_chunks: tab_map::HighlightedChunks<'a>,
 63    input_chunk: &'a str,
 64    style_id: StyleId,
 65    output_position: WrapPoint,
 66    max_output_row: u32,
 67    transforms: Cursor<'a, Transform, WrapPoint, TabPoint>,
 68}
 69
 70pub struct BufferRows<'a> {
 71    input_buffer_rows: fold_map::BufferRows<'a>,
 72    input_buffer_row: u32,
 73    output_row: u32,
 74    max_output_row: u32,
 75    transforms: Cursor<'a, Transform, WrapPoint, TabPoint>,
 76}
 77
 78impl WrapMap {
 79    pub fn new(
 80        tab_snapshot: TabSnapshot,
 81        settings: Settings,
 82        wrap_width: Option<f32>,
 83        cx: &mut MutableAppContext,
 84    ) -> Self {
 85        let this = Self(Arc::new(Mutex::new(WrapMapState {
 86            background_task: None,
 87            wrap_width: None,
 88            updates: watch::channel(),
 89            pending_edits: Default::default(),
 90            snapshot: Snapshot::new(tab_snapshot),
 91            line_wrapper: Arc::new(LineWrapper::new(
 92                cx.platform().fonts(),
 93                cx.font_cache().clone(),
 94                settings,
 95            )),
 96        })));
 97        this.set_wrap_width(wrap_width, cx);
 98        this
 99    }
100
101    pub fn is_rewrapping(&self) -> bool {
102        self.0.lock().background_task.is_some()
103    }
104
105    pub fn notifications(&self) -> impl Stream<Item = ()> {
106        let state = self.0.lock();
107        let mut rx = state.updates.1.clone();
108        // The first item in the stream always returns what's stored on the watch, but we only want
109        // to receive notifications occurring after calling this method, so we discard the first
110        // item.
111        let _ = rx.blocking_recv();
112        rx
113    }
114
115    pub fn sync(
116        &self,
117        tab_snapshot: TabSnapshot,
118        edits: Vec<TabEdit>,
119        cx: &mut MutableAppContext,
120    ) -> Snapshot {
121        self.0.lock().pending_edits.push_back((tab_snapshot, edits));
122        self.flush_edits(cx.background());
123        self.0.lock().snapshot.clone()
124    }
125
126    pub fn set_wrap_width(&self, wrap_width: Option<f32>, cx: &mut MutableAppContext) {
127        let mut state = self.0.lock();
128        if wrap_width == state.wrap_width {
129            return;
130        }
131
132        state.wrap_width = wrap_width;
133        state.background_task.take();
134
135        if let Some(wrap_width) = wrap_width {
136            let mut new_snapshot = state.snapshot.clone();
137            let line_wrapper = state.line_wrapper.clone();
138            let task = cx.background().spawn(async move {
139                let tab_snapshot = new_snapshot.tab_snapshot.clone();
140                let range = TabPoint::zero()..tab_snapshot.max_point();
141                new_snapshot
142                    .update(
143                        tab_snapshot,
144                        &[TabEdit {
145                            old_lines: range.clone(),
146                            new_lines: range.clone(),
147                        }],
148                        wrap_width,
149                        line_wrapper.as_ref(),
150                    )
151                    .await;
152                new_snapshot
153            });
154
155            let executor = cx.background();
156            match executor.block_with_timeout(Duration::from_millis(5), task) {
157                Ok(snapshot) => {
158                    state.snapshot = snapshot;
159                }
160                Err(wrap_task) => {
161                    let this = self.clone();
162                    let exec = executor.clone();
163                    state.background_task = Some(executor.spawn(async move {
164                        let snapshot = wrap_task.await;
165                        {
166                            let mut state = this.0.lock();
167                            state.snapshot = snapshot;
168                            state.background_task = None;
169                        }
170                        this.flush_edits(&exec);
171                        this.0.lock().updates.0.blocking_send(()).ok();
172                    }));
173                }
174            }
175        }
176    }
177
178    fn flush_edits(&self, executor: &Arc<Background>) {
179        let mut state = self.0.lock();
180
181        while let Some((tab_snapshot, _)) = state.pending_edits.front() {
182            if tab_snapshot.version() <= state.snapshot.tab_snapshot.version() {
183                state.pending_edits.pop_front();
184            } else {
185                break;
186            }
187        }
188
189        if state.pending_edits.is_empty() {
190            return;
191        }
192
193        if let Some(wrap_width) = state.wrap_width {
194            if state.background_task.is_none() {
195                let pending_edits = state.pending_edits.clone();
196                let mut snapshot = state.snapshot.clone();
197                let line_wrapper = state.line_wrapper.clone();
198
199                let update_task = executor.spawn(async move {
200                    for (tab_snapshot, edits) in pending_edits {
201                        snapshot
202                            .update(tab_snapshot, &edits, wrap_width, &line_wrapper)
203                            .await;
204                    }
205                    snapshot
206                });
207
208                match executor.block_with_timeout(Duration::from_micros(500), update_task) {
209                    Ok(snapshot) => {
210                        state.snapshot = snapshot;
211                    }
212                    Err(update_task) => {
213                        let this = self.clone();
214                        let exec = executor.clone();
215                        state.background_task = Some(executor.spawn(async move {
216                            let snapshot = update_task.await;
217                            {
218                                let mut state = this.0.lock();
219                                state.snapshot = snapshot;
220                                state.background_task = None;
221                            }
222                            this.flush_edits(&exec);
223                            this.0.lock().updates.0.blocking_send(()).ok();
224                        }));
225                    }
226                }
227            }
228        }
229
230        while let Some((tab_snapshot, _)) = state.pending_edits.front() {
231            if tab_snapshot.version() <= state.snapshot.tab_snapshot.version() {
232                state.pending_edits.pop_front();
233            } else {
234                break;
235            }
236        }
237
238        for (tab_snapshot, edits) in state.pending_edits.clone() {
239            state.snapshot.interpolate(tab_snapshot, &edits);
240        }
241    }
242}
243
244impl Snapshot {
245    fn new(tab_snapshot: TabSnapshot) -> Self {
246        let extent = tab_snapshot.text_summary();
247        Self {
248            transforms: SumTree::from_item(
249                Transform {
250                    summary: TransformSummary {
251                        input: extent.clone(),
252                        output: extent.clone(),
253                    },
254                    display_text: None,
255                },
256                &(),
257            ),
258            tab_snapshot,
259        }
260    }
261
262    fn interpolate(&mut self, new_tab_snapshot: TabSnapshot, edits: &[TabEdit]) {
263        let mut new_transforms;
264        if edits.is_empty() {
265            new_transforms = self.transforms.clone();
266        } else {
267            let mut old_cursor = self.transforms.cursor::<TabPoint, ()>();
268            let mut edits = edits.into_iter().peekable();
269            new_transforms =
270                old_cursor.slice(&edits.peek().unwrap().old_lines.start, Bias::Right, &());
271
272            while let Some(edit) = edits.next() {
273                if edit.new_lines.start > TabPoint::from(new_transforms.summary().input.lines) {
274                    let summary = new_tab_snapshot.text_summary_for_range(
275                        TabPoint::from(new_transforms.summary().input.lines)..edit.new_lines.start,
276                    );
277                    new_transforms.push_or_extend(Transform::isomorphic(summary));
278                }
279
280                if !edit.new_lines.is_empty() {
281                    new_transforms.push_or_extend(Transform::isomorphic(
282                        new_tab_snapshot.text_summary_for_range(edit.new_lines.clone()),
283                    ));
284                }
285
286                old_cursor.seek_forward(&edit.old_lines.end, Bias::Right, &());
287                if let Some(next_edit) = edits.peek() {
288                    if next_edit.old_lines.start > old_cursor.seek_end(&()) {
289                        if old_cursor.seek_end(&()) > edit.old_lines.end {
290                            let summary = self.tab_snapshot.text_summary_for_range(
291                                edit.old_lines.end..old_cursor.seek_end(&()),
292                            );
293                            new_transforms.push_or_extend(Transform::isomorphic(summary));
294                        }
295                        old_cursor.next(&());
296                        new_transforms.push_tree(
297                            old_cursor.slice(&next_edit.old_lines.start, Bias::Right, &()),
298                            &(),
299                        );
300                    }
301                } else {
302                    if old_cursor.seek_end(&()) > edit.old_lines.end {
303                        let summary = self
304                            .tab_snapshot
305                            .text_summary_for_range(edit.old_lines.end..old_cursor.seek_end(&()));
306                        new_transforms.push_or_extend(Transform::isomorphic(summary));
307                    }
308                    old_cursor.next(&());
309                    new_transforms.push_tree(old_cursor.suffix(&()), &());
310                }
311            }
312        }
313
314        self.transforms = new_transforms;
315        self.tab_snapshot = new_tab_snapshot;
316    }
317
318    async fn update(
319        &mut self,
320        new_tab_snapshot: TabSnapshot,
321        edits: &[TabEdit],
322        wrap_width: f32,
323        line_wrapper: &LineWrapper,
324    ) {
325        #[derive(Debug)]
326        struct RowEdit {
327            old_rows: Range<u32>,
328            new_rows: Range<u32>,
329        }
330
331        let mut edits = edits.into_iter().peekable();
332        let mut row_edits = Vec::new();
333        while let Some(edit) = edits.next() {
334            let mut row_edit = RowEdit {
335                old_rows: edit.old_lines.start.row()..edit.old_lines.end.row() + 1,
336                new_rows: edit.new_lines.start.row()..edit.new_lines.end.row() + 1,
337            };
338
339            while let Some(next_edit) = edits.peek() {
340                if next_edit.old_lines.start.row() <= row_edit.old_rows.end {
341                    row_edit.old_rows.end = next_edit.old_lines.end.row() + 1;
342                    row_edit.new_rows.end = next_edit.new_lines.end.row() + 1;
343                    edits.next();
344                } else {
345                    break;
346                }
347            }
348
349            row_edits.push(row_edit);
350        }
351
352        let mut new_transforms;
353        if row_edits.is_empty() {
354            new_transforms = self.transforms.clone();
355        } else {
356            let mut row_edits = row_edits.into_iter().peekable();
357            let mut old_cursor = self.transforms.cursor::<TabPoint, ()>();
358
359            new_transforms = old_cursor.slice(
360                &TabPoint::new(row_edits.peek().unwrap().old_rows.start, 0),
361                Bias::Right,
362                &(),
363            );
364
365            while let Some(edit) = row_edits.next() {
366                if edit.new_rows.start > new_transforms.summary().input.lines.row {
367                    let summary = new_tab_snapshot.text_summary_for_range(
368                        TabPoint::new(new_transforms.summary().input.lines.row, 0)
369                            ..TabPoint::new(edit.new_rows.start, 0),
370                    );
371                    new_transforms.push_or_extend(Transform::isomorphic(summary));
372                }
373
374                let mut line = String::new();
375                let mut remaining = None;
376                let mut chunks = new_tab_snapshot.chunks_at(TabPoint::new(edit.new_rows.start, 0));
377                for _ in edit.new_rows.start..edit.new_rows.end {
378                    while let Some(chunk) = remaining.take().or_else(|| chunks.next()) {
379                        if let Some(ix) = chunk.find('\n') {
380                            line.push_str(&chunk[..ix + 1]);
381                            remaining = Some(&chunk[ix + 1..]);
382                            break;
383                        } else {
384                            line.push_str(chunk)
385                        }
386                    }
387
388                    if line.is_empty() {
389                        break;
390                    }
391
392                    let mut prev_boundary_ix = 0;
393                    for boundary_ix in line_wrapper.wrap_line_without_shaping(&line, wrap_width) {
394                        let wrapped = &line[prev_boundary_ix..boundary_ix];
395                        new_transforms
396                            .push_or_extend(Transform::isomorphic(TextSummary::from(wrapped)));
397                        new_transforms.push_or_extend(Transform::newline());
398                        prev_boundary_ix = boundary_ix;
399                    }
400
401                    if prev_boundary_ix < line.len() {
402                        new_transforms.push_or_extend(Transform::isomorphic(TextSummary::from(
403                            &line[prev_boundary_ix..],
404                        )));
405                    }
406
407                    line.clear();
408                    yield_now().await;
409                }
410
411                old_cursor.seek_forward(&TabPoint::new(edit.old_rows.end, 0), Bias::Right, &());
412                if let Some(next_edit) = row_edits.peek() {
413                    if next_edit.old_rows.start > old_cursor.seek_end(&()).row() {
414                        if old_cursor.seek_end(&()) > TabPoint::new(edit.old_rows.end, 0) {
415                            let summary = self.tab_snapshot.text_summary_for_range(
416                                TabPoint::new(edit.old_rows.end, 0)..old_cursor.seek_end(&()),
417                            );
418                            new_transforms.push_or_extend(Transform::isomorphic(summary));
419                        }
420                        old_cursor.next(&());
421                        new_transforms.push_tree(
422                            old_cursor.slice(
423                                &TabPoint::new(next_edit.old_rows.start, 0),
424                                Bias::Right,
425                                &(),
426                            ),
427                            &(),
428                        );
429                    }
430                } else {
431                    if old_cursor.seek_end(&()) > TabPoint::new(edit.old_rows.end, 0) {
432                        let summary = self.tab_snapshot.text_summary_for_range(
433                            TabPoint::new(edit.old_rows.end, 0)..old_cursor.seek_end(&()),
434                        );
435                        new_transforms.push_or_extend(Transform::isomorphic(summary));
436                    }
437                    old_cursor.next(&());
438                    new_transforms.push_tree(old_cursor.suffix(&()), &());
439                }
440            }
441        }
442
443        self.transforms = new_transforms;
444        self.tab_snapshot = new_tab_snapshot;
445    }
446
447    pub fn chunks_at(&self, point: WrapPoint) -> Chunks {
448        let mut transforms = self.transforms.cursor::<WrapPoint, TabPoint>();
449        transforms.seek(&point, Bias::Right, &());
450        let input_position =
451            TabPoint(transforms.sum_start().0 + (point.0 - transforms.seek_start().0));
452        let input_chunks = self.tab_snapshot.chunks_at(input_position);
453        Chunks {
454            input_chunks,
455            transforms,
456            output_position: point,
457            input_chunk: "",
458        }
459    }
460
461    pub fn highlighted_chunks_for_rows(&mut self, rows: Range<u32>) -> HighlightedChunks {
462        let output_start = WrapPoint::new(rows.start, 0);
463        let output_end = WrapPoint::new(rows.end, 0);
464        let mut transforms = self.transforms.cursor::<WrapPoint, TabPoint>();
465        transforms.seek(&output_start, Bias::Right, &());
466        let input_start =
467            TabPoint(transforms.sum_start().0 + (output_start.0 - transforms.seek_start().0));
468        let input_end = self
469            .to_input_point(output_end)
470            .min(self.tab_snapshot.max_point());
471        HighlightedChunks {
472            input_chunks: self.tab_snapshot.highlighted_chunks(input_start..input_end),
473            input_chunk: "",
474            style_id: StyleId::default(),
475            output_position: output_start,
476            max_output_row: rows.end,
477            transforms,
478        }
479    }
480
481    pub fn max_point(&self) -> WrapPoint {
482        self.to_output_point(self.tab_snapshot.max_point())
483    }
484
485    pub fn line_len(&self, row: u32) -> u32 {
486        let mut len = 0;
487        for chunk in self.chunks_at(WrapPoint::new(row, 0)) {
488            if let Some(newline_ix) = chunk.find('\n') {
489                len += newline_ix;
490                break;
491            } else {
492                len += chunk.len();
493            }
494        }
495        len as u32
496    }
497
498    pub fn longest_row(&self) -> u32 {
499        self.transforms.summary().output.longest_row
500    }
501
502    pub fn buffer_rows(&self, start_row: u32) -> BufferRows {
503        let mut transforms = self.transforms.cursor::<WrapPoint, TabPoint>();
504        transforms.seek(&WrapPoint::new(start_row, 0), Bias::Right, &());
505        let input_row = transforms.sum_start().row() + (start_row - transforms.seek_start().row());
506        let mut input_buffer_rows = self.tab_snapshot.buffer_rows(input_row);
507        let input_buffer_row = input_buffer_rows.next().unwrap();
508        BufferRows {
509            transforms,
510            input_buffer_row,
511            input_buffer_rows,
512            output_row: start_row,
513            max_output_row: self.max_point().row(),
514        }
515    }
516
517    pub fn to_input_point(&self, point: WrapPoint) -> TabPoint {
518        let mut cursor = self.transforms.cursor::<WrapPoint, TabPoint>();
519        cursor.seek(&point, Bias::Right, &());
520        TabPoint(cursor.sum_start().0 + (point.0 - cursor.seek_start().0))
521    }
522
523    pub fn to_output_point(&self, point: TabPoint) -> WrapPoint {
524        let mut cursor = self.transforms.cursor::<TabPoint, WrapPoint>();
525        cursor.seek(&point, Bias::Right, &());
526        WrapPoint(cursor.sum_start().0 + (point.0 - cursor.seek_start().0))
527    }
528
529    pub fn clip_point(&self, mut point: WrapPoint, bias: Bias) -> WrapPoint {
530        if bias == Bias::Left {
531            let mut cursor = self.transforms.cursor::<WrapPoint, ()>();
532            cursor.seek(&point, Bias::Right, &());
533            let transform = cursor.item().expect("invalid point");
534            if !transform.is_isomorphic() {
535                *point.column_mut() -= 1;
536            }
537        }
538
539        self.to_output_point(
540            self.tab_snapshot
541                .clip_point(self.to_input_point(point), bias),
542        )
543    }
544}
545
546impl<'a> Iterator for Chunks<'a> {
547    type Item = &'a str;
548
549    fn next(&mut self) -> Option<Self::Item> {
550        let transform = self.transforms.item()?;
551        if let Some(display_text) = transform.display_text {
552            self.output_position.0 += transform.summary.output.lines;
553            self.transforms.next(&());
554            return Some(display_text);
555        }
556
557        if self.input_chunk.is_empty() {
558            self.input_chunk = self.input_chunks.next().unwrap();
559        }
560
561        let mut input_len = 0;
562        let transform_end = self.transforms.seek_end(&());
563        for c in self.input_chunk.chars() {
564            let char_len = c.len_utf8();
565            input_len += char_len;
566            if c == '\n' {
567                *self.output_position.row_mut() += 1;
568                *self.output_position.column_mut() = 0;
569            } else {
570                *self.output_position.column_mut() += char_len as u32;
571            }
572
573            if self.output_position >= transform_end {
574                self.transforms.next(&());
575                break;
576            }
577        }
578
579        let (prefix, suffix) = self.input_chunk.split_at(input_len);
580        self.input_chunk = suffix;
581        Some(prefix)
582    }
583}
584
585impl<'a> Iterator for HighlightedChunks<'a> {
586    type Item = (&'a str, StyleId);
587
588    fn next(&mut self) -> Option<Self::Item> {
589        if self.output_position.row() >= self.max_output_row {
590            return None;
591        }
592
593        let transform = self.transforms.item()?;
594        if let Some(display_text) = transform.display_text {
595            self.output_position.0 += transform.summary.output.lines;
596            self.transforms.next(&());
597            return Some((display_text, self.style_id));
598        }
599
600        if self.input_chunk.is_empty() {
601            let (chunk, style_id) = self.input_chunks.next().unwrap();
602            self.input_chunk = chunk;
603            self.style_id = style_id;
604        }
605
606        let mut input_len = 0;
607        let transform_end = self.transforms.seek_end(&());
608        for c in self.input_chunk.chars() {
609            let char_len = c.len_utf8();
610            input_len += char_len;
611            if c == '\n' {
612                *self.output_position.row_mut() += 1;
613                *self.output_position.column_mut() = 0;
614            } else {
615                *self.output_position.column_mut() += char_len as u32;
616            }
617
618            if self.output_position >= transform_end {
619                self.transforms.next(&());
620                break;
621            }
622        }
623
624        let (prefix, suffix) = self.input_chunk.split_at(input_len);
625        self.input_chunk = suffix;
626        Some((prefix, self.style_id))
627    }
628}
629
630impl<'a> Iterator for BufferRows<'a> {
631    type Item = u32;
632
633    fn next(&mut self) -> Option<Self::Item> {
634        if self.output_row > self.max_output_row {
635            return None;
636        }
637
638        let buffer_row = self.input_buffer_row;
639        self.output_row += 1;
640        self.transforms
641            .seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left, &());
642        if self.transforms.item().map_or(false, |t| t.is_isomorphic()) {
643            self.input_buffer_row = self.input_buffer_rows.next().unwrap();
644        }
645
646        Some(buffer_row)
647    }
648}
649
650impl Transform {
651    fn isomorphic(summary: TextSummary) -> Self {
652        #[cfg(test)]
653        assert!(!summary.lines.is_zero());
654
655        Self {
656            summary: TransformSummary {
657                input: summary.clone(),
658                output: summary,
659            },
660            display_text: None,
661        }
662    }
663
664    fn newline() -> Self {
665        Self {
666            summary: TransformSummary {
667                input: TextSummary::default(),
668                output: TextSummary {
669                    lines: Point::new(1, 0),
670                    first_line_chars: 0,
671                    last_line_chars: 0,
672                    longest_row: 0,
673                    longest_row_chars: 0,
674                },
675            },
676            display_text: Some("\n"),
677        }
678    }
679
680    fn is_isomorphic(&self) -> bool {
681        self.display_text.is_none()
682    }
683}
684
685impl sum_tree::Item for Transform {
686    type Summary = TransformSummary;
687
688    fn summary(&self) -> Self::Summary {
689        self.summary.clone()
690    }
691}
692
693impl SumTree<Transform> {
694    pub fn push_or_extend(&mut self, transform: Transform) {
695        let mut transform = Some(transform);
696        self.update_last(
697            |last_transform| {
698                if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
699                    let transform = transform.take().unwrap();
700                    last_transform.summary.input += &transform.summary.input;
701                    last_transform.summary.output += &transform.summary.output;
702                }
703            },
704            &(),
705        );
706
707        if let Some(transform) = transform {
708            self.push(transform, &());
709        }
710    }
711}
712
713impl WrapPoint {
714    pub fn new(row: u32, column: u32) -> Self {
715        Self(super::Point::new(row, column))
716    }
717
718    pub fn zero() -> Self {
719        Self::new(0, 0)
720    }
721
722    pub fn row(self) -> u32 {
723        self.0.row
724    }
725
726    pub fn column(self) -> u32 {
727        self.0.column
728    }
729
730    pub fn row_mut(&mut self) -> &mut u32 {
731        &mut self.0.row
732    }
733
734    pub fn column_mut(&mut self) -> &mut u32 {
735        &mut self.0.column
736    }
737}
738
739impl sum_tree::Summary for TransformSummary {
740    type Context = ();
741
742    fn add_summary(&mut self, other: &Self, _: &()) {
743        self.input += &other.input;
744        self.output += &other.output;
745    }
746}
747
748impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
749    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
750        self.0 += summary.input.lines;
751    }
752}
753
754impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
755    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
756        self.0 += summary.output.lines;
757    }
758}
759
760#[cfg(test)]
761mod tests {
762    use super::*;
763    use crate::{
764        editor::{
765            display_map::{fold_map::FoldMap, tab_map::TabMap},
766            Buffer,
767        },
768        util::RandomCharIter,
769    };
770    use rand::prelude::*;
771    use std::env;
772
773    #[gpui::test]
774    async fn test_random_wraps(mut cx: gpui::TestAppContext) {
775        let iterations = env::var("ITERATIONS")
776            .map(|i| i.parse().expect("invalid `ITERATIONS` variable"))
777            .unwrap_or(100);
778        let operations = env::var("OPERATIONS")
779            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
780            .unwrap_or(10);
781        let seed_range = if let Ok(seed) = env::var("SEED") {
782            let seed = seed.parse().expect("invalid `SEED` variable");
783            seed..seed + 1
784        } else {
785            0..iterations
786        };
787
788        for seed in seed_range {
789            cx.foreground().forbid_parking();
790
791            dbg!(seed);
792            let mut rng = StdRng::seed_from_u64(seed);
793            let font_cache = cx.font_cache().clone();
794            let font_system = cx.platform().fonts();
795            let wrap_width = rng.gen_range(0.0..=1000.0);
796            let settings = Settings {
797                tab_size: rng.gen_range(1..=4),
798                buffer_font_family: font_cache.load_family(&["Helvetica"]).unwrap(),
799                buffer_font_size: 14.0,
800                ..Settings::new(&font_cache).unwrap()
801            };
802            log::info!("Tab size: {}", settings.tab_size);
803            log::info!("Wrap width: {}", wrap_width);
804
805            let buffer = cx.add_model(|cx| {
806                let len = rng.gen_range(0..10);
807                let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
808                Buffer::new(0, text, cx)
809            });
810            let (fold_map, folds_snapshot) = cx.read(|cx| FoldMap::new(buffer.clone(), cx));
811            let (tab_map, tabs_snapshot) = TabMap::new(folds_snapshot.clone(), settings.tab_size);
812            log::info!(
813                "Unwrapped text (unexpanded tabs): {:?}",
814                folds_snapshot.text()
815            );
816            log::info!("Unwrapped text (expanded tabs): {:?}", tabs_snapshot.text());
817            let wrap_map = cx.update(|cx| {
818                WrapMap::new(
819                    tabs_snapshot.clone(),
820                    settings.clone(),
821                    Some(wrap_width),
822                    cx,
823                )
824            });
825            let mut notifications = wrap_map.notifications();
826
827            let mut line_wrapper = LineWrapper::new(font_system, font_cache, settings);
828            let unwrapped_text = tabs_snapshot.text();
829            let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
830
831            if wrap_map.is_rewrapping() {
832                notifications.recv().await;
833            }
834
835            let snapshot = cx.update(|cx| wrap_map.sync(tabs_snapshot, Vec::new(), cx));
836            let actual_text = snapshot.text();
837            assert_eq!(
838                actual_text, expected_text,
839                "unwrapped text is: {:?}",
840                unwrapped_text
841            );
842            log::info!("Wrapped text: {:?}", actual_text);
843
844            let mut interpolated_snapshot = snapshot.clone();
845            for _i in 0..operations {
846                buffer.update(&mut cx, |buffer, cx| buffer.randomly_mutate(&mut rng, cx));
847                let (folds_snapshot, edits) = cx.read(|cx| fold_map.read(cx));
848                log::info!(
849                    "Unwrapped text (unexpanded tabs): {:?}",
850                    folds_snapshot.text()
851                );
852                let (tabs_snapshot, edits) = tab_map.sync(folds_snapshot, edits);
853                log::info!("Unwrapped text (expanded tabs): {:?}", tabs_snapshot.text());
854                interpolated_snapshot.interpolate(tabs_snapshot.clone(), &edits);
855                interpolated_snapshot.check_invariants(&mut rng);
856
857                let unwrapped_text = tabs_snapshot.text();
858                let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
859                let mut snapshot = cx.update(|cx| wrap_map.sync(tabs_snapshot.clone(), edits, cx));
860                snapshot.check_invariants(&mut rng);
861
862                if wrap_map.is_rewrapping() {
863                    notifications.recv().await;
864                    snapshot = cx.update(|cx| wrap_map.sync(tabs_snapshot, Vec::new(), cx));
865                }
866
867                snapshot.check_invariants(&mut rng);
868                let actual_text = snapshot.text();
869                assert_eq!(
870                    actual_text, expected_text,
871                    "unwrapped text is: {:?}",
872                    unwrapped_text
873                );
874                log::info!("New wrapped text: {:?}", actual_text);
875
876                interpolated_snapshot = snapshot.clone();
877            }
878        }
879    }
880
881    fn wrap_text(unwrapped_text: &str, wrap_width: f32, line_wrapper: &mut LineWrapper) -> String {
882        let mut wrapped_text = String::new();
883        for (row, line) in unwrapped_text.split('\n').enumerate() {
884            if row > 0 {
885                wrapped_text.push('\n')
886            }
887
888            let mut prev_ix = 0;
889            for ix in line_wrapper.wrap_line_without_shaping(line, wrap_width) {
890                wrapped_text.push_str(&line[prev_ix..ix]);
891                wrapped_text.push('\n');
892                prev_ix = ix;
893            }
894            wrapped_text.push_str(&line[prev_ix..]);
895        }
896        wrapped_text
897    }
898
899    impl Snapshot {
900        fn text(&self) -> String {
901            self.chunks_at(WrapPoint::zero()).collect()
902        }
903
904        fn check_invariants(&mut self, rng: &mut impl Rng) {
905            assert_eq!(
906                TabPoint::from(self.transforms.summary().input.lines),
907                self.tab_snapshot.max_point()
908            );
909
910            {
911                let mut transforms = self.transforms.cursor::<(), ()>().peekable();
912                while let Some(transform) = transforms.next() {
913                    let next_transform = transforms.peek();
914                    assert!(
915                        !transform.is_isomorphic()
916                            || next_transform.map_or(true, |t| !t.is_isomorphic())
917                    );
918                }
919            }
920
921            for _ in 0..5 {
922                let mut end_row = rng.gen_range(0..=self.max_point().row());
923                let start_row = rng.gen_range(0..=end_row);
924                end_row += 1;
925
926                let mut expected_text = self
927                    .chunks_at(WrapPoint::new(start_row, 0))
928                    .collect::<String>();
929                if expected_text.ends_with("\n") {
930                    expected_text.push('\n');
931                }
932                let mut expected_text = expected_text
933                    .lines()
934                    .take((end_row - start_row) as usize)
935                    .collect::<Vec<_>>()
936                    .join("\n");
937                if end_row <= self.max_point().row() {
938                    expected_text.push('\n');
939                }
940                let actual_text = self
941                    .highlighted_chunks_for_rows(start_row..end_row)
942                    .map(|c| c.0)
943                    .collect::<String>();
944                assert_eq!(
945                    expected_text,
946                    actual_text,
947                    "chunks != highlighted_chunks for rows {:?}",
948                    start_row..end_row
949                );
950            }
951        }
952    }
953}