block_map.rs

   1use super::wrap_map::{self, WrapEdit, WrapPoint, WrapSnapshot};
   2use crate::{Anchor, ToPoint as _};
   3use collections::{Bound, HashMap, HashSet};
   4use gpui::{AppContext, ElementBox};
   5use language::{BufferSnapshot, Chunk, Patch};
   6use parking_lot::Mutex;
   7use std::{
   8    cell::RefCell,
   9    cmp::{self, Ordering},
  10    fmt::Debug,
  11    ops::{Deref, Range},
  12    sync::{
  13        atomic::{AtomicUsize, Ordering::SeqCst},
  14        Arc,
  15    },
  16};
  17use sum_tree::{Bias, SumTree};
  18use text::{Edit, Point};
  19
  20const NEWLINES: &'static [u8] = &[b'\n'; u8::MAX as usize];
  21
  22pub struct BlockMap {
  23    next_block_id: AtomicUsize,
  24    wrap_snapshot: RefCell<WrapSnapshot>,
  25    blocks: Vec<Arc<Block>>,
  26    transforms: RefCell<SumTree<Transform>>,
  27    buffer_header_height: u8,
  28    excerpt_header_height: u8,
  29}
  30
  31pub struct BlockMapWriter<'a>(&'a mut BlockMap);
  32
  33pub struct BlockSnapshot {
  34    wrap_snapshot: WrapSnapshot,
  35    transforms: SumTree<Transform>,
  36}
  37
  38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
  39pub struct BlockId(usize);
  40
  41#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
  42pub struct BlockPoint(pub super::Point);
  43
  44#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
  45struct BlockRow(u32);
  46
  47#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
  48struct WrapRow(u32);
  49
  50pub type RenderBlock = Arc<dyn Fn(&BlockContext) -> ElementBox>;
  51
  52pub struct Block {
  53    id: BlockId,
  54    position: Anchor,
  55    height: u8,
  56    render: Mutex<RenderBlock>,
  57    disposition: BlockDisposition,
  58}
  59
  60#[derive(Clone)]
  61pub struct BlockProperties<P>
  62where
  63    P: Clone,
  64{
  65    pub position: P,
  66    pub height: u8,
  67    pub render: Arc<dyn Fn(&BlockContext) -> ElementBox>,
  68    pub disposition: BlockDisposition,
  69}
  70
  71pub struct BlockContext<'a> {
  72    pub cx: &'a AppContext,
  73    pub anchor_x: f32,
  74    pub scroll_x: f32,
  75    pub gutter_width: f32,
  76    pub gutter_padding: f32,
  77    pub em_width: f32,
  78    pub line_height: f32,
  79}
  80
  81#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
  82pub enum BlockDisposition {
  83    Above,
  84    Below,
  85}
  86
  87#[derive(Clone, Debug)]
  88struct Transform {
  89    summary: TransformSummary,
  90    block: Option<TransformBlock>,
  91}
  92
  93#[derive(Clone)]
  94pub enum TransformBlock {
  95    Custom(Arc<Block>),
  96    ExcerptHeader {
  97        buffer: BufferSnapshot,
  98        range: Range<text::Anchor>,
  99        height: u8,
 100        starts_new_buffer: bool,
 101    },
 102}
 103
 104impl TransformBlock {
 105    fn disposition(&self) -> BlockDisposition {
 106        match self {
 107            TransformBlock::Custom(block) => block.disposition,
 108            TransformBlock::ExcerptHeader { .. } => BlockDisposition::Above,
 109        }
 110    }
 111
 112    pub fn height(&self) -> u8 {
 113        match self {
 114            TransformBlock::Custom(block) => block.height,
 115            TransformBlock::ExcerptHeader { height, .. } => *height,
 116        }
 117    }
 118}
 119
 120impl Debug for TransformBlock {
 121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 122        match self {
 123            Self::Custom(block) => f.debug_struct("Custom").field("block", block).finish(),
 124            Self::ExcerptHeader { buffer, .. } => f
 125                .debug_struct("ExcerptHeader")
 126                .field("path", &buffer.path())
 127                .finish(),
 128        }
 129    }
 130}
 131
 132#[derive(Clone, Debug, Default)]
 133struct TransformSummary {
 134    input_rows: u32,
 135    output_rows: u32,
 136}
 137
 138pub struct BlockChunks<'a> {
 139    transforms: sum_tree::Cursor<'a, Transform, (BlockRow, WrapRow)>,
 140    input_chunks: wrap_map::WrapChunks<'a>,
 141    input_chunk: Chunk<'a>,
 142    output_row: u32,
 143    max_output_row: u32,
 144}
 145
 146pub struct BlockBufferRows<'a> {
 147    transforms: sum_tree::Cursor<'a, Transform, (BlockRow, WrapRow)>,
 148    input_buffer_rows: wrap_map::WrapBufferRows<'a>,
 149    output_row: u32,
 150    started: bool,
 151}
 152
 153impl BlockMap {
 154    pub fn new(
 155        wrap_snapshot: WrapSnapshot,
 156        buffer_header_height: u8,
 157        excerpt_header_height: u8,
 158    ) -> Self {
 159        let row_count = wrap_snapshot.max_point().row() + 1;
 160        let map = Self {
 161            next_block_id: AtomicUsize::new(0),
 162            blocks: Vec::new(),
 163            transforms: RefCell::new(SumTree::from_item(Transform::isomorphic(row_count), &())),
 164            wrap_snapshot: RefCell::new(wrap_snapshot.clone()),
 165            buffer_header_height,
 166            excerpt_header_height,
 167        };
 168        map.sync(
 169            &wrap_snapshot,
 170            Patch::new(vec![Edit {
 171                old: 0..row_count,
 172                new: 0..row_count,
 173            }]),
 174        );
 175        map
 176    }
 177
 178    pub fn read(&self, wrap_snapshot: WrapSnapshot, edits: Patch<u32>) -> BlockSnapshot {
 179        self.sync(&wrap_snapshot, edits);
 180        *self.wrap_snapshot.borrow_mut() = wrap_snapshot.clone();
 181        BlockSnapshot {
 182            wrap_snapshot,
 183            transforms: self.transforms.borrow().clone(),
 184        }
 185    }
 186
 187    pub fn write(&mut self, wrap_snapshot: WrapSnapshot, edits: Patch<u32>) -> BlockMapWriter {
 188        self.sync(&wrap_snapshot, edits);
 189        *self.wrap_snapshot.borrow_mut() = wrap_snapshot;
 190        BlockMapWriter(self)
 191    }
 192
 193    fn sync(&self, wrap_snapshot: &WrapSnapshot, mut edits: Patch<u32>) {
 194        let buffer = wrap_snapshot.buffer_snapshot();
 195
 196        // Handle changing the last excerpt if it is empty.
 197        if buffer.trailing_excerpt_update_count()
 198            != self
 199                .wrap_snapshot
 200                .borrow()
 201                .buffer_snapshot()
 202                .trailing_excerpt_update_count()
 203        {
 204            let max_point = wrap_snapshot.max_point();
 205            let edit_start = wrap_snapshot.prev_row_boundary(max_point);
 206            let edit_end = max_point.row() + 1;
 207            edits = edits.compose([WrapEdit {
 208                old: edit_start..edit_end,
 209                new: edit_start..edit_end,
 210            }]);
 211        }
 212
 213        let edits = edits.into_inner();
 214        if edits.is_empty() {
 215            return;
 216        }
 217
 218        let mut transforms = self.transforms.borrow_mut();
 219        let mut new_transforms = SumTree::new();
 220        let old_row_count = transforms.summary().input_rows;
 221        let new_row_count = wrap_snapshot.max_point().row() + 1;
 222        let mut cursor = transforms.cursor::<WrapRow>();
 223        let mut last_block_ix = 0;
 224        let mut blocks_in_edit = Vec::new();
 225        let mut edits = edits.into_iter().peekable();
 226
 227        while let Some(edit) = edits.next() {
 228            // Preserve any old transforms that precede this edit.
 229            let old_start = WrapRow(edit.old.start);
 230            let new_start = WrapRow(edit.new.start);
 231            new_transforms.push_tree(cursor.slice(&old_start, Bias::Left, &()), &());
 232            if let Some(transform) = cursor.item() {
 233                if transform.is_isomorphic() && old_start == cursor.end(&()) {
 234                    new_transforms.push(transform.clone(), &());
 235                    cursor.next(&());
 236                    while let Some(transform) = cursor.item() {
 237                        if transform
 238                            .block
 239                            .as_ref()
 240                            .map_or(false, |b| b.disposition().is_below())
 241                        {
 242                            new_transforms.push(transform.clone(), &());
 243                            cursor.next(&());
 244                        } else {
 245                            break;
 246                        }
 247                    }
 248                }
 249            }
 250
 251            // Preserve any portion of an old transform that precedes this edit.
 252            let extent_before_edit = old_start.0 - cursor.start().0;
 253            push_isomorphic(&mut new_transforms, extent_before_edit);
 254
 255            // Skip over any old transforms that intersect this edit.
 256            let mut old_end = WrapRow(edit.old.end);
 257            let mut new_end = WrapRow(edit.new.end);
 258            cursor.seek(&old_end, Bias::Left, &());
 259            cursor.next(&());
 260            if old_end == *cursor.start() {
 261                while let Some(transform) = cursor.item() {
 262                    if transform
 263                        .block
 264                        .as_ref()
 265                        .map_or(false, |b| b.disposition().is_below())
 266                    {
 267                        cursor.next(&());
 268                    } else {
 269                        break;
 270                    }
 271                }
 272            }
 273
 274            // Combine this edit with any subsequent edits that intersect the same transform.
 275            while let Some(next_edit) = edits.peek() {
 276                if next_edit.old.start <= cursor.start().0 {
 277                    old_end = WrapRow(next_edit.old.end);
 278                    new_end = WrapRow(next_edit.new.end);
 279                    cursor.seek(&old_end, Bias::Left, &());
 280                    cursor.next(&());
 281                    if old_end == *cursor.start() {
 282                        while let Some(transform) = cursor.item() {
 283                            if transform
 284                                .block
 285                                .as_ref()
 286                                .map_or(false, |b| b.disposition().is_below())
 287                            {
 288                                cursor.next(&());
 289                            } else {
 290                                break;
 291                            }
 292                        }
 293                    }
 294                    edits.next();
 295                } else {
 296                    break;
 297                }
 298            }
 299
 300            // Find the blocks within this edited region.
 301            let new_buffer_start =
 302                wrap_snapshot.to_point(WrapPoint::new(new_start.0, 0), Bias::Left);
 303            let start_bound = Bound::Included(new_buffer_start);
 304            let start_block_ix = match self.blocks[last_block_ix..].binary_search_by(|probe| {
 305                probe
 306                    .position
 307                    .to_point(&buffer)
 308                    .cmp(&new_buffer_start)
 309                    .then(Ordering::Greater)
 310            }) {
 311                Ok(ix) | Err(ix) => last_block_ix + ix,
 312            };
 313
 314            let end_bound;
 315            let end_block_ix = if new_end.0 > wrap_snapshot.max_point().row() {
 316                end_bound = Bound::Unbounded;
 317                self.blocks.len()
 318            } else {
 319                let new_buffer_end =
 320                    wrap_snapshot.to_point(WrapPoint::new(new_end.0, 0), Bias::Left);
 321                end_bound = Bound::Excluded(new_buffer_end);
 322                match self.blocks[start_block_ix..].binary_search_by(|probe| {
 323                    probe
 324                        .position
 325                        .to_point(&buffer)
 326                        .cmp(&new_buffer_end)
 327                        .then(Ordering::Greater)
 328                }) {
 329                    Ok(ix) | Err(ix) => start_block_ix + ix,
 330                }
 331            };
 332            last_block_ix = end_block_ix;
 333
 334            debug_assert!(blocks_in_edit.is_empty());
 335            blocks_in_edit.extend(
 336                self.blocks[start_block_ix..end_block_ix]
 337                    .iter()
 338                    .map(|block| {
 339                        let mut position = block.position.to_point(&buffer);
 340                        match block.disposition {
 341                            BlockDisposition::Above => position.column = 0,
 342                            BlockDisposition::Below => {
 343                                position.column = buffer.line_len(position.row)
 344                            }
 345                        }
 346                        let position = wrap_snapshot.from_point(position, Bias::Left);
 347                        (position.row(), TransformBlock::Custom(block.clone()))
 348                    }),
 349            );
 350            blocks_in_edit.extend(
 351                buffer
 352                    .excerpt_boundaries_in_range((start_bound, end_bound))
 353                    .map(|excerpt_boundary| {
 354                        (
 355                            wrap_snapshot
 356                                .from_point(Point::new(excerpt_boundary.row, 0), Bias::Left)
 357                                .row(),
 358                            TransformBlock::ExcerptHeader {
 359                                buffer: excerpt_boundary.buffer,
 360                                range: excerpt_boundary.range,
 361                                height: if excerpt_boundary.starts_new_buffer {
 362                                    self.buffer_header_height
 363                                } else {
 364                                    self.excerpt_header_height
 365                                },
 366                                starts_new_buffer: excerpt_boundary.starts_new_buffer,
 367                            },
 368                        )
 369                    }),
 370            );
 371
 372            // Place excerpt headers above custom blocks on the same row.
 373            blocks_in_edit.sort_unstable_by(|(row_a, block_a), (row_b, block_b)| {
 374                row_a.cmp(&row_b).then_with(|| match (block_a, block_b) {
 375                    (
 376                        TransformBlock::ExcerptHeader { .. },
 377                        TransformBlock::ExcerptHeader { .. },
 378                    ) => Ordering::Equal,
 379                    (TransformBlock::ExcerptHeader { .. }, _) => Ordering::Less,
 380                    (_, TransformBlock::ExcerptHeader { .. }) => Ordering::Greater,
 381                    (TransformBlock::Custom(block_a), TransformBlock::Custom(block_b)) => block_a
 382                        .disposition
 383                        .cmp(&block_b.disposition)
 384                        .then_with(|| block_a.id.cmp(&block_b.id)),
 385                })
 386            });
 387
 388            // For each of these blocks, insert a new isomorphic transform preceding the block,
 389            // and then insert the block itself.
 390            for (block_row, block) in blocks_in_edit.drain(..) {
 391                let insertion_row = match block.disposition() {
 392                    BlockDisposition::Above => block_row,
 393                    BlockDisposition::Below => block_row + 1,
 394                };
 395                let extent_before_block = insertion_row - new_transforms.summary().input_rows;
 396                push_isomorphic(&mut new_transforms, extent_before_block);
 397                new_transforms.push(Transform::block(block), &());
 398            }
 399
 400            old_end = WrapRow(old_end.0.min(old_row_count));
 401            new_end = WrapRow(new_end.0.min(new_row_count));
 402
 403            // Insert an isomorphic transform after the final block.
 404            let extent_after_last_block = new_end.0 - new_transforms.summary().input_rows;
 405            push_isomorphic(&mut new_transforms, extent_after_last_block);
 406
 407            // Preserve any portion of the old transform after this edit.
 408            let extent_after_edit = cursor.start().0 - old_end.0;
 409            push_isomorphic(&mut new_transforms, extent_after_edit);
 410        }
 411
 412        new_transforms.push_tree(cursor.suffix(&()), &());
 413        debug_assert_eq!(
 414            new_transforms.summary().input_rows,
 415            wrap_snapshot.max_point().row() + 1
 416        );
 417
 418        drop(cursor);
 419        *transforms = new_transforms;
 420    }
 421
 422    pub fn replace(&mut self, mut renderers: HashMap<BlockId, RenderBlock>) {
 423        for block in &self.blocks {
 424            if let Some(render) = renderers.remove(&block.id) {
 425                *block.render.lock() = render;
 426            }
 427        }
 428    }
 429}
 430
 431fn push_isomorphic(tree: &mut SumTree<Transform>, rows: u32) {
 432    if rows == 0 {
 433        return;
 434    }
 435
 436    let mut extent = Some(rows);
 437    tree.update_last(
 438        |last_transform| {
 439            if last_transform.is_isomorphic() {
 440                let extent = extent.take().unwrap();
 441                last_transform.summary.input_rows += extent;
 442                last_transform.summary.output_rows += extent;
 443            }
 444        },
 445        &(),
 446    );
 447    if let Some(extent) = extent {
 448        tree.push(Transform::isomorphic(extent), &());
 449    }
 450}
 451
 452impl BlockPoint {
 453    pub fn new(row: u32, column: u32) -> Self {
 454        Self(Point::new(row, column))
 455    }
 456}
 457
 458impl Deref for BlockPoint {
 459    type Target = Point;
 460
 461    fn deref(&self) -> &Self::Target {
 462        &self.0
 463    }
 464}
 465
 466impl std::ops::DerefMut for BlockPoint {
 467    fn deref_mut(&mut self) -> &mut Self::Target {
 468        &mut self.0
 469    }
 470}
 471
 472impl<'a> BlockMapWriter<'a> {
 473    pub fn insert(
 474        &mut self,
 475        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
 476    ) -> Vec<BlockId> {
 477        let mut ids = Vec::new();
 478        let mut edits = Patch::default();
 479        let wrap_snapshot = &*self.0.wrap_snapshot.borrow();
 480        let buffer = wrap_snapshot.buffer_snapshot();
 481
 482        for block in blocks {
 483            let id = BlockId(self.0.next_block_id.fetch_add(1, SeqCst));
 484            ids.push(id);
 485
 486            let position = block.position;
 487            let point = position.to_point(&buffer);
 488            let wrap_row = wrap_snapshot
 489                .from_point(Point::new(point.row, 0), Bias::Left)
 490                .row();
 491            let start_row = wrap_snapshot.prev_row_boundary(WrapPoint::new(wrap_row, 0));
 492            let end_row = wrap_snapshot
 493                .next_row_boundary(WrapPoint::new(wrap_row, 0))
 494                .unwrap_or(wrap_snapshot.max_point().row() + 1);
 495
 496            let block_ix = match self
 497                .0
 498                .blocks
 499                .binary_search_by(|probe| probe.position.cmp(&position, &buffer).unwrap())
 500            {
 501                Ok(ix) | Err(ix) => ix,
 502            };
 503            self.0.blocks.insert(
 504                block_ix,
 505                Arc::new(Block {
 506                    id,
 507                    position,
 508                    height: block.height,
 509                    render: Mutex::new(block.render),
 510                    disposition: block.disposition,
 511                }),
 512            );
 513
 514            edits = edits.compose([Edit {
 515                old: start_row..end_row,
 516                new: start_row..end_row,
 517            }]);
 518        }
 519
 520        self.0.sync(wrap_snapshot, edits);
 521        ids
 522    }
 523
 524    pub fn remove(&mut self, block_ids: HashSet<BlockId>) {
 525        let wrap_snapshot = &*self.0.wrap_snapshot.borrow();
 526        let buffer = wrap_snapshot.buffer_snapshot();
 527        let mut edits = Patch::default();
 528        let mut last_block_buffer_row = None;
 529        self.0.blocks.retain(|block| {
 530            if block_ids.contains(&block.id) {
 531                let buffer_row = block.position.to_point(&buffer).row;
 532                if last_block_buffer_row != Some(buffer_row) {
 533                    last_block_buffer_row = Some(buffer_row);
 534                    let wrap_row = wrap_snapshot
 535                        .from_point(Point::new(buffer_row, 0), Bias::Left)
 536                        .row();
 537                    let start_row = wrap_snapshot.prev_row_boundary(WrapPoint::new(wrap_row, 0));
 538                    let end_row = wrap_snapshot
 539                        .next_row_boundary(WrapPoint::new(wrap_row, 0))
 540                        .unwrap_or(wrap_snapshot.max_point().row() + 1);
 541                    edits.push(Edit {
 542                        old: start_row..end_row,
 543                        new: start_row..end_row,
 544                    })
 545                }
 546                false
 547            } else {
 548                true
 549            }
 550        });
 551        self.0.sync(wrap_snapshot, edits);
 552    }
 553}
 554
 555impl BlockSnapshot {
 556    #[cfg(test)]
 557    pub fn text(&self) -> String {
 558        self.chunks(0..self.transforms.summary().output_rows, false)
 559            .map(|chunk| chunk.text)
 560            .collect()
 561    }
 562
 563    pub fn chunks<'a>(&'a self, rows: Range<u32>, language_aware: bool) -> BlockChunks<'a> {
 564        let max_output_row = cmp::min(rows.end, self.transforms.summary().output_rows);
 565        let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
 566        let input_end = {
 567            cursor.seek(&BlockRow(rows.end), Bias::Right, &());
 568            let overshoot = if cursor
 569                .item()
 570                .map_or(false, |transform| transform.is_isomorphic())
 571            {
 572                rows.end - cursor.start().0 .0
 573            } else {
 574                0
 575            };
 576            cursor.start().1 .0 + overshoot
 577        };
 578        let input_start = {
 579            cursor.seek(&BlockRow(rows.start), Bias::Right, &());
 580            let overshoot = if cursor
 581                .item()
 582                .map_or(false, |transform| transform.is_isomorphic())
 583            {
 584                rows.start - cursor.start().0 .0
 585            } else {
 586                0
 587            };
 588            cursor.start().1 .0 + overshoot
 589        };
 590        BlockChunks {
 591            input_chunks: self
 592                .wrap_snapshot
 593                .chunks(input_start..input_end, language_aware),
 594            input_chunk: Default::default(),
 595            transforms: cursor,
 596            output_row: rows.start,
 597            max_output_row,
 598        }
 599    }
 600
 601    pub fn buffer_rows<'a>(&'a self, start_row: u32) -> BlockBufferRows<'a> {
 602        let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
 603        cursor.seek(&BlockRow(start_row), Bias::Right, &());
 604        let (output_start, input_start) = cursor.start();
 605        let overshoot = if cursor.item().map_or(false, |t| t.is_isomorphic()) {
 606            start_row - output_start.0
 607        } else {
 608            0
 609        };
 610        let input_start_row = input_start.0 + overshoot;
 611        BlockBufferRows {
 612            transforms: cursor,
 613            input_buffer_rows: self.wrap_snapshot.buffer_rows(input_start_row),
 614            output_row: start_row,
 615            started: false,
 616        }
 617    }
 618
 619    pub fn blocks_in_range<'a>(
 620        &'a self,
 621        rows: Range<u32>,
 622    ) -> impl Iterator<Item = (u32, &'a TransformBlock)> {
 623        let mut cursor = self.transforms.cursor::<BlockRow>();
 624        cursor.seek(&BlockRow(rows.start), Bias::Right, &());
 625        std::iter::from_fn(move || {
 626            while let Some(transform) = cursor.item() {
 627                let start_row = cursor.start().0;
 628                if start_row >= rows.end {
 629                    break;
 630                }
 631                if let Some(block) = &transform.block {
 632                    cursor.next(&());
 633                    return Some((start_row, block));
 634                } else {
 635                    cursor.next(&());
 636                }
 637            }
 638            None
 639        })
 640    }
 641
 642    pub fn max_point(&self) -> BlockPoint {
 643        let row = self.transforms.summary().output_rows - 1;
 644        BlockPoint::new(row, self.line_len(row))
 645    }
 646
 647    pub fn longest_row(&self) -> u32 {
 648        let input_row = self.wrap_snapshot.longest_row();
 649        self.to_block_point(WrapPoint::new(input_row, 0)).row
 650    }
 651
 652    pub fn line_len(&self, row: u32) -> u32 {
 653        let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
 654        cursor.seek(&BlockRow(row), Bias::Right, &());
 655        if let Some(transform) = cursor.item() {
 656            let (output_start, input_start) = cursor.start();
 657            let overshoot = row - output_start.0;
 658            if transform.block.is_some() {
 659                0
 660            } else {
 661                self.wrap_snapshot.line_len(input_start.0 + overshoot)
 662            }
 663        } else {
 664            panic!("row out of range");
 665        }
 666    }
 667
 668    pub fn is_block_line(&self, row: u32) -> bool {
 669        let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
 670        cursor.seek(&BlockRow(row), Bias::Right, &());
 671        cursor.item().map_or(false, |t| t.block.is_some())
 672    }
 673
 674    pub fn clip_point(&self, point: BlockPoint, bias: Bias) -> BlockPoint {
 675        let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
 676        cursor.seek(&BlockRow(point.row), Bias::Right, &());
 677
 678        let max_input_row = WrapRow(self.transforms.summary().input_rows);
 679        let mut search_left =
 680            (bias == Bias::Left && cursor.start().1 .0 > 0) || cursor.end(&()).1 == max_input_row;
 681        let mut reversed = false;
 682
 683        loop {
 684            if let Some(transform) = cursor.item() {
 685                if transform.is_isomorphic() {
 686                    let (output_start_row, input_start_row) = cursor.start();
 687                    let (output_end_row, input_end_row) = cursor.end(&());
 688                    let output_start = Point::new(output_start_row.0, 0);
 689                    let input_start = Point::new(input_start_row.0, 0);
 690                    let input_end = Point::new(input_end_row.0, 0);
 691                    let input_point = if point.row >= output_end_row.0 {
 692                        let line_len = self.wrap_snapshot.line_len(input_end_row.0 - 1);
 693                        self.wrap_snapshot
 694                            .clip_point(WrapPoint::new(input_end_row.0 - 1, line_len), bias)
 695                    } else {
 696                        let output_overshoot = point.0.saturating_sub(output_start);
 697                        self.wrap_snapshot
 698                            .clip_point(WrapPoint(input_start + output_overshoot), bias)
 699                    };
 700
 701                    if (input_start..input_end).contains(&input_point.0) {
 702                        let input_overshoot = input_point.0.saturating_sub(input_start);
 703                        return BlockPoint(output_start + input_overshoot);
 704                    }
 705                }
 706
 707                if search_left {
 708                    cursor.prev(&());
 709                } else {
 710                    cursor.next(&());
 711                }
 712            } else if reversed {
 713                return self.max_point();
 714            } else {
 715                reversed = true;
 716                search_left = !search_left;
 717                cursor.seek(&BlockRow(point.row), Bias::Right, &());
 718            }
 719        }
 720    }
 721
 722    pub fn to_block_point(&self, wrap_point: WrapPoint) -> BlockPoint {
 723        let mut cursor = self.transforms.cursor::<(WrapRow, BlockRow)>();
 724        cursor.seek(&WrapRow(wrap_point.row()), Bias::Right, &());
 725        if let Some(transform) = cursor.item() {
 726            debug_assert!(transform.is_isomorphic());
 727        } else {
 728            return self.max_point();
 729        }
 730
 731        let (input_start_row, output_start_row) = cursor.start();
 732        let input_start = Point::new(input_start_row.0, 0);
 733        let output_start = Point::new(output_start_row.0, 0);
 734        let input_overshoot = wrap_point.0 - input_start;
 735        BlockPoint(output_start + input_overshoot)
 736    }
 737
 738    pub fn to_wrap_point(&self, block_point: BlockPoint) -> WrapPoint {
 739        let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
 740        cursor.seek(&BlockRow(block_point.row), Bias::Right, &());
 741        if let Some(transform) = cursor.item() {
 742            match transform.block.as_ref().map(|b| b.disposition()) {
 743                Some(BlockDisposition::Above) => WrapPoint::new(cursor.start().1 .0, 0),
 744                Some(BlockDisposition::Below) => {
 745                    let wrap_row = cursor.start().1 .0 - 1;
 746                    WrapPoint::new(wrap_row, self.wrap_snapshot.line_len(wrap_row))
 747                }
 748                None => {
 749                    let overshoot = block_point.row - cursor.start().0 .0;
 750                    let wrap_row = cursor.start().1 .0 + overshoot;
 751                    WrapPoint::new(wrap_row, block_point.column)
 752                }
 753            }
 754        } else {
 755            self.wrap_snapshot.max_point()
 756        }
 757    }
 758}
 759
 760impl Transform {
 761    fn isomorphic(rows: u32) -> Self {
 762        Self {
 763            summary: TransformSummary {
 764                input_rows: rows,
 765                output_rows: rows,
 766            },
 767            block: None,
 768        }
 769    }
 770
 771    fn block(block: TransformBlock) -> Self {
 772        Self {
 773            summary: TransformSummary {
 774                input_rows: 0,
 775                output_rows: block.height() as u32,
 776            },
 777            block: Some(block),
 778        }
 779    }
 780
 781    fn is_isomorphic(&self) -> bool {
 782        self.block.is_none()
 783    }
 784}
 785
 786impl<'a> Iterator for BlockChunks<'a> {
 787    type Item = Chunk<'a>;
 788
 789    fn next(&mut self) -> Option<Self::Item> {
 790        if self.output_row >= self.max_output_row {
 791            return None;
 792        }
 793
 794        let transform = self.transforms.item()?;
 795        if transform.block.is_some() {
 796            let block_start = self.transforms.start().0 .0;
 797            let mut block_end = self.transforms.end(&()).0 .0;
 798            self.transforms.next(&());
 799            if self.transforms.item().is_none() {
 800                block_end -= 1;
 801            }
 802
 803            let start_in_block = self.output_row - block_start;
 804            let end_in_block = cmp::min(self.max_output_row, block_end) - block_start;
 805            let line_count = end_in_block - start_in_block;
 806            self.output_row += line_count;
 807
 808            return Some(Chunk {
 809                text: unsafe { std::str::from_utf8_unchecked(&NEWLINES[..line_count as usize]) },
 810                highlight_id: None,
 811                diagnostic: None,
 812            });
 813        }
 814
 815        if self.input_chunk.text.is_empty() {
 816            if let Some(input_chunk) = self.input_chunks.next() {
 817                self.input_chunk = input_chunk;
 818            } else {
 819                self.output_row += 1;
 820                if self.output_row < self.max_output_row {
 821                    self.transforms.next(&());
 822                    return Some(Chunk {
 823                        text: "\n",
 824                        ..Default::default()
 825                    });
 826                } else {
 827                    return None;
 828                }
 829            }
 830        }
 831
 832        let transform_end = self.transforms.end(&()).0 .0;
 833        let (prefix_rows, prefix_bytes) =
 834            offset_for_row(self.input_chunk.text, transform_end - self.output_row);
 835        self.output_row += prefix_rows;
 836        let (prefix, suffix) = self.input_chunk.text.split_at(prefix_bytes);
 837        self.input_chunk.text = suffix;
 838        if self.output_row == transform_end {
 839            self.transforms.next(&());
 840        }
 841
 842        Some(Chunk {
 843            text: prefix,
 844            ..self.input_chunk
 845        })
 846    }
 847}
 848
 849impl<'a> Iterator for BlockBufferRows<'a> {
 850    type Item = Option<u32>;
 851
 852    fn next(&mut self) -> Option<Self::Item> {
 853        if self.started {
 854            self.output_row += 1;
 855        } else {
 856            self.started = true;
 857        }
 858
 859        if self.output_row >= self.transforms.end(&()).0 .0 {
 860            self.transforms.next(&());
 861        }
 862
 863        let transform = self.transforms.item()?;
 864        if transform.block.is_some() {
 865            Some(None)
 866        } else {
 867            Some(self.input_buffer_rows.next().unwrap())
 868        }
 869    }
 870}
 871
 872impl sum_tree::Item for Transform {
 873    type Summary = TransformSummary;
 874
 875    fn summary(&self) -> Self::Summary {
 876        self.summary.clone()
 877    }
 878}
 879
 880impl sum_tree::Summary for TransformSummary {
 881    type Context = ();
 882
 883    fn add_summary(&mut self, summary: &Self, _: &()) {
 884        self.input_rows += summary.input_rows;
 885        self.output_rows += summary.output_rows;
 886    }
 887}
 888
 889impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapRow {
 890    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 891        self.0 += summary.input_rows;
 892    }
 893}
 894
 895impl<'a> sum_tree::Dimension<'a, TransformSummary> for BlockRow {
 896    fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
 897        self.0 += summary.output_rows;
 898    }
 899}
 900
 901impl BlockDisposition {
 902    fn is_below(&self) -> bool {
 903        matches!(self, BlockDisposition::Below)
 904    }
 905}
 906
 907impl<'a> Deref for BlockContext<'a> {
 908    type Target = AppContext;
 909
 910    fn deref(&self) -> &Self::Target {
 911        &self.cx
 912    }
 913}
 914
 915impl Block {
 916    pub fn render(&self, cx: &BlockContext) -> ElementBox {
 917        self.render.lock()(cx)
 918    }
 919
 920    pub fn position(&self) -> &Anchor {
 921        &self.position
 922    }
 923}
 924
 925impl Debug for Block {
 926    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 927        f.debug_struct("Block")
 928            .field("id", &self.id)
 929            .field("position", &self.position)
 930            .field("disposition", &self.disposition)
 931            .finish()
 932    }
 933}
 934
 935// Count the number of bytes prior to a target point. If the string doesn't contain the target
 936// point, return its total extent. Otherwise return the target point itself.
 937fn offset_for_row(s: &str, target: u32) -> (u32, usize) {
 938    let mut row = 0;
 939    let mut offset = 0;
 940    for (ix, line) in s.split('\n').enumerate() {
 941        if ix > 0 {
 942            row += 1;
 943            offset += 1;
 944        }
 945        if row >= target {
 946            break;
 947        }
 948        offset += line.len() as usize;
 949    }
 950    (row, offset)
 951}
 952
 953#[cfg(test)]
 954mod tests {
 955    use super::*;
 956    use crate::display_map::{fold_map::FoldMap, tab_map::TabMap, wrap_map::WrapMap};
 957    use crate::multi_buffer::MultiBuffer;
 958    use gpui::{elements::Empty, Element};
 959    use rand::prelude::*;
 960    use std::env;
 961    use text::RandomCharIter;
 962
 963    #[gpui::test]
 964    fn test_offset_for_row() {
 965        assert_eq!(offset_for_row("", 0), (0, 0));
 966        assert_eq!(offset_for_row("", 1), (0, 0));
 967        assert_eq!(offset_for_row("abcd", 0), (0, 0));
 968        assert_eq!(offset_for_row("abcd", 1), (0, 4));
 969        assert_eq!(offset_for_row("\n", 0), (0, 0));
 970        assert_eq!(offset_for_row("\n", 1), (1, 1));
 971        assert_eq!(offset_for_row("abc\ndef\nghi", 0), (0, 0));
 972        assert_eq!(offset_for_row("abc\ndef\nghi", 1), (1, 4));
 973        assert_eq!(offset_for_row("abc\ndef\nghi", 2), (2, 8));
 974        assert_eq!(offset_for_row("abc\ndef\nghi", 3), (2, 11));
 975    }
 976
 977    #[gpui::test]
 978    fn test_basic_blocks(cx: &mut gpui::MutableAppContext) {
 979        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
 980        let font_id = cx
 981            .font_cache()
 982            .select_font(family_id, &Default::default())
 983            .unwrap();
 984
 985        let text = "aaa\nbbb\nccc\nddd";
 986
 987        let buffer = MultiBuffer::build_simple(text, cx);
 988        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 989        let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
 990        let (fold_map, folds_snapshot) = FoldMap::new(buffer_snapshot.clone());
 991        let (tab_map, tabs_snapshot) = TabMap::new(folds_snapshot.clone(), 1);
 992        let (wrap_map, wraps_snapshot) = WrapMap::new(tabs_snapshot, font_id, 14.0, None, cx);
 993        let mut block_map = BlockMap::new(wraps_snapshot.clone(), 1, 1);
 994
 995        let mut writer = block_map.write(wraps_snapshot.clone(), Default::default());
 996        writer.insert(vec![
 997            BlockProperties {
 998                position: buffer_snapshot.anchor_after(Point::new(1, 0)),
 999                height: 1,
1000                disposition: BlockDisposition::Above,
1001                render: Arc::new(|_| Empty::new().named("block 1")),
1002            },
1003            BlockProperties {
1004                position: buffer_snapshot.anchor_after(Point::new(1, 2)),
1005                height: 2,
1006                disposition: BlockDisposition::Above,
1007                render: Arc::new(|_| Empty::new().named("block 2")),
1008            },
1009            BlockProperties {
1010                position: buffer_snapshot.anchor_after(Point::new(3, 3)),
1011                height: 3,
1012                disposition: BlockDisposition::Below,
1013                render: Arc::new(|_| Empty::new().named("block 3")),
1014            },
1015        ]);
1016
1017        let snapshot = block_map.read(wraps_snapshot, Default::default());
1018        assert_eq!(snapshot.text(), "aaa\n\n\n\nbbb\nccc\nddd\n\n\n");
1019
1020        let blocks = snapshot
1021            .blocks_in_range(0..8)
1022            .map(|(start_row, block)| {
1023                let block = block.as_custom().unwrap();
1024                (
1025                    start_row..start_row + block.height as u32,
1026                    block
1027                        .render(&BlockContext {
1028                            cx,
1029                            anchor_x: 0.,
1030                            gutter_padding: 0.,
1031                            scroll_x: 0.,
1032                            gutter_width: 0.,
1033                            line_height: 0.,
1034                            em_width: 0.,
1035                        })
1036                        .name()
1037                        .unwrap()
1038                        .to_string(),
1039                )
1040            })
1041            .collect::<Vec<_>>();
1042
1043        // When multiple blocks are on the same line, the newer blocks appear first.
1044        assert_eq!(
1045            blocks,
1046            &[
1047                (1..2, "block 1".to_string()),
1048                (2..4, "block 2".to_string()),
1049                (7..10, "block 3".to_string()),
1050            ]
1051        );
1052
1053        assert_eq!(
1054            snapshot.to_block_point(WrapPoint::new(0, 3)),
1055            BlockPoint::new(0, 3)
1056        );
1057        assert_eq!(
1058            snapshot.to_block_point(WrapPoint::new(1, 0)),
1059            BlockPoint::new(4, 0)
1060        );
1061        assert_eq!(
1062            snapshot.to_block_point(WrapPoint::new(3, 3)),
1063            BlockPoint::new(6, 3)
1064        );
1065
1066        assert_eq!(
1067            snapshot.to_wrap_point(BlockPoint::new(0, 3)),
1068            WrapPoint::new(0, 3)
1069        );
1070        assert_eq!(
1071            snapshot.to_wrap_point(BlockPoint::new(1, 0)),
1072            WrapPoint::new(1, 0)
1073        );
1074        assert_eq!(
1075            snapshot.to_wrap_point(BlockPoint::new(3, 0)),
1076            WrapPoint::new(1, 0)
1077        );
1078        assert_eq!(
1079            snapshot.to_wrap_point(BlockPoint::new(7, 0)),
1080            WrapPoint::new(3, 3)
1081        );
1082
1083        assert_eq!(
1084            snapshot.clip_point(BlockPoint::new(1, 0), Bias::Left),
1085            BlockPoint::new(0, 3)
1086        );
1087        assert_eq!(
1088            snapshot.clip_point(BlockPoint::new(1, 0), Bias::Right),
1089            BlockPoint::new(4, 0)
1090        );
1091        assert_eq!(
1092            snapshot.clip_point(BlockPoint::new(1, 1), Bias::Left),
1093            BlockPoint::new(0, 3)
1094        );
1095        assert_eq!(
1096            snapshot.clip_point(BlockPoint::new(1, 1), Bias::Right),
1097            BlockPoint::new(4, 0)
1098        );
1099        assert_eq!(
1100            snapshot.clip_point(BlockPoint::new(4, 0), Bias::Left),
1101            BlockPoint::new(4, 0)
1102        );
1103        assert_eq!(
1104            snapshot.clip_point(BlockPoint::new(4, 0), Bias::Right),
1105            BlockPoint::new(4, 0)
1106        );
1107        assert_eq!(
1108            snapshot.clip_point(BlockPoint::new(6, 3), Bias::Left),
1109            BlockPoint::new(6, 3)
1110        );
1111        assert_eq!(
1112            snapshot.clip_point(BlockPoint::new(6, 3), Bias::Right),
1113            BlockPoint::new(6, 3)
1114        );
1115        assert_eq!(
1116            snapshot.clip_point(BlockPoint::new(7, 0), Bias::Left),
1117            BlockPoint::new(6, 3)
1118        );
1119        assert_eq!(
1120            snapshot.clip_point(BlockPoint::new(7, 0), Bias::Right),
1121            BlockPoint::new(6, 3)
1122        );
1123
1124        assert_eq!(
1125            snapshot.buffer_rows(0).collect::<Vec<_>>(),
1126            &[
1127                Some(0),
1128                None,
1129                None,
1130                None,
1131                Some(1),
1132                Some(2),
1133                Some(3),
1134                None,
1135                None,
1136                None
1137            ]
1138        );
1139
1140        // Insert a line break, separating two block decorations into separate lines.
1141        let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1142            buffer.edit([Point::new(1, 1)..Point::new(1, 1)], "!!!\n", cx);
1143            buffer.snapshot(cx)
1144        });
1145
1146        let (folds_snapshot, fold_edits) =
1147            fold_map.read(buffer_snapshot, subscription.consume().into_inner());
1148        let (tabs_snapshot, tab_edits) = tab_map.sync(folds_snapshot, fold_edits);
1149        let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
1150            wrap_map.sync(tabs_snapshot, tab_edits, cx)
1151        });
1152        let snapshot = block_map.read(wraps_snapshot, wrap_edits);
1153        assert_eq!(snapshot.text(), "aaa\n\nb!!!\n\n\nbb\nccc\nddd\n\n\n");
1154    }
1155
1156    #[gpui::test]
1157    fn test_blocks_on_wrapped_lines(cx: &mut gpui::MutableAppContext) {
1158        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
1159        let font_id = cx
1160            .font_cache()
1161            .select_font(family_id, &Default::default())
1162            .unwrap();
1163
1164        let text = "one two three\nfour five six\nseven eight";
1165
1166        let buffer = MultiBuffer::build_simple(text, cx);
1167        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1168        let (_, folds_snapshot) = FoldMap::new(buffer_snapshot.clone());
1169        let (_, tabs_snapshot) = TabMap::new(folds_snapshot.clone(), 1);
1170        let (_, wraps_snapshot) = WrapMap::new(tabs_snapshot, font_id, 14.0, Some(60.), cx);
1171        let mut block_map = BlockMap::new(wraps_snapshot.clone(), 1, 1);
1172
1173        let mut writer = block_map.write(wraps_snapshot.clone(), Default::default());
1174        writer.insert(vec![
1175            BlockProperties {
1176                position: buffer_snapshot.anchor_after(Point::new(1, 12)),
1177                disposition: BlockDisposition::Above,
1178                render: Arc::new(|_| Empty::new().named("block 1")),
1179                height: 1,
1180            },
1181            BlockProperties {
1182                position: buffer_snapshot.anchor_after(Point::new(1, 1)),
1183                disposition: BlockDisposition::Below,
1184                render: Arc::new(|_| Empty::new().named("block 2")),
1185                height: 1,
1186            },
1187        ]);
1188
1189        // Blocks with an 'above' disposition go above their corresponding buffer line.
1190        // Blocks with a 'below' disposition go below their corresponding buffer line.
1191        let snapshot = block_map.read(wraps_snapshot, Default::default());
1192        assert_eq!(
1193            snapshot.text(),
1194            "one two \nthree\n\nfour five \nsix\n\nseven \neight"
1195        );
1196    }
1197
1198    #[gpui::test(iterations = 100)]
1199    fn test_random_blocks(cx: &mut gpui::MutableAppContext, mut rng: StdRng) {
1200        let operations = env::var("OPERATIONS")
1201            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1202            .unwrap_or(10);
1203
1204        let wrap_width = if rng.gen_bool(0.2) {
1205            None
1206        } else {
1207            Some(rng.gen_range(0.0..=100.0))
1208        };
1209        let tab_size = 1;
1210        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
1211        let font_id = cx
1212            .font_cache()
1213            .select_font(family_id, &Default::default())
1214            .unwrap();
1215        let font_size = 14.0;
1216        let buffer_start_header_height = rng.gen_range(1..=5);
1217        let excerpt_header_height = rng.gen_range(1..=5);
1218
1219        log::info!("Wrap width: {:?}", wrap_width);
1220        log::info!("Excerpt Header Height: {:?}", excerpt_header_height);
1221
1222        let buffer = if rng.gen() {
1223            let len = rng.gen_range(0..10);
1224            let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1225            log::info!("initial buffer text: {:?}", text);
1226            MultiBuffer::build_simple(&text, cx)
1227        } else {
1228            MultiBuffer::build_random(&mut rng, cx)
1229        };
1230
1231        let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
1232        let (fold_map, folds_snapshot) = FoldMap::new(buffer_snapshot.clone());
1233        let (tab_map, tabs_snapshot) = TabMap::new(folds_snapshot.clone(), tab_size);
1234        let (wrap_map, wraps_snapshot) =
1235            WrapMap::new(tabs_snapshot, font_id, font_size, wrap_width, cx);
1236        let mut block_map = BlockMap::new(
1237            wraps_snapshot.clone(),
1238            buffer_start_header_height,
1239            excerpt_header_height,
1240        );
1241        let mut custom_blocks = Vec::new();
1242
1243        for _ in 0..operations {
1244            let mut buffer_edits = Vec::new();
1245            match rng.gen_range(0..=100) {
1246                0..=19 => {
1247                    let wrap_width = if rng.gen_bool(0.2) {
1248                        None
1249                    } else {
1250                        Some(rng.gen_range(0.0..=100.0))
1251                    };
1252                    log::info!("Setting wrap width to {:?}", wrap_width);
1253                    wrap_map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1254                }
1255                20..=39 => {
1256                    let block_count = rng.gen_range(1..=5);
1257                    let block_properties = (0..block_count)
1258                        .map(|_| {
1259                            let buffer = buffer.read(cx).read(cx);
1260                            let position = buffer.anchor_after(
1261                                buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Left),
1262                            );
1263
1264                            let disposition = if rng.gen() {
1265                                BlockDisposition::Above
1266                            } else {
1267                                BlockDisposition::Below
1268                            };
1269                            let height = rng.gen_range(1..5);
1270                            log::info!(
1271                                "inserting block {:?} {:?} with height {}",
1272                                disposition,
1273                                position.to_point(&buffer),
1274                                height
1275                            );
1276                            BlockProperties {
1277                                position,
1278                                height,
1279                                disposition,
1280                                render: Arc::new(|_| Empty::new().boxed()),
1281                            }
1282                        })
1283                        .collect::<Vec<_>>();
1284
1285                    let (folds_snapshot, fold_edits) =
1286                        fold_map.read(buffer_snapshot.clone(), vec![]);
1287                    let (tabs_snapshot, tab_edits) = tab_map.sync(folds_snapshot, fold_edits);
1288                    let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
1289                        wrap_map.sync(tabs_snapshot, tab_edits, cx)
1290                    });
1291                    let mut block_map = block_map.write(wraps_snapshot, wrap_edits);
1292                    let block_ids = block_map.insert(block_properties.clone());
1293                    for (block_id, props) in block_ids.into_iter().zip(block_properties) {
1294                        custom_blocks.push((block_id, props));
1295                    }
1296                }
1297                40..=59 if !custom_blocks.is_empty() => {
1298                    let block_count = rng.gen_range(1..=4.min(custom_blocks.len()));
1299                    let block_ids_to_remove = (0..block_count)
1300                        .map(|_| {
1301                            custom_blocks
1302                                .remove(rng.gen_range(0..custom_blocks.len()))
1303                                .0
1304                        })
1305                        .collect();
1306
1307                    let (folds_snapshot, fold_edits) =
1308                        fold_map.read(buffer_snapshot.clone(), vec![]);
1309                    let (tabs_snapshot, tab_edits) = tab_map.sync(folds_snapshot, fold_edits);
1310                    let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
1311                        wrap_map.sync(tabs_snapshot, tab_edits, cx)
1312                    });
1313                    let mut block_map = block_map.write(wraps_snapshot, wrap_edits);
1314                    block_map.remove(block_ids_to_remove);
1315                }
1316                _ => {
1317                    buffer.update(cx, |buffer, cx| {
1318                        let mutation_count = rng.gen_range(1..=5);
1319                        let subscription = buffer.subscribe();
1320                        buffer.randomly_mutate(&mut rng, mutation_count, cx);
1321                        buffer_snapshot = buffer.snapshot(cx);
1322                        buffer_edits.extend(subscription.consume());
1323                        log::info!("buffer text: {:?}", buffer_snapshot.text());
1324                    });
1325                }
1326            }
1327
1328            let (folds_snapshot, fold_edits) = fold_map.read(buffer_snapshot.clone(), buffer_edits);
1329            let (tabs_snapshot, tab_edits) = tab_map.sync(folds_snapshot, fold_edits);
1330            let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
1331                wrap_map.sync(tabs_snapshot, tab_edits, cx)
1332            });
1333            let blocks_snapshot = block_map.read(wraps_snapshot.clone(), wrap_edits);
1334            assert_eq!(
1335                blocks_snapshot.transforms.summary().input_rows,
1336                wraps_snapshot.max_point().row() + 1
1337            );
1338            log::info!("blocks text: {:?}", blocks_snapshot.text());
1339
1340            let mut expected_blocks = Vec::new();
1341            expected_blocks.extend(custom_blocks.iter().map(|(id, block)| {
1342                let mut position = block.position.to_point(&buffer_snapshot);
1343                match block.disposition {
1344                    BlockDisposition::Above => {
1345                        position.column = 0;
1346                    }
1347                    BlockDisposition::Below => {
1348                        position.column = buffer_snapshot.line_len(position.row);
1349                    }
1350                };
1351                let row = wraps_snapshot.from_point(position, Bias::Left).row();
1352                (
1353                    row,
1354                    ExpectedBlock::Custom {
1355                        disposition: block.disposition,
1356                        id: *id,
1357                        height: block.height,
1358                    },
1359                )
1360            }));
1361            expected_blocks.extend(buffer_snapshot.excerpt_boundaries_in_range(0..).map(
1362                |boundary| {
1363                    let position =
1364                        wraps_snapshot.from_point(Point::new(boundary.row, 0), Bias::Left);
1365                    (
1366                        position.row(),
1367                        ExpectedBlock::ExcerptHeader {
1368                            height: if boundary.starts_new_buffer {
1369                                buffer_start_header_height
1370                            } else {
1371                                excerpt_header_height
1372                            },
1373                            starts_new_buffer: boundary.starts_new_buffer,
1374                        },
1375                    )
1376                },
1377            ));
1378            expected_blocks.sort_unstable();
1379            let mut sorted_blocks_iter = expected_blocks.into_iter().peekable();
1380
1381            let input_buffer_rows = buffer_snapshot.buffer_rows(0).collect::<Vec<_>>();
1382            let mut expected_buffer_rows = Vec::new();
1383            let mut expected_text = String::new();
1384            let mut expected_block_positions = Vec::new();
1385            let input_text = wraps_snapshot.text();
1386            for (row, input_line) in input_text.split('\n').enumerate() {
1387                let row = row as u32;
1388                if row > 0 {
1389                    expected_text.push('\n');
1390                }
1391
1392                let buffer_row = input_buffer_rows[wraps_snapshot
1393                    .to_point(WrapPoint::new(row, 0), Bias::Left)
1394                    .row as usize];
1395
1396                while let Some((block_row, block)) = sorted_blocks_iter.peek() {
1397                    if *block_row == row && block.disposition() == BlockDisposition::Above {
1398                        let (_, block) = sorted_blocks_iter.next().unwrap();
1399                        let height = block.height() as usize;
1400                        expected_block_positions
1401                            .push((expected_text.matches('\n').count() as u32, block));
1402                        let text = "\n".repeat(height);
1403                        expected_text.push_str(&text);
1404                        for _ in 0..height {
1405                            expected_buffer_rows.push(None);
1406                        }
1407                    } else {
1408                        break;
1409                    }
1410                }
1411
1412                let soft_wrapped = wraps_snapshot.to_tab_point(WrapPoint::new(row, 0)).column() > 0;
1413                expected_buffer_rows.push(if soft_wrapped { None } else { buffer_row });
1414                expected_text.push_str(input_line);
1415
1416                while let Some((block_row, block)) = sorted_blocks_iter.peek() {
1417                    if *block_row == row && block.disposition() == BlockDisposition::Below {
1418                        let (_, block) = sorted_blocks_iter.next().unwrap();
1419                        let height = block.height() as usize;
1420                        expected_block_positions
1421                            .push((expected_text.matches('\n').count() as u32 + 1, block));
1422                        let text = "\n".repeat(height);
1423                        expected_text.push_str(&text);
1424                        for _ in 0..height {
1425                            expected_buffer_rows.push(None);
1426                        }
1427                    } else {
1428                        break;
1429                    }
1430                }
1431            }
1432
1433            let expected_lines = expected_text.split('\n').collect::<Vec<_>>();
1434            let expected_row_count = expected_lines.len();
1435            for start_row in 0..expected_row_count {
1436                let expected_text = expected_lines[start_row..].join("\n");
1437                let actual_text = blocks_snapshot
1438                    .chunks(start_row as u32..blocks_snapshot.max_point().row + 1, false)
1439                    .map(|chunk| chunk.text)
1440                    .collect::<String>();
1441                assert_eq!(
1442                    actual_text, expected_text,
1443                    "incorrect text starting from row {}",
1444                    start_row
1445                );
1446                assert_eq!(
1447                    blocks_snapshot
1448                        .buffer_rows(start_row as u32)
1449                        .collect::<Vec<_>>(),
1450                    &expected_buffer_rows[start_row..]
1451                );
1452            }
1453
1454            assert_eq!(
1455                blocks_snapshot
1456                    .blocks_in_range(0..(expected_row_count as u32))
1457                    .map(|(row, block)| (row, block.clone().into()))
1458                    .collect::<Vec<_>>(),
1459                expected_block_positions
1460            );
1461
1462            let mut expected_longest_rows = Vec::new();
1463            let mut longest_line_len = -1_isize;
1464            for (row, line) in expected_lines.iter().enumerate() {
1465                let row = row as u32;
1466
1467                assert_eq!(
1468                    blocks_snapshot.line_len(row),
1469                    line.len() as u32,
1470                    "invalid line len for row {}",
1471                    row
1472                );
1473
1474                let line_char_count = line.chars().count() as isize;
1475                match line_char_count.cmp(&longest_line_len) {
1476                    Ordering::Less => {}
1477                    Ordering::Equal => expected_longest_rows.push(row),
1478                    Ordering::Greater => {
1479                        longest_line_len = line_char_count;
1480                        expected_longest_rows.clear();
1481                        expected_longest_rows.push(row);
1482                    }
1483                }
1484            }
1485
1486            let longest_row = blocks_snapshot.longest_row();
1487            assert!(
1488                expected_longest_rows.contains(&longest_row),
1489                "incorrect longest row {}. expected {:?} with length {}",
1490                longest_row,
1491                expected_longest_rows,
1492                longest_line_len,
1493            );
1494
1495            for row in 0..=blocks_snapshot.wrap_snapshot.max_point().row() {
1496                let wrap_point = WrapPoint::new(row, 0);
1497                let block_point = blocks_snapshot.to_block_point(wrap_point);
1498                assert_eq!(blocks_snapshot.to_wrap_point(block_point), wrap_point);
1499            }
1500
1501            let mut block_point = BlockPoint::new(0, 0);
1502            for c in expected_text.chars() {
1503                let left_point = blocks_snapshot.clip_point(block_point, Bias::Left);
1504                let left_buffer_point = blocks_snapshot.to_point(left_point, Bias::Left);
1505                assert_eq!(
1506                    blocks_snapshot.to_block_point(blocks_snapshot.to_wrap_point(left_point)),
1507                    left_point
1508                );
1509                assert_eq!(
1510                    left_buffer_point,
1511                    buffer_snapshot.clip_point(left_buffer_point, Bias::Right),
1512                    "{:?} is not valid in buffer coordinates",
1513                    left_point
1514                );
1515
1516                let right_point = blocks_snapshot.clip_point(block_point, Bias::Right);
1517                let right_buffer_point = blocks_snapshot.to_point(right_point, Bias::Right);
1518                assert_eq!(
1519                    blocks_snapshot.to_block_point(blocks_snapshot.to_wrap_point(right_point)),
1520                    right_point
1521                );
1522                assert_eq!(
1523                    right_buffer_point,
1524                    buffer_snapshot.clip_point(right_buffer_point, Bias::Left),
1525                    "{:?} is not valid in buffer coordinates",
1526                    right_point
1527                );
1528
1529                if c == '\n' {
1530                    block_point.0 += Point::new(1, 0);
1531                } else {
1532                    block_point.column += c.len_utf8() as u32;
1533                }
1534            }
1535        }
1536
1537        #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
1538        enum ExpectedBlock {
1539            ExcerptHeader {
1540                height: u8,
1541                starts_new_buffer: bool,
1542            },
1543            Custom {
1544                disposition: BlockDisposition,
1545                id: BlockId,
1546                height: u8,
1547            },
1548        }
1549
1550        impl ExpectedBlock {
1551            fn height(&self) -> u8 {
1552                match self {
1553                    ExpectedBlock::ExcerptHeader { height, .. } => *height,
1554                    ExpectedBlock::Custom { height, .. } => *height,
1555                }
1556            }
1557
1558            fn disposition(&self) -> BlockDisposition {
1559                match self {
1560                    ExpectedBlock::ExcerptHeader { .. } => BlockDisposition::Above,
1561                    ExpectedBlock::Custom { disposition, .. } => *disposition,
1562                }
1563            }
1564        }
1565
1566        impl From<TransformBlock> for ExpectedBlock {
1567            fn from(block: TransformBlock) -> Self {
1568                match block {
1569                    TransformBlock::Custom(block) => ExpectedBlock::Custom {
1570                        id: block.id,
1571                        disposition: block.disposition,
1572                        height: block.height,
1573                    },
1574                    TransformBlock::ExcerptHeader {
1575                        height,
1576                        starts_new_buffer,
1577                        ..
1578                    } => ExpectedBlock::ExcerptHeader {
1579                        height,
1580                        starts_new_buffer,
1581                    },
1582                }
1583            }
1584        }
1585    }
1586
1587    impl TransformBlock {
1588        fn as_custom(&self) -> Option<&Block> {
1589            match self {
1590                TransformBlock::Custom(block) => Some(block),
1591                TransformBlock::ExcerptHeader { .. } => None,
1592            }
1593        }
1594    }
1595
1596    impl BlockSnapshot {
1597        fn to_point(&self, point: BlockPoint, bias: Bias) -> Point {
1598            self.wrap_snapshot.to_point(self.to_wrap_point(point), bias)
1599        }
1600    }
1601}