1use super::{
2 wrap_map::{self, WrapEdit, WrapPoint, WrapSnapshot},
3 Highlights,
4};
5use crate::{EditorStyle, GutterDimensions};
6use collections::{Bound, HashMap, HashSet};
7use gpui::{AnyElement, Pixels, WindowContext};
8use language::{BufferSnapshot, Chunk, Patch, Point};
9use multi_buffer::{Anchor, ExcerptId, ExcerptRange, MultiBufferRow, ToPoint as _};
10use parking_lot::Mutex;
11use std::{
12 cell::RefCell,
13 cmp::{self, Ordering},
14 fmt::Debug,
15 ops::{Deref, DerefMut, Range, RangeBounds},
16 sync::{
17 atomic::{AtomicUsize, Ordering::SeqCst},
18 Arc,
19 },
20};
21use sum_tree::{Bias, SumTree};
22use text::Edit;
23
24const NEWLINES: &[u8] = &[b'\n'; u8::MAX as usize];
25
26/// Tracks custom blocks such as diagnostics that should be displayed within buffer.
27///
28/// See the [`display_map` module documentation](crate::display_map) for more information.
29pub struct BlockMap {
30 next_block_id: AtomicUsize,
31 wrap_snapshot: RefCell<WrapSnapshot>,
32 blocks: Vec<Arc<Block>>,
33 transforms: RefCell<SumTree<Transform>>,
34 show_excerpt_controls: bool,
35 buffer_header_height: u8,
36 excerpt_header_height: u8,
37 excerpt_footer_height: u8,
38}
39
40pub struct BlockMapWriter<'a>(&'a mut BlockMap);
41
42#[derive(Clone)]
43pub struct BlockSnapshot {
44 wrap_snapshot: WrapSnapshot,
45 transforms: SumTree<Transform>,
46}
47
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
49pub struct BlockId(usize);
50
51#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
52pub struct BlockPoint(pub Point);
53
54#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
55pub struct BlockRow(pub(super) u32);
56
57#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
58struct WrapRow(u32);
59
60pub type RenderBlock = Box<dyn Send + Fn(&mut BlockContext) -> AnyElement>;
61
62pub struct Block {
63 id: BlockId,
64 position: Anchor,
65 height: u8,
66 style: BlockStyle,
67 render: Mutex<RenderBlock>,
68 disposition: BlockDisposition,
69}
70
71pub struct BlockProperties<P> {
72 pub position: P,
73 pub height: u8,
74 pub style: BlockStyle,
75 pub render: Box<dyn Send + Fn(&mut BlockContext) -> AnyElement>,
76 pub disposition: BlockDisposition,
77}
78
79#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
80pub enum BlockStyle {
81 Fixed,
82 Flex,
83 Sticky,
84}
85
86pub struct BlockContext<'a, 'b> {
87 pub context: &'b mut WindowContext<'a>,
88 pub anchor_x: Pixels,
89 pub max_width: Pixels,
90 pub gutter_dimensions: &'b GutterDimensions,
91 pub em_width: Pixels,
92 pub line_height: Pixels,
93 pub block_id: usize,
94 pub editor_style: &'b EditorStyle,
95}
96
97/// Whether the block should be considered above or below the anchor line
98#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
99pub enum BlockDisposition {
100 Above,
101 Below,
102}
103
104#[derive(Clone, Debug)]
105struct Transform {
106 summary: TransformSummary,
107 block: Option<TransformBlock>,
108}
109
110pub(crate) enum BlockType {
111 Custom(BlockId),
112 Header,
113 Footer,
114}
115
116pub(crate) trait BlockLike {
117 fn block_type(&self) -> BlockType;
118 fn disposition(&self) -> BlockDisposition;
119}
120
121#[allow(clippy::large_enum_variant)]
122#[derive(Clone)]
123pub enum TransformBlock {
124 Custom(Arc<Block>),
125 ExcerptHeader {
126 id: ExcerptId,
127 buffer: BufferSnapshot,
128 range: ExcerptRange<text::Anchor>,
129 height: u8,
130 starts_new_buffer: bool,
131 show_excerpt_controls: bool,
132 },
133 ExcerptFooter {
134 id: ExcerptId,
135 disposition: BlockDisposition,
136 height: u8,
137 },
138}
139
140impl BlockLike for TransformBlock {
141 fn block_type(&self) -> BlockType {
142 match self {
143 TransformBlock::Custom(block) => BlockType::Custom(block.id),
144 TransformBlock::ExcerptHeader { .. } => BlockType::Header,
145 TransformBlock::ExcerptFooter { .. } => BlockType::Footer,
146 }
147 }
148
149 fn disposition(&self) -> BlockDisposition {
150 self.disposition()
151 }
152}
153
154impl TransformBlock {
155 fn disposition(&self) -> BlockDisposition {
156 match self {
157 TransformBlock::Custom(block) => block.disposition,
158 TransformBlock::ExcerptHeader { .. } => BlockDisposition::Above,
159 TransformBlock::ExcerptFooter { disposition, .. } => *disposition,
160 }
161 }
162
163 pub fn height(&self) -> u8 {
164 match self {
165 TransformBlock::Custom(block) => block.height,
166 TransformBlock::ExcerptHeader { height, .. } => *height,
167 TransformBlock::ExcerptFooter { height, .. } => *height,
168 }
169 }
170}
171
172impl Debug for TransformBlock {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 match self {
175 Self::Custom(block) => f.debug_struct("Custom").field("block", block).finish(),
176 Self::ExcerptHeader {
177 buffer,
178 starts_new_buffer,
179 id,
180 ..
181 } => f
182 .debug_struct("ExcerptHeader")
183 .field("id", &id)
184 .field("path", &buffer.file().map(|f| f.path()))
185 .field("starts_new_buffer", &starts_new_buffer)
186 .finish(),
187 TransformBlock::ExcerptFooter {
188 id, disposition, ..
189 } => f
190 .debug_struct("ExcerptFooter")
191 .field("id", &id)
192 .field("disposition", &disposition)
193 .finish(),
194 }
195 }
196}
197
198#[derive(Clone, Debug, Default)]
199struct TransformSummary {
200 input_rows: u32,
201 output_rows: u32,
202}
203
204pub struct BlockChunks<'a> {
205 transforms: sum_tree::Cursor<'a, Transform, (BlockRow, WrapRow)>,
206 input_chunks: wrap_map::WrapChunks<'a>,
207 input_chunk: Chunk<'a>,
208 output_row: u32,
209 max_output_row: u32,
210}
211
212#[derive(Clone)]
213pub struct BlockBufferRows<'a> {
214 transforms: sum_tree::Cursor<'a, Transform, (BlockRow, WrapRow)>,
215 input_buffer_rows: wrap_map::WrapBufferRows<'a>,
216 output_row: BlockRow,
217 started: bool,
218}
219
220impl BlockMap {
221 pub fn new(
222 wrap_snapshot: WrapSnapshot,
223 show_excerpt_controls: bool,
224 buffer_header_height: u8,
225 excerpt_header_height: u8,
226 excerpt_footer_height: u8,
227 ) -> Self {
228 let row_count = wrap_snapshot.max_point().row() + 1;
229 let map = Self {
230 next_block_id: AtomicUsize::new(0),
231 blocks: Vec::new(),
232 transforms: RefCell::new(SumTree::from_item(Transform::isomorphic(row_count), &())),
233 wrap_snapshot: RefCell::new(wrap_snapshot.clone()),
234 show_excerpt_controls,
235 buffer_header_height,
236 excerpt_header_height,
237 excerpt_footer_height,
238 };
239 map.sync(
240 &wrap_snapshot,
241 Patch::new(vec![Edit {
242 old: 0..row_count,
243 new: 0..row_count,
244 }]),
245 );
246 map
247 }
248
249 pub fn read(&self, wrap_snapshot: WrapSnapshot, edits: Patch<u32>) -> BlockSnapshot {
250 self.sync(&wrap_snapshot, edits);
251 *self.wrap_snapshot.borrow_mut() = wrap_snapshot.clone();
252 BlockSnapshot {
253 wrap_snapshot,
254 transforms: self.transforms.borrow().clone(),
255 }
256 }
257
258 pub fn write(&mut self, wrap_snapshot: WrapSnapshot, edits: Patch<u32>) -> BlockMapWriter {
259 self.sync(&wrap_snapshot, edits);
260 *self.wrap_snapshot.borrow_mut() = wrap_snapshot;
261 BlockMapWriter(self)
262 }
263
264 fn sync(&self, wrap_snapshot: &WrapSnapshot, mut edits: Patch<u32>) {
265 let buffer = wrap_snapshot.buffer_snapshot();
266
267 // Handle changing the last excerpt if it is empty.
268 if buffer.trailing_excerpt_update_count()
269 != self
270 .wrap_snapshot
271 .borrow()
272 .buffer_snapshot()
273 .trailing_excerpt_update_count()
274 {
275 let max_point = wrap_snapshot.max_point();
276 let edit_start = wrap_snapshot.prev_row_boundary(max_point);
277 let edit_end = max_point.row() + 1;
278 edits = edits.compose([WrapEdit {
279 old: edit_start..edit_end,
280 new: edit_start..edit_end,
281 }]);
282 }
283
284 let edits = edits.into_inner();
285 if edits.is_empty() {
286 return;
287 }
288
289 let mut transforms = self.transforms.borrow_mut();
290 let mut new_transforms = SumTree::new();
291 let old_row_count = transforms.summary().input_rows;
292 let new_row_count = wrap_snapshot.max_point().row() + 1;
293 let mut cursor = transforms.cursor::<WrapRow>();
294 let mut last_block_ix = 0;
295 let mut blocks_in_edit = Vec::new();
296 let mut edits = edits.into_iter().peekable();
297
298 while let Some(edit) = edits.next() {
299 // Preserve any old transforms that precede this edit.
300 let old_start = WrapRow(edit.old.start);
301 let new_start = WrapRow(edit.new.start);
302 new_transforms.append(cursor.slice(&old_start, Bias::Left, &()), &());
303 if let Some(transform) = cursor.item() {
304 if transform.is_isomorphic() && old_start == cursor.end(&()) {
305 new_transforms.push(transform.clone(), &());
306 cursor.next(&());
307 while let Some(transform) = cursor.item() {
308 if transform
309 .block
310 .as_ref()
311 .map_or(false, |b| b.disposition().is_below())
312 {
313 new_transforms.push(transform.clone(), &());
314 cursor.next(&());
315 } else {
316 break;
317 }
318 }
319 }
320 }
321
322 // Preserve any portion of an old transform that precedes this edit.
323 let extent_before_edit = old_start.0 - cursor.start().0;
324 push_isomorphic(&mut new_transforms, extent_before_edit);
325
326 // Skip over any old transforms that intersect this edit.
327 let mut old_end = WrapRow(edit.old.end);
328 let mut new_end = WrapRow(edit.new.end);
329 cursor.seek(&old_end, Bias::Left, &());
330 cursor.next(&());
331 if old_end == *cursor.start() {
332 while let Some(transform) = cursor.item() {
333 if transform
334 .block
335 .as_ref()
336 .map_or(false, |b| b.disposition().is_below())
337 {
338 cursor.next(&());
339 } else {
340 break;
341 }
342 }
343 }
344
345 // Combine this edit with any subsequent edits that intersect the same transform.
346 while let Some(next_edit) = edits.peek() {
347 if next_edit.old.start <= cursor.start().0 {
348 old_end = WrapRow(next_edit.old.end);
349 new_end = WrapRow(next_edit.new.end);
350 cursor.seek(&old_end, Bias::Left, &());
351 cursor.next(&());
352 if old_end == *cursor.start() {
353 while let Some(transform) = cursor.item() {
354 if transform
355 .block
356 .as_ref()
357 .map_or(false, |b| b.disposition().is_below())
358 {
359 cursor.next(&());
360 } else {
361 break;
362 }
363 }
364 }
365 edits.next();
366 } else {
367 break;
368 }
369 }
370
371 // Find the blocks within this edited region.
372 let new_buffer_start =
373 wrap_snapshot.to_point(WrapPoint::new(new_start.0, 0), Bias::Left);
374 let start_bound = Bound::Included(new_buffer_start);
375 let start_block_ix = match self.blocks[last_block_ix..].binary_search_by(|probe| {
376 probe
377 .position
378 .to_point(buffer)
379 .cmp(&new_buffer_start)
380 .then(Ordering::Greater)
381 }) {
382 Ok(ix) | Err(ix) => last_block_ix + ix,
383 };
384
385 let end_bound;
386 let end_block_ix = if new_end.0 > wrap_snapshot.max_point().row() {
387 end_bound = Bound::Unbounded;
388 self.blocks.len()
389 } else {
390 let new_buffer_end =
391 wrap_snapshot.to_point(WrapPoint::new(new_end.0, 0), Bias::Left);
392 end_bound = Bound::Excluded(new_buffer_end);
393 match self.blocks[start_block_ix..].binary_search_by(|probe| {
394 probe
395 .position
396 .to_point(buffer)
397 .cmp(&new_buffer_end)
398 .then(Ordering::Greater)
399 }) {
400 Ok(ix) | Err(ix) => start_block_ix + ix,
401 }
402 };
403 last_block_ix = end_block_ix;
404
405 debug_assert!(blocks_in_edit.is_empty());
406 blocks_in_edit.extend(
407 self.blocks[start_block_ix..end_block_ix]
408 .iter()
409 .map(|block| {
410 let mut position = block.position.to_point(buffer);
411 match block.disposition {
412 BlockDisposition::Above => position.column = 0,
413 BlockDisposition::Below => {
414 position.column = buffer.line_len(MultiBufferRow(position.row))
415 }
416 }
417 let position = wrap_snapshot.make_wrap_point(position, Bias::Left);
418 (position.row(), TransformBlock::Custom(block.clone()))
419 }),
420 );
421
422 if buffer.show_headers() {
423 blocks_in_edit.extend(BlockMap::header_blocks(
424 self.show_excerpt_controls,
425 self.excerpt_footer_height,
426 self.buffer_header_height,
427 self.excerpt_header_height,
428 buffer,
429 (start_bound, end_bound),
430 wrap_snapshot,
431 ));
432 }
433
434 BlockMap::sort_blocks(&mut blocks_in_edit);
435
436 // For each of these blocks, insert a new isomorphic transform preceding the block,
437 // and then insert the block itself.
438 for (block_row, block) in blocks_in_edit.drain(..) {
439 let insertion_row = match block.disposition() {
440 BlockDisposition::Above => block_row,
441 BlockDisposition::Below => block_row + 1,
442 };
443 let extent_before_block = insertion_row - new_transforms.summary().input_rows;
444 push_isomorphic(&mut new_transforms, extent_before_block);
445 new_transforms.push(Transform::block(block), &());
446 }
447
448 old_end = WrapRow(old_end.0.min(old_row_count));
449 new_end = WrapRow(new_end.0.min(new_row_count));
450
451 // Insert an isomorphic transform after the final block.
452 let extent_after_last_block = new_end.0 - new_transforms.summary().input_rows;
453 push_isomorphic(&mut new_transforms, extent_after_last_block);
454
455 // Preserve any portion of the old transform after this edit.
456 let extent_after_edit = cursor.start().0 - old_end.0;
457 push_isomorphic(&mut new_transforms, extent_after_edit);
458 }
459
460 new_transforms.append(cursor.suffix(&()), &());
461 debug_assert_eq!(
462 new_transforms.summary().input_rows,
463 wrap_snapshot.max_point().row() + 1
464 );
465
466 drop(cursor);
467 *transforms = new_transforms;
468 }
469
470 pub fn replace(&mut self, mut renderers: HashMap<BlockId, RenderBlock>) {
471 for block in &self.blocks {
472 if let Some(render) = renderers.remove(&block.id) {
473 *block.render.lock() = render;
474 }
475 }
476 }
477
478 pub fn show_excerpt_controls(&self) -> bool {
479 self.show_excerpt_controls
480 }
481
482 pub fn header_blocks<'a, 'b: 'a, 'c: 'a + 'b, R, T>(
483 show_excerpt_controls: bool,
484 excerpt_footer_height: u8,
485 buffer_header_height: u8,
486 excerpt_header_height: u8,
487 buffer: &'b multi_buffer::MultiBufferSnapshot,
488 range: R,
489 wrap_snapshot: &'c WrapSnapshot,
490 ) -> impl Iterator<Item = (u32, TransformBlock)> + 'b
491 where
492 R: RangeBounds<T>,
493 T: multi_buffer::ToOffset,
494 {
495 buffer
496 .excerpt_boundaries_in_range(range)
497 .flat_map(move |excerpt_boundary| {
498 let wrap_row = wrap_snapshot
499 .make_wrap_point(Point::new(excerpt_boundary.row.0, 0), Bias::Left)
500 .row();
501
502 [
503 show_excerpt_controls
504 .then(|| {
505 excerpt_boundary.prev.as_ref().map(|prev| {
506 (
507 wrap_row,
508 TransformBlock::ExcerptFooter {
509 id: prev.id,
510 height: excerpt_footer_height,
511 disposition: if excerpt_boundary.next.is_some() {
512 BlockDisposition::Above
513 } else {
514 BlockDisposition::Below
515 },
516 },
517 )
518 })
519 })
520 .flatten(),
521 excerpt_boundary.next.map(|next| {
522 let starts_new_buffer = excerpt_boundary
523 .prev
524 .map_or(true, |prev| prev.buffer_id != next.buffer_id);
525
526 (
527 wrap_row,
528 TransformBlock::ExcerptHeader {
529 id: next.id,
530 buffer: next.buffer,
531 range: next.range,
532 height: if starts_new_buffer {
533 buffer_header_height
534 } else {
535 excerpt_header_height
536 },
537 starts_new_buffer,
538 show_excerpt_controls,
539 },
540 )
541 }),
542 ]
543 })
544 .flatten()
545 }
546
547 pub(crate) fn sort_blocks<B: BlockLike>(blocks: &mut Vec<(u32, B)>) {
548 // Place excerpt headers and footers above custom blocks on the same row
549 blocks.sort_unstable_by(|(row_a, block_a), (row_b, block_b)| {
550 row_a.cmp(row_b).then_with(|| {
551 block_a
552 .disposition()
553 .cmp(&block_b.disposition())
554 .then_with(|| match ((block_a.block_type()), (block_b.block_type())) {
555 (BlockType::Footer, BlockType::Footer) => Ordering::Equal,
556 (BlockType::Footer, _) => Ordering::Less,
557 (_, BlockType::Footer) => Ordering::Greater,
558 (BlockType::Header, BlockType::Header) => Ordering::Equal,
559 (BlockType::Header, _) => Ordering::Less,
560 (_, BlockType::Header) => Ordering::Greater,
561 (BlockType::Custom(a_id), BlockType::Custom(b_id)) => a_id.cmp(&b_id),
562 })
563 })
564 });
565 }
566}
567
568fn push_isomorphic(tree: &mut SumTree<Transform>, rows: u32) {
569 if rows == 0 {
570 return;
571 }
572
573 let mut extent = Some(rows);
574 tree.update_last(
575 |last_transform| {
576 if last_transform.is_isomorphic() {
577 let extent = extent.take().unwrap();
578 last_transform.summary.input_rows += extent;
579 last_transform.summary.output_rows += extent;
580 }
581 },
582 &(),
583 );
584 if let Some(extent) = extent {
585 tree.push(Transform::isomorphic(extent), &());
586 }
587}
588
589impl BlockPoint {
590 pub fn new(row: u32, column: u32) -> Self {
591 Self(Point::new(row, column))
592 }
593}
594
595impl Deref for BlockPoint {
596 type Target = Point;
597
598 fn deref(&self) -> &Self::Target {
599 &self.0
600 }
601}
602
603impl std::ops::DerefMut for BlockPoint {
604 fn deref_mut(&mut self) -> &mut Self::Target {
605 &mut self.0
606 }
607}
608
609impl<'a> BlockMapWriter<'a> {
610 pub fn insert(
611 &mut self,
612 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
613 ) -> Vec<BlockId> {
614 let mut ids = Vec::new();
615 let mut edits = Patch::default();
616 let wrap_snapshot = &*self.0.wrap_snapshot.borrow();
617 let buffer = wrap_snapshot.buffer_snapshot();
618
619 for block in blocks {
620 let id = BlockId(self.0.next_block_id.fetch_add(1, SeqCst));
621 ids.push(id);
622
623 let position = block.position;
624 let point = position.to_point(buffer);
625 let wrap_row = wrap_snapshot
626 .make_wrap_point(Point::new(point.row, 0), Bias::Left)
627 .row();
628 let start_row = wrap_snapshot.prev_row_boundary(WrapPoint::new(wrap_row, 0));
629 let end_row = wrap_snapshot
630 .next_row_boundary(WrapPoint::new(wrap_row, 0))
631 .unwrap_or(wrap_snapshot.max_point().row() + 1);
632
633 let block_ix = match self
634 .0
635 .blocks
636 .binary_search_by(|probe| probe.position.cmp(&position, buffer))
637 {
638 Ok(ix) | Err(ix) => ix,
639 };
640 self.0.blocks.insert(
641 block_ix,
642 Arc::new(Block {
643 id,
644 position,
645 height: block.height,
646 render: Mutex::new(block.render),
647 disposition: block.disposition,
648 style: block.style,
649 }),
650 );
651
652 edits = edits.compose([Edit {
653 old: start_row..end_row,
654 new: start_row..end_row,
655 }]);
656 }
657
658 self.0.sync(wrap_snapshot, edits);
659 ids
660 }
661
662 pub fn remove(&mut self, block_ids: HashSet<BlockId>) {
663 let wrap_snapshot = &*self.0.wrap_snapshot.borrow();
664 let buffer = wrap_snapshot.buffer_snapshot();
665 let mut edits = Patch::default();
666 let mut last_block_buffer_row = None;
667 self.0.blocks.retain(|block| {
668 if block_ids.contains(&block.id) {
669 let buffer_row = block.position.to_point(buffer).row;
670 if last_block_buffer_row != Some(buffer_row) {
671 last_block_buffer_row = Some(buffer_row);
672 let wrap_row = wrap_snapshot
673 .make_wrap_point(Point::new(buffer_row, 0), Bias::Left)
674 .row();
675 let start_row = wrap_snapshot.prev_row_boundary(WrapPoint::new(wrap_row, 0));
676 let end_row = wrap_snapshot
677 .next_row_boundary(WrapPoint::new(wrap_row, 0))
678 .unwrap_or(wrap_snapshot.max_point().row() + 1);
679 edits.push(Edit {
680 old: start_row..end_row,
681 new: start_row..end_row,
682 })
683 }
684 false
685 } else {
686 true
687 }
688 });
689 self.0.sync(wrap_snapshot, edits);
690 }
691}
692
693impl BlockSnapshot {
694 #[cfg(test)]
695 pub fn text(&self) -> String {
696 self.chunks(
697 0..self.transforms.summary().output_rows,
698 false,
699 Highlights::default(),
700 )
701 .map(|chunk| chunk.text)
702 .collect()
703 }
704
705 pub(crate) fn chunks<'a>(
706 &'a self,
707 rows: Range<u32>,
708 language_aware: bool,
709 highlights: Highlights<'a>,
710 ) -> BlockChunks<'a> {
711 let max_output_row = cmp::min(rows.end, self.transforms.summary().output_rows);
712 let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
713 let input_end = {
714 cursor.seek(&BlockRow(rows.end), Bias::Right, &());
715 let overshoot = if cursor
716 .item()
717 .map_or(false, |transform| transform.is_isomorphic())
718 {
719 rows.end - cursor.start().0 .0
720 } else {
721 0
722 };
723 cursor.start().1 .0 + overshoot
724 };
725 let input_start = {
726 cursor.seek(&BlockRow(rows.start), Bias::Right, &());
727 let overshoot = if cursor
728 .item()
729 .map_or(false, |transform| transform.is_isomorphic())
730 {
731 rows.start - cursor.start().0 .0
732 } else {
733 0
734 };
735 cursor.start().1 .0 + overshoot
736 };
737 BlockChunks {
738 input_chunks: self.wrap_snapshot.chunks(
739 input_start..input_end,
740 language_aware,
741 highlights,
742 ),
743 input_chunk: Default::default(),
744 transforms: cursor,
745 output_row: rows.start,
746 max_output_row,
747 }
748 }
749
750 pub(super) fn buffer_rows(&self, start_row: BlockRow) -> BlockBufferRows {
751 let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
752 cursor.seek(&start_row, Bias::Right, &());
753 let (output_start, input_start) = cursor.start();
754 let overshoot = if cursor.item().map_or(false, |t| t.is_isomorphic()) {
755 start_row.0 - output_start.0
756 } else {
757 0
758 };
759 let input_start_row = input_start.0 + overshoot;
760 BlockBufferRows {
761 transforms: cursor,
762 input_buffer_rows: self.wrap_snapshot.buffer_rows(input_start_row),
763 output_row: start_row,
764 started: false,
765 }
766 }
767
768 pub fn blocks_in_range(
769 &self,
770 rows: Range<u32>,
771 ) -> impl Iterator<Item = (u32, &TransformBlock)> {
772 let mut cursor = self.transforms.cursor::<BlockRow>();
773 cursor.seek(&BlockRow(rows.start), Bias::Right, &());
774 std::iter::from_fn(move || {
775 while let Some(transform) = cursor.item() {
776 let start_row = cursor.start().0;
777 if start_row >= rows.end {
778 break;
779 }
780 if let Some(block) = &transform.block {
781 cursor.next(&());
782 return Some((start_row, block));
783 } else {
784 cursor.next(&());
785 }
786 }
787 None
788 })
789 }
790
791 pub fn max_point(&self) -> BlockPoint {
792 let row = self.transforms.summary().output_rows - 1;
793 BlockPoint::new(row, self.line_len(BlockRow(row)))
794 }
795
796 pub fn longest_row(&self) -> u32 {
797 let input_row = self.wrap_snapshot.longest_row();
798 self.to_block_point(WrapPoint::new(input_row, 0)).row
799 }
800
801 pub(super) fn line_len(&self, row: BlockRow) -> u32 {
802 let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
803 cursor.seek(&BlockRow(row.0), Bias::Right, &());
804 if let Some(transform) = cursor.item() {
805 let (output_start, input_start) = cursor.start();
806 let overshoot = row.0 - output_start.0;
807 if transform.block.is_some() {
808 0
809 } else {
810 self.wrap_snapshot.line_len(input_start.0 + overshoot)
811 }
812 } else {
813 panic!("row out of range");
814 }
815 }
816
817 pub(super) fn is_block_line(&self, row: BlockRow) -> bool {
818 let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
819 cursor.seek(&row, Bias::Right, &());
820 cursor.item().map_or(false, |t| t.block.is_some())
821 }
822
823 pub fn clip_point(&self, point: BlockPoint, bias: Bias) -> BlockPoint {
824 let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
825 cursor.seek(&BlockRow(point.row), Bias::Right, &());
826
827 let max_input_row = WrapRow(self.transforms.summary().input_rows);
828 let mut search_left =
829 (bias == Bias::Left && cursor.start().1 .0 > 0) || cursor.end(&()).1 == max_input_row;
830 let mut reversed = false;
831
832 loop {
833 if let Some(transform) = cursor.item() {
834 if transform.is_isomorphic() {
835 let (output_start_row, input_start_row) = cursor.start();
836 let (output_end_row, input_end_row) = cursor.end(&());
837 let output_start = Point::new(output_start_row.0, 0);
838 let input_start = Point::new(input_start_row.0, 0);
839 let input_end = Point::new(input_end_row.0, 0);
840 let input_point = if point.row >= output_end_row.0 {
841 let line_len = self.wrap_snapshot.line_len(input_end_row.0 - 1);
842 self.wrap_snapshot
843 .clip_point(WrapPoint::new(input_end_row.0 - 1, line_len), bias)
844 } else {
845 let output_overshoot = point.0.saturating_sub(output_start);
846 self.wrap_snapshot
847 .clip_point(WrapPoint(input_start + output_overshoot), bias)
848 };
849
850 if (input_start..input_end).contains(&input_point.0) {
851 let input_overshoot = input_point.0.saturating_sub(input_start);
852 return BlockPoint(output_start + input_overshoot);
853 }
854 }
855
856 if search_left {
857 cursor.prev(&());
858 } else {
859 cursor.next(&());
860 }
861 } else if reversed {
862 return self.max_point();
863 } else {
864 reversed = true;
865 search_left = !search_left;
866 cursor.seek(&BlockRow(point.row), Bias::Right, &());
867 }
868 }
869 }
870
871 pub fn to_block_point(&self, wrap_point: WrapPoint) -> BlockPoint {
872 let mut cursor = self.transforms.cursor::<(WrapRow, BlockRow)>();
873 cursor.seek(&WrapRow(wrap_point.row()), Bias::Right, &());
874 if let Some(transform) = cursor.item() {
875 debug_assert!(transform.is_isomorphic());
876 } else {
877 return self.max_point();
878 }
879
880 let (input_start_row, output_start_row) = cursor.start();
881 let input_start = Point::new(input_start_row.0, 0);
882 let output_start = Point::new(output_start_row.0, 0);
883 let input_overshoot = wrap_point.0 - input_start;
884 BlockPoint(output_start + input_overshoot)
885 }
886
887 pub fn to_wrap_point(&self, block_point: BlockPoint) -> WrapPoint {
888 let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
889 cursor.seek(&BlockRow(block_point.row), Bias::Right, &());
890 if let Some(transform) = cursor.item() {
891 match transform.block.as_ref().map(|b| b.disposition()) {
892 Some(BlockDisposition::Above) => WrapPoint::new(cursor.start().1 .0, 0),
893 Some(BlockDisposition::Below) => {
894 let wrap_row = cursor.start().1 .0 - 1;
895 WrapPoint::new(wrap_row, self.wrap_snapshot.line_len(wrap_row))
896 }
897 None => {
898 let overshoot = block_point.row - cursor.start().0 .0;
899 let wrap_row = cursor.start().1 .0 + overshoot;
900 WrapPoint::new(wrap_row, block_point.column)
901 }
902 }
903 } else {
904 self.wrap_snapshot.max_point()
905 }
906 }
907}
908
909impl Transform {
910 fn isomorphic(rows: u32) -> Self {
911 Self {
912 summary: TransformSummary {
913 input_rows: rows,
914 output_rows: rows,
915 },
916 block: None,
917 }
918 }
919
920 fn block(block: TransformBlock) -> Self {
921 Self {
922 summary: TransformSummary {
923 input_rows: 0,
924 output_rows: block.height() as u32,
925 },
926 block: Some(block),
927 }
928 }
929
930 fn is_isomorphic(&self) -> bool {
931 self.block.is_none()
932 }
933}
934
935impl<'a> Iterator for BlockChunks<'a> {
936 type Item = Chunk<'a>;
937
938 fn next(&mut self) -> Option<Self::Item> {
939 if self.output_row >= self.max_output_row {
940 return None;
941 }
942
943 let transform = self.transforms.item()?;
944 if transform.block.is_some() {
945 let block_start = self.transforms.start().0 .0;
946 let mut block_end = self.transforms.end(&()).0 .0;
947 self.transforms.next(&());
948 if self.transforms.item().is_none() {
949 block_end -= 1;
950 }
951
952 let start_in_block = self.output_row - block_start;
953 let end_in_block = cmp::min(self.max_output_row, block_end) - block_start;
954 let line_count = end_in_block - start_in_block;
955 self.output_row += line_count;
956
957 return Some(Chunk {
958 text: unsafe { std::str::from_utf8_unchecked(&NEWLINES[..line_count as usize]) },
959 ..Default::default()
960 });
961 }
962
963 if self.input_chunk.text.is_empty() {
964 if let Some(input_chunk) = self.input_chunks.next() {
965 self.input_chunk = input_chunk;
966 } else {
967 self.output_row += 1;
968 if self.output_row < self.max_output_row {
969 self.transforms.next(&());
970 return Some(Chunk {
971 text: "\n",
972 ..Default::default()
973 });
974 } else {
975 return None;
976 }
977 }
978 }
979
980 let transform_end = self.transforms.end(&()).0 .0;
981 let (prefix_rows, prefix_bytes) =
982 offset_for_row(self.input_chunk.text, transform_end - self.output_row);
983 self.output_row += prefix_rows;
984 let (prefix, suffix) = self.input_chunk.text.split_at(prefix_bytes);
985 self.input_chunk.text = suffix;
986 if self.output_row == transform_end {
987 self.transforms.next(&());
988 }
989
990 Some(Chunk {
991 text: prefix,
992 ..self.input_chunk.clone()
993 })
994 }
995}
996
997impl<'a> Iterator for BlockBufferRows<'a> {
998 type Item = Option<BlockRow>;
999
1000 fn next(&mut self) -> Option<Self::Item> {
1001 if self.started {
1002 self.output_row.0 += 1;
1003 } else {
1004 self.started = true;
1005 }
1006
1007 if self.output_row.0 >= self.transforms.end(&()).0 .0 {
1008 self.transforms.next(&());
1009 }
1010
1011 let transform = self.transforms.item()?;
1012 if transform.block.is_some() {
1013 Some(None)
1014 } else {
1015 Some(self.input_buffer_rows.next().unwrap().map(BlockRow))
1016 }
1017 }
1018}
1019
1020impl sum_tree::Item for Transform {
1021 type Summary = TransformSummary;
1022
1023 fn summary(&self) -> Self::Summary {
1024 self.summary.clone()
1025 }
1026}
1027
1028impl sum_tree::Summary for TransformSummary {
1029 type Context = ();
1030
1031 fn add_summary(&mut self, summary: &Self, _: &()) {
1032 self.input_rows += summary.input_rows;
1033 self.output_rows += summary.output_rows;
1034 }
1035}
1036
1037impl<'a> sum_tree::Dimension<'a, TransformSummary> for WrapRow {
1038 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1039 self.0 += summary.input_rows;
1040 }
1041}
1042
1043impl<'a> sum_tree::Dimension<'a, TransformSummary> for BlockRow {
1044 fn add_summary(&mut self, summary: &'a TransformSummary, _: &()) {
1045 self.0 += summary.output_rows;
1046 }
1047}
1048
1049impl BlockDisposition {
1050 fn is_below(&self) -> bool {
1051 matches!(self, BlockDisposition::Below)
1052 }
1053}
1054
1055impl<'a> Deref for BlockContext<'a, '_> {
1056 type Target = WindowContext<'a>;
1057
1058 fn deref(&self) -> &Self::Target {
1059 self.context
1060 }
1061}
1062
1063impl DerefMut for BlockContext<'_, '_> {
1064 fn deref_mut(&mut self) -> &mut Self::Target {
1065 self.context
1066 }
1067}
1068
1069impl Block {
1070 pub fn render(&self, cx: &mut BlockContext) -> AnyElement {
1071 self.render.lock()(cx)
1072 }
1073
1074 pub fn position(&self) -> &Anchor {
1075 &self.position
1076 }
1077
1078 pub fn style(&self) -> BlockStyle {
1079 self.style
1080 }
1081}
1082
1083impl Debug for Block {
1084 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1085 f.debug_struct("Block")
1086 .field("id", &self.id)
1087 .field("position", &self.position)
1088 .field("disposition", &self.disposition)
1089 .finish()
1090 }
1091}
1092
1093// Count the number of bytes prior to a target point. If the string doesn't contain the target
1094// point, return its total extent. Otherwise return the target point itself.
1095fn offset_for_row(s: &str, target: u32) -> (u32, usize) {
1096 let mut row = 0;
1097 let mut offset = 0;
1098 for (ix, line) in s.split('\n').enumerate() {
1099 if ix > 0 {
1100 row += 1;
1101 offset += 1;
1102 }
1103 if row >= target {
1104 break;
1105 }
1106 offset += line.len();
1107 }
1108 (row, offset)
1109}
1110
1111#[cfg(test)]
1112mod tests {
1113 use std::env;
1114
1115 use super::*;
1116 use crate::display_map::inlay_map::InlayMap;
1117 use crate::display_map::{fold_map::FoldMap, tab_map::TabMap, wrap_map::WrapMap};
1118 use gpui::{div, font, px, Element};
1119 use multi_buffer::MultiBuffer;
1120 use rand::prelude::*;
1121 use settings::SettingsStore;
1122 use util::RandomCharIter;
1123
1124 #[gpui::test]
1125 fn test_offset_for_row() {
1126 assert_eq!(offset_for_row("", 0), (0, 0));
1127 assert_eq!(offset_for_row("", 1), (0, 0));
1128 assert_eq!(offset_for_row("abcd", 0), (0, 0));
1129 assert_eq!(offset_for_row("abcd", 1), (0, 4));
1130 assert_eq!(offset_for_row("\n", 0), (0, 0));
1131 assert_eq!(offset_for_row("\n", 1), (1, 1));
1132 assert_eq!(offset_for_row("abc\ndef\nghi", 0), (0, 0));
1133 assert_eq!(offset_for_row("abc\ndef\nghi", 1), (1, 4));
1134 assert_eq!(offset_for_row("abc\ndef\nghi", 2), (2, 8));
1135 assert_eq!(offset_for_row("abc\ndef\nghi", 3), (2, 11));
1136 }
1137
1138 #[gpui::test]
1139 fn test_basic_blocks(cx: &mut gpui::TestAppContext) {
1140 cx.update(|cx| init_test(cx));
1141
1142 let text = "aaa\nbbb\nccc\nddd";
1143
1144 let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
1145 let buffer_snapshot = cx.update(|cx| buffer.read(cx).snapshot(cx));
1146 let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
1147 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1148 let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot);
1149 let (mut tab_map, tab_snapshot) = TabMap::new(fold_snapshot, 1.try_into().unwrap());
1150 let (wrap_map, wraps_snapshot) =
1151 cx.update(|cx| WrapMap::new(tab_snapshot, font("Helvetica"), px(14.0), None, cx));
1152 let mut block_map = BlockMap::new(wraps_snapshot.clone(), true, 1, 1, 1);
1153
1154 let mut writer = block_map.write(wraps_snapshot.clone(), Default::default());
1155 let block_ids = writer.insert(vec![
1156 BlockProperties {
1157 style: BlockStyle::Fixed,
1158 position: buffer_snapshot.anchor_after(Point::new(1, 0)),
1159 height: 1,
1160 disposition: BlockDisposition::Above,
1161 render: Box::new(|_| div().into_any()),
1162 },
1163 BlockProperties {
1164 style: BlockStyle::Fixed,
1165 position: buffer_snapshot.anchor_after(Point::new(1, 2)),
1166 height: 2,
1167 disposition: BlockDisposition::Above,
1168 render: Box::new(|_| div().into_any()),
1169 },
1170 BlockProperties {
1171 style: BlockStyle::Fixed,
1172 position: buffer_snapshot.anchor_after(Point::new(3, 3)),
1173 height: 3,
1174 disposition: BlockDisposition::Below,
1175 render: Box::new(|_| div().into_any()),
1176 },
1177 ]);
1178
1179 let snapshot = block_map.read(wraps_snapshot, Default::default());
1180 assert_eq!(snapshot.text(), "aaa\n\n\n\nbbb\nccc\nddd\n\n\n");
1181
1182 let blocks = snapshot
1183 .blocks_in_range(0..8)
1184 .map(|(start_row, block)| {
1185 let block = block.as_custom().unwrap();
1186 (start_row..start_row + block.height as u32, block.id)
1187 })
1188 .collect::<Vec<_>>();
1189
1190 // When multiple blocks are on the same line, the newer blocks appear first.
1191 assert_eq!(
1192 blocks,
1193 &[
1194 (1..2, block_ids[0]),
1195 (2..4, block_ids[1]),
1196 (7..10, block_ids[2]),
1197 ]
1198 );
1199
1200 assert_eq!(
1201 snapshot.to_block_point(WrapPoint::new(0, 3)),
1202 BlockPoint::new(0, 3)
1203 );
1204 assert_eq!(
1205 snapshot.to_block_point(WrapPoint::new(1, 0)),
1206 BlockPoint::new(4, 0)
1207 );
1208 assert_eq!(
1209 snapshot.to_block_point(WrapPoint::new(3, 3)),
1210 BlockPoint::new(6, 3)
1211 );
1212
1213 assert_eq!(
1214 snapshot.to_wrap_point(BlockPoint::new(0, 3)),
1215 WrapPoint::new(0, 3)
1216 );
1217 assert_eq!(
1218 snapshot.to_wrap_point(BlockPoint::new(1, 0)),
1219 WrapPoint::new(1, 0)
1220 );
1221 assert_eq!(
1222 snapshot.to_wrap_point(BlockPoint::new(3, 0)),
1223 WrapPoint::new(1, 0)
1224 );
1225 assert_eq!(
1226 snapshot.to_wrap_point(BlockPoint::new(7, 0)),
1227 WrapPoint::new(3, 3)
1228 );
1229
1230 assert_eq!(
1231 snapshot.clip_point(BlockPoint::new(1, 0), Bias::Left),
1232 BlockPoint::new(0, 3)
1233 );
1234 assert_eq!(
1235 snapshot.clip_point(BlockPoint::new(1, 0), Bias::Right),
1236 BlockPoint::new(4, 0)
1237 );
1238 assert_eq!(
1239 snapshot.clip_point(BlockPoint::new(1, 1), Bias::Left),
1240 BlockPoint::new(0, 3)
1241 );
1242 assert_eq!(
1243 snapshot.clip_point(BlockPoint::new(1, 1), Bias::Right),
1244 BlockPoint::new(4, 0)
1245 );
1246 assert_eq!(
1247 snapshot.clip_point(BlockPoint::new(4, 0), Bias::Left),
1248 BlockPoint::new(4, 0)
1249 );
1250 assert_eq!(
1251 snapshot.clip_point(BlockPoint::new(4, 0), Bias::Right),
1252 BlockPoint::new(4, 0)
1253 );
1254 assert_eq!(
1255 snapshot.clip_point(BlockPoint::new(6, 3), Bias::Left),
1256 BlockPoint::new(6, 3)
1257 );
1258 assert_eq!(
1259 snapshot.clip_point(BlockPoint::new(6, 3), Bias::Right),
1260 BlockPoint::new(6, 3)
1261 );
1262 assert_eq!(
1263 snapshot.clip_point(BlockPoint::new(7, 0), Bias::Left),
1264 BlockPoint::new(6, 3)
1265 );
1266 assert_eq!(
1267 snapshot.clip_point(BlockPoint::new(7, 0), Bias::Right),
1268 BlockPoint::new(6, 3)
1269 );
1270
1271 assert_eq!(
1272 snapshot
1273 .buffer_rows(BlockRow(0))
1274 .map(|row| row.map(|r| r.0))
1275 .collect::<Vec<_>>(),
1276 &[
1277 Some(0),
1278 None,
1279 None,
1280 None,
1281 Some(1),
1282 Some(2),
1283 Some(3),
1284 None,
1285 None,
1286 None
1287 ]
1288 );
1289
1290 // Insert a line break, separating two block decorations into separate lines.
1291 let buffer_snapshot = buffer.update(cx, |buffer, cx| {
1292 buffer.edit([(Point::new(1, 1)..Point::new(1, 1), "!!!\n")], None, cx);
1293 buffer.snapshot(cx)
1294 });
1295
1296 let (inlay_snapshot, inlay_edits) =
1297 inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
1298 let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1299 let (tab_snapshot, tab_edits) =
1300 tab_map.sync(fold_snapshot, fold_edits, 4.try_into().unwrap());
1301 let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
1302 wrap_map.sync(tab_snapshot, tab_edits, cx)
1303 });
1304 let snapshot = block_map.read(wraps_snapshot, wrap_edits);
1305 assert_eq!(snapshot.text(), "aaa\n\nb!!!\n\n\nbb\nccc\nddd\n\n\n");
1306 }
1307
1308 #[gpui::test]
1309 fn test_blocks_on_wrapped_lines(cx: &mut gpui::TestAppContext) {
1310 cx.update(|cx| init_test(cx));
1311
1312 let _font_id = cx.text_system().font_id(&font("Helvetica")).unwrap();
1313
1314 let text = "one two three\nfour five six\nseven eight";
1315
1316 let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
1317 let buffer_snapshot = cx.update(|cx| buffer.read(cx).snapshot(cx));
1318 let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1319 let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
1320 let (_, tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
1321 let (_, wraps_snapshot) = cx.update(|cx| {
1322 WrapMap::new(tab_snapshot, font("Helvetica"), px(14.0), Some(px(60.)), cx)
1323 });
1324 let mut block_map = BlockMap::new(wraps_snapshot.clone(), true, 1, 1, 0);
1325
1326 let mut writer = block_map.write(wraps_snapshot.clone(), Default::default());
1327 writer.insert(vec![
1328 BlockProperties {
1329 style: BlockStyle::Fixed,
1330 position: buffer_snapshot.anchor_after(Point::new(1, 12)),
1331 disposition: BlockDisposition::Above,
1332 render: Box::new(|_| div().into_any()),
1333 height: 1,
1334 },
1335 BlockProperties {
1336 style: BlockStyle::Fixed,
1337 position: buffer_snapshot.anchor_after(Point::new(1, 1)),
1338 disposition: BlockDisposition::Below,
1339 render: Box::new(|_| div().into_any()),
1340 height: 1,
1341 },
1342 ]);
1343
1344 // Blocks with an 'above' disposition go above their corresponding buffer line.
1345 // Blocks with a 'below' disposition go below their corresponding buffer line.
1346 let snapshot = block_map.read(wraps_snapshot, Default::default());
1347 assert_eq!(
1348 snapshot.text(),
1349 "one two \nthree\n\nfour five \nsix\n\nseven \neight"
1350 );
1351 }
1352
1353 #[gpui::test(iterations = 100)]
1354 fn test_random_blocks(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1355 cx.update(|cx| init_test(cx));
1356
1357 let operations = env::var("OPERATIONS")
1358 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1359 .unwrap_or(10);
1360
1361 let wrap_width = if rng.gen_bool(0.2) {
1362 None
1363 } else {
1364 Some(px(rng.gen_range(0.0..=100.0)))
1365 };
1366 let tab_size = 1.try_into().unwrap();
1367 let font_size = px(14.0);
1368 let buffer_start_header_height = rng.gen_range(1..=5);
1369 let excerpt_header_height = rng.gen_range(1..=5);
1370 let excerpt_footer_height = rng.gen_range(1..=5);
1371
1372 log::info!("Wrap width: {:?}", wrap_width);
1373 log::info!("Excerpt Header Height: {:?}", excerpt_header_height);
1374 log::info!("Excerpt Footer Height: {:?}", excerpt_footer_height);
1375
1376 let buffer = if rng.gen() {
1377 let len = rng.gen_range(0..10);
1378 let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
1379 log::info!("initial buffer text: {:?}", text);
1380 cx.update(|cx| MultiBuffer::build_simple(&text, cx))
1381 } else {
1382 cx.update(|cx| MultiBuffer::build_random(&mut rng, cx))
1383 };
1384
1385 let mut buffer_snapshot = cx.update(|cx| buffer.read(cx).snapshot(cx));
1386 let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
1387 let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot);
1388 let (mut tab_map, tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
1389 let (wrap_map, wraps_snapshot) = cx
1390 .update(|cx| WrapMap::new(tab_snapshot, font("Helvetica"), font_size, wrap_width, cx));
1391 let mut block_map = BlockMap::new(
1392 wraps_snapshot,
1393 true,
1394 buffer_start_header_height,
1395 excerpt_header_height,
1396 excerpt_footer_height,
1397 );
1398 let mut custom_blocks = Vec::new();
1399
1400 for _ in 0..operations {
1401 let mut buffer_edits = Vec::new();
1402 match rng.gen_range(0..=100) {
1403 0..=19 => {
1404 let wrap_width = if rng.gen_bool(0.2) {
1405 None
1406 } else {
1407 Some(px(rng.gen_range(0.0..=100.0)))
1408 };
1409 log::info!("Setting wrap width to {:?}", wrap_width);
1410 wrap_map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1411 }
1412 20..=39 => {
1413 let block_count = rng.gen_range(1..=5);
1414 let block_properties = (0..block_count)
1415 .map(|_| {
1416 let buffer = cx.update(|cx| buffer.read(cx).read(cx).clone());
1417 let position = buffer.anchor_after(
1418 buffer.clip_offset(rng.gen_range(0..=buffer.len()), Bias::Left),
1419 );
1420
1421 let disposition = if rng.gen() {
1422 BlockDisposition::Above
1423 } else {
1424 BlockDisposition::Below
1425 };
1426 let height = rng.gen_range(1..5);
1427 log::info!(
1428 "inserting block {:?} {:?} with height {}",
1429 disposition,
1430 position.to_point(&buffer),
1431 height
1432 );
1433 BlockProperties {
1434 style: BlockStyle::Fixed,
1435 position,
1436 height,
1437 disposition,
1438 render: Box::new(|_| div().into_any()),
1439 }
1440 })
1441 .collect::<Vec<_>>();
1442
1443 let (inlay_snapshot, inlay_edits) =
1444 inlay_map.sync(buffer_snapshot.clone(), vec![]);
1445 let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1446 let (tab_snapshot, tab_edits) =
1447 tab_map.sync(fold_snapshot, fold_edits, tab_size);
1448 let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
1449 wrap_map.sync(tab_snapshot, tab_edits, cx)
1450 });
1451 let mut block_map = block_map.write(wraps_snapshot, wrap_edits);
1452 let block_ids =
1453 block_map.insert(block_properties.iter().map(|props| BlockProperties {
1454 position: props.position,
1455 height: props.height,
1456 style: props.style,
1457 render: Box::new(|_| div().into_any()),
1458 disposition: props.disposition,
1459 }));
1460 for (block_id, props) in block_ids.into_iter().zip(block_properties) {
1461 custom_blocks.push((block_id, props));
1462 }
1463 }
1464 40..=59 if !custom_blocks.is_empty() => {
1465 let block_count = rng.gen_range(1..=4.min(custom_blocks.len()));
1466 let block_ids_to_remove = (0..block_count)
1467 .map(|_| {
1468 custom_blocks
1469 .remove(rng.gen_range(0..custom_blocks.len()))
1470 .0
1471 })
1472 .collect();
1473
1474 let (inlay_snapshot, inlay_edits) =
1475 inlay_map.sync(buffer_snapshot.clone(), vec![]);
1476 let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1477 let (tab_snapshot, tab_edits) =
1478 tab_map.sync(fold_snapshot, fold_edits, tab_size);
1479 let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
1480 wrap_map.sync(tab_snapshot, tab_edits, cx)
1481 });
1482 let mut block_map = block_map.write(wraps_snapshot, wrap_edits);
1483 block_map.remove(block_ids_to_remove);
1484 }
1485 _ => {
1486 buffer.update(cx, |buffer, cx| {
1487 let mutation_count = rng.gen_range(1..=5);
1488 let subscription = buffer.subscribe();
1489 buffer.randomly_mutate(&mut rng, mutation_count, cx);
1490 buffer_snapshot = buffer.snapshot(cx);
1491 buffer_edits.extend(subscription.consume());
1492 log::info!("buffer text: {:?}", buffer_snapshot.text());
1493 });
1494 }
1495 }
1496
1497 let (inlay_snapshot, inlay_edits) =
1498 inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
1499 let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
1500 let (tab_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
1501 let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
1502 wrap_map.sync(tab_snapshot, tab_edits, cx)
1503 });
1504 let blocks_snapshot = block_map.read(wraps_snapshot.clone(), wrap_edits);
1505 assert_eq!(
1506 blocks_snapshot.transforms.summary().input_rows,
1507 wraps_snapshot.max_point().row() + 1
1508 );
1509 log::info!("blocks text: {:?}", blocks_snapshot.text());
1510
1511 let mut expected_blocks = Vec::new();
1512 expected_blocks.extend(custom_blocks.iter().map(|(id, block)| {
1513 let mut position = block.position.to_point(&buffer_snapshot);
1514 match block.disposition {
1515 BlockDisposition::Above => {
1516 position.column = 0;
1517 }
1518 BlockDisposition::Below => {
1519 position.column = buffer_snapshot.line_len(MultiBufferRow(position.row));
1520 }
1521 };
1522 let row = wraps_snapshot.make_wrap_point(position, Bias::Left).row();
1523 (
1524 row,
1525 ExpectedBlock::Custom {
1526 disposition: block.disposition,
1527 id: *id,
1528 height: block.height,
1529 },
1530 )
1531 }));
1532
1533 // Note that this needs to be synced with the related section in BlockMap::sync
1534 expected_blocks.extend(
1535 BlockMap::header_blocks(
1536 true,
1537 excerpt_footer_height,
1538 buffer_start_header_height,
1539 excerpt_header_height,
1540 &buffer_snapshot,
1541 0..,
1542 &wraps_snapshot,
1543 )
1544 .map(|(row, block)| (row, block.into())),
1545 );
1546
1547 BlockMap::sort_blocks(&mut expected_blocks);
1548
1549 let mut sorted_blocks_iter = expected_blocks.into_iter().peekable();
1550
1551 let input_buffer_rows = buffer_snapshot
1552 .buffer_rows(MultiBufferRow(0))
1553 .collect::<Vec<_>>();
1554 let mut expected_buffer_rows = Vec::new();
1555 let mut expected_text = String::new();
1556 let mut expected_block_positions = Vec::new();
1557 let input_text = wraps_snapshot.text();
1558 for (row, input_line) in input_text.split('\n').enumerate() {
1559 let row = row as u32;
1560 if row > 0 {
1561 expected_text.push('\n');
1562 }
1563
1564 let buffer_row = input_buffer_rows[wraps_snapshot
1565 .to_point(WrapPoint::new(row, 0), Bias::Left)
1566 .row as usize];
1567
1568 while let Some((block_row, block)) = sorted_blocks_iter.peek() {
1569 if *block_row == row && block.disposition() == BlockDisposition::Above {
1570 let (_, block) = sorted_blocks_iter.next().unwrap();
1571 let height = block.height() as usize;
1572 expected_block_positions
1573 .push((expected_text.matches('\n').count() as u32, block));
1574 let text = "\n".repeat(height);
1575 expected_text.push_str(&text);
1576 for _ in 0..height {
1577 expected_buffer_rows.push(None);
1578 }
1579 } else {
1580 break;
1581 }
1582 }
1583
1584 let soft_wrapped = wraps_snapshot.to_tab_point(WrapPoint::new(row, 0)).column() > 0;
1585 expected_buffer_rows.push(if soft_wrapped { None } else { buffer_row });
1586 expected_text.push_str(input_line);
1587
1588 while let Some((block_row, block)) = sorted_blocks_iter.peek() {
1589 if *block_row == row && block.disposition() == BlockDisposition::Below {
1590 let (_, block) = sorted_blocks_iter.next().unwrap();
1591 let height = block.height() as usize;
1592 expected_block_positions
1593 .push((expected_text.matches('\n').count() as u32 + 1, block));
1594 let text = "\n".repeat(height);
1595 expected_text.push_str(&text);
1596 for _ in 0..height {
1597 expected_buffer_rows.push(None);
1598 }
1599 } else {
1600 break;
1601 }
1602 }
1603 }
1604
1605 let expected_lines = expected_text.split('\n').collect::<Vec<_>>();
1606 let expected_row_count = expected_lines.len();
1607 for start_row in 0..expected_row_count {
1608 let expected_text = expected_lines[start_row..].join("\n");
1609 let actual_text = blocks_snapshot
1610 .chunks(
1611 start_row as u32..blocks_snapshot.max_point().row + 1,
1612 false,
1613 Highlights::default(),
1614 )
1615 .map(|chunk| chunk.text)
1616 .collect::<String>();
1617 assert_eq!(
1618 actual_text, expected_text,
1619 "incorrect text starting from row {}",
1620 start_row
1621 );
1622 assert_eq!(
1623 blocks_snapshot
1624 .buffer_rows(BlockRow(start_row as u32))
1625 .map(|row| row.map(|r| r.0))
1626 .collect::<Vec<_>>(),
1627 &expected_buffer_rows[start_row..]
1628 );
1629 }
1630
1631 assert_eq!(
1632 blocks_snapshot
1633 .blocks_in_range(0..(expected_row_count as u32))
1634 .map(|(row, block)| (row, block.clone().into()))
1635 .collect::<Vec<_>>(),
1636 expected_block_positions
1637 );
1638
1639 let mut expected_longest_rows = Vec::new();
1640 let mut longest_line_len = -1_isize;
1641 for (row, line) in expected_lines.iter().enumerate() {
1642 let row = row as u32;
1643
1644 assert_eq!(
1645 blocks_snapshot.line_len(BlockRow(row)),
1646 line.len() as u32,
1647 "invalid line len for row {}",
1648 row
1649 );
1650
1651 let line_char_count = line.chars().count() as isize;
1652 match line_char_count.cmp(&longest_line_len) {
1653 Ordering::Less => {}
1654 Ordering::Equal => expected_longest_rows.push(row),
1655 Ordering::Greater => {
1656 longest_line_len = line_char_count;
1657 expected_longest_rows.clear();
1658 expected_longest_rows.push(row);
1659 }
1660 }
1661 }
1662
1663 let longest_row = blocks_snapshot.longest_row();
1664 assert!(
1665 expected_longest_rows.contains(&longest_row),
1666 "incorrect longest row {}. expected {:?} with length {}",
1667 longest_row,
1668 expected_longest_rows,
1669 longest_line_len,
1670 );
1671
1672 for row in 0..=blocks_snapshot.wrap_snapshot.max_point().row() {
1673 let wrap_point = WrapPoint::new(row, 0);
1674 let block_point = blocks_snapshot.to_block_point(wrap_point);
1675 assert_eq!(blocks_snapshot.to_wrap_point(block_point), wrap_point);
1676 }
1677
1678 let mut block_point = BlockPoint::new(0, 0);
1679 for c in expected_text.chars() {
1680 let left_point = blocks_snapshot.clip_point(block_point, Bias::Left);
1681 let left_buffer_point = blocks_snapshot.to_point(left_point, Bias::Left);
1682 assert_eq!(
1683 blocks_snapshot.to_block_point(blocks_snapshot.to_wrap_point(left_point)),
1684 left_point
1685 );
1686 assert_eq!(
1687 left_buffer_point,
1688 buffer_snapshot.clip_point(left_buffer_point, Bias::Right),
1689 "{:?} is not valid in buffer coordinates",
1690 left_point
1691 );
1692
1693 let right_point = blocks_snapshot.clip_point(block_point, Bias::Right);
1694 let right_buffer_point = blocks_snapshot.to_point(right_point, Bias::Right);
1695 assert_eq!(
1696 blocks_snapshot.to_block_point(blocks_snapshot.to_wrap_point(right_point)),
1697 right_point
1698 );
1699 assert_eq!(
1700 right_buffer_point,
1701 buffer_snapshot.clip_point(right_buffer_point, Bias::Left),
1702 "{:?} is not valid in buffer coordinates",
1703 right_point
1704 );
1705
1706 if c == '\n' {
1707 block_point.0 += Point::new(1, 0);
1708 } else {
1709 block_point.column += c.len_utf8() as u32;
1710 }
1711 }
1712 }
1713
1714 #[derive(Debug, Eq, PartialEq)]
1715 enum ExpectedBlock {
1716 ExcerptHeader {
1717 height: u8,
1718 starts_new_buffer: bool,
1719 },
1720 ExcerptFooter {
1721 height: u8,
1722 disposition: BlockDisposition,
1723 },
1724 Custom {
1725 disposition: BlockDisposition,
1726 id: BlockId,
1727 height: u8,
1728 },
1729 }
1730
1731 impl BlockLike for ExpectedBlock {
1732 fn block_type(&self) -> BlockType {
1733 match self {
1734 ExpectedBlock::Custom { id, .. } => BlockType::Custom(*id),
1735 ExpectedBlock::ExcerptHeader { .. } => BlockType::Header,
1736 ExpectedBlock::ExcerptFooter { .. } => BlockType::Footer,
1737 }
1738 }
1739
1740 fn disposition(&self) -> BlockDisposition {
1741 self.disposition()
1742 }
1743 }
1744
1745 impl ExpectedBlock {
1746 fn height(&self) -> u8 {
1747 match self {
1748 ExpectedBlock::ExcerptHeader { height, .. } => *height,
1749 ExpectedBlock::Custom { height, .. } => *height,
1750 ExpectedBlock::ExcerptFooter { height, .. } => *height,
1751 }
1752 }
1753
1754 fn disposition(&self) -> BlockDisposition {
1755 match self {
1756 ExpectedBlock::ExcerptHeader { .. } => BlockDisposition::Above,
1757 ExpectedBlock::Custom { disposition, .. } => *disposition,
1758 ExpectedBlock::ExcerptFooter { disposition, .. } => *disposition,
1759 }
1760 }
1761 }
1762
1763 impl From<TransformBlock> for ExpectedBlock {
1764 fn from(block: TransformBlock) -> Self {
1765 match block {
1766 TransformBlock::Custom(block) => ExpectedBlock::Custom {
1767 id: block.id,
1768 disposition: block.disposition,
1769 height: block.height,
1770 },
1771 TransformBlock::ExcerptHeader {
1772 height,
1773 starts_new_buffer,
1774 ..
1775 } => ExpectedBlock::ExcerptHeader {
1776 height,
1777 starts_new_buffer,
1778 },
1779 TransformBlock::ExcerptFooter {
1780 height,
1781 disposition,
1782 ..
1783 } => ExpectedBlock::ExcerptFooter {
1784 height,
1785 disposition,
1786 },
1787 }
1788 }
1789 }
1790 }
1791
1792 fn init_test(cx: &mut gpui::AppContext) {
1793 let settings = SettingsStore::test(cx);
1794 cx.set_global(settings);
1795 theme::init(theme::LoadThemes::JustBase, cx);
1796 }
1797
1798 impl TransformBlock {
1799 fn as_custom(&self) -> Option<&Block> {
1800 match self {
1801 TransformBlock::Custom(block) => Some(block),
1802 TransformBlock::ExcerptHeader { .. } => None,
1803 TransformBlock::ExcerptFooter { .. } => None,
1804 }
1805 }
1806 }
1807
1808 impl BlockSnapshot {
1809 fn to_point(&self, point: BlockPoint, bias: Bias) -> Point {
1810 self.wrap_snapshot.to_point(self.to_wrap_point(point), bias)
1811 }
1812 }
1813}