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        let start_row = DisplayPoint::new(rows.start, 0).to_point(self).row;
 352        let end_row = DisplayPoint::new(rows.end, 0).to_point(self).row;
 353        self.buffer_snapshot
 354            .excerpt_headers_in_range(start_row..end_row)
 355            .map(move |(rows, render)| {
 356                let start_row = Point::new(rows.start, 0).to_display_point(self).row();
 357                let end_row = Point::new(rows.end, 0).to_display_point(self).row();
 358                (start_row..end_row, render)
 359            })
 360    }
 361
 362    pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
 363        self.folds_snapshot.intersects_fold(offset)
 364    }
 365
 366    pub fn is_line_folded(&self, display_row: u32) -> bool {
 367        let block_point = BlockPoint(Point::new(display_row, 0));
 368        let wrap_point = self.blocks_snapshot.to_wrap_point(block_point);
 369        let tab_point = self.wraps_snapshot.to_tab_point(wrap_point);
 370        self.folds_snapshot.is_line_folded(tab_point.row())
 371    }
 372
 373    pub fn is_block_line(&self, display_row: u32) -> bool {
 374        self.blocks_snapshot.is_block_line(display_row)
 375    }
 376
 377    pub fn soft_wrap_indent(&self, display_row: u32) -> Option<u32> {
 378        let wrap_row = self
 379            .blocks_snapshot
 380            .to_wrap_point(BlockPoint::new(display_row, 0))
 381            .row();
 382        self.wraps_snapshot.soft_wrap_indent(wrap_row)
 383    }
 384
 385    pub fn text(&self) -> String {
 386        self.text_chunks(0).collect()
 387    }
 388
 389    pub fn line(&self, display_row: u32) -> String {
 390        let mut result = String::new();
 391        for chunk in self.text_chunks(display_row) {
 392            if let Some(ix) = chunk.find('\n') {
 393                result.push_str(&chunk[0..ix]);
 394                break;
 395            } else {
 396                result.push_str(chunk);
 397            }
 398        }
 399        result
 400    }
 401
 402    pub fn line_indent(&self, display_row: u32) -> (u32, bool) {
 403        let mut indent = 0;
 404        let mut is_blank = true;
 405        for c in self.chars_at(DisplayPoint::new(display_row, 0)) {
 406            if c == ' ' {
 407                indent += 1;
 408            } else {
 409                is_blank = c == '\n';
 410                break;
 411            }
 412        }
 413        (indent, is_blank)
 414    }
 415
 416    pub fn line_len(&self, row: u32) -> u32 {
 417        self.blocks_snapshot.line_len(row)
 418    }
 419
 420    pub fn longest_row(&self) -> u32 {
 421        self.blocks_snapshot.longest_row()
 422    }
 423}
 424
 425#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
 426pub struct DisplayPoint(BlockPoint);
 427
 428impl DisplayPoint {
 429    pub fn new(row: u32, column: u32) -> Self {
 430        Self(BlockPoint(Point::new(row, column)))
 431    }
 432
 433    pub fn zero() -> Self {
 434        Self::new(0, 0)
 435    }
 436
 437    #[cfg(test)]
 438    pub fn is_zero(&self) -> bool {
 439        self.0.is_zero()
 440    }
 441
 442    pub fn row(self) -> u32 {
 443        self.0.row
 444    }
 445
 446    pub fn column(self) -> u32 {
 447        self.0.column
 448    }
 449
 450    pub fn row_mut(&mut self) -> &mut u32 {
 451        &mut self.0.row
 452    }
 453
 454    pub fn column_mut(&mut self) -> &mut u32 {
 455        &mut self.0.column
 456    }
 457
 458    pub fn to_point(self, map: &DisplaySnapshot) -> Point {
 459        map.display_point_to_point(self, Bias::Left)
 460    }
 461
 462    pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
 463        let unblocked_point = map.blocks_snapshot.to_wrap_point(self.0);
 464        let unwrapped_point = map.wraps_snapshot.to_tab_point(unblocked_point);
 465        let unexpanded_point = map.tabs_snapshot.to_fold_point(unwrapped_point, bias).0;
 466        unexpanded_point.to_buffer_offset(&map.folds_snapshot)
 467    }
 468}
 469
 470impl ToDisplayPoint for usize {
 471    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 472        map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
 473    }
 474}
 475
 476impl ToDisplayPoint for Point {
 477    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 478        map.point_to_display_point(*self, Bias::Left)
 479    }
 480}
 481
 482impl ToDisplayPoint for Anchor {
 483    fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
 484        self.to_point(&map.buffer_snapshot).to_display_point(map)
 485    }
 486}
 487
 488#[cfg(test)]
 489mod tests {
 490    use super::*;
 491    use crate::{movement, test::*};
 492    use gpui::{color::Color, elements::*, MutableAppContext};
 493    use language::{Buffer, Language, LanguageConfig, RandomCharIter, SelectionGoal};
 494    use rand::{prelude::*, Rng};
 495    use std::{env, sync::Arc};
 496    use theme::SyntaxTheme;
 497    use util::test::sample_text;
 498    use Bias::*;
 499
 500    #[gpui::test(iterations = 100)]
 501    async fn test_random_display_map(mut cx: gpui::TestAppContext, mut rng: StdRng) {
 502        cx.foreground().set_block_on_ticks(0..=50);
 503        cx.foreground().forbid_parking();
 504        let operations = env::var("OPERATIONS")
 505            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
 506            .unwrap_or(10);
 507
 508        let font_cache = cx.font_cache().clone();
 509        let tab_size = rng.gen_range(1..=4);
 510        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 511        let font_id = font_cache
 512            .select_font(family_id, &Default::default())
 513            .unwrap();
 514        let font_size = 14.0;
 515        let max_wrap_width = 300.0;
 516        let mut wrap_width = if rng.gen_bool(0.1) {
 517            None
 518        } else {
 519            Some(rng.gen_range(0.0..=max_wrap_width))
 520        };
 521
 522        log::info!("tab size: {}", tab_size);
 523        log::info!("wrap width: {:?}", wrap_width);
 524
 525        let buffer = cx.update(|cx| {
 526            if rng.gen() {
 527                let len = rng.gen_range(0..10);
 528                let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
 529                MultiBuffer::build_simple(&text, cx)
 530            } else {
 531                MultiBuffer::build_random(&mut rng, cx)
 532            }
 533        });
 534
 535        let map = cx.add_model(|cx| {
 536            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
 537        });
 538        let (_observer, notifications) = Observer::new(&map, &mut cx);
 539        let mut fold_count = 0;
 540        let mut blocks = Vec::new();
 541
 542        let snapshot = map.update(&mut cx, |map, cx| map.snapshot(cx));
 543        log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
 544        log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
 545        log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
 546        log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
 547        log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
 548        log::info!("display text: {:?}", snapshot.text());
 549
 550        for _i in 0..operations {
 551            match rng.gen_range(0..100) {
 552                0..=19 => {
 553                    wrap_width = if rng.gen_bool(0.2) {
 554                        None
 555                    } else {
 556                        Some(rng.gen_range(0.0..=max_wrap_width))
 557                    };
 558                    log::info!("setting wrap width to {:?}", wrap_width);
 559                    map.update(&mut cx, |map, cx| map.set_wrap_width(wrap_width, cx));
 560                }
 561                20..=44 => {
 562                    map.update(&mut cx, |map, cx| {
 563                        if rng.gen() || blocks.is_empty() {
 564                            let buffer = map.snapshot(cx).buffer_snapshot;
 565                            let block_properties = (0..rng.gen_range(1..=1))
 566                                .map(|_| {
 567                                    let position =
 568                                        buffer.anchor_after(buffer.clip_offset(
 569                                            rng.gen_range(0..=buffer.len()),
 570                                            Bias::Left,
 571                                        ));
 572
 573                                    let disposition = if rng.gen() {
 574                                        BlockDisposition::Above
 575                                    } else {
 576                                        BlockDisposition::Below
 577                                    };
 578                                    let height = rng.gen_range(1..5);
 579                                    log::info!(
 580                                        "inserting block {:?} {:?} with height {}",
 581                                        disposition,
 582                                        position.to_point(&buffer),
 583                                        height
 584                                    );
 585                                    BlockProperties {
 586                                        position,
 587                                        height,
 588                                        disposition,
 589                                        render: Arc::new(|_| Empty::new().boxed()),
 590                                    }
 591                                })
 592                                .collect::<Vec<_>>();
 593                            blocks.extend(map.insert_blocks(block_properties, cx));
 594                        } else {
 595                            blocks.shuffle(&mut rng);
 596                            let remove_count = rng.gen_range(1..=4.min(blocks.len()));
 597                            let block_ids_to_remove = (0..remove_count)
 598                                .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
 599                                .collect();
 600                            log::info!("removing block ids {:?}", block_ids_to_remove);
 601                            map.remove_blocks(block_ids_to_remove, cx);
 602                        }
 603                    });
 604                }
 605                45..=79 => {
 606                    let mut ranges = Vec::new();
 607                    for _ in 0..rng.gen_range(1..=3) {
 608                        buffer.read_with(&cx, |buffer, cx| {
 609                            let buffer = buffer.read(cx);
 610                            let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
 611                            let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
 612                            ranges.push(start..end);
 613                        });
 614                    }
 615
 616                    if rng.gen() && fold_count > 0 {
 617                        log::info!("unfolding ranges: {:?}", ranges);
 618                        map.update(&mut cx, |map, cx| {
 619                            map.unfold(ranges, cx);
 620                        });
 621                    } else {
 622                        log::info!("folding ranges: {:?}", ranges);
 623                        map.update(&mut cx, |map, cx| {
 624                            map.fold(ranges, cx);
 625                        });
 626                    }
 627                }
 628                _ => {
 629                    buffer.update(&mut cx, |buffer, cx| buffer.randomly_edit(&mut rng, 5, cx));
 630                }
 631            }
 632
 633            if map.read_with(&cx, |map, cx| map.is_rewrapping(cx)) {
 634                notifications.recv().await.unwrap();
 635            }
 636
 637            let snapshot = map.update(&mut cx, |map, cx| map.snapshot(cx));
 638            fold_count = snapshot.fold_count();
 639            log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
 640            log::info!("fold text: {:?}", snapshot.folds_snapshot.text());
 641            log::info!("tab text: {:?}", snapshot.tabs_snapshot.text());
 642            log::info!("wrap text: {:?}", snapshot.wraps_snapshot.text());
 643            log::info!("block text: {:?}", snapshot.blocks_snapshot.text());
 644            log::info!("display text: {:?}", snapshot.text());
 645
 646            // Line boundaries
 647            for _ in 0..5 {
 648                let row = rng.gen_range(0..=snapshot.max_point().row());
 649                let column = rng.gen_range(0..=snapshot.line_len(row));
 650                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
 651
 652                let (prev_display_bound, prev_buffer_bound) = snapshot.prev_row_boundary(point);
 653                let (next_display_bound, next_buffer_bound) = snapshot.next_row_boundary(point);
 654
 655                assert!(prev_display_bound <= point);
 656                assert!(next_display_bound >= point);
 657                assert_eq!(prev_buffer_bound.column, 0);
 658                assert_eq!(prev_display_bound.column(), 0);
 659                if next_buffer_bound < snapshot.buffer_snapshot.max_point() {
 660                    assert_eq!(
 661                        snapshot.buffer_snapshot.chars_at(next_buffer_bound).next(),
 662                        Some('\n')
 663                    );
 664                }
 665
 666                assert_eq!(
 667                    prev_display_bound,
 668                    prev_buffer_bound.to_display_point(&snapshot),
 669                    "row boundary before {:?}. reported buffer row boundary: {:?}",
 670                    point,
 671                    prev_buffer_bound
 672                );
 673                assert_eq!(
 674                    next_display_bound,
 675                    next_buffer_bound.to_display_point(&snapshot),
 676                    "display row boundary after {:?}. reported buffer row boundary: {:?}",
 677                    point,
 678                    next_buffer_bound
 679                );
 680                assert_eq!(
 681                    prev_buffer_bound,
 682                    prev_display_bound.to_point(&snapshot),
 683                    "row boundary before {:?}. reported display row boundary: {:?}",
 684                    point,
 685                    prev_display_bound
 686                );
 687                assert_eq!(
 688                    next_buffer_bound,
 689                    next_display_bound.to_point(&snapshot),
 690                    "row boundary after {:?}. reported display row boundary: {:?}",
 691                    point,
 692                    next_display_bound
 693                );
 694            }
 695
 696            // Movement
 697            let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
 698            let max_point = snapshot.clip_point(snapshot.max_point(), Right);
 699            for _ in 0..5 {
 700                let row = rng.gen_range(0..=snapshot.max_point().row());
 701                let column = rng.gen_range(0..=snapshot.line_len(row));
 702                let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
 703
 704                log::info!("Moving from point {:?}", point);
 705
 706                let moved_right = movement::right(&snapshot, point).unwrap();
 707                log::info!("Right {:?}", moved_right);
 708                if point < max_point {
 709                    assert!(moved_right > point);
 710                    if point.column() == snapshot.line_len(point.row())
 711                        || snapshot.soft_wrap_indent(point.row()).is_some()
 712                            && point.column() == snapshot.line_len(point.row()) - 1
 713                    {
 714                        assert!(moved_right.row() > point.row());
 715                    }
 716                } else {
 717                    assert_eq!(moved_right, point);
 718                }
 719
 720                let moved_left = movement::left(&snapshot, point).unwrap();
 721                log::info!("Left {:?}", moved_left);
 722                if point > min_point {
 723                    assert!(moved_left < point);
 724                    if point.column() == 0 {
 725                        assert!(moved_left.row() < point.row());
 726                    }
 727                } else {
 728                    assert_eq!(moved_left, point);
 729                }
 730            }
 731        }
 732    }
 733
 734    #[gpui::test(retries = 5)]
 735    fn test_soft_wraps(cx: &mut MutableAppContext) {
 736        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
 737        cx.foreground().forbid_parking();
 738
 739        let font_cache = cx.font_cache();
 740
 741        let tab_size = 4;
 742        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 743        let font_id = font_cache
 744            .select_font(family_id, &Default::default())
 745            .unwrap();
 746        let font_size = 12.0;
 747        let wrap_width = Some(64.);
 748
 749        let text = "one two three four five\nsix seven eight";
 750        let buffer = MultiBuffer::build_simple(text, cx);
 751        let map = cx.add_model(|cx| {
 752            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, wrap_width, cx)
 753        });
 754
 755        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 756        assert_eq!(
 757            snapshot.text_chunks(0).collect::<String>(),
 758            "one two \nthree four \nfive\nsix seven \neight"
 759        );
 760        assert_eq!(
 761            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
 762            DisplayPoint::new(0, 7)
 763        );
 764        assert_eq!(
 765            snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
 766            DisplayPoint::new(1, 0)
 767        );
 768        assert_eq!(
 769            movement::right(&snapshot, DisplayPoint::new(0, 7)).unwrap(),
 770            DisplayPoint::new(1, 0)
 771        );
 772        assert_eq!(
 773            movement::left(&snapshot, DisplayPoint::new(1, 0)).unwrap(),
 774            DisplayPoint::new(0, 7)
 775        );
 776        assert_eq!(
 777            movement::up(&snapshot, DisplayPoint::new(1, 10), SelectionGoal::None).unwrap(),
 778            (DisplayPoint::new(0, 7), SelectionGoal::Column(10))
 779        );
 780        assert_eq!(
 781            movement::down(
 782                &snapshot,
 783                DisplayPoint::new(0, 7),
 784                SelectionGoal::Column(10)
 785            )
 786            .unwrap(),
 787            (DisplayPoint::new(1, 10), SelectionGoal::Column(10))
 788        );
 789        assert_eq!(
 790            movement::down(
 791                &snapshot,
 792                DisplayPoint::new(1, 10),
 793                SelectionGoal::Column(10)
 794            )
 795            .unwrap(),
 796            (DisplayPoint::new(2, 4), SelectionGoal::Column(10))
 797        );
 798
 799        let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
 800        buffer.update(cx, |buffer, cx| {
 801            buffer.edit(vec![ix..ix], "and ", cx);
 802        });
 803
 804        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 805        assert_eq!(
 806            snapshot.text_chunks(1).collect::<String>(),
 807            "three four \nfive\nsix and \nseven eight"
 808        );
 809
 810        // Re-wrap on font size changes
 811        map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
 812
 813        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
 814        assert_eq!(
 815            snapshot.text_chunks(1).collect::<String>(),
 816            "three \nfour five\nsix and \nseven \neight"
 817        )
 818    }
 819
 820    #[gpui::test]
 821    fn test_text_chunks(cx: &mut gpui::MutableAppContext) {
 822        let text = sample_text(6, 6, 'a');
 823        let buffer = MultiBuffer::build_simple(&text, cx);
 824        let tab_size = 4;
 825        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
 826        let font_id = cx
 827            .font_cache()
 828            .select_font(family_id, &Default::default())
 829            .unwrap();
 830        let font_size = 14.0;
 831        let map = cx.add_model(|cx| {
 832            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
 833        });
 834        buffer.update(cx, |buffer, cx| {
 835            buffer.edit(
 836                vec![
 837                    Point::new(1, 0)..Point::new(1, 0),
 838                    Point::new(1, 1)..Point::new(1, 1),
 839                    Point::new(2, 1)..Point::new(2, 1),
 840                ],
 841                "\t",
 842                cx,
 843            )
 844        });
 845
 846        assert_eq!(
 847            map.update(cx, |map, cx| map.snapshot(cx))
 848                .text_chunks(1)
 849                .collect::<String>()
 850                .lines()
 851                .next(),
 852            Some("    b   bbbbb")
 853        );
 854        assert_eq!(
 855            map.update(cx, |map, cx| map.snapshot(cx))
 856                .text_chunks(2)
 857                .collect::<String>()
 858                .lines()
 859                .next(),
 860            Some("c   ccccc")
 861        );
 862    }
 863
 864    #[gpui::test]
 865    async fn test_chunks(mut cx: gpui::TestAppContext) {
 866        use unindent::Unindent as _;
 867
 868        let text = r#"
 869            fn outer() {}
 870
 871            mod module {
 872                fn inner() {}
 873            }"#
 874        .unindent();
 875
 876        let theme = SyntaxTheme::new(vec![
 877            ("mod.body".to_string(), Color::red().into()),
 878            ("fn.name".to_string(), Color::blue().into()),
 879        ]);
 880        let lang = Arc::new(
 881            Language::new(
 882                LanguageConfig {
 883                    name: "Test".to_string(),
 884                    path_suffixes: vec![".test".to_string()],
 885                    ..Default::default()
 886                },
 887                Some(tree_sitter_rust::language()),
 888            )
 889            .with_highlights_query(
 890                r#"
 891                (mod_item name: (identifier) body: _ @mod.body)
 892                (function_item name: (identifier) @fn.name)
 893                "#,
 894            )
 895            .unwrap(),
 896        );
 897        lang.set_theme(&theme);
 898
 899        let buffer =
 900            cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
 901        buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
 902        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 903
 904        let tab_size = 2;
 905        let font_cache = cx.font_cache();
 906        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
 907        let font_id = font_cache
 908            .select_font(family_id, &Default::default())
 909            .unwrap();
 910        let font_size = 14.0;
 911
 912        let map =
 913            cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
 914        assert_eq!(
 915            cx.update(|cx| chunks(0..5, &map, &theme, cx)),
 916            vec![
 917                ("fn ".to_string(), None),
 918                ("outer".to_string(), Some(Color::blue())),
 919                ("() {}\n\nmod module ".to_string(), None),
 920                ("{\n    fn ".to_string(), Some(Color::red())),
 921                ("inner".to_string(), Some(Color::blue())),
 922                ("() {}\n}".to_string(), Some(Color::red())),
 923            ]
 924        );
 925        assert_eq!(
 926            cx.update(|cx| chunks(3..5, &map, &theme, cx)),
 927            vec![
 928                ("    fn ".to_string(), Some(Color::red())),
 929                ("inner".to_string(), Some(Color::blue())),
 930                ("() {}\n}".to_string(), Some(Color::red())),
 931            ]
 932        );
 933
 934        map.update(&mut cx, |map, cx| {
 935            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
 936        });
 937        assert_eq!(
 938            cx.update(|cx| chunks(0..2, &map, &theme, cx)),
 939            vec![
 940                ("fn ".to_string(), None),
 941                ("out".to_string(), Some(Color::blue())),
 942                ("".to_string(), None),
 943                ("  fn ".to_string(), Some(Color::red())),
 944                ("inner".to_string(), Some(Color::blue())),
 945                ("() {}\n}".to_string(), Some(Color::red())),
 946            ]
 947        );
 948    }
 949
 950    #[gpui::test]
 951    async fn test_chunks_with_soft_wrapping(mut cx: gpui::TestAppContext) {
 952        use unindent::Unindent as _;
 953
 954        cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
 955
 956        let text = r#"
 957            fn outer() {}
 958
 959            mod module {
 960                fn inner() {}
 961            }"#
 962        .unindent();
 963
 964        let theme = SyntaxTheme::new(vec![
 965            ("mod.body".to_string(), Color::red().into()),
 966            ("fn.name".to_string(), Color::blue().into()),
 967        ]);
 968        let lang = Arc::new(
 969            Language::new(
 970                LanguageConfig {
 971                    name: "Test".to_string(),
 972                    path_suffixes: vec![".test".to_string()],
 973                    ..Default::default()
 974                },
 975                Some(tree_sitter_rust::language()),
 976            )
 977            .with_highlights_query(
 978                r#"
 979                (mod_item name: (identifier) body: _ @mod.body)
 980                (function_item name: (identifier) @fn.name)
 981                "#,
 982            )
 983            .unwrap(),
 984        );
 985        lang.set_theme(&theme);
 986
 987        let buffer =
 988            cx.add_model(|cx| Buffer::new(0, text, cx).with_language(Some(lang), None, cx));
 989        buffer.condition(&cx, |buf, _| !buf.is_parsing()).await;
 990        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 991
 992        let font_cache = cx.font_cache();
 993
 994        let tab_size = 4;
 995        let family_id = font_cache.load_family(&["Courier"]).unwrap();
 996        let font_id = font_cache
 997            .select_font(family_id, &Default::default())
 998            .unwrap();
 999        let font_size = 16.0;
1000
1001        let map = cx
1002            .add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, Some(40.0), cx));
1003        assert_eq!(
1004            cx.update(|cx| chunks(0..5, &map, &theme, cx)),
1005            [
1006                ("fn \n".to_string(), None),
1007                ("oute\nr".to_string(), Some(Color::blue())),
1008                ("() \n{}\n\n".to_string(), None),
1009            ]
1010        );
1011        assert_eq!(
1012            cx.update(|cx| chunks(3..5, &map, &theme, cx)),
1013            [("{}\n\n".to_string(), None)]
1014        );
1015
1016        map.update(&mut cx, |map, cx| {
1017            map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1018        });
1019        assert_eq!(
1020            cx.update(|cx| chunks(1..4, &map, &theme, cx)),
1021            [
1022                ("out".to_string(), Some(Color::blue())),
1023                ("\n".to_string(), None),
1024                ("  \nfn ".to_string(), Some(Color::red())),
1025                ("i\n".to_string(), Some(Color::blue()))
1026            ]
1027        );
1028    }
1029
1030    #[gpui::test]
1031    fn test_clip_point(cx: &mut gpui::MutableAppContext) {
1032        use Bias::{Left, Right};
1033
1034        let text = "\n'a', 'α',\t'✋',\t'❎', '🍐'\n";
1035        let display_text = "\n'a', 'α',   '✋',    '❎', '🍐'\n";
1036        let buffer = MultiBuffer::build_simple(text, cx);
1037
1038        let tab_size = 4;
1039        let font_cache = cx.font_cache();
1040        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1041        let font_id = font_cache
1042            .select_font(family_id, &Default::default())
1043            .unwrap();
1044        let font_size = 14.0;
1045        let map = cx.add_model(|cx| {
1046            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1047        });
1048        let map = map.update(cx, |map, cx| map.snapshot(cx));
1049
1050        assert_eq!(map.text(), display_text);
1051        for (input_column, bias, output_column) in vec![
1052            ("'a', '".len(), Left, "'a', '".len()),
1053            ("'a', '".len() + 1, Left, "'a', '".len()),
1054            ("'a', '".len() + 1, Right, "'a', 'α".len()),
1055            ("'a', 'α', ".len(), Left, "'a', 'α',".len()),
1056            ("'a', 'α', ".len(), Right, "'a', 'α',   ".len()),
1057            ("'a', 'α',   '".len() + 1, Left, "'a', 'α',   '".len()),
1058            ("'a', 'α',   '".len() + 1, Right, "'a', 'α',   '✋".len()),
1059            ("'a', 'α',   '✋',".len(), Right, "'a', 'α',   '✋',".len()),
1060            ("'a', 'α',   '✋', ".len(), Left, "'a', 'α',   '✋',".len()),
1061            (
1062                "'a', 'α',   '✋', ".len(),
1063                Right,
1064                "'a', 'α',   '✋',    ".len(),
1065            ),
1066        ] {
1067            assert_eq!(
1068                map.clip_point(DisplayPoint::new(1, input_column as u32), bias),
1069                DisplayPoint::new(1, output_column as u32),
1070                "clip_point(({}, {}))",
1071                1,
1072                input_column,
1073            );
1074        }
1075    }
1076
1077    #[gpui::test]
1078    fn test_tabs_with_multibyte_chars(cx: &mut gpui::MutableAppContext) {
1079        let text = "\t\tα\nβ\t\n🏀β\t\tγ";
1080        let buffer = MultiBuffer::build_simple(text, cx);
1081        let tab_size = 4;
1082        let font_cache = cx.font_cache();
1083        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1084        let font_id = font_cache
1085            .select_font(family_id, &Default::default())
1086            .unwrap();
1087        let font_size = 14.0;
1088
1089        let map = cx.add_model(|cx| {
1090            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1091        });
1092        let map = map.update(cx, |map, cx| map.snapshot(cx));
1093        assert_eq!(map.text(), "✅       α\nβ   \n🏀β      γ");
1094        assert_eq!(
1095            map.text_chunks(0).collect::<String>(),
1096            "✅       α\nβ   \n🏀β      γ"
1097        );
1098        assert_eq!(map.text_chunks(1).collect::<String>(), "β   \n🏀β      γ");
1099        assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β      γ");
1100
1101        let point = Point::new(0, "\t\t".len() as u32);
1102        let display_point = DisplayPoint::new(0, "".len() as u32);
1103        assert_eq!(point.to_display_point(&map), display_point);
1104        assert_eq!(display_point.to_point(&map), point);
1105
1106        let point = Point::new(1, "β\t".len() as u32);
1107        let display_point = DisplayPoint::new(1, "β   ".len() as u32);
1108        assert_eq!(point.to_display_point(&map), display_point);
1109        assert_eq!(display_point.to_point(&map), point,);
1110
1111        let point = Point::new(2, "🏀β\t\t".len() as u32);
1112        let display_point = DisplayPoint::new(2, "🏀β      ".len() as u32);
1113        assert_eq!(point.to_display_point(&map), display_point);
1114        assert_eq!(display_point.to_point(&map), point,);
1115
1116        // Display points inside of expanded tabs
1117        assert_eq!(
1118            DisplayPoint::new(0, "".len() as u32).to_point(&map),
1119            Point::new(0, "\t".len() as u32),
1120        );
1121        assert_eq!(
1122            DisplayPoint::new(0, "".len() as u32).to_point(&map),
1123            Point::new(0, "".len() as u32),
1124        );
1125
1126        // Clipping display points inside of multi-byte characters
1127        assert_eq!(
1128            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Left),
1129            DisplayPoint::new(0, 0)
1130        );
1131        assert_eq!(
1132            map.clip_point(DisplayPoint::new(0, "".len() as u32 - 1), Bias::Right),
1133            DisplayPoint::new(0, "".len() as u32)
1134        );
1135    }
1136
1137    #[gpui::test]
1138    fn test_max_point(cx: &mut gpui::MutableAppContext) {
1139        let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1140        let tab_size = 4;
1141        let font_cache = cx.font_cache();
1142        let family_id = font_cache.load_family(&["Helvetica"]).unwrap();
1143        let font_id = font_cache
1144            .select_font(family_id, &Default::default())
1145            .unwrap();
1146        let font_size = 14.0;
1147        let map = cx.add_model(|cx| {
1148            DisplayMap::new(buffer.clone(), tab_size, font_id, font_size, None, cx)
1149        });
1150        assert_eq!(
1151            map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1152            DisplayPoint::new(1, 11)
1153        )
1154    }
1155
1156    fn chunks<'a>(
1157        rows: Range<u32>,
1158        map: &ModelHandle<DisplayMap>,
1159        theme: &'a SyntaxTheme,
1160        cx: &mut MutableAppContext,
1161    ) -> Vec<(String, Option<Color>)> {
1162        let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1163        let mut chunks: Vec<(String, Option<Color>)> = Vec::new();
1164        for chunk in snapshot.chunks(rows, Some(theme)) {
1165            let color = chunk.highlight_style.map(|s| s.color);
1166            if let Some((last_chunk, last_color)) = chunks.last_mut() {
1167                if color == *last_color {
1168                    last_chunk.push_str(chunk.text);
1169                } else {
1170                    chunks.push((chunk.text.to_string(), color));
1171                }
1172            } else {
1173                chunks.push((chunk.text.to_string(), color));
1174            }
1175        }
1176        chunks
1177    }
1178}