hunk_diff.rs

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