display_map.rs

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