block_map.rs

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