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