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