wrap_map.rs

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