display_map.rs

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