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, AppContext, 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    input_position: TabPoint,
 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: &AppContext,
 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: &AppContext,
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: &AppContext) {
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                new_transforms.push_or_extend(Transform::isomorphic(
281                    new_tab_snapshot.text_summary_for_range(edit.new_lines.clone()),
282                ));
283
284                old_cursor.seek_forward(&edit.old_lines.end, Bias::Right, &());
285                if let Some(next_edit) = edits.peek() {
286                    if next_edit.old_lines.start > old_cursor.seek_end(&()) {
287                        if old_cursor.seek_end(&()) > edit.old_lines.end {
288                            let summary = self.tab_snapshot.text_summary_for_range(
289                                edit.old_lines.end..old_cursor.seek_end(&()),
290                            );
291                            new_transforms.push_or_extend(Transform::isomorphic(summary));
292                        }
293                        old_cursor.next(&());
294                        new_transforms.push_tree(
295                            old_cursor.slice(&next_edit.old_lines.start, Bias::Right, &()),
296                            &(),
297                        );
298                    }
299                } else {
300                    if old_cursor.seek_end(&()) > edit.old_lines.end {
301                        let summary = self
302                            .tab_snapshot
303                            .text_summary_for_range(edit.old_lines.end..old_cursor.seek_end(&()));
304                        new_transforms.push_or_extend(Transform::isomorphic(summary));
305                    }
306                    old_cursor.next(&());
307                    new_transforms.push_tree(old_cursor.suffix(&()), &());
308                }
309            }
310        }
311
312        self.transforms = new_transforms;
313        self.tab_snapshot = new_tab_snapshot;
314    }
315
316    async fn update(
317        &mut self,
318        new_tab_snapshot: TabSnapshot,
319        edits: &[TabEdit],
320        wrap_width: f32,
321        line_wrapper: &LineWrapper,
322    ) {
323        #[derive(Debug)]
324        struct RowEdit {
325            old_rows: Range<u32>,
326            new_rows: Range<u32>,
327        }
328
329        let mut edits = edits.into_iter().peekable();
330        let mut row_edits = Vec::new();
331        while let Some(edit) = edits.next() {
332            let mut row_edit = RowEdit {
333                old_rows: edit.old_lines.start.row()..edit.old_lines.end.row() + 1,
334                new_rows: edit.new_lines.start.row()..edit.new_lines.end.row() + 1,
335            };
336
337            while let Some(next_edit) = edits.peek() {
338                if next_edit.old_lines.start.row() <= row_edit.old_rows.end {
339                    row_edit.old_rows.end = next_edit.old_lines.end.row() + 1;
340                    row_edit.new_rows.end = next_edit.new_lines.end.row() + 1;
341                    edits.next();
342                } else {
343                    break;
344                }
345            }
346
347            row_edits.push(row_edit);
348        }
349
350        let mut new_transforms;
351        if row_edits.is_empty() {
352            new_transforms = self.transforms.clone();
353        } else {
354            let mut row_edits = row_edits.into_iter().peekable();
355            let mut old_cursor = self.transforms.cursor::<TabPoint, ()>();
356
357            new_transforms = old_cursor.slice(
358                &TabPoint::new(row_edits.peek().unwrap().old_rows.start, 0),
359                Bias::Right,
360                &(),
361            );
362
363            while let Some(edit) = row_edits.next() {
364                if edit.new_rows.start > new_transforms.summary().input.lines.row {
365                    let summary = new_tab_snapshot.text_summary_for_range(
366                        TabPoint::new(new_transforms.summary().input.lines.row, 0)
367                            ..TabPoint::new(edit.new_rows.start, 0),
368                    );
369                    new_transforms.push_or_extend(Transform::isomorphic(summary));
370                }
371
372                let mut line = String::new();
373                let mut remaining = None;
374                let mut chunks = new_tab_snapshot.chunks_at(TabPoint::new(edit.new_rows.start, 0));
375                for _ in edit.new_rows.start..edit.new_rows.end {
376                    while let Some(chunk) = remaining.take().or_else(|| chunks.next()) {
377                        if let Some(ix) = chunk.find('\n') {
378                            line.push_str(&chunk[..ix + 1]);
379                            remaining = Some(&chunk[ix + 1..]);
380                            break;
381                        } else {
382                            line.push_str(chunk)
383                        }
384                    }
385
386                    if line.is_empty() {
387                        break;
388                    }
389
390                    let mut prev_boundary_ix = 0;
391                    for boundary_ix in line_wrapper.wrap_line_without_shaping(&line, wrap_width) {
392                        let wrapped = &line[prev_boundary_ix..boundary_ix];
393                        new_transforms
394                            .push_or_extend(Transform::isomorphic(TextSummary::from(wrapped)));
395                        new_transforms.push_or_extend(Transform::newline());
396                        prev_boundary_ix = boundary_ix;
397                    }
398
399                    if prev_boundary_ix < line.len() {
400                        new_transforms.push_or_extend(Transform::isomorphic(TextSummary::from(
401                            &line[prev_boundary_ix..],
402                        )));
403                    }
404
405                    line.clear();
406                    yield_now().await;
407                }
408
409                old_cursor.seek_forward(&TabPoint::new(edit.old_rows.end, 0), Bias::Right, &());
410                if let Some(next_edit) = row_edits.peek() {
411                    if next_edit.old_rows.start > old_cursor.seek_end(&()).row() {
412                        if old_cursor.seek_end(&()) > TabPoint::new(edit.old_rows.end, 0) {
413                            let summary = self.tab_snapshot.text_summary_for_range(
414                                TabPoint::new(edit.old_rows.end, 0)..old_cursor.seek_end(&()),
415                            );
416                            new_transforms.push_or_extend(Transform::isomorphic(summary));
417                        }
418                        old_cursor.next(&());
419                        new_transforms.push_tree(
420                            old_cursor.slice(
421                                &TabPoint::new(next_edit.old_rows.start, 0),
422                                Bias::Right,
423                                &(),
424                            ),
425                            &(),
426                        );
427                    }
428                } else {
429                    if old_cursor.seek_end(&()) > TabPoint::new(edit.old_rows.end, 0) {
430                        let summary = self.tab_snapshot.text_summary_for_range(
431                            TabPoint::new(edit.old_rows.end, 0)..old_cursor.seek_end(&()),
432                        );
433                        new_transforms.push_or_extend(Transform::isomorphic(summary));
434                    }
435                    old_cursor.next(&());
436                    new_transforms.push_tree(old_cursor.suffix(&()), &());
437                }
438            }
439        }
440
441        self.transforms = new_transforms;
442        self.tab_snapshot = new_tab_snapshot;
443    }
444
445    pub fn chunks_at(&self, point: WrapPoint) -> Chunks {
446        let mut transforms = self.transforms.cursor::<WrapPoint, TabPoint>();
447        transforms.seek(&point, Bias::Right, &());
448        let input_position =
449            TabPoint(transforms.sum_start().0 + (point.0 - transforms.seek_start().0));
450        let input_chunks = self.tab_snapshot.chunks_at(input_position);
451        Chunks {
452            input_chunks,
453            transforms,
454            input_position,
455            input_chunk: "",
456        }
457    }
458
459    pub fn highlighted_chunks_for_rows(&mut self, rows: Range<u32>) -> HighlightedChunks {
460        let output_start = WrapPoint::new(rows.start, 0);
461        let output_end = WrapPoint::new(rows.end, 0);
462        let mut transforms = self.transforms.cursor::<WrapPoint, TabPoint>();
463        transforms.seek(&output_start, Bias::Right, &());
464        let input_start =
465            TabPoint(transforms.sum_start().0 + (output_start.0 - transforms.seek_start().0));
466        let input_end = self
467            .to_input_point(output_end)
468            .min(self.tab_snapshot.max_point());
469        HighlightedChunks {
470            input_chunks: self.tab_snapshot.highlighted_chunks(input_start..input_end),
471            input_chunk: "",
472            style_id: StyleId::default(),
473            output_position: output_start,
474            max_output_row: rows.end,
475            transforms,
476        }
477    }
478
479    pub fn max_point(&self) -> WrapPoint {
480        self.to_output_point(self.tab_snapshot.max_point())
481    }
482
483    pub fn line_len(&self, row: u32) -> u32 {
484        let mut len = 0;
485        for chunk in self.chunks_at(WrapPoint::new(row, 0)) {
486            if let Some(newline_ix) = chunk.find('\n') {
487                len += newline_ix;
488                break;
489            } else {
490                len += chunk.len();
491            }
492        }
493        len as u32
494    }
495
496    pub fn longest_row(&self) -> u32 {
497        self.transforms.summary().output.longest_row
498    }
499
500    pub fn buffer_rows(&self, start_row: u32) -> BufferRows {
501        let mut transforms = self.transforms.cursor::<WrapPoint, TabPoint>();
502        transforms.seek(&WrapPoint::new(start_row, 0), Bias::Right, &());
503        let input_row = transforms.sum_start().row() + (start_row - transforms.seek_start().row());
504        let mut input_buffer_rows = self.tab_snapshot.buffer_rows(input_row);
505        let input_buffer_row = input_buffer_rows.next().unwrap();
506        BufferRows {
507            transforms,
508            input_buffer_row,
509            input_buffer_rows,
510            output_row: start_row,
511            max_output_row: self.max_point().row(),
512        }
513    }
514
515    pub fn to_input_point(&self, point: WrapPoint) -> TabPoint {
516        let mut cursor = self.transforms.cursor::<WrapPoint, TabPoint>();
517        cursor.seek(&point, Bias::Right, &());
518        TabPoint(cursor.sum_start().0 + (point.0 - cursor.seek_start().0))
519    }
520
521    pub fn to_output_point(&self, point: TabPoint) -> WrapPoint {
522        let mut cursor = self.transforms.cursor::<TabPoint, WrapPoint>();
523        cursor.seek(&point, Bias::Right, &());
524        WrapPoint(cursor.sum_start().0 + (point.0 - cursor.seek_start().0))
525    }
526
527    pub fn clip_point(&self, mut point: WrapPoint, bias: Bias) -> WrapPoint {
528        if bias == Bias::Left {
529            let mut cursor = self.transforms.cursor::<WrapPoint, ()>();
530            cursor.seek(&point, Bias::Right, &());
531            let transform = cursor.item().expect("invalid point");
532            if !transform.is_isomorphic() {
533                *point.column_mut() -= 1;
534            }
535        }
536
537        self.to_output_point(
538            self.tab_snapshot
539                .clip_point(self.to_input_point(point), bias),
540        )
541    }
542}
543
544impl<'a> Iterator for Chunks<'a> {
545    type Item = &'a str;
546
547    fn next(&mut self) -> Option<Self::Item> {
548        let transform = self.transforms.item()?;
549        if let Some(display_text) = transform.display_text {
550            self.transforms.next(&());
551            return Some(display_text);
552        }
553
554        if self.input_chunk.is_empty() {
555            self.input_chunk = self.input_chunks.next().unwrap();
556        }
557
558        let mut input_len = 0;
559        let transform_end = self.transforms.sum_end(&());
560        for c in self.input_chunk.chars() {
561            let char_len = c.len_utf8();
562            input_len += char_len;
563            if c == '\n' {
564                *self.input_position.row_mut() += 1;
565                *self.input_position.column_mut() = 0;
566            } else {
567                *self.input_position.column_mut() += char_len as u32;
568            }
569
570            if self.input_position >= transform_end {
571                self.transforms.next(&());
572                break;
573            }
574        }
575
576        let (prefix, suffix) = self.input_chunk.split_at(input_len);
577        self.input_chunk = suffix;
578        Some(prefix)
579    }
580}
581
582impl<'a> Iterator for HighlightedChunks<'a> {
583    type Item = (&'a str, StyleId);
584
585    fn next(&mut self) -> Option<Self::Item> {
586        if self.output_position.row() >= self.max_output_row {
587            return None;
588        }
589
590        let transform = self.transforms.item()?;
591        if let Some(display_text) = transform.display_text {
592            self.output_position.0 += transform.summary.output.lines;
593            self.transforms.next(&());
594            return Some((display_text, self.style_id));
595        }
596
597        if self.input_chunk.is_empty() {
598            let (chunk, style_id) = self.input_chunks.next().unwrap();
599            self.input_chunk = chunk;
600            self.style_id = style_id;
601        }
602
603        let mut input_len = 0;
604        let transform_end = self.transforms.seek_end(&());
605        for c in self.input_chunk.chars() {
606            let char_len = c.len_utf8();
607            input_len += char_len;
608            if c == '\n' {
609                *self.output_position.row_mut() += 1;
610                *self.output_position.column_mut() = 0;
611            } else {
612                *self.output_position.column_mut() += char_len as u32;
613            }
614
615            if self.output_position >= transform_end {
616                self.transforms.next(&());
617                break;
618            }
619        }
620
621        let (prefix, suffix) = self.input_chunk.split_at(input_len);
622        self.input_chunk = suffix;
623        Some((prefix, self.style_id))
624    }
625}
626
627impl<'a> Iterator for BufferRows<'a> {
628    type Item = u32;
629
630    fn next(&mut self) -> Option<Self::Item> {
631        if self.output_row > self.max_output_row {
632            return None;
633        }
634
635        let buffer_row = self.input_buffer_row;
636        self.output_row += 1;
637        self.transforms
638            .seek_forward(&WrapPoint::new(self.output_row, 0), Bias::Left, &());
639        if self.transforms.item().map_or(false, |t| t.is_isomorphic()) {
640            self.input_buffer_row = self.input_buffer_rows.next().unwrap();
641        }
642
643        Some(buffer_row)
644    }
645}
646
647impl Transform {
648    fn isomorphic(summary: TextSummary) -> Self {
649        Self {
650            summary: TransformSummary {
651                input: summary.clone(),
652                output: summary,
653            },
654            display_text: None,
655        }
656    }
657
658    fn newline() -> Self {
659        Self {
660            summary: TransformSummary {
661                input: TextSummary::default(),
662                output: TextSummary {
663                    lines: Point::new(1, 0),
664                    first_line_chars: 0,
665                    last_line_chars: 0,
666                    longest_row: 0,
667                    longest_row_chars: 0,
668                },
669            },
670            display_text: Some("\n"),
671        }
672    }
673
674    fn is_isomorphic(&self) -> bool {
675        self.display_text.is_none()
676    }
677}
678
679impl sum_tree::Item for Transform {
680    type Summary = TransformSummary;
681
682    fn summary(&self) -> Self::Summary {
683        self.summary.clone()
684    }
685}
686
687impl SumTree<Transform> {
688    pub fn push_or_extend(&mut self, transform: Transform) {
689        let mut transform = Some(transform);
690        self.update_last(
691            |last_transform| {
692                if last_transform.is_isomorphic() && transform.as_ref().unwrap().is_isomorphic() {
693                    let transform = transform.take().unwrap();
694                    last_transform.summary.input += &transform.summary.input;
695                    last_transform.summary.output += &transform.summary.output;
696                }
697            },
698            &(),
699        );
700
701        if let Some(transform) = transform {
702            self.push(transform, &());
703        }
704    }
705}
706
707impl WrapPoint {
708    pub fn new(row: u32, column: u32) -> Self {
709        Self(super::Point::new(row, column))
710    }
711
712    pub fn zero() -> Self {
713        Self::new(0, 0)
714    }
715
716    pub fn row(self) -> u32 {
717        self.0.row
718    }
719
720    pub fn column(self) -> u32 {
721        self.0.column
722    }
723
724    pub fn row_mut(&mut self) -> &mut u32 {
725        &mut self.0.row
726    }
727
728    pub fn column_mut(&mut self) -> &mut u32 {
729        &mut self.0.column
730    }
731}
732
733impl sum_tree::Summary for TransformSummary {
734    type Context = ();
735
736    fn add_summary(&mut self, other: &Self, _: &()) {
737        self.input += &other.input;
738        self.output += &other.output;
739    }
740}
741
742impl<'a> sum_tree::Dimension<'a, TransformSummary> for TabPoint {
743    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
744        self.0 += summary.input.lines;
745    }
746}
747
748impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapPoint {
749    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
750        self.0 += summary.output.lines;
751    }
752}
753
754#[cfg(test)]
755mod tests {
756    use super::*;
757    use crate::{
758        editor::{
759            display_map::{fold_map::FoldMap, tab_map::TabMap},
760            Buffer,
761        },
762        util::RandomCharIter,
763    };
764    use rand::prelude::*;
765    use std::env;
766
767    #[gpui::test]
768    async fn test_random_wraps(mut cx: gpui::TestAppContext) {
769        let iterations = env::var("ITERATIONS")
770            .map(|i| i.parse().expect("invalid `ITERATIONS` variable"))
771            .unwrap_or(100);
772        let operations = env::var("OPERATIONS")
773            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
774            .unwrap_or(10);
775        let seed_range = if let Ok(seed) = env::var("SEED") {
776            let seed = seed.parse().expect("invalid `SEED` variable");
777            seed..seed + 1
778        } else {
779            0..iterations
780        };
781
782        for seed in seed_range {
783            cx.foreground().forbid_parking();
784
785            dbg!(seed);
786            let mut rng = StdRng::seed_from_u64(seed);
787            let font_cache = cx.font_cache().clone();
788            let font_system = cx.platform().fonts();
789            let wrap_width = rng.gen_range(100.0..=1000.0);
790            let settings = Settings {
791                tab_size: rng.gen_range(1..=4),
792                buffer_font_family: font_cache.load_family(&["Helvetica"]).unwrap(),
793                buffer_font_size: 14.0,
794                ..Settings::new(&font_cache).unwrap()
795            };
796            log::info!("Tab size: {}", settings.tab_size);
797            log::info!("Wrap width: {}", wrap_width);
798
799            let buffer = cx.add_model(|cx| {
800                let len = rng.gen_range(0..10);
801                let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
802                log::info!("Initial buffer text: {:?} (len: {})", text, text.len());
803                Buffer::new(0, text, cx)
804            });
805            let (fold_map, folds_snapshot) = cx.read(|cx| FoldMap::new(buffer.clone(), cx));
806            let (tab_map, tabs_snapshot) = TabMap::new(folds_snapshot.clone(), settings.tab_size);
807            let wrap_map = cx.read(|cx| {
808                WrapMap::new(
809                    tabs_snapshot.clone(),
810                    settings.clone(),
811                    Some(wrap_width),
812                    cx,
813                )
814            });
815            let mut notifications = wrap_map.notifications();
816
817            let mut line_wrapper = LineWrapper::new(font_system, font_cache, settings);
818            let unwrapped_text = tabs_snapshot.text();
819            let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
820
821            if wrap_map.is_rewrapping() {
822                notifications.recv().await;
823            }
824
825            let snapshot = cx.read(|cx| wrap_map.sync(tabs_snapshot, Vec::new(), cx));
826            let actual_text = snapshot.text();
827
828            assert_eq!(
829                actual_text, expected_text,
830                "unwrapped text is: {:?}",
831                unwrapped_text
832            );
833
834            let mut interpolated_snapshot = snapshot.clone();
835            for _i in 0..operations {
836                buffer.update(&mut cx, |buffer, cx| buffer.randomly_mutate(&mut rng, cx));
837                let (folds_snapshot, edits) = cx.read(|cx| fold_map.read(cx));
838                let (tabs_snapshot, edits) = tab_map.sync(folds_snapshot, edits);
839                interpolated_snapshot.interpolate(tabs_snapshot.clone(), &edits);
840                interpolated_snapshot.check_invariants();
841
842                let unwrapped_text = tabs_snapshot.text();
843                let expected_text = wrap_text(&unwrapped_text, wrap_width, &mut line_wrapper);
844                let mut snapshot = cx.read(|cx| wrap_map.sync(tabs_snapshot.clone(), edits, cx));
845
846                if wrap_map.is_rewrapping() {
847                    notifications.recv().await;
848                    snapshot = cx.read(|cx| wrap_map.sync(tabs_snapshot, Vec::new(), cx));
849                }
850
851                snapshot.check_invariants();
852                let actual_text = snapshot.text();
853                assert_eq!(
854                    actual_text, expected_text,
855                    "unwrapped text is: {:?}",
856                    unwrapped_text
857                );
858
859                interpolated_snapshot = snapshot.clone();
860            }
861        }
862    }
863
864    fn wrap_text(unwrapped_text: &str, wrap_width: f32, line_wrapper: &mut LineWrapper) -> String {
865        let mut wrapped_text = String::new();
866        for (row, line) in unwrapped_text.split('\n').enumerate() {
867            if row > 0 {
868                wrapped_text.push('\n')
869            }
870
871            let mut prev_ix = 0;
872            for ix in line_wrapper.wrap_line_without_shaping(line, wrap_width) {
873                wrapped_text.push_str(&line[prev_ix..ix]);
874                wrapped_text.push('\n');
875                prev_ix = ix;
876            }
877            wrapped_text.push_str(&line[prev_ix..]);
878        }
879        wrapped_text
880    }
881
882    impl Snapshot {
883        fn text(&self) -> String {
884            self.chunks_at(WrapPoint::zero()).collect()
885        }
886
887        fn check_invariants(&self) {
888            assert_eq!(
889                TabPoint::from(self.transforms.summary().input.lines),
890                self.tab_snapshot.max_point()
891            );
892
893            let mut transforms = self.transforms.cursor::<(), ()>().peekable();
894            while let Some(transform) = transforms.next() {
895                let next_transform = transforms.peek();
896                assert!(
897                    !transform.is_isomorphic()
898                        || next_transform.map_or(true, |t| !t.is_isomorphic())
899                );
900            }
901        }
902    }
903}