display_map.rs

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