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