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