block_map.rs

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