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