display_map.rs

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