display_map.rs

   1mod block_map;
   2mod fold_map;
   3mod tab_map;
   4mod wrap_map;
   5
   6use crate::{
   7    multi_buffer::RenderHeaderFn, Anchor, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint,
   8};
   9use block_map::{BlockMap, BlockPoint};
  10use fold_map::{FoldMap, ToFoldPoint as _};
  11use gpui::{fonts::FontId, Entity, ModelContext, ModelHandle};
  12use language::{Point, Subscription as BufferSubscription};
  13use std::{
  14    collections::{HashMap, HashSet},
  15    ops::Range,
  16};
  17use sum_tree::Bias;
  18use tab_map::TabMap;
  19use theme::SyntaxTheme;
  20use wrap_map::WrapMap;
  21
  22pub use block_map::{
  23    AlignedBlock, BlockBufferRows as DisplayBufferRows, BlockChunks as DisplayChunks, BlockContext,
  24    BlockDisposition, BlockId, BlockProperties, RenderBlock,
  25};
  26
  27pub trait ToDisplayPoint {
  28    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint;
  29}
  30
  31pub struct DisplayMap {
  32    buffer: ModelHandle<MultiBuffer>,
  33    buffer_subscription: BufferSubscription,
  34    fold_map: FoldMap,
  35    tab_map: TabMap,
  36    wrap_map: ModelHandle<WrapMap>,
  37    block_map: BlockMap,
  38}
  39
  40impl Entity for DisplayMap {
  41    type Event = ();
  42}
  43
  44impl DisplayMap {
  45    pub fn new(
  46        buffer: ModelHandle<MultiBuffer>,
  47        tab_size: usize,
  48        font_id: FontId,
  49        font_size: f32,
  50        wrap_width: Option<f32>,
  51        cx: &mut ModelContext<Self>,
  52    ) -> Self {
  53        let buffer_subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
  54        let (fold_map, snapshot) = FoldMap::new(buffer.read(cx).snapshot(cx));
  55        let (tab_map, snapshot) = TabMap::new(snapshot, tab_size);
  56        let (wrap_map, snapshot) = WrapMap::new(snapshot, font_id, font_size, wrap_width, cx);
  57        let block_map = BlockMap::new(snapshot);
  58        cx.observe(&wrap_map, |_, _, cx| cx.notify()).detach();
  59        DisplayMap {
  60            buffer,
  61            buffer_subscription,
  62            fold_map,
  63            tab_map,
  64            wrap_map,
  65            block_map,
  66        }
  67    }
  68
  69    pub fn snapshot(&self, cx: &mut ModelContext<Self>) -> DisplaySnapshot {
  70        let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
  71        let edits = self.buffer_subscription.consume().into_inner();
  72        let (folds_snapshot, edits) = self.fold_map.read(buffer_snapshot, edits);
  73        let (tabs_snapshot, edits) = self.tab_map.sync(folds_snapshot.clone(), edits);
  74        let (wraps_snapshot, edits) = self
  75            .wrap_map
  76            .update(cx, |map, cx| map.sync(tabs_snapshot.clone(), edits, cx));
  77        let blocks_snapshot = self.block_map.read(wraps_snapshot.clone(), edits);
  78
  79        DisplaySnapshot {
  80            buffer_snapshot: self.buffer.read(cx).snapshot(cx),
  81            folds_snapshot,
  82            tabs_snapshot,
  83            wraps_snapshot,
  84            blocks_snapshot,
  85        }
  86    }
  87
  88    pub fn fold<T: ToOffset>(
  89        &mut self,
  90        ranges: impl IntoIterator<Item = Range<T>>,
  91        cx: &mut ModelContext<Self>,
  92    ) {
  93        let snapshot = self.buffer.read(cx).snapshot(cx);
  94        let edits = self.buffer_subscription.consume().into_inner();
  95        let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
  96        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
  97        let (snapshot, edits) = self
  98            .wrap_map
  99            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 100        self.block_map.read(snapshot, edits);
 101        let (snapshot, edits) = fold_map.fold(ranges);
 102        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
 103        let (snapshot, edits) = self
 104            .wrap_map
 105            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 106        self.block_map.read(snapshot, edits);
 107    }
 108
 109    pub fn unfold<T: ToOffset>(
 110        &mut self,
 111        ranges: impl IntoIterator<Item = Range<T>>,
 112        cx: &mut ModelContext<Self>,
 113    ) {
 114        let snapshot = self.buffer.read(cx).snapshot(cx);
 115        let edits = self.buffer_subscription.consume().into_inner();
 116        let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
 117        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
 118        let (snapshot, edits) = self
 119            .wrap_map
 120            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 121        self.block_map.read(snapshot, edits);
 122        let (snapshot, edits) = fold_map.unfold(ranges);
 123        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
 124        let (snapshot, edits) = self
 125            .wrap_map
 126            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 127        self.block_map.read(snapshot, edits);
 128    }
 129
 130    pub fn insert_blocks<P>(
 131        &mut self,
 132        blocks: impl IntoIterator<Item = BlockProperties<P>>,
 133        cx: &mut ModelContext<Self>,
 134    ) -> Vec<BlockId>
 135    where
 136        P: ToOffset + Clone,
 137    {
 138        let snapshot = self.buffer.read(cx).snapshot(cx);
 139        let edits = self.buffer_subscription.consume().into_inner();
 140        let (snapshot, edits) = self.fold_map.read(snapshot, edits);
 141        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
 142        let (snapshot, edits) = self
 143            .wrap_map
 144            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 145        let mut block_map = self.block_map.write(snapshot, edits);
 146        block_map.insert(blocks)
 147    }
 148
 149    pub fn replace_blocks(&mut self, styles: HashMap<BlockId, RenderBlock>) {
 150        self.block_map.replace(styles);
 151    }
 152
 153    pub fn remove_blocks(&mut self, ids: HashSet<BlockId>, cx: &mut ModelContext<Self>) {
 154        let snapshot = self.buffer.read(cx).snapshot(cx);
 155        let edits = self.buffer_subscription.consume().into_inner();
 156        let (snapshot, edits) = self.fold_map.read(snapshot, edits);
 157        let (snapshot, edits) = self.tab_map.sync(snapshot, edits);
 158        let (snapshot, edits) = self
 159            .wrap_map
 160            .update(cx, |map, cx| map.sync(snapshot, edits, cx));
 161        let mut block_map = self.block_map.write(snapshot, edits);
 162        block_map.remove(ids);
 163    }
 164
 165    pub fn set_font(&self, font_id: FontId, font_size: f32, cx: &mut ModelContext<Self>) {
 166        self.wrap_map
 167            .update(cx, |map, cx| map.set_font(font_id, font_size, cx));
 168    }
 169
 170    pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut ModelContext<Self>) -> bool {
 171        self.wrap_map
 172            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 173    }
 174
 175    #[cfg(test)]
 176    pub fn is_rewrapping(&self, cx: &gpui::AppContext) -> bool {
 177        self.wrap_map.read(cx).is_rewrapping()
 178    }
 179}
 180
 181pub struct DisplaySnapshot {
 182    pub buffer_snapshot: MultiBufferSnapshot,
 183    folds_snapshot: fold_map::FoldSnapshot,
 184    tabs_snapshot: tab_map::TabSnapshot,
 185    wraps_snapshot: wrap_map::WrapSnapshot,
 186    blocks_snapshot: block_map::BlockSnapshot,
 187}
 188
 189impl DisplaySnapshot {
 190    #[cfg(test)]
 191    pub fn fold_count(&self) -> usize {
 192        self.folds_snapshot.fold_count()
 193    }
 194
 195    pub fn is_empty(&self) -> bool {
 196        self.buffer_snapshot.len() == 0
 197    }
 198
 199    pub fn buffer_rows<'a>(&'a self, start_row: u32) -> DisplayBufferRows<'a> {
 200        self.blocks_snapshot.buffer_rows(start_row)
 201    }
 202
 203    pub fn buffer_row_count(&self) -> u32 {
 204        self.buffer_snapshot.max_point().row + 1
 205    }
 206
 207    pub fn prev_row_boundary(&self, input_display_point: DisplayPoint) -> (DisplayPoint, Point) {
 208        let mut display_point = input_display_point;
 209        loop {
 210            *display_point.column_mut() = 0;
 211            let mut point = display_point.to_point(self);
 212            point = self.buffer_snapshot.clip_point(point, Bias::Left);
 213            point.column = 0;
 214            let next_display_point = self.point_to_display_point_with_clipping(point, Bias::Left);
 215            if next_display_point == display_point {
 216                return (display_point, point);
 217            }
 218            if next_display_point > display_point {
 219                panic!("invalid display point {:?}", input_display_point);
 220            }
 221            display_point = next_display_point;
 222        }
 223    }
 224
 225    pub fn next_row_boundary(&self, input_display_point: DisplayPoint) -> (DisplayPoint, Point) {
 226        let mut display_point = input_display_point;
 227        loop {
 228            *display_point.column_mut() = self.line_len(display_point.row());
 229            let mut point = self.display_point_to_point(display_point, Bias::Right);
 230            point = self.buffer_snapshot.clip_point(point, Bias::Right);
 231            point.column = self.buffer_snapshot.line_len(point.row);
 232            let next_display_point = self.point_to_display_point(point, Bias::Right);
 233            if next_display_point == display_point {
 234                return (display_point, point);
 235            }
 236            if next_display_point < display_point {
 237                panic!("invalid display point {:?}", input_display_point);
 238            }
 239            display_point = next_display_point;
 240        }
 241    }
 242
 243    fn point_to_display_point(&self, point: Point, bias: Bias) -> DisplayPoint {
 244        let fold_point = point.to_fold_point(&self.folds_snapshot, bias);
 245        let tab_point = self.tabs_snapshot.to_tab_point(fold_point);
 246        let wrap_point = self.wraps_snapshot.from_tab_point(tab_point);
 247        let block_point = self.blocks_snapshot.to_block_point(wrap_point);
 248        DisplayPoint(block_point)
 249    }
 250
 251    fn point_to_display_point_with_clipping(&self, point: Point, bias: Bias) -> DisplayPoint {
 252        let fold_point = point.to_fold_point(&self.folds_snapshot, bias);
 253        let tab_point = self.tabs_snapshot.to_tab_point(fold_point);
 254        let wrap_point = self
 255            .wraps_snapshot
 256            .from_tab_point_with_clipping(tab_point, bias);
 257        let block_point = self.blocks_snapshot.to_block_point(wrap_point);
 258        DisplayPoint(block_point)
 259    }
 260
 261    fn display_point_to_point(&self, point: DisplayPoint, bias: Bias) -> Point {
 262        let block_point = point.0;
 263        let wrap_point = self.blocks_snapshot.to_wrap_point(block_point);
 264        let tab_point = self.wraps_snapshot.to_tab_point(wrap_point);
 265        let fold_point = self.tabs_snapshot.to_fold_point(tab_point, bias).0;
 266        fold_point.to_buffer_point(&self.folds_snapshot)
 267    }
 268
 269    pub fn max_point(&self) -> DisplayPoint {
 270        DisplayPoint(self.blocks_snapshot.max_point())
 271    }
 272
 273    pub fn text_chunks(&self, display_row: u32) -> impl Iterator<Item = &str> {
 274        self.blocks_snapshot
 275            .chunks(display_row..self.max_point().row() + 1, None)
 276            .map(|h| h.text)
 277    }
 278
 279    pub fn chunks<'a>(
 280        &'a self,
 281        display_rows: Range<u32>,
 282        theme: Option<&'a SyntaxTheme>,
 283    ) -> DisplayChunks<'a> {
 284        self.blocks_snapshot.chunks(display_rows, theme)
 285    }
 286
 287    pub fn chars_at<'a>(&'a self, point: DisplayPoint) -> impl Iterator<Item = char> + 'a {
 288        let mut column = 0;
 289        let mut chars = self.text_chunks(point.row()).flat_map(str::chars);
 290        while column < point.column() {
 291            if let Some(c) = chars.next() {
 292                column += c.len_utf8() as u32;
 293            } else {
 294                break;
 295            }
 296        }
 297        chars
 298    }
 299
 300    pub fn column_to_chars(&self, display_row: u32, target: u32) -> u32 {
 301        let mut count = 0;
 302        let mut column = 0;
 303        for c in self.chars_at(DisplayPoint::new(display_row, 0)) {
 304            if column >= target {
 305                break;
 306            }
 307            count += 1;
 308            column += c.len_utf8() as u32;
 309        }
 310        count
 311    }
 312
 313    pub fn column_from_chars(&self, display_row: u32, char_count: u32) -> u32 {
 314        let mut count = 0;
 315        let mut column = 0;
 316        for c in self.chars_at(DisplayPoint::new(display_row, 0)) {
 317            if c == '\n' || count >= char_count {
 318                break;
 319            }
 320            count += 1;
 321            column += c.len_utf8() as u32;
 322        }
 323        column
 324    }
 325
 326    pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
 327        DisplayPoint(self.blocks_snapshot.clip_point(point.0, bias))
 328    }
 329
 330    pub fn folds_in_range<'a, T>(
 331        &'a self,
 332        range: Range<T>,
 333    ) -> impl Iterator<Item = &'a Range<Anchor>>
 334    where
 335        T: ToOffset,
 336    {
 337        self.folds_snapshot.folds_in_range(range)
 338    }
 339
 340    pub fn blocks_in_range<'a>(
 341        &'a self,
 342        rows: Range<u32>,
 343    ) -> impl Iterator<Item = (u32, &'a AlignedBlock)> {
 344        self.blocks_snapshot.blocks_in_range(rows)
 345    }
 346
 347    pub fn excerpt_headers_in_range<'a>(
 348        &'a self,
 349        rows: Range<u32>,
 350    ) -> impl 'a + Iterator<Item = (Range<u32>, RenderHeaderFn)> {
 351        todo!();
 352        let start_row = DisplayPoint::new(rows.start, 0).to_point(self).row;
 353        let end_row = DisplayPoint::new(rows.end, 0).to_point(self).row;
 354        self.buffer_snapshot
 355            .excerpt_headers_in_range(start_row..end_row)
 356            .map(move |(row, header_height, render)| {
 357                let start_row = Point::new(rows.start, 0).to_display_point(self).row();
 358                let end_row = Point::new(rows.end, 0).to_display_point(self).row();
 359                (start_row..end_row, render)
 360            })
 361    }
 362
 363    pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
 364        self.folds_snapshot.intersects_fold(offset)
 365    }
 366
 367    pub fn is_line_folded(&self, display_row: u32) -> bool {
 368        let block_point = BlockPoint(Point::new(display_row, 0));
 369        let wrap_point = self.blocks_snapshot.to_wrap_point(block_point);
 370        let tab_point = self.wraps_snapshot.to_tab_point(wrap_point);
 371        self.folds_snapshot.is_line_folded(tab_point.row())
 372    }
 373
 374    pub fn is_block_line(&self, display_row: u32) -> bool {
 375        self.blocks_snapshot.is_block_line(display_row)
 376    }
 377
 378    pub fn soft_wrap_indent(&self, display_row: u32) -> Option<u32> {
 379        let wrap_row = self
 380            .blocks_snapshot
 381            .to_wrap_point(BlockPoint::new(display_row, 0))
 382            .row();
 383        self.wraps_snapshot.soft_wrap_indent(wrap_row)
 384    }
 385
 386    pub fn text(&self) -> String {
 387        self.text_chunks(0).collect()
 388    }
 389
 390    pub fn line(&self, display_row: u32) -> String {
 391        let mut result = String::new();
 392        for chunk in self.text_chunks(display_row) {
 393            if let Some(ix) = chunk.find('\n') {
 394                result.push_str(&chunk[0..ix]);
 395                break;
 396            } else {
 397                result.push_str(chunk);
 398            }
 399        }
 400        result
 401    }
 402
 403    pub fn line_indent(&self, display_row: u32) -> (u32, bool) {
 404        let mut indent = 0;
 405        let mut is_blank = true;
 406        for c in self.chars_at(DisplayPoint::new(display_row, 0)) {
 407            if c == ' ' {
 408                indent += 1;
 409            } else {
 410                is_blank = c == '\n';
 411                break;
 412            }
 413        }
 414        (indent, is_blank)
 415    }
 416
 417    pub fn line_len(&self, row: u32) -> u32 {
 418        self.blocks_snapshot.line_len(row)
 419    }
 420
 421    pub fn longest_row(&self) -> u32 {
 422        self.blocks_snapshot.longest_row()
 423    }
 424}
 425
 426#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 427pub struct DisplayPoint(BlockPoint);
 428
 429impl DisplayPoint {
 430    pub fn new(row: u32, column: u32) -> Self {
 431        Self(BlockPoint(Point::new(row, column)))
 432    }
 433
 434    pub fn zero() -> Self {
 435        Self::new(0, 0)
 436    }
 437
 438    #[cfg(test)]
 439    pub fn is_zero(&self) -> bool {
 440        self.0.is_zero()
 441    }
 442
 443    pub fn row(self) -> u32 {
 444        self.0.row
 445    }
 446
 447    pub fn column(self) -> u32 {
 448        self.0.column
 449    }
 450
 451    pub fn row_mut(&mut self) -> &mut u32 {
 452        &mut self.0.row
 453    }
 454
 455    pub fn column_mut(&mut self) -> &mut u32 {
 456        &mut self.0.column
 457    }
 458
 459    pub fn to_point(self, map: &DisplaySnapshot) -> Point {
 460        map.display_point_to_point(self, Bias::Left)
 461    }
 462
 463    pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
 464        let unblocked_point = map.blocks_snapshot.to_wrap_point(self.0);
 465        let unwrapped_point = map.wraps_snapshot.to_tab_point(unblocked_point);
 466        let unexpanded_point = map.tabs_snapshot.to_fold_point(unwrapped_point, bias).0;
 467        unexpanded_point.to_buffer_offset(&map.folds_snapshot)
 468    }
 469}
 470
 471impl ToDisplayPoint for usize {
 472    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 473        map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
 474    }
 475}
 476
 477impl ToDisplayPoint for Point {
 478    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 479        map.point_to_display_point(*self, Bias::Left)
 480    }
 481}
 482
 483impl ToDisplayPoint for Anchor {
 484    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 485        self.to_point(&map.buffer_snapshot).to_display_point(map)
 486    }
 487}
 488
 489#[cfg(test)]
 490mod tests {
 491    use super::*;
 492    use crate::{movement, test::*};
 493    use gpui::{color::Color, elements::*, MutableAppContext};
 494    use language::{Buffer, Language, LanguageConfig, RandomCharIter, SelectionGoal};
 495    use rand::{prelude::*, Rng};
 496    use std::{env, sync::Arc};
 497    use theme::SyntaxTheme;
 498    use util::test::sample_text;
 499    use Bias::*;
 500
 501    #[gpui::test(iterations = 100)]
 502    async fn test_random_display_map(mut cx: gpui::TestAppContext, mut rng: StdRng) {
 503        cx.foreground().set_block_on_ticks(0..=50);
 504        cx.foreground().forbid_parking();
 505        let operations = env::var("OPERATIONS")
 506            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
 507            .unwrap_or(10);
 508
 509        let font_cache = cx.font_cache().clone();
 510        let tab_size = rng.gen_range(1..=4);
 511        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 512        let font_id = font_cache
 513            .select_font(family_id, &Default::default())
 514            .unwrap();
 515        let font_size = 14.0;
 516        let max_wrap_width = 300.0;
 517        let mut wrap_width = if rng.gen_bool(0.1) {
 518            None
 519        } else {
 520            Some(rng.gen_range(0.0..=max_wrap_width))
 521        };
 522
 523        log::info!("tab size: {}", tab_size);
 524        log::info!("wrap width: {:?}", wrap_width);
 525
 526        let buffer = cx.update(|cx| {
 527            if rng.gen() {
 528                let len = rng.gen_range(0..10);
 529                let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
 530                MultiBuffer::build_simple(&text, cx)
 531            } else {
 532                MultiBuffer::build_random(&mut rng, cx)
 533            }
 534        });
 535
 536        let map = cx.add_model(|cx| {
 537            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
 538        });
 539        let (_observer, notifications) = Observer::new(&map, &mut cx);
 540        let mut fold_count = 0;
 541        let mut blocks = Vec::new();
 542
 543        let snapshot = map.update(&mut cx, |map, cx| map.snapshot(cx));
 544        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
 545        log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
 546        log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
 547        log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
 548        log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
 549        log::info!("display text: {:?}", snapshot.text());
 550
 551        for _i in 0..operations {
 552            match rng.gen_range(0..100) {
 553                0..=19 => {
 554                    wrap_width = if rng.gen_bool(0.2) {
 555                        None
 556                    } else {
 557                        Some(rng.gen_range(0.0..=max_wrap_width))
 558                    };
 559                    log::info!("setting wrap width to {:?}", wrap_width);
 560                    map.update(&mut cx, |map, cx| map.set_wrap_width(wrap_width, cx));
 561                }
 562                20..=44 => {
 563                    map.update(&mut cx, |map, cx| {
 564                        if rng.gen() || blocks.is_empty() {
 565                            let buffer = map.snapshot(cx).buffer_snapshot;
 566                            let block_properties = (0..rng.gen_range(1..=1))
 567                                .map(|_| {
 568                                    let position =
 569                                        buffer.anchor_after(buffer.clip_offset(
 570                                            rng.gen_range(0..=buffer.len()),
 571                                            Bias::Left,
 572                                        ));
 573
 574                                    let disposition = if rng.gen() {
 575                                        BlockDisposition::Above
 576                                    } else {
 577                                        BlockDisposition::Below
 578                                    };
 579                                    let height = rng.gen_range(1..5);
 580                                    log::info!(
 581                                        "inserting block {:?} {:?} with height {}",
 582                                        disposition,
 583                                        position.to_point(&buffer),
 584                                        height
 585                                    );
 586                                    BlockProperties {
 587                                        position,
 588                                        height,
 589                                        disposition,
 590                                        render: Arc::new(|_| Empty::new().boxed()),
 591                                    }
 592                                })
 593                                .collect::<Vec<_>>();
 594                            blocks.extend(map.insert_blocks(block_properties, cx));
 595                        } else {
 596                            blocks.shuffle(&mut rng);
 597                            let remove_count = rng.gen_range(1..=4.min(blocks.len()));
 598                            let block_ids_to_remove = (0..remove_count)
 599                                .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
 600                                .collect();
 601                            log::info!("removing block ids {:?}", block_ids_to_remove);
 602                            map.remove_blocks(block_ids_to_remove, cx);
 603                        }
 604                    });
 605                }
 606                45..=79 => {
 607                    let mut ranges = Vec::new();
 608                    for _ in 0..rng.gen_range(1..=3) {
 609                        buffer.read_with(&cx, |buffer, cx| {
 610                            let buffer = buffer.read(cx);
 611                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
 612                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
 613                            ranges.push(start..end);
 614                        });
 615                    }
 616
 617                    if rng.gen() && fold_count > 0 {
 618                        log::info!("unfolding ranges: {:?}", ranges);
 619                        map.update(&mut cx, |map, cx| {
 620                            map.unfold(ranges, cx);
 621                        });
 622                    } else {
 623                        log::info!("folding ranges: {:?}", ranges);
 624                        map.update(&mut cx, |map, cx| {
 625                            map.fold(ranges, cx);
 626                        });
 627                    }
 628                }
 629                _ => {
 630                    buffer.update(&mut cx, |buffer, cx| buffer.randomly_edit(&mut rng, 5, cx));
 631                }
 632            }
 633
 634            if map.read_with(&cx, |map, cx| map.is_rewrapping(cx)) {
 635                notifications.recv().await.unwrap();
 636            }
 637
 638            let snapshot = map.update(&mut cx, |map, cx| map.snapshot(cx));
 639            fold_count = snapshot.fold_count();
 640            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
 641            log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
 642            log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
 643            log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
 644            log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
 645            log::info!("display text: {:?}", snapshot.text());
 646
 647            // Line boundaries
 648            for _ in 0..5 {
 649                let row = rng.gen_range(0..=snapshot.max_point().row());
 650                let column = rng.gen_range(0..=snapshot.line_len(row));
 651                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
 652
 653                let (prev_display_bound, prev_buffer_bound) = snapshot.prev_row_boundary(point);
 654                let (next_display_bound, next_buffer_bound) = snapshot.next_row_boundary(point);
 655
 656                assert!(prev_display_bound <= point);
 657                assert!(next_display_bound >= point);
 658                assert_eq!(prev_buffer_bound.column, 0);
 659                assert_eq!(prev_display_bound.column(), 0);
 660                if next_buffer_bound < snapshot.buffer_snapshot.max_point() {
 661                    assert_eq!(
 662                        snapshot.buffer_snapshot.chars_at(next_buffer_bound).next(),
 663                        Some('\n')
 664                    );
 665                }
 666
 667                assert_eq!(
 668                    prev_display_bound,
 669                    prev_buffer_bound.to_display_point(&snapshot),
 670                    "row boundary before {:?}. reported buffer row boundary: {:?}",
 671                    point,
 672                    prev_buffer_bound
 673                );
 674                assert_eq!(
 675                    next_display_bound,
 676                    next_buffer_bound.to_display_point(&snapshot),
 677                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
 678                    point,
 679                    next_buffer_bound
 680                );
 681                assert_eq!(
 682                    prev_buffer_bound,
 683                    prev_display_bound.to_point(&snapshot),
 684                    "row boundary before {:?}. reported display row boundary: {:?}",
 685                    point,
 686                    prev_display_bound
 687                );
 688                assert_eq!(
 689                    next_buffer_bound,
 690                    next_display_bound.to_point(&snapshot),
 691                    "row boundary after {:?}. reported display row boundary: {:?}",
 692                    point,
 693                    next_display_bound
 694                );
 695            }
 696
 697            // Movement
 698            let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
 699            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
 700            for _ in 0..5 {
 701                let row = rng.gen_range(0..=snapshot.max_point().row());
 702                let column = rng.gen_range(0..=snapshot.line_len(row));
 703                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
 704
 705                log::info!("Moving from point {:?}", point);
 706
 707                let moved_right = movement::right(&snapshot, point).unwrap();
 708                log::info!("Right {:?}", moved_right);
 709                if point < max_point {
 710                    assert!(moved_right > point);
 711                    if point.column() == snapshot.line_len(point.row())
 712                        || snapshot.soft_wrap_indent(point.row()).is_some()
 713                            && point.column() == snapshot.line_len(point.row()) - 1
 714                    {
 715                        assert!(moved_right.row() > point.row());
 716                    }
 717                } else {
 718                    assert_eq!(moved_right, point);
 719                }
 720
 721                let moved_left = movement::left(&snapshot, point).unwrap();
 722                log::info!("Left {:?}", moved_left);
 723                if point > min_point {
 724                    assert!(moved_left < point);
 725                    if point.column() == 0 {
 726                        assert!(moved_left.row() < point.row());
 727                    }
 728                } else {
 729                    assert_eq!(moved_left, point);
 730                }
 731            }
 732        }
 733    }
 734
 735    #[gpui::test(retries = 5)]
 736    fn test_soft_wraps(cx: &mut MutableAppContext) {
 737        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
 738        cx.foreground().forbid_parking();
 739
 740        let font_cache = cx.font_cache();
 741
 742        let tab_size = 4;
 743        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 744        let font_id = font_cache
 745            .select_font(family_id, &Default::default())
 746            .unwrap();
 747        let font_size = 12.0;
 748        let wrap_width = Some(64.);
 749
 750        let text = "one two three four five\nsix seven eight";
 751        let buffer = MultiBuffer::build_simple(text, cx);
 752        let map = cx.add_model(|cx| {
 753            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
 754        });
 755
 756        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 757        assert_eq!(
 758            snapshot.text_chunks(0).collect::<String>(),
 759            "one two \nthree four \nfive\nsix seven \neight"
 760        );
 761        assert_eq!(
 762            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
 763            DisplayPoint::new(0, 7)
 764        );
 765        assert_eq!(
 766            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
 767            DisplayPoint::new(1, 0)
 768        );
 769        assert_eq!(
 770            movement::right(&snapshot, DisplayPoint::new(0, 7)).unwrap(),
 771            DisplayPoint::new(1, 0)
 772        );
 773        assert_eq!(
 774            movement::left(&snapshot, DisplayPoint::new(1, 0)).unwrap(),
 775            DisplayPoint::new(0, 7)
 776        );
 777        assert_eq!(
 778            movement::up(&snapshot, DisplayPoint::new(1, 10), SelectionGoal::None).unwrap(),
 779            (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
 780        );
 781        assert_eq!(
 782            movement::down(
 783                &snapshot,
 784                DisplayPoint::new(0, 7),
 785                SelectionGoal::Column(10)
 786            )
 787            .unwrap(),
 788            (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
 789        );
 790        assert_eq!(
 791            movement::down(
 792                &snapshot,
 793                DisplayPoint::new(1, 10),
 794                SelectionGoal::Column(10)
 795            )
 796            .unwrap(),
 797            (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
 798        );
 799
 800        let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
 801        buffer.update(cx, |buffer, cx| {
 802            buffer.edit(vec![ix..ix], "and ", cx);
 803        });
 804
 805        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 806        assert_eq!(
 807            snapshot.text_chunks(1).collect::<String>(),
 808            "three four \nfive\nsix and \nseven eight"
 809        );
 810
 811        // Re-wrap on font size changes
 812        map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
 813
 814        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 815        assert_eq!(
 816            snapshot.text_chunks(1).collect::<String>(),
 817            "three \nfour five\nsix and \nseven \neight"
 818        )
 819    }
 820
 821    #[gpui::test]
 822    fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
 823        let text = sample_text(6, 6, 'a');
 824        let buffer = MultiBuffer::build_simple(&text, cx);
 825        let tab_size = 4;
 826        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
 827        let font_id = cx
 828            .font_cache()
 829            .select_font(family_id, &Default::default())
 830            .unwrap();
 831        let font_size = 14.0;
 832        let map = cx.add_model(|cx| {
 833            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
 834        });
 835        buffer.update(cx, |buffer, cx| {
 836            buffer.edit(
 837                vec![
 838                    Point::new(1, 0)..Point::new(1, 0),
 839                    Point::new(1, 1)..Point::new(1, 1),
 840                    Point::new(2, 1)..Point::new(2, 1),
 841                ],
 842                "\t",
 843                cx,
 844            )
 845        });
 846
 847        assert_eq!(
 848            map.update(cx, |map, cx| map.snapshot(cx))
 849                .text_chunks(1)
 850                .collect::<String>()
 851                .lines()
 852                .next(),
 853            Some("    b   bbbbb")
 854        );
 855        assert_eq!(
 856            map.update(cx, |map, cx| map.snapshot(cx))
 857                .text_chunks(2)
 858                .collect::<String>()
 859                .lines()
 860                .next(),
 861            Some("c   ccccc")
 862        );
 863    }
 864
 865    #[gpui::test]
 866    async fn test_chunks(mut cx: gpui::TestAppContext) {
 867        use unindent::Unindent as _;
 868
 869        let text = r#"
 870            fn outer() {}
 871
 872            mod module {
 873                fn inner() {}
 874            }"#
 875        .unindent();
 876
 877        let theme = SyntaxTheme::new(vec![
 878            ("mod.body".to_string(), Color::red().into()),
 879            ("fn.name".to_string(), Color::blue().into()),
 880        ]);
 881        let lang = Arc::new(
 882            Language::new(
 883                LanguageConfig {
 884                    name: "Test".to_string(),
 885                    path_suffixes: vec![".test".to_string()],
 886                    ..Default::default()
 887                },
 888                Some(tree_sitter_rust::language()),
 889            )
 890            .with_highlights_query(
 891                r#"
 892                (mod_item name: (identifier) body: _ @mod.body)
 893                (function_item name: (identifier) @fn.name)
 894                "#,
 895            )
 896            .unwrap(),
 897        );
 898        lang.set_theme(&theme);
 899
 900        let buffer =
 901            cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
 902        buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
 903        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 904
 905        let tab_size = 2;
 906        let font_cache = cx.font_cache();
 907        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 908        let font_id = font_cache
 909            .select_font(family_id, &Default::default())
 910            .unwrap();
 911        let font_size = 14.0;
 912
 913        let map =
 914            cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
 915        assert_eq!(
 916            cx.update(|cx| chunks(0..5, &map, &theme, cx)),
 917            vec![
 918                ("fn ".to_string(), None),
 919                ("outer".to_string(), Some(Color::blue())),
 920                ("() {}\n\nmod module ".to_string(), None),
 921                ("{\n    fn ".to_string(), Some(Color::red())),
 922                ("inner".to_string(), Some(Color::blue())),
 923                ("() {}\n}".to_string(), Some(Color::red())),
 924            ]
 925        );
 926        assert_eq!(
 927            cx.update(|cx| chunks(3..5, &map, &theme, cx)),
 928            vec![
 929                ("    fn ".to_string(), Some(Color::red())),
 930                ("inner".to_string(), Some(Color::blue())),
 931                ("() {}\n}".to_string(), Some(Color::red())),
 932            ]
 933        );
 934
 935        map.update(&mut cx, |map, cx| {
 936            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
 937        });
 938        assert_eq!(
 939            cx.update(|cx| chunks(0..2, &map, &theme, cx)),
 940            vec![
 941                ("fn ".to_string(), None),
 942                ("out".to_string(), Some(Color::blue())),
 943                ("".to_string(), None),
 944                ("  fn ".to_string(), Some(Color::red())),
 945                ("inner".to_string(), Some(Color::blue())),
 946                ("() {}\n}".to_string(), Some(Color::red())),
 947            ]
 948        );
 949    }
 950
 951    #[gpui::test]
 952    async fn test_chunks_with_soft_wrapping(mut cx: gpui::TestAppContext) {
 953        use unindent::Unindent as _;
 954
 955        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
 956
 957        let text = r#"
 958            fn outer() {}
 959
 960            mod module {
 961                fn inner() {}
 962            }"#
 963        .unindent();
 964
 965        let theme = SyntaxTheme::new(vec![
 966            ("mod.body".to_string(), Color::red().into()),
 967            ("fn.name".to_string(), Color::blue().into()),
 968        ]);
 969        let lang = Arc::new(
 970            Language::new(
 971                LanguageConfig {
 972                    name: "Test".to_string(),
 973                    path_suffixes: vec![".test".to_string()],
 974                    ..Default::default()
 975                },
 976                Some(tree_sitter_rust::language()),
 977            )
 978            .with_highlights_query(
 979                r#"
 980                (mod_item name: (identifier) body: _ @mod.body)
 981                (function_item name: (identifier) @fn.name)
 982                "#,
 983            )
 984            .unwrap(),
 985        );
 986        lang.set_theme(&theme);
 987
 988        let buffer =
 989            cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
 990        buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
 991        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 992
 993        let font_cache = cx.font_cache();
 994
 995        let tab_size = 4;
 996        let family_id = font_cache.load_family(&["Courier"]).unwrap();
 997        let font_id = font_cache
 998            .select_font(family_id, &Default::default())
 999            .unwrap();
1000        let font_size = 16.0;
1001
1002        let map = cx
1003            .add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, Some(40.0), cx));
1004        assert_eq!(
1005            cx.update(|cx| chunks(0..5, &map, &theme, cx)),
1006            [
1007                ("fn \n".to_string(), None),
1008                ("oute\nr".to_string(), Some(Color::blue())),
1009                ("() \n{}\n\n".to_string(), None),
1010            ]
1011        );
1012        assert_eq!(
1013            cx.update(|cx| chunks(3..5, &map, &theme, cx)),
1014            [("{}\n\n".to_string(), None)]
1015        );
1016
1017        map.update(&mut cx, |map, cx| {
1018            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1019        });
1020        assert_eq!(
1021            cx.update(|cx| chunks(1..4, &map, &theme, cx)),
1022            [
1023                ("out".to_string(), Some(Color::blue())),
1024                ("\n".to_string(), None),
1025                ("  \nfn ".to_string(), Some(Color::red())),
1026                ("i\n".to_string(), Some(Color::blue()))
1027            ]
1028        );
1029    }
1030
1031    #[gpui::test]
1032    fn test_clip_point(cx: &mut gpui::MutableAppContext) {
1033        use Bias::{Left, Right};
1034
1035        let text = "\n'a', 'α',\t'✋',\t'❎', '🍐'\n";
1036        let display_text = "\n'a', 'α',   '✋',    '❎', '🍐'\n";
1037        let buffer = MultiBuffer::build_simple(text, cx);
1038
1039        let tab_size = 4;
1040        let font_cache = cx.font_cache();
1041        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1042        let font_id = font_cache
1043            .select_font(family_id, &Default::default())
1044            .unwrap();
1045        let font_size = 14.0;
1046        let map = cx.add_model(|cx| {
1047            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1048        });
1049        let map = map.update(cx, |map, cx| map.snapshot(cx));
1050
1051        assert_eq!(map.text(), display_text);
1052        for (input_column, bias, output_column) in vec![
1053            ("'a', '".len(), Left, "'a', '".len()),
1054            ("'a', '".len() + 1, Left, "'a', '".len()),
1055            ("'a', '".len() + 1, Right, "'a', 'α".len()),
1056            ("'a', 'α', ".len(), Left, "'a', 'α',".len()),
1057            ("'a', 'α', ".len(), Right, "'a', 'α',   ".len()),
1058            ("'a', 'α',   '".len() + 1, Left, "'a', 'α',   '".len()),
1059            ("'a', 'α',   '".len() + 1, Right, "'a', 'α',   '✋".len()),
1060            ("'a', 'α',   '✋',".len(), Right, "'a', 'α',   '✋',".len()),
1061            ("'a', 'α',   '✋', ".len(), Left, "'a', 'α',   '✋',".len()),
1062            (
1063                "'a', 'α',   '✋', ".len(),
1064                Right,
1065                "'a', 'α',   '✋',    ".len(),
1066            ),
1067        ] {
1068            assert_eq!(
1069                map.clip_point(DisplayPoint::new(1, input_column as u32), bias),
1070                DisplayPoint::new(1, output_column as u32),
1071                "clip_point(({}, {}))",
1072                1,
1073                input_column,
1074            );
1075        }
1076    }
1077
1078    #[gpui::test]
1079    fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
1080        let text = "\t\tα\nβ\t\n🏀β\t\tγ";
1081        let buffer = MultiBuffer::build_simple(text, cx);
1082        let tab_size = 4;
1083        let font_cache = cx.font_cache();
1084        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1085        let font_id = font_cache
1086            .select_font(family_id, &Default::default())
1087            .unwrap();
1088        let font_size = 14.0;
1089
1090        let map = cx.add_model(|cx| {
1091            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1092        });
1093        let map = map.update(cx, |map, cx| map.snapshot(cx));
1094        assert_eq!(map.text(), "✅       α\nβ   \n🏀β      γ");
1095        assert_eq!(
1096            map.text_chunks(0).collect::<String>(),
1097            "✅       α\nβ   \n🏀β      γ"
1098        );
1099        assert_eq!(map.text_chunks(1).collect::<String>(), "β   \n🏀β      γ");
1100        assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β      γ");
1101
1102        let point = Point::new(0, "\t\t".len() as u32);
1103        let display_point = DisplayPoint::new(0, "".len() as u32);
1104        assert_eq!(point.to_display_point(&map), display_point);
1105        assert_eq!(display_point.to_point(&map), point);
1106
1107        let point = Point::new(1, "β\t".len() as u32);
1108        let display_point = DisplayPoint::new(1, "β   ".len() as u32);
1109        assert_eq!(point.to_display_point(&map), display_point);
1110        assert_eq!(display_point.to_point(&map), point,);
1111
1112        let point = Point::new(2, "🏀β\t\t".len() as u32);
1113        let display_point = DisplayPoint::new(2, "🏀β      ".len() as u32);
1114        assert_eq!(point.to_display_point(&map), display_point);
1115        assert_eq!(display_point.to_point(&map), point,);
1116
1117        // Display points inside of expanded tabs
1118        assert_eq!(
1119            DisplayPoint::new(0, "".len() as u32).to_point(&map),
1120            Point::new(0, "\t".len() as u32),
1121        );
1122        assert_eq!(
1123            DisplayPoint::new(0, "".len() as u32).to_point(&map),
1124            Point::new(0, "".len() as u32),
1125        );
1126
1127        // Clipping display points inside of multi-byte characters
1128        assert_eq!(
1129            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Left),
1130            DisplayPoint::new(0, 0)
1131        );
1132        assert_eq!(
1133            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Bias::Right),
1134            DisplayPoint::new(0, "".len() as u32)
1135        );
1136    }
1137
1138    #[gpui::test]
1139    fn test_max_point(cx: &mut gpui::MutableAppContext) {
1140        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1141        let tab_size = 4;
1142        let font_cache = cx.font_cache();
1143        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1144        let font_id = font_cache
1145            .select_font(family_id, &Default::default())
1146            .unwrap();
1147        let font_size = 14.0;
1148        let map = cx.add_model(|cx| {
1149            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1150        });
1151        assert_eq!(
1152            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1153            DisplayPoint::new(1, 11)
1154        )
1155    }
1156
1157    fn chunks<'a>(
1158        rows: Range<u32>,
1159        map: &ModelHandle<DisplayMap>,
1160        theme: &'a SyntaxTheme,
1161        cx: &mut MutableAppContext,
1162    ) -> Vec<(String, Option<Color>)> {
1163        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1164        let mut chunks: Vec<(String, Option<Color>)> = Vec::new();
1165        for chunk in snapshot.chunks(rows, Some(theme)) {
1166            let color = chunk.highlight_style.map(|s| s.color);
1167            if let Some((last_chunk, last_color)) = chunks.last_mut() {
1168                if color == *last_color {
1169                    last_chunk.push_str(chunk.text);
1170                } else {
1171                    chunks.push((chunk.text.to_string(), color));
1172                }
1173            } else {
1174                chunks.push((chunk.text.to_string(), color));
1175            }
1176        }
1177        chunks
1178    }
1179}