wrap_map.rs

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