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