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