1use collections::{hash_map, HashMap, HashSet};
2use git::diff::DiffHunkStatus;
3use gpui::{Action, AnchorCorner, AppContext, CursorStyle, Hsla, Model, MouseButton, Task, View};
4use language::{Buffer, BufferId, Point};
5use multi_buffer::{
6 Anchor, AnchorRangeExt, ExcerptRange, MultiBuffer, MultiBufferDiffHunk, MultiBufferRow,
7 MultiBufferSnapshot, ToPoint,
8};
9use std::{ops::Range, sync::Arc};
10use text::OffsetRangeExt;
11use ui::{
12 prelude::*, ActiveTheme, ContextMenu, IconButtonShape, InteractiveElement, IntoElement,
13 ParentElement, PopoverMenu, Styled, Tooltip, ViewContext, VisualContext,
14};
15use util::RangeExt;
16use workspace::Item;
17
18use crate::{
19 editor_settings::CurrentLineHighlight, hunk_status, hunks_for_selections, ApplyAllDiffHunks,
20 ApplyDiffHunk, BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, DiffRowHighlight,
21 DisplayRow, DisplaySnapshot, Editor, EditorElement, ExpandAllHunkDiffs, GoToHunk, GoToPrevHunk,
22 RevertFile, RevertSelectedHunks, ToDisplayPoint, ToggleHunkDiff,
23};
24
25#[derive(Debug, Clone)]
26pub(super) struct HoveredHunk {
27 pub multi_buffer_range: Range<Anchor>,
28 pub status: DiffHunkStatus,
29 pub diff_base_byte_range: Range<usize>,
30}
31
32#[derive(Debug, Default)]
33pub(super) struct ExpandedHunks {
34 pub(crate) hunks: Vec<ExpandedHunk>,
35 diff_base: HashMap<BufferId, DiffBaseBuffer>,
36 hunk_update_tasks: HashMap<Option<BufferId>, Task<()>>,
37 expand_all: bool,
38}
39
40#[derive(Debug, Clone)]
41pub(super) struct ExpandedHunk {
42 pub blocks: Vec<CustomBlockId>,
43 pub hunk_range: Range<Anchor>,
44 pub diff_base_byte_range: Range<usize>,
45 pub status: DiffHunkStatus,
46 pub folded: bool,
47}
48
49#[derive(Debug)]
50struct DiffBaseBuffer {
51 buffer: Model<Buffer>,
52 diff_base_version: usize,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum DisplayDiffHunk {
57 Folded {
58 display_row: DisplayRow,
59 },
60
61 Unfolded {
62 diff_base_byte_range: Range<usize>,
63 display_row_range: Range<DisplayRow>,
64 multi_buffer_range: Range<Anchor>,
65 status: DiffHunkStatus,
66 },
67}
68
69impl ExpandedHunks {
70 pub fn hunks(&self, include_folded: bool) -> impl Iterator<Item = &ExpandedHunk> {
71 self.hunks
72 .iter()
73 .filter(move |hunk| include_folded || !hunk.folded)
74 }
75}
76
77impl Editor {
78 pub fn set_expand_all_diff_hunks(&mut self) {
79 self.expanded_hunks.expand_all = true;
80 }
81
82 pub(super) fn toggle_hovered_hunk(
83 &mut self,
84 hovered_hunk: &HoveredHunk,
85 cx: &mut ViewContext<Editor>,
86 ) {
87 let editor_snapshot = self.snapshot(cx);
88 if let Some(diff_hunk) = to_diff_hunk(hovered_hunk, &editor_snapshot.buffer_snapshot) {
89 self.toggle_hunks_expanded(vec![diff_hunk], cx);
90 self.change_selections(None, cx, |selections| selections.refresh());
91 }
92 }
93
94 pub fn toggle_hunk_diff(&mut self, _: &ToggleHunkDiff, cx: &mut ViewContext<Self>) {
95 let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
96 let selections = self.selections.disjoint_anchors();
97 self.toggle_hunks_expanded(
98 hunks_for_selections(&multi_buffer_snapshot, &selections),
99 cx,
100 );
101 }
102
103 pub fn expand_all_hunk_diffs(&mut self, _: &ExpandAllHunkDiffs, cx: &mut ViewContext<Self>) {
104 let snapshot = self.snapshot(cx);
105 let display_rows_with_expanded_hunks = self
106 .expanded_hunks
107 .hunks(false)
108 .map(|hunk| &hunk.hunk_range)
109 .map(|anchor_range| {
110 (
111 anchor_range
112 .start
113 .to_display_point(&snapshot.display_snapshot)
114 .row(),
115 anchor_range
116 .end
117 .to_display_point(&snapshot.display_snapshot)
118 .row(),
119 )
120 })
121 .collect::<HashMap<_, _>>();
122 let hunks = snapshot
123 .display_snapshot
124 .buffer_snapshot
125 .git_diff_hunks_in_range(MultiBufferRow::MIN..MultiBufferRow::MAX)
126 .filter(|hunk| {
127 let hunk_display_row_range = Point::new(hunk.row_range.start.0, 0)
128 .to_display_point(&snapshot.display_snapshot)
129 ..Point::new(hunk.row_range.end.0, 0)
130 .to_display_point(&snapshot.display_snapshot);
131 let row_range_end =
132 display_rows_with_expanded_hunks.get(&hunk_display_row_range.start.row());
133 row_range_end.is_none() || row_range_end != Some(&hunk_display_row_range.end.row())
134 });
135 self.toggle_hunks_expanded(hunks.collect(), cx);
136 }
137
138 fn toggle_hunks_expanded(
139 &mut self,
140 hunks_to_toggle: Vec<MultiBufferDiffHunk>,
141 cx: &mut ViewContext<Self>,
142 ) {
143 if self.expanded_hunks.expand_all {
144 return;
145 }
146
147 let previous_toggle_task = self.expanded_hunks.hunk_update_tasks.remove(&None);
148 let new_toggle_task = cx.spawn(move |editor, mut cx| async move {
149 if let Some(task) = previous_toggle_task {
150 task.await;
151 }
152
153 editor
154 .update(&mut cx, |editor, cx| {
155 let snapshot = editor.snapshot(cx);
156 let mut hunks_to_toggle = hunks_to_toggle.into_iter().fuse().peekable();
157 let mut highlights_to_remove =
158 Vec::with_capacity(editor.expanded_hunks.hunks.len());
159 let mut blocks_to_remove = HashSet::default();
160 let mut hunks_to_expand = Vec::new();
161 editor.expanded_hunks.hunks.retain(|expanded_hunk| {
162 if expanded_hunk.folded {
163 return true;
164 }
165 let expanded_hunk_row_range = expanded_hunk
166 .hunk_range
167 .start
168 .to_display_point(&snapshot)
169 .row()
170 ..expanded_hunk
171 .hunk_range
172 .end
173 .to_display_point(&snapshot)
174 .row();
175 let mut retain = true;
176 while let Some(hunk_to_toggle) = hunks_to_toggle.peek() {
177 match diff_hunk_to_display(hunk_to_toggle, &snapshot) {
178 DisplayDiffHunk::Folded { .. } => {
179 hunks_to_toggle.next();
180 continue;
181 }
182 DisplayDiffHunk::Unfolded {
183 diff_base_byte_range,
184 display_row_range,
185 multi_buffer_range,
186 status,
187 } => {
188 let hunk_to_toggle_row_range = display_row_range;
189 if hunk_to_toggle_row_range.start > expanded_hunk_row_range.end
190 {
191 break;
192 } else if expanded_hunk_row_range == hunk_to_toggle_row_range {
193 highlights_to_remove.push(expanded_hunk.hunk_range.clone());
194 blocks_to_remove
195 .extend(expanded_hunk.blocks.iter().copied());
196 hunks_to_toggle.next();
197 retain = false;
198 break;
199 } else {
200 hunks_to_expand.push(HoveredHunk {
201 status,
202 multi_buffer_range,
203 diff_base_byte_range,
204 });
205 hunks_to_toggle.next();
206 continue;
207 }
208 }
209 }
210 }
211
212 retain
213 });
214 for hunk in hunks_to_toggle {
215 let remaining_hunk_point_range = Point::new(hunk.row_range.start.0, 0)
216 ..Point::new(hunk.row_range.end.0, 0);
217 let hunk_start = snapshot
218 .buffer_snapshot
219 .anchor_before(remaining_hunk_point_range.start);
220 let hunk_end = snapshot
221 .buffer_snapshot
222 .anchor_in_excerpt(hunk_start.excerpt_id, hunk.buffer_range.end)
223 .unwrap();
224 hunks_to_expand.push(HoveredHunk {
225 status: hunk_status(&hunk),
226 multi_buffer_range: hunk_start..hunk_end,
227 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
228 });
229 }
230
231 editor.remove_highlighted_rows::<DiffRowHighlight>(highlights_to_remove, cx);
232 editor.remove_blocks(blocks_to_remove, None, cx);
233 for hunk in hunks_to_expand {
234 editor.expand_diff_hunk(None, &hunk, cx);
235 }
236 cx.notify();
237 })
238 .ok();
239 });
240
241 self.expanded_hunks
242 .hunk_update_tasks
243 .insert(None, cx.background_executor().spawn(new_toggle_task));
244 }
245
246 pub(super) fn expand_diff_hunk(
247 &mut self,
248 diff_base_buffer: Option<Model<Buffer>>,
249 hunk: &HoveredHunk,
250 cx: &mut ViewContext<'_, Editor>,
251 ) -> Option<()> {
252 let buffer = self.buffer.clone();
253 let multi_buffer_snapshot = buffer.read(cx).snapshot(cx);
254 let hunk_range = hunk.multi_buffer_range.clone();
255 let (diff_base_buffer, deleted_text_lines) = buffer.update(cx, |buffer, cx| {
256 let buffer = buffer.buffer(hunk_range.start.buffer_id?)?;
257 let diff_base_buffer = diff_base_buffer
258 .or_else(|| self.current_diff_base_buffer(&buffer, cx))
259 .or_else(|| create_diff_base_buffer(&buffer, cx))?;
260 let deleted_text_lines = buffer.read(cx).diff_base().map(|diff_base| {
261 let diff_start_row = diff_base
262 .offset_to_point(hunk.diff_base_byte_range.start)
263 .row;
264 let diff_end_row = diff_base.offset_to_point(hunk.diff_base_byte_range.end).row;
265 diff_end_row - diff_start_row
266 })?;
267 Some((diff_base_buffer, deleted_text_lines))
268 })?;
269
270 let block_insert_index = match self.expanded_hunks.hunks.binary_search_by(|probe| {
271 probe
272 .hunk_range
273 .start
274 .cmp(&hunk_range.start, &multi_buffer_snapshot)
275 }) {
276 Ok(_already_present) => return None,
277 Err(ix) => ix,
278 };
279
280 let blocks;
281 match hunk.status {
282 DiffHunkStatus::Removed => {
283 blocks = self.insert_blocks(
284 [
285 self.hunk_header_block(&hunk, cx),
286 Self::deleted_text_block(hunk, diff_base_buffer, deleted_text_lines, cx),
287 ],
288 None,
289 cx,
290 );
291 }
292 DiffHunkStatus::Added => {
293 self.highlight_rows::<DiffRowHighlight>(
294 hunk_range.clone(),
295 added_hunk_color(cx),
296 false,
297 cx,
298 );
299 blocks = self.insert_blocks([self.hunk_header_block(&hunk, cx)], None, cx);
300 }
301 DiffHunkStatus::Modified => {
302 self.highlight_rows::<DiffRowHighlight>(
303 hunk_range.clone(),
304 added_hunk_color(cx),
305 false,
306 cx,
307 );
308 blocks = self.insert_blocks(
309 [
310 self.hunk_header_block(&hunk, cx),
311 Self::deleted_text_block(hunk, diff_base_buffer, deleted_text_lines, cx),
312 ],
313 None,
314 cx,
315 );
316 }
317 };
318 self.expanded_hunks.hunks.insert(
319 block_insert_index,
320 ExpandedHunk {
321 blocks,
322 hunk_range,
323 status: hunk.status,
324 folded: false,
325 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
326 },
327 );
328
329 Some(())
330 }
331
332 fn apply_diff_hunks_in_range(
333 &mut self,
334 range: Range<Anchor>,
335 cx: &mut ViewContext<'_, Editor>,
336 ) -> Option<()> {
337 let (buffer, range, _) = self
338 .buffer
339 .read(cx)
340 .range_to_buffer_ranges(range, cx)
341 .into_iter()
342 .next()?;
343
344 buffer.update(cx, |branch_buffer, cx| {
345 branch_buffer.merge_into_base(vec![range], cx);
346 });
347
348 if let Some(project) = self.project.clone() {
349 self.save(true, project, cx).detach_and_log_err(cx);
350 }
351
352 None
353 }
354
355 pub(crate) fn apply_all_diff_hunks(
356 &mut self,
357 _: &ApplyAllDiffHunks,
358 cx: &mut ViewContext<Self>,
359 ) {
360 let buffers = self.buffer.read(cx).all_buffers();
361 for branch_buffer in buffers {
362 branch_buffer.update(cx, |branch_buffer, cx| {
363 branch_buffer.merge_into_base(Vec::new(), cx);
364 });
365 }
366
367 if let Some(project) = self.project.clone() {
368 self.save(true, project, cx).detach_and_log_err(cx);
369 }
370 }
371
372 pub(crate) fn apply_selected_diff_hunks(
373 &mut self,
374 _: &ApplyDiffHunk,
375 cx: &mut ViewContext<Self>,
376 ) {
377 let snapshot = self.buffer.read(cx).snapshot(cx);
378 let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
379 let mut ranges_by_buffer = HashMap::default();
380 self.transact(cx, |editor, cx| {
381 for hunk in hunks {
382 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
383 ranges_by_buffer
384 .entry(buffer.clone())
385 .or_insert_with(Vec::new)
386 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
387 }
388 }
389
390 for (buffer, ranges) in ranges_by_buffer {
391 buffer.update(cx, |buffer, cx| {
392 buffer.merge_into_base(ranges, cx);
393 });
394 }
395 });
396
397 if let Some(project) = self.project.clone() {
398 self.save(true, project, cx).detach_and_log_err(cx);
399 }
400 }
401
402 fn hunk_header_block(
403 &self,
404 hunk: &HoveredHunk,
405 cx: &mut ViewContext<'_, Editor>,
406 ) -> BlockProperties<Anchor> {
407 let is_branch_buffer = self
408 .buffer
409 .read(cx)
410 .point_to_buffer_offset(hunk.multi_buffer_range.start, cx)
411 .map_or(false, |(buffer, _, _)| {
412 buffer.read(cx).diff_base_buffer().is_some()
413 });
414
415 let border_color = cx.theme().colors().border_variant;
416 let bg_color = cx.theme().colors().editor_background;
417 let gutter_color = match hunk.status {
418 DiffHunkStatus::Added => cx.theme().status().created,
419 DiffHunkStatus::Modified => cx.theme().status().modified,
420 DiffHunkStatus::Removed => cx.theme().status().deleted,
421 };
422
423 BlockProperties {
424 placement: BlockPlacement::Above(hunk.multi_buffer_range.start),
425 height: 1,
426 style: BlockStyle::Sticky,
427 priority: 0,
428 render: Box::new({
429 let editor = cx.view().clone();
430 let hunk = hunk.clone();
431
432 move |cx| {
433 let hunk_controls_menu_handle =
434 editor.read(cx).hunk_controls_menu_handle.clone();
435
436 h_flex()
437 .id(cx.block_id)
438 .h(cx.line_height())
439 .w_full()
440 .border_t_1()
441 .border_color(border_color)
442 .bg(bg_color)
443 .child(
444 div()
445 .id("gutter-strip")
446 .w(EditorElement::diff_hunk_strip_width(cx.line_height()))
447 .h_full()
448 .bg(gutter_color)
449 .cursor(CursorStyle::PointingHand)
450 .on_click({
451 let editor = editor.clone();
452 let hunk = hunk.clone();
453 move |_event, cx| {
454 editor.update(cx, |editor, cx| {
455 editor.toggle_hovered_hunk(&hunk, cx);
456 });
457 }
458 }),
459 )
460 .child(
461 h_flex()
462 .px_6()
463 .size_full()
464 .justify_end()
465 .child(
466 h_flex()
467 .gap_1()
468 .when(!is_branch_buffer, |row| {
469 row.child(
470 IconButton::new("next-hunk", IconName::ArrowDown)
471 .shape(IconButtonShape::Square)
472 .icon_size(IconSize::Small)
473 .tooltip({
474 let focus_handle = editor.focus_handle(cx);
475 move |cx| {
476 Tooltip::for_action_in(
477 "Next Hunk",
478 &GoToHunk,
479 &focus_handle,
480 cx,
481 )
482 }
483 })
484 .on_click({
485 let editor = editor.clone();
486 let hunk = hunk.clone();
487 move |_event, cx| {
488 editor.update(cx, |editor, cx| {
489 editor.go_to_subsequent_hunk(
490 hunk.multi_buffer_range.end,
491 cx,
492 );
493 });
494 }
495 }),
496 )
497 .child(
498 IconButton::new("prev-hunk", IconName::ArrowUp)
499 .shape(IconButtonShape::Square)
500 .icon_size(IconSize::Small)
501 .tooltip({
502 let focus_handle = editor.focus_handle(cx);
503 move |cx| {
504 Tooltip::for_action_in(
505 "Previous Hunk",
506 &GoToPrevHunk,
507 &focus_handle,
508 cx,
509 )
510 }
511 })
512 .on_click({
513 let editor = editor.clone();
514 let hunk = hunk.clone();
515 move |_event, cx| {
516 editor.update(cx, |editor, cx| {
517 editor.go_to_preceding_hunk(
518 hunk.multi_buffer_range.start,
519 cx,
520 );
521 });
522 }
523 }),
524 )
525 })
526 .child(
527 IconButton::new("discard", IconName::Undo)
528 .shape(IconButtonShape::Square)
529 .icon_size(IconSize::Small)
530 .tooltip({
531 let focus_handle = editor.focus_handle(cx);
532 move |cx| {
533 Tooltip::for_action_in(
534 "Discard Hunk",
535 &RevertSelectedHunks,
536 &focus_handle,
537 cx,
538 )
539 }
540 })
541 .on_click({
542 let editor = editor.clone();
543 let hunk = hunk.clone();
544 move |_event, cx| {
545 let multi_buffer =
546 editor.read(cx).buffer().clone();
547 let multi_buffer_snapshot =
548 multi_buffer.read(cx).snapshot(cx);
549 let mut revert_changes = HashMap::default();
550 if let Some(hunk) =
551 crate::hunk_diff::to_diff_hunk(
552 &hunk,
553 &multi_buffer_snapshot,
554 )
555 {
556 Editor::prepare_revert_change(
557 &mut revert_changes,
558 &multi_buffer,
559 &hunk,
560 cx,
561 );
562 }
563 if !revert_changes.is_empty() {
564 editor.update(cx, |editor, cx| {
565 editor.revert(revert_changes, cx)
566 });
567 }
568 }
569 }),
570 )
571 .map(|this| {
572 if is_branch_buffer {
573 this.child(
574 IconButton::new("apply", IconName::Check)
575 .shape(IconButtonShape::Square)
576 .icon_size(IconSize::Small)
577 .tooltip({
578 let focus_handle =
579 editor.focus_handle(cx);
580 move |cx| {
581 Tooltip::for_action_in(
582 "Apply Hunk",
583 &ApplyDiffHunk,
584 &focus_handle,
585 cx,
586 )
587 }
588 })
589 .on_click({
590 let editor = editor.clone();
591 let hunk = hunk.clone();
592 move |_event, cx| {
593 editor.update(cx, |editor, cx| {
594 editor
595 .apply_diff_hunks_in_range(
596 hunk.multi_buffer_range
597 .clone(),
598 cx,
599 );
600 });
601 }
602 }),
603 )
604 } else {
605 this.child({
606 let focus = editor.focus_handle(cx);
607 PopoverMenu::new("hunk-controls-dropdown")
608 .trigger(
609 IconButton::new(
610 "toggle_editor_selections_icon",
611 IconName::EllipsisVertical,
612 )
613 .shape(IconButtonShape::Square)
614 .icon_size(IconSize::Small)
615 .style(ButtonStyle::Subtle)
616 .selected(
617 hunk_controls_menu_handle
618 .is_deployed(),
619 )
620 .when(
621 !hunk_controls_menu_handle
622 .is_deployed(),
623 |this| {
624 this.tooltip(|cx| {
625 Tooltip::text(
626 "Hunk Controls",
627 cx,
628 )
629 })
630 },
631 ),
632 )
633 .anchor(AnchorCorner::TopRight)
634 .with_handle(hunk_controls_menu_handle)
635 .menu(move |cx| {
636 let focus = focus.clone();
637 let menu = ContextMenu::build(
638 cx,
639 move |menu, _| {
640 menu.context(focus.clone())
641 .action(
642 "Discard All Hunks",
643 RevertFile
644 .boxed_clone(),
645 )
646 },
647 );
648 Some(menu)
649 })
650 })
651 }
652 }),
653 )
654 .when(!is_branch_buffer, |div| {
655 div.child(
656 IconButton::new("collapse", IconName::Close)
657 .shape(IconButtonShape::Square)
658 .icon_size(IconSize::Small)
659 .tooltip({
660 let focus_handle = editor.focus_handle(cx);
661 move |cx| {
662 Tooltip::for_action_in(
663 "Collapse Hunk",
664 &ToggleHunkDiff,
665 &focus_handle,
666 cx,
667 )
668 }
669 })
670 .on_click({
671 let editor = editor.clone();
672 let hunk = hunk.clone();
673 move |_event, cx| {
674 editor.update(cx, |editor, cx| {
675 editor.toggle_hovered_hunk(&hunk, cx);
676 });
677 }
678 }),
679 )
680 }),
681 )
682 .into_any_element()
683 }
684 }),
685 }
686 }
687
688 fn deleted_text_block(
689 hunk: &HoveredHunk,
690 diff_base_buffer: Model<Buffer>,
691 deleted_text_height: u32,
692 cx: &mut ViewContext<'_, Editor>,
693 ) -> BlockProperties<Anchor> {
694 let gutter_color = match hunk.status {
695 DiffHunkStatus::Added => unreachable!(),
696 DiffHunkStatus::Modified => cx.theme().status().modified,
697 DiffHunkStatus::Removed => cx.theme().status().deleted,
698 };
699 let deleted_hunk_color = deleted_hunk_color(cx);
700 let (editor_height, editor_with_deleted_text) =
701 editor_with_deleted_text(diff_base_buffer, deleted_hunk_color, hunk, cx);
702 let editor = cx.view().clone();
703 let hunk = hunk.clone();
704 let height = editor_height.max(deleted_text_height);
705 BlockProperties {
706 placement: BlockPlacement::Above(hunk.multi_buffer_range.start),
707 height,
708 style: BlockStyle::Flex,
709 priority: 0,
710 render: Box::new(move |cx| {
711 let width = EditorElement::diff_hunk_strip_width(cx.line_height());
712 let gutter_dimensions = editor.read(cx.context).gutter_dimensions;
713
714 h_flex()
715 .id(cx.block_id)
716 .bg(deleted_hunk_color)
717 .h(height as f32 * cx.line_height())
718 .w_full()
719 .child(
720 h_flex()
721 .id("gutter")
722 .max_w(gutter_dimensions.full_width())
723 .min_w(gutter_dimensions.full_width())
724 .size_full()
725 .child(
726 h_flex()
727 .id("gutter hunk")
728 .bg(gutter_color)
729 .pl(gutter_dimensions.margin
730 + gutter_dimensions
731 .git_blame_entries_width
732 .unwrap_or_default())
733 .max_w(width)
734 .min_w(width)
735 .size_full()
736 .cursor(CursorStyle::PointingHand)
737 .on_mouse_down(MouseButton::Left, {
738 let editor = editor.clone();
739 let hunk = hunk.clone();
740 move |_event, cx| {
741 editor.update(cx, |editor, cx| {
742 editor.toggle_hovered_hunk(&hunk, cx);
743 });
744 }
745 }),
746 ),
747 )
748 .child(editor_with_deleted_text.clone())
749 .into_any_element()
750 }),
751 }
752 }
753
754 pub(super) fn clear_expanded_diff_hunks(&mut self, cx: &mut ViewContext<'_, Editor>) -> bool {
755 if self.expanded_hunks.expand_all {
756 return false;
757 }
758 self.expanded_hunks.hunk_update_tasks.clear();
759 self.clear_row_highlights::<DiffRowHighlight>();
760 let to_remove = self
761 .expanded_hunks
762 .hunks
763 .drain(..)
764 .flat_map(|expanded_hunk| expanded_hunk.blocks.into_iter())
765 .collect::<HashSet<_>>();
766 if to_remove.is_empty() {
767 false
768 } else {
769 self.remove_blocks(to_remove, None, cx);
770 true
771 }
772 }
773
774 pub(super) fn sync_expanded_diff_hunks(
775 &mut self,
776 buffer: Model<Buffer>,
777 cx: &mut ViewContext<'_, Self>,
778 ) {
779 let buffer_id = buffer.read(cx).remote_id();
780 let buffer_diff_base_version = buffer.read(cx).diff_base_version();
781 self.expanded_hunks
782 .hunk_update_tasks
783 .remove(&Some(buffer_id));
784 let diff_base_buffer = self.current_diff_base_buffer(&buffer, cx);
785 let new_sync_task = cx.spawn(move |editor, mut cx| async move {
786 let diff_base_buffer_unchanged = diff_base_buffer.is_some();
787 let Ok(diff_base_buffer) =
788 cx.update(|cx| diff_base_buffer.or_else(|| create_diff_base_buffer(&buffer, cx)))
789 else {
790 return;
791 };
792 editor
793 .update(&mut cx, |editor, cx| {
794 if let Some(diff_base_buffer) = &diff_base_buffer {
795 editor.expanded_hunks.diff_base.insert(
796 buffer_id,
797 DiffBaseBuffer {
798 buffer: diff_base_buffer.clone(),
799 diff_base_version: buffer_diff_base_version,
800 },
801 );
802 }
803
804 let snapshot = editor.snapshot(cx);
805 let mut recalculated_hunks = snapshot
806 .buffer_snapshot
807 .git_diff_hunks_in_range(MultiBufferRow::MIN..MultiBufferRow::MAX)
808 .filter(|hunk| hunk.buffer_id == buffer_id)
809 .fuse()
810 .peekable();
811 let mut highlights_to_remove =
812 Vec::with_capacity(editor.expanded_hunks.hunks.len());
813 let mut blocks_to_remove = HashSet::default();
814 let mut hunks_to_reexpand =
815 Vec::with_capacity(editor.expanded_hunks.hunks.len());
816 editor.expanded_hunks.hunks.retain_mut(|expanded_hunk| {
817 if expanded_hunk.hunk_range.start.buffer_id != Some(buffer_id) {
818 return true;
819 };
820
821 let mut retain = false;
822 if diff_base_buffer_unchanged {
823 let expanded_hunk_display_range = expanded_hunk
824 .hunk_range
825 .start
826 .to_display_point(&snapshot)
827 .row()
828 ..expanded_hunk
829 .hunk_range
830 .end
831 .to_display_point(&snapshot)
832 .row();
833 while let Some(buffer_hunk) = recalculated_hunks.peek() {
834 match diff_hunk_to_display(buffer_hunk, &snapshot) {
835 DisplayDiffHunk::Folded { display_row } => {
836 recalculated_hunks.next();
837 if !expanded_hunk.folded
838 && expanded_hunk_display_range
839 .to_inclusive()
840 .contains(&display_row)
841 {
842 retain = true;
843 expanded_hunk.folded = true;
844 highlights_to_remove
845 .push(expanded_hunk.hunk_range.clone());
846 for block in expanded_hunk.blocks.drain(..) {
847 blocks_to_remove.insert(block);
848 }
849 break;
850 } else {
851 continue;
852 }
853 }
854 DisplayDiffHunk::Unfolded {
855 diff_base_byte_range,
856 display_row_range,
857 multi_buffer_range,
858 status,
859 } => {
860 let hunk_display_range = display_row_range;
861
862 if expanded_hunk_display_range.start
863 > hunk_display_range.end
864 {
865 recalculated_hunks.next();
866 if editor.expanded_hunks.expand_all {
867 hunks_to_reexpand.push(HoveredHunk {
868 status,
869 multi_buffer_range,
870 diff_base_byte_range,
871 });
872 }
873 continue;
874 }
875
876 if expanded_hunk_display_range.end
877 < hunk_display_range.start
878 {
879 break;
880 }
881
882 if !expanded_hunk.folded
883 && expanded_hunk_display_range == hunk_display_range
884 && expanded_hunk.status == hunk_status(buffer_hunk)
885 && expanded_hunk.diff_base_byte_range
886 == buffer_hunk.diff_base_byte_range
887 {
888 recalculated_hunks.next();
889 retain = true;
890 } else {
891 hunks_to_reexpand.push(HoveredHunk {
892 status,
893 multi_buffer_range,
894 diff_base_byte_range,
895 });
896 }
897 break;
898 }
899 }
900 }
901 }
902 if !retain {
903 blocks_to_remove.extend(expanded_hunk.blocks.drain(..));
904 highlights_to_remove.push(expanded_hunk.hunk_range.clone());
905 }
906 retain
907 });
908
909 if editor.expanded_hunks.expand_all {
910 for hunk in recalculated_hunks {
911 match diff_hunk_to_display(&hunk, &snapshot) {
912 DisplayDiffHunk::Folded { .. } => {}
913 DisplayDiffHunk::Unfolded {
914 diff_base_byte_range,
915 multi_buffer_range,
916 status,
917 ..
918 } => {
919 hunks_to_reexpand.push(HoveredHunk {
920 status,
921 multi_buffer_range,
922 diff_base_byte_range,
923 });
924 }
925 }
926 }
927 }
928
929 editor.remove_highlighted_rows::<DiffRowHighlight>(highlights_to_remove, cx);
930 editor.remove_blocks(blocks_to_remove, None, cx);
931
932 if let Some(diff_base_buffer) = &diff_base_buffer {
933 for hunk in hunks_to_reexpand {
934 editor.expand_diff_hunk(Some(diff_base_buffer.clone()), &hunk, cx);
935 }
936 }
937 })
938 .ok();
939 });
940
941 self.expanded_hunks.hunk_update_tasks.insert(
942 Some(buffer_id),
943 cx.background_executor().spawn(new_sync_task),
944 );
945 }
946
947 fn current_diff_base_buffer(
948 &mut self,
949 buffer: &Model<Buffer>,
950 cx: &mut AppContext,
951 ) -> Option<Model<Buffer>> {
952 buffer.update(cx, |buffer, _| {
953 match self.expanded_hunks.diff_base.entry(buffer.remote_id()) {
954 hash_map::Entry::Occupied(o) => {
955 if o.get().diff_base_version != buffer.diff_base_version() {
956 o.remove();
957 None
958 } else {
959 Some(o.get().buffer.clone())
960 }
961 }
962 hash_map::Entry::Vacant(_) => None,
963 }
964 })
965 }
966
967 fn go_to_subsequent_hunk(&mut self, position: Anchor, cx: &mut ViewContext<Self>) {
968 let snapshot = self.snapshot(cx);
969 let position = position.to_point(&snapshot.buffer_snapshot);
970 if let Some(hunk) = self.go_to_hunk_after_position(&snapshot, position, cx) {
971 let multi_buffer_start = snapshot
972 .buffer_snapshot
973 .anchor_before(Point::new(hunk.row_range.start.0, 0));
974 let multi_buffer_end = snapshot
975 .buffer_snapshot
976 .anchor_after(Point::new(hunk.row_range.end.0, 0));
977 self.expand_diff_hunk(
978 None,
979 &HoveredHunk {
980 multi_buffer_range: multi_buffer_start..multi_buffer_end,
981 status: hunk_status(&hunk),
982 diff_base_byte_range: hunk.diff_base_byte_range,
983 },
984 cx,
985 );
986 }
987 }
988
989 fn go_to_preceding_hunk(&mut self, position: Anchor, cx: &mut ViewContext<Self>) {
990 let snapshot = self.snapshot(cx);
991 let position = position.to_point(&snapshot.buffer_snapshot);
992 let hunk = self.go_to_hunk_before_position(&snapshot, position, cx);
993 if let Some(hunk) = hunk {
994 let multi_buffer_start = snapshot
995 .buffer_snapshot
996 .anchor_before(Point::new(hunk.row_range.start.0, 0));
997 let multi_buffer_end = snapshot
998 .buffer_snapshot
999 .anchor_after(Point::new(hunk.row_range.end.0, 0));
1000 self.expand_diff_hunk(
1001 None,
1002 &HoveredHunk {
1003 multi_buffer_range: multi_buffer_start..multi_buffer_end,
1004 status: hunk_status(&hunk),
1005 diff_base_byte_range: hunk.diff_base_byte_range,
1006 },
1007 cx,
1008 );
1009 }
1010 }
1011}
1012
1013fn to_diff_hunk(
1014 hovered_hunk: &HoveredHunk,
1015 multi_buffer_snapshot: &MultiBufferSnapshot,
1016) -> Option<MultiBufferDiffHunk> {
1017 let buffer_id = hovered_hunk
1018 .multi_buffer_range
1019 .start
1020 .buffer_id
1021 .or(hovered_hunk.multi_buffer_range.end.buffer_id)?;
1022 let buffer_range = hovered_hunk.multi_buffer_range.start.text_anchor
1023 ..hovered_hunk.multi_buffer_range.end.text_anchor;
1024 let point_range = hovered_hunk
1025 .multi_buffer_range
1026 .to_point(multi_buffer_snapshot);
1027 Some(MultiBufferDiffHunk {
1028 row_range: MultiBufferRow(point_range.start.row)..MultiBufferRow(point_range.end.row),
1029 buffer_id,
1030 buffer_range,
1031 diff_base_byte_range: hovered_hunk.diff_base_byte_range.clone(),
1032 })
1033}
1034
1035fn create_diff_base_buffer(buffer: &Model<Buffer>, cx: &mut AppContext) -> Option<Model<Buffer>> {
1036 buffer
1037 .update(cx, |buffer, _| {
1038 let language = buffer.language().cloned();
1039 let diff_base = buffer.diff_base()?.clone();
1040 Some((buffer.line_ending(), diff_base, language))
1041 })
1042 .map(|(line_ending, diff_base, language)| {
1043 cx.new_model(|cx| {
1044 let buffer = Buffer::local_normalized(diff_base, line_ending, cx);
1045 match language {
1046 Some(language) => buffer.with_language(language, cx),
1047 None => buffer,
1048 }
1049 })
1050 })
1051}
1052
1053fn added_hunk_color(cx: &AppContext) -> Hsla {
1054 let mut created_color = cx.theme().status().git().created;
1055 created_color.fade_out(0.7);
1056 created_color
1057}
1058
1059fn deleted_hunk_color(cx: &AppContext) -> Hsla {
1060 let mut deleted_color = cx.theme().status().deleted;
1061 deleted_color.fade_out(0.7);
1062 deleted_color
1063}
1064
1065fn editor_with_deleted_text(
1066 diff_base_buffer: Model<Buffer>,
1067 deleted_color: Hsla,
1068 hunk: &HoveredHunk,
1069 cx: &mut ViewContext<'_, Editor>,
1070) -> (u32, View<Editor>) {
1071 let parent_editor = cx.view().downgrade();
1072 let editor = cx.new_view(|cx| {
1073 let multi_buffer =
1074 cx.new_model(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1075 multi_buffer.update(cx, |multi_buffer, cx| {
1076 multi_buffer.push_excerpts(
1077 diff_base_buffer,
1078 Some(ExcerptRange {
1079 context: hunk.diff_base_byte_range.clone(),
1080 primary: None,
1081 }),
1082 cx,
1083 );
1084 });
1085
1086 let mut editor = Editor::for_multibuffer(multi_buffer, None, true, cx);
1087 editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1088 editor.set_show_wrap_guides(false, cx);
1089 editor.set_show_gutter(false, cx);
1090 editor.scroll_manager.set_forbid_vertical_scroll(true);
1091 editor.set_read_only(true);
1092 editor.set_show_inline_completions(Some(false), cx);
1093
1094 enum DeletedBlockRowHighlight {}
1095 editor.highlight_rows::<DeletedBlockRowHighlight>(
1096 Anchor::min()..Anchor::max(),
1097 deleted_color,
1098 false,
1099 cx,
1100 );
1101 editor.set_current_line_highlight(Some(CurrentLineHighlight::None)); //
1102 editor
1103 ._subscriptions
1104 .extend([cx.on_blur(&editor.focus_handle, |editor, cx| {
1105 editor.change_selections(None, cx, |s| {
1106 s.try_cancel();
1107 });
1108 })]);
1109
1110 let original_multi_buffer_range = hunk.multi_buffer_range.clone();
1111 let diff_base_range = hunk.diff_base_byte_range.clone();
1112 editor
1113 .register_action::<RevertSelectedHunks>({
1114 let parent_editor = parent_editor.clone();
1115 move |_, cx| {
1116 parent_editor
1117 .update(cx, |editor, cx| {
1118 let Some((buffer, original_text)) =
1119 editor.buffer().update(cx, |buffer, cx| {
1120 let (_, buffer, _) = buffer.excerpt_containing(
1121 original_multi_buffer_range.start,
1122 cx,
1123 )?;
1124 let original_text =
1125 buffer.read(cx).diff_base()?.slice(diff_base_range.clone());
1126 Some((buffer, Arc::from(original_text.to_string())))
1127 })
1128 else {
1129 return;
1130 };
1131 buffer.update(cx, |buffer, cx| {
1132 buffer.edit(
1133 Some((
1134 original_multi_buffer_range.start.text_anchor
1135 ..original_multi_buffer_range.end.text_anchor,
1136 original_text,
1137 )),
1138 None,
1139 cx,
1140 )
1141 });
1142 })
1143 .ok();
1144 }
1145 })
1146 .detach();
1147 let hunk = hunk.clone();
1148 editor
1149 .register_action::<ToggleHunkDiff>(move |_, cx| {
1150 parent_editor
1151 .update(cx, |editor, cx| {
1152 editor.toggle_hovered_hunk(&hunk, cx);
1153 })
1154 .ok();
1155 })
1156 .detach();
1157 editor
1158 });
1159
1160 let editor_height = editor.update(cx, |editor, cx| editor.max_point(cx).row().0);
1161 (editor_height, editor)
1162}
1163
1164impl DisplayDiffHunk {
1165 pub fn start_display_row(&self) -> DisplayRow {
1166 match self {
1167 &DisplayDiffHunk::Folded { display_row } => display_row,
1168 DisplayDiffHunk::Unfolded {
1169 display_row_range, ..
1170 } => display_row_range.start,
1171 }
1172 }
1173
1174 pub fn contains_display_row(&self, display_row: DisplayRow) -> bool {
1175 let range = match self {
1176 &DisplayDiffHunk::Folded { display_row } => display_row..=display_row,
1177
1178 DisplayDiffHunk::Unfolded {
1179 display_row_range, ..
1180 } => display_row_range.start..=display_row_range.end,
1181 };
1182
1183 range.contains(&display_row)
1184 }
1185}
1186
1187pub fn diff_hunk_to_display(
1188 hunk: &MultiBufferDiffHunk,
1189 snapshot: &DisplaySnapshot,
1190) -> DisplayDiffHunk {
1191 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
1192 let hunk_start_point_sub = Point::new(hunk.row_range.start.0.saturating_sub(1), 0);
1193 let hunk_end_point_sub = Point::new(
1194 hunk.row_range
1195 .end
1196 .0
1197 .saturating_sub(1)
1198 .max(hunk.row_range.start.0),
1199 0,
1200 );
1201
1202 let status = hunk_status(hunk);
1203 let is_removal = status == DiffHunkStatus::Removed;
1204
1205 let folds_start = Point::new(hunk.row_range.start.0.saturating_sub(2), 0);
1206 let folds_end = Point::new(hunk.row_range.end.0 + 2, 0);
1207 let folds_range = folds_start..folds_end;
1208
1209 let containing_fold = snapshot.folds_in_range(folds_range).find(|fold| {
1210 let fold_point_range = fold.range.to_point(&snapshot.buffer_snapshot);
1211 let fold_point_range = fold_point_range.start..=fold_point_range.end;
1212
1213 let folded_start = fold_point_range.contains(&hunk_start_point);
1214 let folded_end = fold_point_range.contains(&hunk_end_point_sub);
1215 let folded_start_sub = fold_point_range.contains(&hunk_start_point_sub);
1216
1217 (folded_start && folded_end) || (is_removal && folded_start_sub)
1218 });
1219
1220 if let Some(fold) = containing_fold {
1221 let row = fold.range.start.to_display_point(snapshot).row();
1222 DisplayDiffHunk::Folded { display_row: row }
1223 } else {
1224 let start = hunk_start_point.to_display_point(snapshot).row();
1225
1226 let hunk_end_row = hunk.row_range.end.max(hunk.row_range.start);
1227 let hunk_end_point = Point::new(hunk_end_row.0, 0);
1228
1229 let multi_buffer_start = snapshot.buffer_snapshot.anchor_before(hunk_start_point);
1230 let multi_buffer_end = snapshot
1231 .buffer_snapshot
1232 .anchor_in_excerpt(multi_buffer_start.excerpt_id, hunk.buffer_range.end)
1233 .unwrap();
1234 let end = hunk_end_point.to_display_point(snapshot).row();
1235
1236 DisplayDiffHunk::Unfolded {
1237 display_row_range: start..end,
1238 multi_buffer_range: multi_buffer_start..multi_buffer_end,
1239 status,
1240 diff_base_byte_range: hunk.diff_base_byte_range.clone(),
1241 }
1242 }
1243}
1244
1245#[cfg(test)]
1246mod tests {
1247 use super::*;
1248 use crate::{editor_tests::init_test, hunk_status};
1249 use gpui::{Context, TestAppContext};
1250 use language::Capability::ReadWrite;
1251 use multi_buffer::{ExcerptRange, MultiBuffer, MultiBufferRow};
1252 use project::{FakeFs, Project};
1253 use unindent::Unindent as _;
1254
1255 #[gpui::test]
1256 async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
1257 use git::diff::DiffHunkStatus;
1258 init_test(cx, |_| {});
1259
1260 let fs = FakeFs::new(cx.background_executor.clone());
1261 let project = Project::test(fs, [], cx).await;
1262
1263 // buffer has two modified hunks with two rows each
1264 let buffer_1 = project.update(cx, |project, cx| {
1265 project.create_local_buffer(
1266 "
1267 1.zero
1268 1.ONE
1269 1.TWO
1270 1.three
1271 1.FOUR
1272 1.FIVE
1273 1.six
1274 "
1275 .unindent()
1276 .as_str(),
1277 None,
1278 cx,
1279 )
1280 });
1281 buffer_1.update(cx, |buffer, cx| {
1282 buffer.set_diff_base(
1283 Some(
1284 "
1285 1.zero
1286 1.one
1287 1.two
1288 1.three
1289 1.four
1290 1.five
1291 1.six
1292 "
1293 .unindent(),
1294 ),
1295 cx,
1296 );
1297 });
1298
1299 // buffer has a deletion hunk and an insertion hunk
1300 let buffer_2 = project.update(cx, |project, cx| {
1301 project.create_local_buffer(
1302 "
1303 2.zero
1304 2.one
1305 2.two
1306 2.three
1307 2.four
1308 2.five
1309 2.six
1310 "
1311 .unindent()
1312 .as_str(),
1313 None,
1314 cx,
1315 )
1316 });
1317 buffer_2.update(cx, |buffer, cx| {
1318 buffer.set_diff_base(
1319 Some(
1320 "
1321 2.zero
1322 2.one
1323 2.one-and-a-half
1324 2.two
1325 2.three
1326 2.four
1327 2.six
1328 "
1329 .unindent(),
1330 ),
1331 cx,
1332 );
1333 });
1334
1335 cx.background_executor.run_until_parked();
1336
1337 let multibuffer = cx.new_model(|cx| {
1338 let mut multibuffer = MultiBuffer::new(ReadWrite);
1339 multibuffer.push_excerpts(
1340 buffer_1.clone(),
1341 [
1342 // excerpt ends in the middle of a modified hunk
1343 ExcerptRange {
1344 context: Point::new(0, 0)..Point::new(1, 5),
1345 primary: Default::default(),
1346 },
1347 // excerpt begins in the middle of a modified hunk
1348 ExcerptRange {
1349 context: Point::new(5, 0)..Point::new(6, 5),
1350 primary: Default::default(),
1351 },
1352 ],
1353 cx,
1354 );
1355 multibuffer.push_excerpts(
1356 buffer_2.clone(),
1357 [
1358 // excerpt ends at a deletion
1359 ExcerptRange {
1360 context: Point::new(0, 0)..Point::new(1, 5),
1361 primary: Default::default(),
1362 },
1363 // excerpt starts at a deletion
1364 ExcerptRange {
1365 context: Point::new(2, 0)..Point::new(2, 5),
1366 primary: Default::default(),
1367 },
1368 // excerpt fully contains a deletion hunk
1369 ExcerptRange {
1370 context: Point::new(1, 0)..Point::new(2, 5),
1371 primary: Default::default(),
1372 },
1373 // excerpt fully contains an insertion hunk
1374 ExcerptRange {
1375 context: Point::new(4, 0)..Point::new(6, 5),
1376 primary: Default::default(),
1377 },
1378 ],
1379 cx,
1380 );
1381 multibuffer
1382 });
1383
1384 let snapshot = multibuffer.read_with(cx, |b, cx| b.snapshot(cx));
1385
1386 assert_eq!(
1387 snapshot.text(),
1388 "
1389 1.zero
1390 1.ONE
1391 1.FIVE
1392 1.six
1393 2.zero
1394 2.one
1395 2.two
1396 2.one
1397 2.two
1398 2.four
1399 2.five
1400 2.six"
1401 .unindent()
1402 );
1403
1404 let expected = [
1405 (
1406 DiffHunkStatus::Modified,
1407 MultiBufferRow(1)..MultiBufferRow(2),
1408 ),
1409 (
1410 DiffHunkStatus::Modified,
1411 MultiBufferRow(2)..MultiBufferRow(3),
1412 ),
1413 //TODO: Define better when and where removed hunks show up at range extremities
1414 (
1415 DiffHunkStatus::Removed,
1416 MultiBufferRow(6)..MultiBufferRow(6),
1417 ),
1418 (
1419 DiffHunkStatus::Removed,
1420 MultiBufferRow(8)..MultiBufferRow(8),
1421 ),
1422 (
1423 DiffHunkStatus::Added,
1424 MultiBufferRow(10)..MultiBufferRow(11),
1425 ),
1426 ];
1427
1428 assert_eq!(
1429 snapshot
1430 .git_diff_hunks_in_range(MultiBufferRow(0)..MultiBufferRow(12))
1431 .map(|hunk| (hunk_status(&hunk), hunk.row_range))
1432 .collect::<Vec<_>>(),
1433 &expected,
1434 );
1435
1436 assert_eq!(
1437 snapshot
1438 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(12))
1439 .map(|hunk| (hunk_status(&hunk), hunk.row_range))
1440 .collect::<Vec<_>>(),
1441 expected
1442 .iter()
1443 .rev()
1444 .cloned()
1445 .collect::<Vec<_>>()
1446 .as_slice(),
1447 );
1448 }
1449}