git_graph.rs

   1use collections::{BTreeMap, HashMap, IndexSet};
   2use editor::Editor;
   3use git::{
   4    BuildCommitPermalinkParams, GitHostingProviderRegistry, GitRemote, Oid, ParsedGitRemote,
   5    parse_git_remote_url,
   6    repository::{
   7        CommitDiff, CommitFile, InitialGraphCommitData, LogOrder, LogSource, RepoPath,
   8        SearchCommitArgs,
   9    },
  10    status::{FileStatus, StatusCode, TrackedStatus},
  11};
  12use git_ui::{commit_tooltip::CommitAvatar, commit_view::CommitView, git_status_icon};
  13use gpui::{
  14    AnyElement, App, Bounds, ClickEvent, ClipboardItem, Corner, DefiniteLength, DragMoveEvent,
  15    ElementId, Empty, Entity, EventEmitter, FocusHandle, Focusable, Hsla, PathBuilder, Pixels,
  16    Point, ScrollStrategy, ScrollWheelEvent, SharedString, Subscription, Task, TextStyleRefinement,
  17    UniformListScrollHandle, WeakEntity, Window, actions, anchored, deferred, point, prelude::*,
  18    px, uniform_list,
  19};
  20use language::line_diff;
  21use menu::{Cancel, SelectFirst, SelectLast, SelectNext, SelectPrevious};
  22use project::git_store::{
  23    CommitDataState, GitGraphEvent, GitStore, GitStoreEvent, GraphDataResponse, Repository,
  24    RepositoryEvent, RepositoryId,
  25};
  26use search::{
  27    SearchOption, SearchOptions, SearchSource, SelectNextMatch, SelectPreviousMatch,
  28    ToggleCaseSensitive, buffer_search,
  29};
  30use settings::Settings;
  31use smallvec::{SmallVec, smallvec};
  32use std::{
  33    cell::Cell,
  34    ops::Range,
  35    rc::Rc,
  36    sync::{Arc, OnceLock},
  37    time::{Duration, Instant},
  38};
  39use theme::AccentColors;
  40use theme_settings::ThemeSettings;
  41use time::{OffsetDateTime, UtcOffset, format_description::BorrowedFormatItem};
  42use ui::{
  43    ButtonLike, Chip, ColumnWidthConfig, CommonAnimationExt as _, ContextMenu, DiffStat, Divider,
  44    HeaderResizeInfo, HighlightedLabel, RedistributableColumnsState, ScrollableHandle, Table,
  45    TableInteractionState, TableRenderContext, TableResizeBehavior, Tooltip, WithScrollbar,
  46    bind_redistributable_columns, prelude::*, render_redistributable_columns_resize_handles,
  47    render_table_header, table_row::TableRow,
  48};
  49use workspace::{
  50    Workspace,
  51    item::{Item, ItemEvent, TabTooltipContent},
  52};
  53
  54const COMMIT_CIRCLE_RADIUS: Pixels = px(3.5);
  55const COMMIT_CIRCLE_STROKE_WIDTH: Pixels = px(1.5);
  56const LANE_WIDTH: Pixels = px(16.0);
  57const LEFT_PADDING: Pixels = px(12.0);
  58const LINE_WIDTH: Pixels = px(1.5);
  59const RESIZE_HANDLE_WIDTH: f32 = 8.0;
  60const COPIED_STATE_DURATION: Duration = Duration::from_secs(2);
  61
  62struct CopiedState {
  63    copied_at: Option<Instant>,
  64}
  65
  66impl CopiedState {
  67    fn new(_window: &mut Window, _cx: &mut Context<Self>) -> Self {
  68        Self { copied_at: None }
  69    }
  70
  71    fn is_copied(&self) -> bool {
  72        self.copied_at
  73            .map(|t| t.elapsed() < COPIED_STATE_DURATION)
  74            .unwrap_or(false)
  75    }
  76
  77    fn mark_copied(&mut self) {
  78        self.copied_at = Some(Instant::now());
  79    }
  80}
  81
  82struct DraggedSplitHandle;
  83
  84#[derive(Clone)]
  85struct ChangedFileEntry {
  86    status: FileStatus,
  87    file_name: SharedString,
  88    dir_path: SharedString,
  89    repo_path: RepoPath,
  90}
  91
  92impl ChangedFileEntry {
  93    fn from_commit_file(file: &CommitFile, _cx: &App) -> Self {
  94        let file_name: SharedString = file
  95            .path
  96            .file_name()
  97            .map(|n| n.to_string())
  98            .unwrap_or_default()
  99            .into();
 100        let dir_path: SharedString = file
 101            .path
 102            .parent()
 103            .map(|p| p.as_unix_str().to_string())
 104            .unwrap_or_default()
 105            .into();
 106
 107        let status_code = match (&file.old_text, &file.new_text) {
 108            (None, Some(_)) => StatusCode::Added,
 109            (Some(_), None) => StatusCode::Deleted,
 110            _ => StatusCode::Modified,
 111        };
 112
 113        let status = FileStatus::Tracked(TrackedStatus {
 114            index_status: status_code,
 115            worktree_status: StatusCode::Unmodified,
 116        });
 117
 118        Self {
 119            status,
 120            file_name,
 121            dir_path,
 122            repo_path: file.path.clone(),
 123        }
 124    }
 125
 126    fn open_in_commit_view(
 127        &self,
 128        commit_sha: &SharedString,
 129        repository: &WeakEntity<Repository>,
 130        workspace: &WeakEntity<Workspace>,
 131        window: &mut Window,
 132        cx: &mut App,
 133    ) {
 134        CommitView::open(
 135            commit_sha.to_string(),
 136            repository.clone(),
 137            workspace.clone(),
 138            None,
 139            Some(self.repo_path.clone()),
 140            window,
 141            cx,
 142        );
 143    }
 144
 145    fn render(
 146        &self,
 147        ix: usize,
 148        commit_sha: SharedString,
 149        repository: WeakEntity<Repository>,
 150        workspace: WeakEntity<Workspace>,
 151        _cx: &App,
 152    ) -> AnyElement {
 153        let file_name = self.file_name.clone();
 154        let dir_path = self.dir_path.clone();
 155
 156        div()
 157            .w_full()
 158            .child(
 159                ButtonLike::new(("changed-file", ix))
 160                    .child(
 161                        h_flex()
 162                            .min_w_0()
 163                            .w_full()
 164                            .gap_1()
 165                            .overflow_hidden()
 166                            .child(git_status_icon(self.status))
 167                            .child(
 168                                Label::new(file_name.clone())
 169                                    .size(LabelSize::Small)
 170                                    .truncate(),
 171                            )
 172                            .when(!dir_path.is_empty(), |this| {
 173                                this.child(
 174                                    Label::new(dir_path.clone())
 175                                        .size(LabelSize::Small)
 176                                        .color(Color::Muted)
 177                                        .truncate_start(),
 178                                )
 179                            }),
 180                    )
 181                    .tooltip({
 182                        let meta = if dir_path.is_empty() {
 183                            file_name
 184                        } else {
 185                            format!("{}/{}", dir_path, file_name).into()
 186                        };
 187                        move |_, cx| Tooltip::with_meta("View Changes", None, meta.clone(), cx)
 188                    })
 189                    .on_click({
 190                        let entry = self.clone();
 191                        move |_, window, cx| {
 192                            entry.open_in_commit_view(
 193                                &commit_sha,
 194                                &repository,
 195                                &workspace,
 196                                window,
 197                                cx,
 198                            );
 199                        }
 200                    }),
 201            )
 202            .into_any_element()
 203    }
 204}
 205
 206enum QueryState {
 207    Pending(SharedString),
 208    Confirmed((SharedString, Task<()>)),
 209    Empty,
 210}
 211
 212impl QueryState {
 213    fn next_state(&mut self) {
 214        match self {
 215            Self::Confirmed((query, _)) => *self = Self::Pending(std::mem::take(query)),
 216            _ => {}
 217        };
 218    }
 219}
 220
 221struct SearchState {
 222    case_sensitive: bool,
 223    editor: Entity<Editor>,
 224    state: QueryState,
 225    pub matches: IndexSet<Oid>,
 226    pub selected_index: Option<usize>,
 227}
 228
 229pub struct SplitState {
 230    left_ratio: f32,
 231    visible_left_ratio: f32,
 232}
 233
 234impl SplitState {
 235    pub fn new() -> Self {
 236        Self {
 237            left_ratio: 1.0,
 238            visible_left_ratio: 1.0,
 239        }
 240    }
 241
 242    pub fn right_ratio(&self) -> f32 {
 243        1.0 - self.visible_left_ratio
 244    }
 245
 246    fn on_drag_move(
 247        &mut self,
 248        drag_event: &DragMoveEvent<DraggedSplitHandle>,
 249        _window: &mut Window,
 250        _cx: &mut Context<Self>,
 251    ) {
 252        let drag_position = drag_event.event.position;
 253        let bounds = drag_event.bounds;
 254        let bounds_width = bounds.right() - bounds.left();
 255
 256        let min_ratio = 0.1;
 257        let max_ratio = 0.9;
 258
 259        let new_ratio = (drag_position.x - bounds.left()) / bounds_width;
 260        self.visible_left_ratio = new_ratio.clamp(min_ratio, max_ratio);
 261    }
 262
 263    fn commit_ratio(&mut self) {
 264        self.left_ratio = self.visible_left_ratio;
 265    }
 266
 267    fn on_double_click(&mut self) {
 268        self.left_ratio = 1.0;
 269        self.visible_left_ratio = 1.0;
 270    }
 271}
 272
 273actions!(
 274    git_graph,
 275    [
 276        /// Opens the commit view for the selected commit.
 277        OpenCommitView,
 278        /// Focuses the search field.
 279        FocusSearch,
 280    ]
 281);
 282
 283fn timestamp_format() -> &'static [BorrowedFormatItem<'static>] {
 284    static FORMAT: OnceLock<Vec<BorrowedFormatItem<'static>>> = OnceLock::new();
 285    FORMAT.get_or_init(|| {
 286        time::format_description::parse("[day] [month repr:short] [year] [hour]:[minute]")
 287            .unwrap_or_default()
 288    })
 289}
 290
 291fn format_timestamp(timestamp: i64) -> String {
 292    let Ok(datetime) = OffsetDateTime::from_unix_timestamp(timestamp) else {
 293        return "Unknown".to_string();
 294    };
 295
 296    let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
 297    let local_datetime = datetime.to_offset(local_offset);
 298
 299    local_datetime
 300        .format(timestamp_format())
 301        .unwrap_or_default()
 302}
 303
 304fn accent_colors_count(accents: &AccentColors) -> usize {
 305    accents.0.len()
 306}
 307
 308#[derive(Copy, Clone, Debug)]
 309struct BranchColor(u8);
 310
 311#[derive(Debug)]
 312enum LaneState {
 313    Empty,
 314    Active {
 315        child: Oid,
 316        parent: Oid,
 317        color: Option<BranchColor>,
 318        starting_row: usize,
 319        starting_col: usize,
 320        destination_column: Option<usize>,
 321        segments: SmallVec<[CommitLineSegment; 1]>,
 322    },
 323}
 324
 325impl LaneState {
 326    fn to_commit_lines(
 327        &mut self,
 328        ending_row: usize,
 329        lane_column: usize,
 330        parent_column: usize,
 331        parent_color: BranchColor,
 332    ) -> Option<CommitLine> {
 333        let state = std::mem::replace(self, LaneState::Empty);
 334
 335        match state {
 336            LaneState::Active {
 337                #[cfg_attr(not(test), allow(unused_variables))]
 338                parent,
 339                #[cfg_attr(not(test), allow(unused_variables))]
 340                child,
 341                color,
 342                starting_row,
 343                starting_col,
 344                destination_column,
 345                mut segments,
 346            } => {
 347                let final_destination = destination_column.unwrap_or(parent_column);
 348                let final_color = color.unwrap_or(parent_color);
 349
 350                Some(CommitLine {
 351                    #[cfg(test)]
 352                    child,
 353                    #[cfg(test)]
 354                    parent,
 355                    child_column: starting_col,
 356                    full_interval: starting_row..ending_row,
 357                    color_idx: final_color.0 as usize,
 358                    segments: {
 359                        match segments.last_mut() {
 360                            Some(CommitLineSegment::Straight { to_row })
 361                                if *to_row == usize::MAX =>
 362                            {
 363                                if final_destination != lane_column {
 364                                    *to_row = ending_row - 1;
 365
 366                                    let curved_line = CommitLineSegment::Curve {
 367                                        to_column: final_destination,
 368                                        on_row: ending_row,
 369                                        curve_kind: CurveKind::Checkout,
 370                                    };
 371
 372                                    if *to_row == starting_row {
 373                                        let last_index = segments.len() - 1;
 374                                        segments[last_index] = curved_line;
 375                                    } else {
 376                                        segments.push(curved_line);
 377                                    }
 378                                } else {
 379                                    *to_row = ending_row;
 380                                }
 381                            }
 382                            Some(CommitLineSegment::Curve {
 383                                on_row,
 384                                to_column,
 385                                curve_kind,
 386                            }) if *on_row == usize::MAX => {
 387                                if *to_column == usize::MAX {
 388                                    *to_column = final_destination;
 389                                }
 390                                if matches!(curve_kind, CurveKind::Merge) {
 391                                    *on_row = starting_row + 1;
 392                                    if *on_row < ending_row {
 393                                        if *to_column != final_destination {
 394                                            segments.push(CommitLineSegment::Straight {
 395                                                to_row: ending_row - 1,
 396                                            });
 397                                            segments.push(CommitLineSegment::Curve {
 398                                                to_column: final_destination,
 399                                                on_row: ending_row,
 400                                                curve_kind: CurveKind::Checkout,
 401                                            });
 402                                        } else {
 403                                            segments.push(CommitLineSegment::Straight {
 404                                                to_row: ending_row,
 405                                            });
 406                                        }
 407                                    } else if *to_column != final_destination {
 408                                        segments.push(CommitLineSegment::Curve {
 409                                            to_column: final_destination,
 410                                            on_row: ending_row,
 411                                            curve_kind: CurveKind::Checkout,
 412                                        });
 413                                    }
 414                                } else {
 415                                    *on_row = ending_row;
 416                                    if *to_column != final_destination {
 417                                        segments.push(CommitLineSegment::Straight {
 418                                            to_row: ending_row,
 419                                        });
 420                                        segments.push(CommitLineSegment::Curve {
 421                                            to_column: final_destination,
 422                                            on_row: ending_row,
 423                                            curve_kind: CurveKind::Checkout,
 424                                        });
 425                                    }
 426                                }
 427                            }
 428                            Some(CommitLineSegment::Curve {
 429                                on_row, to_column, ..
 430                            }) => {
 431                                if *on_row < ending_row {
 432                                    if *to_column != final_destination {
 433                                        segments.push(CommitLineSegment::Straight {
 434                                            to_row: ending_row - 1,
 435                                        });
 436                                        segments.push(CommitLineSegment::Curve {
 437                                            to_column: final_destination,
 438                                            on_row: ending_row,
 439                                            curve_kind: CurveKind::Checkout,
 440                                        });
 441                                    } else {
 442                                        segments.push(CommitLineSegment::Straight {
 443                                            to_row: ending_row,
 444                                        });
 445                                    }
 446                                } else if *to_column != final_destination {
 447                                    segments.push(CommitLineSegment::Curve {
 448                                        to_column: final_destination,
 449                                        on_row: ending_row,
 450                                        curve_kind: CurveKind::Checkout,
 451                                    });
 452                                }
 453                            }
 454                            _ => {}
 455                        }
 456
 457                        segments
 458                    },
 459                })
 460            }
 461            LaneState::Empty => None,
 462        }
 463    }
 464
 465    fn is_empty(&self) -> bool {
 466        match self {
 467            LaneState::Empty => true,
 468            LaneState::Active { .. } => false,
 469        }
 470    }
 471}
 472
 473struct CommitEntry {
 474    data: Arc<InitialGraphCommitData>,
 475    lane: usize,
 476    color_idx: usize,
 477}
 478
 479type ActiveLaneIdx = usize;
 480
 481enum AllCommitCount {
 482    NotLoaded,
 483    Loaded(usize),
 484}
 485
 486#[derive(Debug)]
 487enum CurveKind {
 488    Merge,
 489    Checkout,
 490}
 491
 492#[derive(Debug)]
 493enum CommitLineSegment {
 494    Straight {
 495        to_row: usize,
 496    },
 497    Curve {
 498        to_column: usize,
 499        on_row: usize,
 500        curve_kind: CurveKind,
 501    },
 502}
 503
 504#[derive(Debug)]
 505struct CommitLine {
 506    #[cfg(test)]
 507    child: Oid,
 508    #[cfg(test)]
 509    parent: Oid,
 510    child_column: usize,
 511    full_interval: Range<usize>,
 512    color_idx: usize,
 513    segments: SmallVec<[CommitLineSegment; 1]>,
 514}
 515
 516impl CommitLine {
 517    fn get_first_visible_segment_idx(&self, first_visible_row: usize) -> Option<(usize, usize)> {
 518        if first_visible_row > self.full_interval.end {
 519            return None;
 520        } else if first_visible_row <= self.full_interval.start {
 521            return Some((0, self.child_column));
 522        }
 523
 524        let mut current_column = self.child_column;
 525
 526        for (idx, segment) in self.segments.iter().enumerate() {
 527            match segment {
 528                CommitLineSegment::Straight { to_row } => {
 529                    if *to_row >= first_visible_row {
 530                        return Some((idx, current_column));
 531                    }
 532                }
 533                CommitLineSegment::Curve {
 534                    to_column, on_row, ..
 535                } => {
 536                    if *on_row >= first_visible_row {
 537                        return Some((idx, current_column));
 538                    }
 539                    current_column = *to_column;
 540                }
 541            }
 542        }
 543
 544        None
 545    }
 546}
 547
 548#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 549struct CommitLineKey {
 550    child: Oid,
 551    parent: Oid,
 552}
 553
 554struct GraphData {
 555    lane_states: SmallVec<[LaneState; 8]>,
 556    lane_colors: HashMap<ActiveLaneIdx, BranchColor>,
 557    parent_to_lanes: HashMap<Oid, SmallVec<[usize; 1]>>,
 558    next_color: BranchColor,
 559    accent_colors_count: usize,
 560    commits: Vec<Rc<CommitEntry>>,
 561    max_commit_count: AllCommitCount,
 562    max_lanes: usize,
 563    lines: Vec<Rc<CommitLine>>,
 564    active_commit_lines: HashMap<CommitLineKey, usize>,
 565    active_commit_lines_by_parent: HashMap<Oid, SmallVec<[usize; 1]>>,
 566}
 567
 568impl GraphData {
 569    fn new(accent_colors_count: usize) -> Self {
 570        GraphData {
 571            lane_states: SmallVec::default(),
 572            lane_colors: HashMap::default(),
 573            parent_to_lanes: HashMap::default(),
 574            next_color: BranchColor(0),
 575            accent_colors_count,
 576            commits: Vec::default(),
 577            max_commit_count: AllCommitCount::NotLoaded,
 578            max_lanes: 0,
 579            lines: Vec::default(),
 580            active_commit_lines: HashMap::default(),
 581            active_commit_lines_by_parent: HashMap::default(),
 582        }
 583    }
 584
 585    fn clear(&mut self) {
 586        self.lane_states.clear();
 587        self.lane_colors.clear();
 588        self.parent_to_lanes.clear();
 589        self.commits.clear();
 590        self.lines.clear();
 591        self.active_commit_lines.clear();
 592        self.active_commit_lines_by_parent.clear();
 593        self.next_color = BranchColor(0);
 594        self.max_commit_count = AllCommitCount::NotLoaded;
 595        self.max_lanes = 0;
 596    }
 597
 598    fn first_empty_lane_idx(&mut self) -> ActiveLaneIdx {
 599        self.lane_states
 600            .iter()
 601            .position(LaneState::is_empty)
 602            .unwrap_or_else(|| {
 603                self.lane_states.push(LaneState::Empty);
 604                self.lane_states.len() - 1
 605            })
 606    }
 607
 608    fn get_lane_color(&mut self, lane_idx: ActiveLaneIdx) -> BranchColor {
 609        let accent_colors_count = self.accent_colors_count;
 610        *self.lane_colors.entry(lane_idx).or_insert_with(|| {
 611            let color_idx = self.next_color;
 612            self.next_color = BranchColor((self.next_color.0 + 1) % accent_colors_count as u8);
 613            color_idx
 614        })
 615    }
 616
 617    fn add_commits(&mut self, commits: &[Arc<InitialGraphCommitData>]) {
 618        self.commits.reserve(commits.len());
 619        self.lines.reserve(commits.len() / 2);
 620
 621        for commit in commits.iter() {
 622            let commit_row = self.commits.len();
 623
 624            let commit_lane = self
 625                .parent_to_lanes
 626                .get(&commit.sha)
 627                .and_then(|lanes| lanes.first().copied());
 628
 629            let commit_lane = commit_lane.unwrap_or_else(|| self.first_empty_lane_idx());
 630
 631            let commit_color = self.get_lane_color(commit_lane);
 632
 633            if let Some(lanes) = self.parent_to_lanes.remove(&commit.sha) {
 634                for lane_column in lanes {
 635                    let state = &mut self.lane_states[lane_column];
 636
 637                    if let LaneState::Active {
 638                        starting_row,
 639                        segments,
 640                        ..
 641                    } = state
 642                    {
 643                        if let Some(CommitLineSegment::Curve {
 644                            to_column,
 645                            curve_kind: CurveKind::Merge,
 646                            ..
 647                        }) = segments.first_mut()
 648                        {
 649                            let curve_row = *starting_row + 1;
 650                            let would_overlap =
 651                                if lane_column != commit_lane && curve_row < commit_row {
 652                                    self.commits[curve_row..commit_row]
 653                                        .iter()
 654                                        .any(|c| c.lane == commit_lane)
 655                                } else {
 656                                    false
 657                                };
 658
 659                            if would_overlap {
 660                                *to_column = lane_column;
 661                            }
 662                        }
 663                    }
 664
 665                    if let Some(commit_line) =
 666                        state.to_commit_lines(commit_row, lane_column, commit_lane, commit_color)
 667                    {
 668                        self.lines.push(Rc::new(commit_line));
 669                    }
 670                }
 671            }
 672
 673            commit
 674                .parents
 675                .iter()
 676                .enumerate()
 677                .for_each(|(parent_idx, parent)| {
 678                    if parent_idx == 0 {
 679                        self.lane_states[commit_lane] = LaneState::Active {
 680                            parent: *parent,
 681                            child: commit.sha,
 682                            color: Some(commit_color),
 683                            starting_col: commit_lane,
 684                            starting_row: commit_row,
 685                            destination_column: None,
 686                            segments: smallvec![CommitLineSegment::Straight { to_row: usize::MAX }],
 687                        };
 688
 689                        self.parent_to_lanes
 690                            .entry(*parent)
 691                            .or_default()
 692                            .push(commit_lane);
 693                    } else {
 694                        let new_lane = self.first_empty_lane_idx();
 695
 696                        self.lane_states[new_lane] = LaneState::Active {
 697                            parent: *parent,
 698                            child: commit.sha,
 699                            color: None,
 700                            starting_col: commit_lane,
 701                            starting_row: commit_row,
 702                            destination_column: None,
 703                            segments: smallvec![CommitLineSegment::Curve {
 704                                to_column: usize::MAX,
 705                                on_row: usize::MAX,
 706                                curve_kind: CurveKind::Merge,
 707                            },],
 708                        };
 709
 710                        self.parent_to_lanes
 711                            .entry(*parent)
 712                            .or_default()
 713                            .push(new_lane);
 714                    }
 715                });
 716
 717            self.max_lanes = self.max_lanes.max(self.lane_states.len());
 718
 719            self.commits.push(Rc::new(CommitEntry {
 720                data: commit.clone(),
 721                lane: commit_lane,
 722                color_idx: commit_color.0 as usize,
 723            }));
 724        }
 725
 726        self.max_commit_count = AllCommitCount::Loaded(self.commits.len());
 727    }
 728}
 729
 730pub fn init(cx: &mut App) {
 731    workspace::register_serializable_item::<GitGraph>(cx);
 732
 733    cx.observe_new(|workspace: &mut workspace::Workspace, _, _| {
 734        workspace.register_action_renderer(|div, workspace, _, cx| {
 735            div.when(
 736                workspace.project().read(cx).active_repository(cx).is_some(),
 737                |div| {
 738                    let workspace = workspace.weak_handle();
 739
 740                    div.on_action({
 741                        let workspace = workspace.clone();
 742                        move |_: &git_ui::git_panel::Open, window, cx| {
 743                            workspace
 744                                .update(cx, |workspace, cx| {
 745                                    let Some(repo) =
 746                                        workspace.project().read(cx).active_repository(cx)
 747                                    else {
 748                                        return;
 749                                    };
 750                                    let selected_repo_id = repo.read(cx).id;
 751
 752                                    let existing = workspace
 753                                        .items_of_type::<GitGraph>(cx)
 754                                        .find(|graph| graph.read(cx).repo_id == selected_repo_id);
 755                                    if let Some(existing) = existing {
 756                                        workspace.activate_item(&existing, true, true, window, cx);
 757                                        return;
 758                                    }
 759
 760                                    let git_store =
 761                                        workspace.project().read(cx).git_store().clone();
 762                                    let workspace_handle = workspace.weak_handle();
 763                                    let git_graph = cx.new(|cx| {
 764                                        GitGraph::new(
 765                                            selected_repo_id,
 766                                            git_store,
 767                                            workspace_handle,
 768                                            window,
 769                                            cx,
 770                                        )
 771                                    });
 772                                    workspace.add_item_to_active_pane(
 773                                        Box::new(git_graph),
 774                                        None,
 775                                        true,
 776                                        window,
 777                                        cx,
 778                                    );
 779                                })
 780                                .ok();
 781                        }
 782                    })
 783                    .on_action(
 784                        move |action: &git_ui::git_panel::OpenAtCommit, window, cx| {
 785                            let sha = action.sha.clone();
 786                            workspace
 787                                .update(cx, |workspace, cx| {
 788                                    let Some(repo) =
 789                                        workspace.project().read(cx).active_repository(cx)
 790                                    else {
 791                                        return;
 792                                    };
 793                                    let selected_repo_id = repo.read(cx).id;
 794
 795                                    let existing = workspace
 796                                        .items_of_type::<GitGraph>(cx)
 797                                        .find(|graph| graph.read(cx).repo_id == selected_repo_id);
 798                                    if let Some(existing) = existing {
 799                                        existing.update(cx, |graph, cx| {
 800                                            graph.select_commit_by_sha(sha.as_str(), cx);
 801                                        });
 802                                        workspace.activate_item(&existing, true, true, window, cx);
 803                                        return;
 804                                    }
 805
 806                                    let git_store =
 807                                        workspace.project().read(cx).git_store().clone();
 808                                    let workspace_handle = workspace.weak_handle();
 809                                    let git_graph = cx.new(|cx| {
 810                                        let mut graph = GitGraph::new(
 811                                            selected_repo_id,
 812                                            git_store,
 813                                            workspace_handle,
 814                                            window,
 815                                            cx,
 816                                        );
 817                                        graph.select_commit_by_sha(sha.as_str(), cx);
 818                                        graph
 819                                    });
 820                                    workspace.add_item_to_active_pane(
 821                                        Box::new(git_graph),
 822                                        None,
 823                                        true,
 824                                        window,
 825                                        cx,
 826                                    );
 827                                })
 828                                .ok();
 829                        },
 830                    )
 831                },
 832            )
 833        });
 834    })
 835    .detach();
 836}
 837
 838fn lane_center_x(bounds: Bounds<Pixels>, lane: f32) -> Pixels {
 839    bounds.origin.x + LEFT_PADDING + lane * LANE_WIDTH + LANE_WIDTH / 2.0
 840}
 841
 842fn to_row_center(
 843    to_row: usize,
 844    row_height: Pixels,
 845    scroll_offset: Pixels,
 846    bounds: Bounds<Pixels>,
 847) -> Pixels {
 848    bounds.origin.y + to_row as f32 * row_height + row_height / 2.0 - scroll_offset
 849}
 850
 851fn draw_commit_circle(center_x: Pixels, center_y: Pixels, color: Hsla, window: &mut Window) {
 852    let radius = COMMIT_CIRCLE_RADIUS;
 853
 854    let mut builder = PathBuilder::fill();
 855
 856    // Start at the rightmost point of the circle
 857    builder.move_to(point(center_x + radius, center_y));
 858
 859    // Draw the circle using two arc_to calls (top half, then bottom half)
 860    builder.arc_to(
 861        point(radius, radius),
 862        px(0.),
 863        false,
 864        true,
 865        point(center_x - radius, center_y),
 866    );
 867    builder.arc_to(
 868        point(radius, radius),
 869        px(0.),
 870        false,
 871        true,
 872        point(center_x + radius, center_y),
 873    );
 874    builder.close();
 875
 876    if let Ok(path) = builder.build() {
 877        window.paint_path(path, color);
 878    }
 879}
 880
 881fn compute_diff_stats(diff: &CommitDiff) -> (usize, usize) {
 882    diff.files.iter().fold((0, 0), |(added, removed), file| {
 883        let old_text = file.old_text.as_deref().unwrap_or("");
 884        let new_text = file.new_text.as_deref().unwrap_or("");
 885        let hunks = line_diff(old_text, new_text);
 886        hunks
 887            .iter()
 888            .fold((added, removed), |(a, r), (old_range, new_range)| {
 889                (
 890                    a + (new_range.end - new_range.start) as usize,
 891                    r + (old_range.end - old_range.start) as usize,
 892                )
 893            })
 894    })
 895}
 896
 897pub struct GitGraph {
 898    focus_handle: FocusHandle,
 899    search_state: SearchState,
 900    graph_data: GraphData,
 901    git_store: Entity<GitStore>,
 902    workspace: WeakEntity<Workspace>,
 903    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 904    row_height: Pixels,
 905    table_interaction_state: Entity<TableInteractionState>,
 906    column_widths: Entity<RedistributableColumnsState>,
 907    selected_entry_idx: Option<usize>,
 908    hovered_entry_idx: Option<usize>,
 909    graph_canvas_bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
 910    log_source: LogSource,
 911    log_order: LogOrder,
 912    selected_commit_diff: Option<CommitDiff>,
 913    selected_commit_diff_stats: Option<(usize, usize)>,
 914    _commit_diff_task: Option<Task<()>>,
 915    commit_details_split_state: Entity<SplitState>,
 916    repo_id: RepositoryId,
 917    changed_files_scroll_handle: UniformListScrollHandle,
 918    pending_select_sha: Option<Oid>,
 919}
 920
 921impl GitGraph {
 922    fn invalidate_state(&mut self, cx: &mut Context<Self>) {
 923        self.graph_data.clear();
 924        self.search_state.matches.clear();
 925        self.search_state.selected_index = None;
 926        self.search_state.state.next_state();
 927        cx.notify();
 928    }
 929
 930    fn row_height(cx: &App) -> Pixels {
 931        let settings = ThemeSettings::get_global(cx);
 932        let font_size = settings.buffer_font_size(cx);
 933        font_size + px(12.0)
 934    }
 935
 936    fn graph_canvas_content_width(&self) -> Pixels {
 937        (LANE_WIDTH * self.graph_data.max_lanes.max(6) as f32) + LEFT_PADDING * 2.0
 938    }
 939
 940    fn preview_column_fractions(&self, window: &Window, cx: &App) -> [f32; 5] {
 941        let fractions = self
 942            .column_widths
 943            .read(cx)
 944            .preview_fractions(window.rem_size());
 945        [
 946            fractions[0],
 947            fractions[1],
 948            fractions[2],
 949            fractions[3],
 950            fractions[4],
 951        ]
 952    }
 953
 954    fn table_column_width_config(&self, window: &Window, cx: &App) -> ColumnWidthConfig {
 955        let [_, description, date, author, commit] = self.preview_column_fractions(window, cx);
 956        let table_total = description + date + author + commit;
 957
 958        let widths = if table_total > 0.0 {
 959            vec![
 960                DefiniteLength::Fraction(description / table_total),
 961                DefiniteLength::Fraction(date / table_total),
 962                DefiniteLength::Fraction(author / table_total),
 963                DefiniteLength::Fraction(commit / table_total),
 964            ]
 965        } else {
 966            vec![
 967                DefiniteLength::Fraction(0.25),
 968                DefiniteLength::Fraction(0.25),
 969                DefiniteLength::Fraction(0.25),
 970                DefiniteLength::Fraction(0.25),
 971            ]
 972        };
 973
 974        ColumnWidthConfig::explicit(widths)
 975    }
 976
 977    fn graph_viewport_width(&self, window: &Window, cx: &App) -> Pixels {
 978        self.column_widths
 979            .read(cx)
 980            .preview_column_width(0, window)
 981            .unwrap_or_else(|| self.graph_canvas_content_width())
 982    }
 983
 984    pub fn new(
 985        repo_id: RepositoryId,
 986        git_store: Entity<GitStore>,
 987        workspace: WeakEntity<Workspace>,
 988        window: &mut Window,
 989        cx: &mut Context<Self>,
 990    ) -> Self {
 991        let focus_handle = cx.focus_handle();
 992        cx.on_focus(&focus_handle, window, |_, _, cx| cx.notify())
 993            .detach();
 994
 995        let accent_colors = cx.theme().accents();
 996        let graph = GraphData::new(accent_colors_count(accent_colors));
 997        let log_source = LogSource::default();
 998        let log_order = LogOrder::default();
 999
1000        cx.subscribe(&git_store, |this, _, event, cx| match event {
1001            GitStoreEvent::RepositoryUpdated(updated_repo_id, repo_event, _) => {
1002                if this.repo_id == *updated_repo_id {
1003                    if let Some(repository) = this.get_repository(cx) {
1004                        this.on_repository_event(repository, repo_event, cx);
1005                    }
1006                }
1007            }
1008            _ => {}
1009        })
1010        .detach();
1011
1012        let search_editor = cx.new(|cx| {
1013            let mut editor = Editor::single_line(window, cx);
1014            editor.set_placeholder_text("Search commits…", window, cx);
1015            editor
1016        });
1017
1018        let table_interaction_state = cx.new(|cx| TableInteractionState::new(cx));
1019        let column_widths = cx.new(|_cx| {
1020            RedistributableColumnsState::new(
1021                5,
1022                vec![
1023                    DefiniteLength::Fraction(0.14),
1024                    DefiniteLength::Fraction(0.6192),
1025                    DefiniteLength::Fraction(0.1032),
1026                    DefiniteLength::Fraction(0.086),
1027                    DefiniteLength::Fraction(0.0516),
1028                ],
1029                vec![
1030                    TableResizeBehavior::Resizable,
1031                    TableResizeBehavior::Resizable,
1032                    TableResizeBehavior::Resizable,
1033                    TableResizeBehavior::Resizable,
1034                    TableResizeBehavior::Resizable,
1035                ],
1036            )
1037        });
1038        let mut row_height = Self::row_height(cx);
1039
1040        cx.observe_global_in::<settings::SettingsStore>(window, move |this, _window, cx| {
1041            let new_row_height = Self::row_height(cx);
1042            if new_row_height != row_height {
1043                this.row_height = new_row_height;
1044                this.table_interaction_state.update(cx, |state, _cx| {
1045                    state.scroll_handle.0.borrow_mut().last_item_size = None;
1046                });
1047                row_height = new_row_height;
1048                cx.notify();
1049            }
1050        })
1051        .detach();
1052
1053        let mut this = GitGraph {
1054            focus_handle,
1055            git_store,
1056            search_state: SearchState {
1057                case_sensitive: false,
1058                editor: search_editor,
1059                matches: IndexSet::default(),
1060                selected_index: None,
1061                state: QueryState::Empty,
1062            },
1063            workspace,
1064            graph_data: graph,
1065            _commit_diff_task: None,
1066            context_menu: None,
1067            row_height,
1068            table_interaction_state,
1069            column_widths,
1070            selected_entry_idx: None,
1071            hovered_entry_idx: None,
1072            graph_canvas_bounds: Rc::new(Cell::new(None)),
1073            selected_commit_diff: None,
1074            selected_commit_diff_stats: None,
1075            log_source,
1076            log_order,
1077            commit_details_split_state: cx.new(|_cx| SplitState::new()),
1078            repo_id,
1079            changed_files_scroll_handle: UniformListScrollHandle::new(),
1080            pending_select_sha: None,
1081        };
1082
1083        this.fetch_initial_graph_data(cx);
1084        this
1085    }
1086
1087    fn on_repository_event(
1088        &mut self,
1089        repository: Entity<Repository>,
1090        event: &RepositoryEvent,
1091        cx: &mut Context<Self>,
1092    ) {
1093        match event {
1094            RepositoryEvent::GraphEvent((source, order), event)
1095                if source == &self.log_source && order == &self.log_order =>
1096            {
1097                match event {
1098                    GitGraphEvent::FullyLoaded => {
1099                        if let Some(pending_sha_index) =
1100                            self.pending_select_sha.take().and_then(|oid| {
1101                                repository
1102                                    .read(cx)
1103                                    .get_graph_data(source.clone(), *order)
1104                                    .and_then(|data| data.commit_oid_to_index.get(&oid).copied())
1105                            })
1106                        {
1107                            self.select_entry(pending_sha_index, ScrollStrategy::Nearest, cx);
1108                        }
1109                    }
1110                    GitGraphEvent::LoadingError => {
1111                        // todo(git_graph): Wire this up with the UI
1112                    }
1113                    GitGraphEvent::CountUpdated(commit_count) => {
1114                        let old_count = self.graph_data.commits.len();
1115
1116                        if let Some(pending_selection_index) =
1117                            repository.update(cx, |repository, cx| {
1118                                let GraphDataResponse {
1119                                    commits,
1120                                    is_loading,
1121                                    error: _,
1122                                } = repository.graph_data(
1123                                    source.clone(),
1124                                    *order,
1125                                    old_count..*commit_count,
1126                                    cx,
1127                                );
1128                                self.graph_data.add_commits(commits);
1129
1130                                let pending_sha_index = self.pending_select_sha.and_then(|oid| {
1131                                    repository.get_graph_data(source.clone(), *order).and_then(
1132                                        |data| data.commit_oid_to_index.get(&oid).copied(),
1133                                    )
1134                                });
1135
1136                                if !is_loading && pending_sha_index.is_none() {
1137                                    self.pending_select_sha.take();
1138                                }
1139
1140                                pending_sha_index
1141                            })
1142                        {
1143                            self.select_entry(pending_selection_index, ScrollStrategy::Nearest, cx);
1144                            self.pending_select_sha.take();
1145                        }
1146
1147                        cx.notify();
1148                    }
1149                }
1150            }
1151            RepositoryEvent::BranchChanged => {
1152                self.pending_select_sha = None;
1153                // Only invalidate if we scanned atleast once,
1154                // meaning we are not inside the initial repo loading state
1155                // NOTE: this fixes an loading performance regression
1156                if repository.read(cx).scan_id > 1 {
1157                    self.invalidate_state(cx);
1158                }
1159            }
1160            RepositoryEvent::GraphEvent(_, _) => {}
1161            _ => {}
1162        }
1163    }
1164
1165    fn fetch_initial_graph_data(&mut self, cx: &mut App) {
1166        if let Some(repository) = self.get_repository(cx) {
1167            repository.update(cx, |repository, cx| {
1168                let commits = repository
1169                    .graph_data(self.log_source.clone(), self.log_order, 0..usize::MAX, cx)
1170                    .commits;
1171                self.graph_data.add_commits(commits);
1172            });
1173        }
1174    }
1175
1176    fn get_repository(&self, cx: &App) -> Option<Entity<Repository>> {
1177        let git_store = self.git_store.read(cx);
1178        git_store.repositories().get(&self.repo_id).cloned()
1179    }
1180
1181    fn render_chip(&self, name: &SharedString, accent_color: gpui::Hsla) -> impl IntoElement {
1182        Chip::new(name.clone())
1183            .label_size(LabelSize::Small)
1184            .bg_color(accent_color.opacity(0.1))
1185            .border_color(accent_color.opacity(0.5))
1186    }
1187
1188    fn render_table_rows(
1189        &mut self,
1190        range: Range<usize>,
1191        _window: &mut Window,
1192        cx: &mut Context<Self>,
1193    ) -> Vec<Vec<AnyElement>> {
1194        let repository = self.get_repository(cx);
1195
1196        let row_height = self.row_height;
1197
1198        // We fetch data outside the visible viewport to avoid loading entries when
1199        // users scroll through the git graph
1200        if let Some(repository) = repository.as_ref() {
1201            const FETCH_RANGE: usize = 100;
1202            repository.update(cx, |repository, cx| {
1203                self.graph_data.commits[range.start.saturating_sub(FETCH_RANGE)
1204                    ..(range.end + FETCH_RANGE)
1205                        .min(self.graph_data.commits.len().saturating_sub(1))]
1206                    .iter()
1207                    .for_each(|commit| {
1208                        repository.fetch_commit_data(commit.data.sha, cx);
1209                    });
1210            });
1211        }
1212
1213        range
1214            .map(|idx| {
1215                let Some((commit, repository)) =
1216                    self.graph_data.commits.get(idx).zip(repository.as_ref())
1217                else {
1218                    return vec![
1219                        div().h(row_height).into_any_element(),
1220                        div().h(row_height).into_any_element(),
1221                        div().h(row_height).into_any_element(),
1222                        div().h(row_height).into_any_element(),
1223                    ];
1224                };
1225
1226                let data = repository.update(cx, |repository, cx| {
1227                    repository.fetch_commit_data(commit.data.sha, cx).clone()
1228                });
1229
1230                let short_sha = commit.data.sha.display_short();
1231                let mut formatted_time = String::new();
1232                let subject: SharedString;
1233                let author_name: SharedString;
1234
1235                if let CommitDataState::Loaded(data) = data {
1236                    subject = data.subject.clone();
1237                    author_name = data.author_name.clone();
1238                    formatted_time = format_timestamp(data.commit_timestamp);
1239                } else {
1240                    subject = "Loading…".into();
1241                    author_name = "".into();
1242                }
1243
1244                let accent_colors = cx.theme().accents();
1245                let accent_color = accent_colors
1246                    .0
1247                    .get(commit.color_idx)
1248                    .copied()
1249                    .unwrap_or_else(|| accent_colors.0.first().copied().unwrap_or_default());
1250
1251                let is_selected = self.selected_entry_idx == Some(idx);
1252                let is_matched = self.search_state.matches.contains(&commit.data.sha);
1253                let column_label = |label: SharedString| {
1254                    Label::new(label)
1255                        .when(!is_selected, |c| c.color(Color::Muted))
1256                        .truncate()
1257                        .into_any_element()
1258                };
1259
1260                let subject_label = if is_matched {
1261                    let query = match &self.search_state.state {
1262                        QueryState::Confirmed((query, _)) => Some(query.clone()),
1263                        _ => None,
1264                    };
1265                    let highlight_ranges = query
1266                        .and_then(|q| {
1267                            let ranges = if self.search_state.case_sensitive {
1268                                subject
1269                                    .match_indices(q.as_str())
1270                                    .map(|(start, matched)| start..start + matched.len())
1271                                    .collect::<Vec<_>>()
1272                            } else {
1273                                let q = q.to_lowercase();
1274                                let subject_lower = subject.to_lowercase();
1275
1276                                subject_lower
1277                                    .match_indices(&q)
1278                                    .filter_map(|(start, matched)| {
1279                                        let end = start + matched.len();
1280                                        subject.is_char_boundary(start).then_some(()).and_then(
1281                                            |_| subject.is_char_boundary(end).then_some(start..end),
1282                                        )
1283                                    })
1284                                    .collect::<Vec<_>>()
1285                            };
1286
1287                            (!ranges.is_empty()).then_some(ranges)
1288                        })
1289                        .unwrap_or_default();
1290                    HighlightedLabel::from_ranges(subject.clone(), highlight_ranges)
1291                        .when(!is_selected, |c| c.color(Color::Muted))
1292                        .truncate()
1293                        .into_any_element()
1294                } else {
1295                    column_label(subject.clone())
1296                };
1297
1298                vec![
1299                    div()
1300                        .id(ElementId::NamedInteger("commit-subject".into(), idx as u64))
1301                        .overflow_hidden()
1302                        .tooltip(Tooltip::text(subject))
1303                        .child(
1304                            h_flex()
1305                                .gap_2()
1306                                .overflow_hidden()
1307                                .children((!commit.data.ref_names.is_empty()).then(|| {
1308                                    h_flex().gap_1().children(
1309                                        commit
1310                                            .data
1311                                            .ref_names
1312                                            .iter()
1313                                            .map(|name| self.render_chip(name, accent_color)),
1314                                    )
1315                                }))
1316                                .child(subject_label),
1317                        )
1318                        .into_any_element(),
1319                    column_label(formatted_time.into()),
1320                    column_label(author_name),
1321                    column_label(short_sha.into()),
1322                ]
1323            })
1324            .collect()
1325    }
1326
1327    fn cancel(&mut self, _: &Cancel, _window: &mut Window, cx: &mut Context<Self>) {
1328        self.selected_entry_idx = None;
1329        self.selected_commit_diff = None;
1330        self.selected_commit_diff_stats = None;
1331        cx.notify();
1332    }
1333
1334    fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
1335        self.select_entry(0, ScrollStrategy::Nearest, cx);
1336    }
1337
1338    fn select_prev(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
1339        if let Some(selected_entry_idx) = &self.selected_entry_idx {
1340            self.select_entry(
1341                selected_entry_idx.saturating_sub(1),
1342                ScrollStrategy::Nearest,
1343                cx,
1344            );
1345        } else {
1346            self.select_first(&SelectFirst, window, cx);
1347        }
1348    }
1349
1350    fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
1351        if let Some(selected_entry_idx) = &self.selected_entry_idx {
1352            self.select_entry(
1353                selected_entry_idx
1354                    .saturating_add(1)
1355                    .min(self.graph_data.commits.len().saturating_sub(1)),
1356                ScrollStrategy::Nearest,
1357                cx,
1358            );
1359        } else {
1360            self.select_prev(&SelectPrevious, window, cx);
1361        }
1362    }
1363
1364    fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
1365        self.select_entry(
1366            self.graph_data.commits.len().saturating_sub(1),
1367            ScrollStrategy::Nearest,
1368            cx,
1369        );
1370    }
1371
1372    fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
1373        self.open_selected_commit_view(window, cx);
1374    }
1375
1376    fn search(&mut self, query: SharedString, cx: &mut Context<Self>) {
1377        let Some(repo) = self.get_repository(cx) else {
1378            return;
1379        };
1380
1381        self.search_state.matches.clear();
1382        self.search_state.selected_index = None;
1383        self.search_state.editor.update(cx, |editor, _cx| {
1384            editor.set_text_style_refinement(Default::default());
1385        });
1386
1387        if query.as_str().is_empty() {
1388            self.search_state.state = QueryState::Empty;
1389            cx.notify();
1390            return;
1391        }
1392
1393        let (request_tx, request_rx) = smol::channel::unbounded::<Oid>();
1394
1395        repo.update(cx, |repo, cx| {
1396            repo.search_commits(
1397                self.log_source.clone(),
1398                SearchCommitArgs {
1399                    query: query.clone(),
1400                    case_sensitive: self.search_state.case_sensitive,
1401                },
1402                request_tx,
1403                cx,
1404            );
1405        });
1406
1407        let search_task = cx.spawn(async move |this, cx| {
1408            while let Ok(first_oid) = request_rx.recv().await {
1409                let mut pending_oids = vec![first_oid];
1410                while let Ok(oid) = request_rx.try_recv() {
1411                    pending_oids.push(oid);
1412                }
1413
1414                this.update(cx, |this, cx| {
1415                    if this.search_state.selected_index.is_none() {
1416                        this.search_state.selected_index = Some(0);
1417                        this.select_commit_by_sha(first_oid, cx);
1418                    }
1419
1420                    this.search_state.matches.extend(pending_oids);
1421                    cx.notify();
1422                })
1423                .ok();
1424            }
1425
1426            this.update(cx, |this, cx| {
1427                if this.search_state.matches.is_empty() {
1428                    this.search_state.editor.update(cx, |editor, cx| {
1429                        editor.set_text_style_refinement(TextStyleRefinement {
1430                            color: Some(Color::Error.color(cx)),
1431                            ..Default::default()
1432                        });
1433                    });
1434                }
1435            })
1436            .ok();
1437        });
1438
1439        self.search_state.state = QueryState::Confirmed((query, search_task));
1440    }
1441
1442    fn confirm_search(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
1443        let query = self.search_state.editor.read(cx).text(cx).into();
1444        self.search(query, cx);
1445    }
1446
1447    fn select_entry(
1448        &mut self,
1449        idx: usize,
1450        scroll_strategy: ScrollStrategy,
1451        cx: &mut Context<Self>,
1452    ) {
1453        if self.selected_entry_idx == Some(idx) {
1454            return;
1455        }
1456
1457        self.selected_entry_idx = Some(idx);
1458        self.selected_commit_diff = None;
1459        self.selected_commit_diff_stats = None;
1460        self.changed_files_scroll_handle
1461            .scroll_to_item(0, ScrollStrategy::Top);
1462        self.table_interaction_state.update(cx, |state, cx| {
1463            state.scroll_handle.scroll_to_item(idx, scroll_strategy);
1464            cx.notify();
1465        });
1466
1467        let Some(commit) = self.graph_data.commits.get(idx) else {
1468            return;
1469        };
1470
1471        let sha = commit.data.sha.to_string();
1472
1473        let Some(repository) = self.get_repository(cx) else {
1474            return;
1475        };
1476
1477        let diff_receiver = repository.update(cx, |repo, _| repo.load_commit_diff(sha));
1478
1479        self._commit_diff_task = Some(cx.spawn(async move |this, cx| {
1480            if let Ok(Ok(diff)) = diff_receiver.await {
1481                this.update(cx, |this, cx| {
1482                    let stats = compute_diff_stats(&diff);
1483                    this.selected_commit_diff = Some(diff);
1484                    this.selected_commit_diff_stats = Some(stats);
1485                    cx.notify();
1486                })
1487                .ok();
1488            }
1489        }));
1490
1491        cx.notify();
1492    }
1493
1494    fn select_previous_match(&mut self, cx: &mut Context<Self>) {
1495        if self.search_state.matches.is_empty() {
1496            return;
1497        }
1498
1499        let mut prev_selection = self.search_state.selected_index.unwrap_or_default();
1500
1501        if prev_selection == 0 {
1502            prev_selection = self.search_state.matches.len() - 1;
1503        } else {
1504            prev_selection -= 1;
1505        }
1506
1507        let Some(&oid) = self.search_state.matches.get_index(prev_selection) else {
1508            return;
1509        };
1510
1511        self.search_state.selected_index = Some(prev_selection);
1512        self.select_commit_by_sha(oid, cx);
1513    }
1514
1515    fn select_next_match(&mut self, cx: &mut Context<Self>) {
1516        if self.search_state.matches.is_empty() {
1517            return;
1518        }
1519
1520        let mut next_selection = self
1521            .search_state
1522            .selected_index
1523            .map(|index| index + 1)
1524            .unwrap_or_default();
1525
1526        if next_selection >= self.search_state.matches.len() {
1527            next_selection = 0;
1528        }
1529
1530        let Some(&oid) = self.search_state.matches.get_index(next_selection) else {
1531            return;
1532        };
1533
1534        self.search_state.selected_index = Some(next_selection);
1535        self.select_commit_by_sha(oid, cx);
1536    }
1537
1538    pub fn set_repo_id(&mut self, repo_id: RepositoryId, cx: &mut Context<Self>) {
1539        if repo_id != self.repo_id
1540            && self
1541                .git_store
1542                .read(cx)
1543                .repositories()
1544                .contains_key(&repo_id)
1545        {
1546            self.repo_id = repo_id;
1547            self.invalidate_state(cx);
1548        }
1549    }
1550
1551    pub fn select_commit_by_sha(&mut self, sha: impl TryInto<Oid>, cx: &mut Context<Self>) {
1552        fn inner(this: &mut GitGraph, oid: Oid, cx: &mut Context<GitGraph>) {
1553            let Some(selected_repository) = this.get_repository(cx) else {
1554                return;
1555            };
1556
1557            let Some(index) = selected_repository
1558                .read(cx)
1559                .get_graph_data(this.log_source.clone(), this.log_order)
1560                .and_then(|data| data.commit_oid_to_index.get(&oid))
1561                .copied()
1562            else {
1563                return;
1564            };
1565
1566            this.select_entry(index, ScrollStrategy::Center, cx);
1567        }
1568
1569        if let Ok(oid) = sha.try_into() {
1570            inner(self, oid, cx);
1571        }
1572    }
1573
1574    fn open_selected_commit_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1575        let Some(selected_entry_index) = self.selected_entry_idx else {
1576            return;
1577        };
1578
1579        self.open_commit_view(selected_entry_index, window, cx);
1580    }
1581
1582    fn open_commit_view(
1583        &mut self,
1584        entry_index: usize,
1585        window: &mut Window,
1586        cx: &mut Context<Self>,
1587    ) {
1588        let Some(commit_entry) = self.graph_data.commits.get(entry_index) else {
1589            return;
1590        };
1591
1592        let Some(repository) = self.get_repository(cx) else {
1593            return;
1594        };
1595
1596        CommitView::open(
1597            commit_entry.data.sha.to_string(),
1598            repository.downgrade(),
1599            self.workspace.clone(),
1600            None,
1601            None,
1602            window,
1603            cx,
1604        );
1605    }
1606
1607    fn get_remote(
1608        &self,
1609        repository: &Repository,
1610        _window: &mut Window,
1611        cx: &mut App,
1612    ) -> Option<GitRemote> {
1613        let remote_url = repository.default_remote_url()?;
1614        let provider_registry = GitHostingProviderRegistry::default_global(cx);
1615        let (provider, parsed) = parse_git_remote_url(provider_registry, &remote_url)?;
1616        Some(GitRemote {
1617            host: provider,
1618            owner: parsed.owner.into(),
1619            repo: parsed.repo.into(),
1620        })
1621    }
1622
1623    fn render_search_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
1624        let color = cx.theme().colors();
1625        let query_focus_handle = self.search_state.editor.focus_handle(cx);
1626        let search_options = {
1627            let mut options = SearchOptions::NONE;
1628            options.set(
1629                SearchOptions::CASE_SENSITIVE,
1630                self.search_state.case_sensitive,
1631            );
1632            options
1633        };
1634
1635        h_flex()
1636            .w_full()
1637            .p_1p5()
1638            .gap_1p5()
1639            .border_b_1()
1640            .border_color(color.border_variant)
1641            .child(
1642                h_flex()
1643                    .h_8()
1644                    .flex_1()
1645                    .min_w_0()
1646                    .px_1p5()
1647                    .gap_1()
1648                    .border_1()
1649                    .border_color(color.border)
1650                    .rounded_md()
1651                    .bg(color.toolbar_background)
1652                    .on_action(cx.listener(Self::confirm_search))
1653                    .child(self.search_state.editor.clone())
1654                    .child(SearchOption::CaseSensitive.as_button(
1655                        search_options,
1656                        SearchSource::Buffer,
1657                        query_focus_handle,
1658                    )),
1659            )
1660            .child(
1661                h_flex()
1662                    .min_w_64()
1663                    .gap_1()
1664                    .child({
1665                        let focus_handle = self.focus_handle.clone();
1666                        IconButton::new("git-graph-search-prev", IconName::ChevronLeft)
1667                            .shape(ui::IconButtonShape::Square)
1668                            .icon_size(IconSize::Small)
1669                            .tooltip(move |_, cx| {
1670                                Tooltip::for_action_in(
1671                                    "Select Previous Match",
1672                                    &SelectPreviousMatch,
1673                                    &focus_handle,
1674                                    cx,
1675                                )
1676                            })
1677                            .map(|this| {
1678                                if self.search_state.matches.is_empty() {
1679                                    this.disabled(true)
1680                                } else {
1681                                    this.disabled(false).on_click(cx.listener(|this, _, _, cx| {
1682                                        this.select_previous_match(cx);
1683                                    }))
1684                                }
1685                            })
1686                    })
1687                    .child({
1688                        let focus_handle = self.focus_handle.clone();
1689                        IconButton::new("git-graph-search-next", IconName::ChevronRight)
1690                            .shape(ui::IconButtonShape::Square)
1691                            .icon_size(IconSize::Small)
1692                            .tooltip(move |_, cx| {
1693                                Tooltip::for_action_in(
1694                                    "Select Next Match",
1695                                    &SelectNextMatch,
1696                                    &focus_handle,
1697                                    cx,
1698                                )
1699                            })
1700                            .map(|this| {
1701                                if self.search_state.matches.is_empty() {
1702                                    this.disabled(true)
1703                                } else {
1704                                    this.disabled(false).on_click(cx.listener(|this, _, _, cx| {
1705                                        this.select_next_match(cx);
1706                                    }))
1707                                }
1708                            })
1709                    })
1710                    .child(
1711                        h_flex()
1712                            .gap_1p5()
1713                            .child(
1714                                Label::new(format!(
1715                                    "{}/{}",
1716                                    self.search_state
1717                                        .selected_index
1718                                        .map(|index| index + 1)
1719                                        .unwrap_or(0),
1720                                    self.search_state.matches.len()
1721                                ))
1722                                .size(LabelSize::Small)
1723                                .when(self.search_state.matches.is_empty(), |this| {
1724                                    this.color(Color::Disabled)
1725                                }),
1726                            )
1727                            .when(
1728                                matches!(
1729                                    &self.search_state.state,
1730                                    QueryState::Confirmed((_, task)) if !task.is_ready()
1731                                ),
1732                                |this| {
1733                                    this.child(
1734                                        Icon::new(IconName::ArrowCircle)
1735                                            .color(Color::Accent)
1736                                            .size(IconSize::Small)
1737                                            .with_rotate_animation(2)
1738                                            .into_any_element(),
1739                                    )
1740                                },
1741                            ),
1742                    ),
1743            )
1744    }
1745
1746    fn render_loading_spinner(&self, cx: &App) -> AnyElement {
1747        let rems = TextSize::Large.rems(cx);
1748        Icon::new(IconName::LoadCircle)
1749            .size(IconSize::Custom(rems))
1750            .color(Color::Accent)
1751            .with_rotate_animation(3)
1752            .into_any_element()
1753    }
1754
1755    fn render_commit_detail_panel(
1756        &self,
1757        window: &mut Window,
1758        cx: &mut Context<Self>,
1759    ) -> impl IntoElement {
1760        let Some(selected_idx) = self.selected_entry_idx else {
1761            return Empty.into_any_element();
1762        };
1763
1764        let Some(commit_entry) = self.graph_data.commits.get(selected_idx) else {
1765            return Empty.into_any_element();
1766        };
1767
1768        let Some(repository) = self.get_repository(cx) else {
1769            return Empty.into_any_element();
1770        };
1771
1772        let data = repository.update(cx, |repository, cx| {
1773            repository
1774                .fetch_commit_data(commit_entry.data.sha, cx)
1775                .clone()
1776        });
1777
1778        let full_sha: SharedString = commit_entry.data.sha.to_string().into();
1779        let ref_names = commit_entry.data.ref_names.clone();
1780
1781        let accent_colors = cx.theme().accents();
1782        let accent_color = accent_colors
1783            .0
1784            .get(commit_entry.color_idx)
1785            .copied()
1786            .unwrap_or_else(|| accent_colors.0.first().copied().unwrap_or_default());
1787
1788        // todo(git graph): We should use the full commit message here
1789        let (author_name, author_email, commit_timestamp, commit_message) = match &data {
1790            CommitDataState::Loaded(data) => (
1791                data.author_name.clone(),
1792                data.author_email.clone(),
1793                Some(data.commit_timestamp),
1794                data.subject.clone(),
1795            ),
1796            CommitDataState::Loading => ("Loading…".into(), "".into(), None, "Loading…".into()),
1797        };
1798
1799        let date_string = commit_timestamp
1800            .and_then(|ts| OffsetDateTime::from_unix_timestamp(ts).ok())
1801            .map(|datetime| {
1802                let local_offset = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
1803                let local_datetime = datetime.to_offset(local_offset);
1804                let format =
1805                    time::format_description::parse("[month repr:short] [day], [year]").ok();
1806                format
1807                    .and_then(|f| local_datetime.format(&f).ok())
1808                    .unwrap_or_default()
1809            })
1810            .unwrap_or_default();
1811
1812        let remote = repository.update(cx, |repo, cx| self.get_remote(repo, window, cx));
1813
1814        let avatar = {
1815            let author_email_for_avatar = if author_email.is_empty() {
1816                None
1817            } else {
1818                Some(author_email.clone())
1819            };
1820
1821            CommitAvatar::new(&full_sha, author_email_for_avatar, remote.as_ref())
1822                .size(px(40.))
1823                .render(window, cx)
1824        };
1825
1826        let changed_files_count = self
1827            .selected_commit_diff
1828            .as_ref()
1829            .map(|diff| diff.files.len())
1830            .unwrap_or(0);
1831
1832        let (total_lines_added, total_lines_removed) =
1833            self.selected_commit_diff_stats.unwrap_or((0, 0));
1834
1835        let sorted_file_entries: Rc<Vec<ChangedFileEntry>> = Rc::new(
1836            self.selected_commit_diff
1837                .as_ref()
1838                .map(|diff| {
1839                    let mut files: Vec<_> = diff.files.iter().collect();
1840                    files.sort_by_key(|file| file.status());
1841                    files
1842                        .into_iter()
1843                        .map(|file| ChangedFileEntry::from_commit_file(file, cx))
1844                        .collect()
1845                })
1846                .unwrap_or_default(),
1847        );
1848
1849        v_flex()
1850            .min_w(px(300.))
1851            .h_full()
1852            .bg(cx.theme().colors().surface_background)
1853            .flex_basis(DefiniteLength::Fraction(
1854                self.commit_details_split_state.read(cx).right_ratio(),
1855            ))
1856            .child(
1857                v_flex()
1858                    .relative()
1859                    .w_full()
1860                    .p_2()
1861                    .gap_2()
1862                    .child(
1863                        div().absolute().top_2().right_2().child(
1864                            IconButton::new("close-detail", IconName::Close)
1865                                .icon_size(IconSize::Small)
1866                                .on_click(cx.listener(move |this, _, _, cx| {
1867                                    this.selected_entry_idx = None;
1868                                    this.selected_commit_diff = None;
1869                                    this.selected_commit_diff_stats = None;
1870                                    this._commit_diff_task = None;
1871                                    cx.notify();
1872                                })),
1873                        ),
1874                    )
1875                    .child(
1876                        v_flex()
1877                            .py_1()
1878                            .w_full()
1879                            .items_center()
1880                            .gap_1()
1881                            .child(avatar)
1882                            .child(
1883                                v_flex()
1884                                    .items_center()
1885                                    .child(Label::new(author_name))
1886                                    .child(
1887                                        Label::new(date_string)
1888                                            .color(Color::Muted)
1889                                            .size(LabelSize::Small),
1890                                    ),
1891                            ),
1892                    )
1893                    .children((!ref_names.is_empty()).then(|| {
1894                        h_flex().gap_1().flex_wrap().justify_center().children(
1895                            ref_names
1896                                .iter()
1897                                .map(|name| self.render_chip(name, accent_color)),
1898                        )
1899                    }))
1900                    .child(
1901                        v_flex()
1902                            .ml_neg_1()
1903                            .gap_1p5()
1904                            .when(!author_email.is_empty(), |this| {
1905                                let copied_state: Entity<CopiedState> = window.use_keyed_state(
1906                                    "author-email-copy",
1907                                    cx,
1908                                    CopiedState::new,
1909                                );
1910                                let is_copied = copied_state.read(cx).is_copied();
1911
1912                                let (icon, icon_color, tooltip_label) = if is_copied {
1913                                    (IconName::Check, Color::Success, "Email Copied!")
1914                                } else {
1915                                    (IconName::Envelope, Color::Muted, "Copy Email")
1916                                };
1917
1918                                let copy_email = author_email.clone();
1919                                let author_email_for_tooltip = author_email.clone();
1920
1921                                this.child(
1922                                    Button::new("author-email-copy", author_email.clone())
1923                                        .start_icon(
1924                                            Icon::new(icon).size(IconSize::Small).color(icon_color),
1925                                        )
1926                                        .label_size(LabelSize::Small)
1927                                        .truncate(true)
1928                                        .color(Color::Muted)
1929                                        .tooltip(move |_, cx| {
1930                                            Tooltip::with_meta(
1931                                                tooltip_label,
1932                                                None,
1933                                                author_email_for_tooltip.clone(),
1934                                                cx,
1935                                            )
1936                                        })
1937                                        .on_click(move |_, _, cx| {
1938                                            copied_state.update(cx, |state, _cx| {
1939                                                state.mark_copied();
1940                                            });
1941                                            cx.write_to_clipboard(ClipboardItem::new_string(
1942                                                copy_email.to_string(),
1943                                            ));
1944                                            let state_id = copied_state.entity_id();
1945                                            cx.spawn(async move |cx| {
1946                                                cx.background_executor()
1947                                                    .timer(COPIED_STATE_DURATION)
1948                                                    .await;
1949                                                cx.update(|cx| {
1950                                                    cx.notify(state_id);
1951                                                })
1952                                            })
1953                                            .detach();
1954                                        }),
1955                                )
1956                            })
1957                            .child({
1958                                let copy_sha = full_sha.clone();
1959                                let copied_state: Entity<CopiedState> =
1960                                    window.use_keyed_state("sha-copy", cx, CopiedState::new);
1961                                let is_copied = copied_state.read(cx).is_copied();
1962
1963                                let (icon, icon_color, tooltip_label) = if is_copied {
1964                                    (IconName::Check, Color::Success, "Commit SHA Copied!")
1965                                } else {
1966                                    (IconName::Hash, Color::Muted, "Copy Commit SHA")
1967                                };
1968
1969                                Button::new("sha-button", &full_sha)
1970                                    .start_icon(
1971                                        Icon::new(icon).size(IconSize::Small).color(icon_color),
1972                                    )
1973                                    .label_size(LabelSize::Small)
1974                                    .truncate(true)
1975                                    .color(Color::Muted)
1976                                    .tooltip({
1977                                        let full_sha = full_sha.clone();
1978                                        move |_, cx| {
1979                                            Tooltip::with_meta(
1980                                                tooltip_label,
1981                                                None,
1982                                                full_sha.clone(),
1983                                                cx,
1984                                            )
1985                                        }
1986                                    })
1987                                    .on_click(move |_, _, cx| {
1988                                        copied_state.update(cx, |state, _cx| {
1989                                            state.mark_copied();
1990                                        });
1991                                        cx.write_to_clipboard(ClipboardItem::new_string(
1992                                            copy_sha.to_string(),
1993                                        ));
1994                                        let state_id = copied_state.entity_id();
1995                                        cx.spawn(async move |cx| {
1996                                            cx.background_executor()
1997                                                .timer(COPIED_STATE_DURATION)
1998                                                .await;
1999                                            cx.update(|cx| {
2000                                                cx.notify(state_id);
2001                                            })
2002                                        })
2003                                        .detach();
2004                                    })
2005                            })
2006                            .when_some(remote.clone(), |this, remote| {
2007                                let provider_name = remote.host.name();
2008                                let icon = match provider_name.as_str() {
2009                                    "GitHub" => IconName::Github,
2010                                    _ => IconName::Link,
2011                                };
2012                                let parsed_remote = ParsedGitRemote {
2013                                    owner: remote.owner.as_ref().into(),
2014                                    repo: remote.repo.as_ref().into(),
2015                                };
2016                                let params = BuildCommitPermalinkParams {
2017                                    sha: full_sha.as_ref(),
2018                                };
2019                                let url = remote
2020                                    .host
2021                                    .build_commit_permalink(&parsed_remote, params)
2022                                    .to_string();
2023
2024                                this.child(
2025                                    Button::new(
2026                                        "view-on-provider",
2027                                        format!("View on {}", provider_name),
2028                                    )
2029                                    .start_icon(
2030                                        Icon::new(icon).size(IconSize::Small).color(Color::Muted),
2031                                    )
2032                                    .label_size(LabelSize::Small)
2033                                    .truncate(true)
2034                                    .color(Color::Muted)
2035                                    .on_click(
2036                                        move |_, _, cx| {
2037                                            cx.open_url(&url);
2038                                        },
2039                                    ),
2040                                )
2041                            }),
2042                    ),
2043            )
2044            .child(Divider::horizontal())
2045            .child(div().p_2().child(Label::new(commit_message)))
2046            .child(Divider::horizontal())
2047            .child(
2048                v_flex()
2049                    .min_w_0()
2050                    .p_2()
2051                    .flex_1()
2052                    .gap_1()
2053                    .child(
2054                        h_flex()
2055                            .gap_1()
2056                            .child(
2057                                Label::new(format!("{} Changed Files", changed_files_count))
2058                                    .size(LabelSize::Small)
2059                                    .color(Color::Muted),
2060                            )
2061                            .child(DiffStat::new(
2062                                "commit-diff-stat",
2063                                total_lines_added,
2064                                total_lines_removed,
2065                            )),
2066                    )
2067                    .child(
2068                        div()
2069                            .id("changed-files-container")
2070                            .flex_1()
2071                            .min_h_0()
2072                            .child({
2073                                let entries = sorted_file_entries;
2074                                let entry_count = entries.len();
2075                                let commit_sha = full_sha.clone();
2076                                let repository = repository.downgrade();
2077                                let workspace = self.workspace.clone();
2078                                uniform_list(
2079                                    "changed-files-list",
2080                                    entry_count,
2081                                    move |range, _window, cx| {
2082                                        range
2083                                            .map(|ix| {
2084                                                entries[ix].render(
2085                                                    ix,
2086                                                    commit_sha.clone(),
2087                                                    repository.clone(),
2088                                                    workspace.clone(),
2089                                                    cx,
2090                                                )
2091                                            })
2092                                            .collect()
2093                                    },
2094                                )
2095                                .size_full()
2096                                .ml_neg_1()
2097                                .track_scroll(&self.changed_files_scroll_handle)
2098                            })
2099                            .vertical_scrollbar_for(&self.changed_files_scroll_handle, window, cx),
2100                    ),
2101            )
2102            .child(Divider::horizontal())
2103            .child(
2104                h_flex().p_1p5().w_full().child(
2105                    Button::new("view-commit", "View Commit")
2106                        .full_width()
2107                        .style(ButtonStyle::Outlined)
2108                        .on_click(cx.listener(|this, _, window, cx| {
2109                            this.open_selected_commit_view(window, cx);
2110                        })),
2111                ),
2112            )
2113            .into_any_element()
2114    }
2115
2116    pub fn render_graph(&self, window: &Window, cx: &mut Context<GitGraph>) -> impl IntoElement {
2117        let row_height = self.row_height;
2118        let table_state = self.table_interaction_state.read(cx);
2119        let viewport_height = table_state
2120            .scroll_handle
2121            .0
2122            .borrow()
2123            .last_item_size
2124            .map(|size| size.item.height)
2125            .unwrap_or(px(600.0));
2126        let loaded_commit_count = self.graph_data.commits.len();
2127
2128        let content_height = row_height * loaded_commit_count;
2129        let max_scroll = (content_height - viewport_height).max(px(0.));
2130        let scroll_offset_y = (-table_state.scroll_offset().y).clamp(px(0.), max_scroll);
2131
2132        let first_visible_row = (scroll_offset_y / row_height).floor() as usize;
2133        let vertical_scroll_offset = scroll_offset_y - (first_visible_row as f32 * row_height);
2134
2135        let graph_viewport_width = self.graph_viewport_width(window, cx);
2136        let graph_width = if self.graph_canvas_content_width() > graph_viewport_width {
2137            self.graph_canvas_content_width()
2138        } else {
2139            graph_viewport_width
2140        };
2141        let last_visible_row =
2142            first_visible_row + (viewport_height / row_height).ceil() as usize + 1;
2143
2144        let viewport_range = first_visible_row.min(loaded_commit_count.saturating_sub(1))
2145            ..(last_visible_row).min(loaded_commit_count);
2146        let rows = self.graph_data.commits[viewport_range.clone()].to_vec();
2147        let commit_lines: Vec<_> = self
2148            .graph_data
2149            .lines
2150            .iter()
2151            .filter(|line| {
2152                line.full_interval.start <= viewport_range.end
2153                    && line.full_interval.end >= viewport_range.start
2154            })
2155            .cloned()
2156            .collect();
2157
2158        let mut lines: BTreeMap<usize, Vec<_>> = BTreeMap::new();
2159
2160        let hovered_entry_idx = self.hovered_entry_idx;
2161        let selected_entry_idx = self.selected_entry_idx;
2162        let is_focused = self.focus_handle.is_focused(window);
2163        let graph_canvas_bounds = self.graph_canvas_bounds.clone();
2164
2165        gpui::canvas(
2166            move |_bounds, _window, _cx| {},
2167            move |bounds: Bounds<Pixels>, _: (), window: &mut Window, cx: &mut App| {
2168                graph_canvas_bounds.set(Some(bounds));
2169
2170                window.paint_layer(bounds, |window| {
2171                    let accent_colors = cx.theme().accents();
2172
2173                    let hover_bg = cx.theme().colors().element_hover.opacity(0.6);
2174                    let selected_bg = if is_focused {
2175                        cx.theme().colors().element_selected
2176                    } else {
2177                        cx.theme().colors().element_hover
2178                    };
2179
2180                    for visible_row_idx in 0..rows.len() {
2181                        let absolute_row_idx = first_visible_row + visible_row_idx;
2182                        let is_hovered = hovered_entry_idx == Some(absolute_row_idx);
2183                        let is_selected = selected_entry_idx == Some(absolute_row_idx);
2184
2185                        if is_hovered || is_selected {
2186                            let row_y = bounds.origin.y + visible_row_idx as f32 * row_height
2187                                - vertical_scroll_offset;
2188
2189                            let row_bounds = Bounds::new(
2190                                point(bounds.origin.x, row_y),
2191                                gpui::Size {
2192                                    width: bounds.size.width,
2193                                    height: row_height,
2194                                },
2195                            );
2196
2197                            let bg_color = if is_selected { selected_bg } else { hover_bg };
2198                            window.paint_quad(gpui::fill(row_bounds, bg_color));
2199                        }
2200                    }
2201
2202                    for (row_idx, row) in rows.into_iter().enumerate() {
2203                        let row_color = accent_colors.color_for_index(row.color_idx as u32);
2204                        let row_y_center =
2205                            bounds.origin.y + row_idx as f32 * row_height + row_height / 2.0
2206                                - vertical_scroll_offset;
2207
2208                        let commit_x = lane_center_x(bounds, row.lane as f32);
2209
2210                        draw_commit_circle(commit_x, row_y_center, row_color, window);
2211                    }
2212
2213                    for line in commit_lines {
2214                        let Some((start_segment_idx, start_column)) =
2215                            line.get_first_visible_segment_idx(first_visible_row)
2216                        else {
2217                            continue;
2218                        };
2219
2220                        let line_x = lane_center_x(bounds, start_column as f32);
2221
2222                        let start_row = line.full_interval.start as i32 - first_visible_row as i32;
2223
2224                        let from_y =
2225                            bounds.origin.y + start_row as f32 * row_height + row_height / 2.0
2226                                - vertical_scroll_offset
2227                                + COMMIT_CIRCLE_RADIUS;
2228
2229                        let mut current_row = from_y;
2230                        let mut current_column = line_x;
2231
2232                        let mut builder = PathBuilder::stroke(LINE_WIDTH);
2233                        builder.move_to(point(line_x, from_y));
2234
2235                        let segments = &line.segments[start_segment_idx..];
2236                        let desired_curve_height = row_height / 3.0;
2237                        let desired_curve_width = LANE_WIDTH / 3.0;
2238
2239                        for (segment_idx, segment) in segments.iter().enumerate() {
2240                            let is_last = segment_idx + 1 == segments.len();
2241
2242                            match segment {
2243                                CommitLineSegment::Straight { to_row } => {
2244                                    let mut dest_row = to_row_center(
2245                                        to_row - first_visible_row,
2246                                        row_height,
2247                                        vertical_scroll_offset,
2248                                        bounds,
2249                                    );
2250                                    if is_last {
2251                                        dest_row -= COMMIT_CIRCLE_RADIUS;
2252                                    }
2253
2254                                    let dest_point = point(current_column, dest_row);
2255
2256                                    current_row = dest_point.y;
2257                                    builder.line_to(dest_point);
2258                                    builder.move_to(dest_point);
2259                                }
2260                                CommitLineSegment::Curve {
2261                                    to_column,
2262                                    on_row,
2263                                    curve_kind,
2264                                } => {
2265                                    let mut to_column = lane_center_x(bounds, *to_column as f32);
2266
2267                                    let mut to_row = to_row_center(
2268                                        *on_row - first_visible_row,
2269                                        row_height,
2270                                        vertical_scroll_offset,
2271                                        bounds,
2272                                    );
2273
2274                                    // This means that this branch was a checkout
2275                                    let going_right = to_column > current_column;
2276                                    let column_shift = if going_right {
2277                                        COMMIT_CIRCLE_RADIUS + COMMIT_CIRCLE_STROKE_WIDTH
2278                                    } else {
2279                                        -COMMIT_CIRCLE_RADIUS - COMMIT_CIRCLE_STROKE_WIDTH
2280                                    };
2281
2282                                    match curve_kind {
2283                                        CurveKind::Checkout => {
2284                                            if is_last {
2285                                                to_column -= column_shift;
2286                                            }
2287
2288                                            let available_curve_width =
2289                                                (to_column - current_column).abs();
2290                                            let available_curve_height =
2291                                                (to_row - current_row).abs();
2292                                            let curve_width =
2293                                                desired_curve_width.min(available_curve_width);
2294                                            let curve_height =
2295                                                desired_curve_height.min(available_curve_height);
2296                                            let signed_curve_width = if going_right {
2297                                                curve_width
2298                                            } else {
2299                                                -curve_width
2300                                            };
2301                                            let curve_start =
2302                                                point(current_column, to_row - curve_height);
2303                                            let curve_end =
2304                                                point(current_column + signed_curve_width, to_row);
2305                                            let curve_control = point(current_column, to_row);
2306
2307                                            builder.move_to(point(current_column, current_row));
2308                                            builder.line_to(curve_start);
2309                                            builder.move_to(curve_start);
2310                                            builder.curve_to(curve_end, curve_control);
2311                                            builder.move_to(curve_end);
2312                                            builder.line_to(point(to_column, to_row));
2313                                        }
2314                                        CurveKind::Merge => {
2315                                            if is_last {
2316                                                to_row -= COMMIT_CIRCLE_RADIUS;
2317                                            }
2318
2319                                            let merge_start = point(
2320                                                current_column + column_shift,
2321                                                current_row - COMMIT_CIRCLE_RADIUS,
2322                                            );
2323                                            let available_curve_width =
2324                                                (to_column - merge_start.x).abs();
2325                                            let available_curve_height =
2326                                                (to_row - merge_start.y).abs();
2327                                            let curve_width =
2328                                                desired_curve_width.min(available_curve_width);
2329                                            let curve_height =
2330                                                desired_curve_height.min(available_curve_height);
2331                                            let signed_curve_width = if going_right {
2332                                                curve_width
2333                                            } else {
2334                                                -curve_width
2335                                            };
2336                                            let curve_start = point(
2337                                                to_column - signed_curve_width,
2338                                                merge_start.y,
2339                                            );
2340                                            let curve_end =
2341                                                point(to_column, merge_start.y + curve_height);
2342                                            let curve_control = point(to_column, merge_start.y);
2343
2344                                            builder.move_to(merge_start);
2345                                            builder.line_to(curve_start);
2346                                            builder.move_to(curve_start);
2347                                            builder.curve_to(curve_end, curve_control);
2348                                            builder.move_to(curve_end);
2349                                            builder.line_to(point(to_column, to_row));
2350                                        }
2351                                    }
2352                                    current_row = to_row;
2353                                    current_column = to_column;
2354                                    builder.move_to(point(current_column, current_row));
2355                                }
2356                            }
2357                        }
2358
2359                        builder.close();
2360                        lines.entry(line.color_idx).or_default().push(builder);
2361                    }
2362
2363                    for (color_idx, builders) in lines {
2364                        let line_color = accent_colors.color_for_index(color_idx as u32);
2365
2366                        for builder in builders {
2367                            if let Ok(path) = builder.build() {
2368                                // we paint each color on it's own layer to stop overlapping lines
2369                                // of different colors changing the color of a line
2370                                window.paint_layer(bounds, |window| {
2371                                    window.paint_path(path, line_color);
2372                                });
2373                            }
2374                        }
2375                    }
2376                })
2377            },
2378        )
2379        .w(graph_width)
2380        .h_full()
2381    }
2382
2383    fn row_at_position(&self, position_y: Pixels, cx: &Context<Self>) -> Option<usize> {
2384        let canvas_bounds = self.graph_canvas_bounds.get()?;
2385        let table_state = self.table_interaction_state.read(cx);
2386        let scroll_offset_y = -table_state.scroll_offset().y;
2387
2388        let local_y = position_y - canvas_bounds.origin.y;
2389
2390        if local_y >= px(0.) && local_y < canvas_bounds.size.height {
2391            let row_in_viewport = (local_y / self.row_height).floor() as usize;
2392            let scroll_rows = (scroll_offset_y / self.row_height).floor() as usize;
2393            let absolute_row = scroll_rows + row_in_viewport;
2394
2395            if absolute_row < self.graph_data.commits.len() {
2396                return Some(absolute_row);
2397            }
2398        }
2399
2400        None
2401    }
2402
2403    fn handle_graph_mouse_move(
2404        &mut self,
2405        event: &gpui::MouseMoveEvent,
2406        _window: &mut Window,
2407        cx: &mut Context<Self>,
2408    ) {
2409        if let Some(row) = self.row_at_position(event.position.y, cx) {
2410            if self.hovered_entry_idx != Some(row) {
2411                self.hovered_entry_idx = Some(row);
2412                cx.notify();
2413            }
2414        } else if self.hovered_entry_idx.is_some() {
2415            self.hovered_entry_idx = None;
2416            cx.notify();
2417        }
2418    }
2419
2420    fn handle_graph_click(
2421        &mut self,
2422        event: &ClickEvent,
2423        window: &mut Window,
2424        cx: &mut Context<Self>,
2425    ) {
2426        if let Some(row) = self.row_at_position(event.position().y, cx) {
2427            self.select_entry(row, ScrollStrategy::Nearest, cx);
2428            if event.click_count() >= 2 {
2429                self.open_commit_view(row, window, cx);
2430            }
2431        }
2432    }
2433
2434    fn handle_graph_scroll(
2435        &mut self,
2436        event: &ScrollWheelEvent,
2437        window: &mut Window,
2438        cx: &mut Context<Self>,
2439    ) {
2440        let line_height = window.line_height();
2441        let delta = event.delta.pixel_delta(line_height);
2442
2443        let table_state = self.table_interaction_state.read(cx);
2444        let current_offset = table_state.scroll_offset();
2445
2446        let viewport_height = table_state.scroll_handle.viewport().size.height;
2447
2448        let commit_count = match self.graph_data.max_commit_count {
2449            AllCommitCount::Loaded(count) => count,
2450            AllCommitCount::NotLoaded => self.graph_data.commits.len(),
2451        };
2452        let content_height = self.row_height * commit_count;
2453        let max_vertical_scroll = (viewport_height - content_height).min(px(0.));
2454
2455        let new_y = (current_offset.y + delta.y).clamp(max_vertical_scroll, px(0.));
2456        let new_offset = Point::new(current_offset.x, new_y);
2457
2458        if new_offset != current_offset {
2459            table_state.set_scroll_offset(new_offset);
2460            cx.notify();
2461        }
2462    }
2463
2464    fn render_commit_view_resize_handle(
2465        &self,
2466        _window: &mut Window,
2467        cx: &mut Context<Self>,
2468    ) -> AnyElement {
2469        div()
2470            .id("commit-view-split-resize-container")
2471            .relative()
2472            .h_full()
2473            .flex_shrink_0()
2474            .w(px(1.))
2475            .bg(cx.theme().colors().border_variant)
2476            .child(
2477                div()
2478                    .id("commit-view-split-resize-handle")
2479                    .absolute()
2480                    .left(px(-RESIZE_HANDLE_WIDTH / 2.0))
2481                    .w(px(RESIZE_HANDLE_WIDTH))
2482                    .h_full()
2483                    .cursor_col_resize()
2484                    .block_mouse_except_scroll()
2485                    .on_click(cx.listener(|this, event: &ClickEvent, _window, cx| {
2486                        if event.click_count() >= 2 {
2487                            this.commit_details_split_state.update(cx, |state, _| {
2488                                state.on_double_click();
2489                            });
2490                        }
2491                        cx.stop_propagation();
2492                    }))
2493                    .on_drag(DraggedSplitHandle, |_, _, _, cx| cx.new(|_| gpui::Empty)),
2494            )
2495            .into_any_element()
2496    }
2497}
2498
2499impl Render for GitGraph {
2500    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2501        // This happens when we changed branches, we should refresh our search as well
2502        if let QueryState::Pending(query) = &mut self.search_state.state {
2503            let query = std::mem::take(query);
2504            self.search_state.state = QueryState::Empty;
2505            self.search(query, cx);
2506        }
2507        let (commit_count, is_loading) = match self.graph_data.max_commit_count {
2508            AllCommitCount::Loaded(count) => (count, true),
2509            AllCommitCount::NotLoaded => {
2510                let (commit_count, is_loading) = if let Some(repository) = self.get_repository(cx) {
2511                    repository.update(cx, |repository, cx| {
2512                        // Start loading the graph data if we haven't started already
2513                        let GraphDataResponse {
2514                            commits,
2515                            is_loading,
2516                            error: _,
2517                        } = repository.graph_data(
2518                            self.log_source.clone(),
2519                            self.log_order,
2520                            0..usize::MAX,
2521                            cx,
2522                        );
2523                        self.graph_data.add_commits(&commits);
2524                        (commits.len(), is_loading)
2525                    })
2526                } else {
2527                    (0, false)
2528                };
2529
2530                (commit_count, is_loading)
2531            }
2532        };
2533
2534        let error = self.get_repository(cx).and_then(|repo| {
2535            repo.read(cx)
2536                .get_graph_data(self.log_source.clone(), self.log_order)
2537                .and_then(|data| data.error.clone())
2538        });
2539
2540        let content = if commit_count == 0 {
2541            let message = if let Some(error) = &error {
2542                format!("Error loading: {}", error)
2543            } else if is_loading {
2544                "Loading".to_string()
2545            } else {
2546                "No commits found".to_string()
2547            };
2548            let label = Label::new(message)
2549                .color(Color::Muted)
2550                .size(LabelSize::Large);
2551            div()
2552                .size_full()
2553                .h_flex()
2554                .gap_1()
2555                .items_center()
2556                .justify_center()
2557                .child(label)
2558                .when(is_loading && error.is_none(), |this| {
2559                    this.child(self.render_loading_spinner(cx))
2560                })
2561        } else {
2562            let header_resize_info = HeaderResizeInfo::from_state(&self.column_widths, cx);
2563            let header_context = TableRenderContext::for_column_widths(
2564                Some(self.column_widths.read(cx).widths_to_render()),
2565                true,
2566            );
2567            let [
2568                graph_fraction,
2569                description_fraction,
2570                date_fraction,
2571                author_fraction,
2572                commit_fraction,
2573            ] = self.preview_column_fractions(window, cx);
2574            let table_fraction =
2575                description_fraction + date_fraction + author_fraction + commit_fraction;
2576            let table_width_config = self.table_column_width_config(window, cx);
2577
2578            h_flex()
2579                .size_full()
2580                .child(
2581                    div()
2582                        .flex_1()
2583                        .min_w_0()
2584                        .size_full()
2585                        .flex()
2586                        .flex_col()
2587                        .child(render_table_header(
2588                            TableRow::from_vec(
2589                                vec![
2590                                    Label::new("Graph")
2591                                        .color(Color::Muted)
2592                                        .truncate()
2593                                        .into_any_element(),
2594                                    Label::new("Description")
2595                                        .color(Color::Muted)
2596                                        .into_any_element(),
2597                                    Label::new("Date").color(Color::Muted).into_any_element(),
2598                                    Label::new("Author").color(Color::Muted).into_any_element(),
2599                                    Label::new("Commit").color(Color::Muted).into_any_element(),
2600                                ],
2601                                5,
2602                            ),
2603                            header_context,
2604                            Some(header_resize_info),
2605                            Some(self.column_widths.entity_id()),
2606                            cx,
2607                        ))
2608                        .child({
2609                            let row_height = self.row_height;
2610                            let selected_entry_idx = self.selected_entry_idx;
2611                            let hovered_entry_idx = self.hovered_entry_idx;
2612                            let weak_self = cx.weak_entity();
2613                            let focus_handle = self.focus_handle.clone();
2614
2615                            bind_redistributable_columns(
2616                                div()
2617                                    .relative()
2618                                    .flex_1()
2619                                    .w_full()
2620                                    .overflow_hidden()
2621                                    .child(
2622                                        h_flex()
2623                                            .size_full()
2624                                            .child(
2625                                                div()
2626                                                    .w(DefiniteLength::Fraction(graph_fraction))
2627                                                    .h_full()
2628                                                    .min_w_0()
2629                                                    .overflow_hidden()
2630                                                    .child(
2631                                                        div()
2632                                                            .id("graph-canvas")
2633                                                            .size_full()
2634                                                            .overflow_hidden()
2635                                                            .child(
2636                                                                div()
2637                                                                    .size_full()
2638                                                                    .child(self.render_graph(window, cx)),
2639                                                            )
2640                                                            .on_scroll_wheel(
2641                                                                cx.listener(Self::handle_graph_scroll),
2642                                                            )
2643                                                            .on_mouse_move(
2644                                                                cx.listener(Self::handle_graph_mouse_move),
2645                                                            )
2646                                                            .on_click(cx.listener(Self::handle_graph_click))
2647                                                            .on_hover(cx.listener(
2648                                                                |this, &is_hovered: &bool, _, cx| {
2649                                                                    if !is_hovered
2650                                                                        && this.hovered_entry_idx.is_some()
2651                                                                    {
2652                                                                        this.hovered_entry_idx = None;
2653                                                                        cx.notify();
2654                                                                    }
2655                                                                },
2656                                                            )),
2657                                                    ),
2658                                            )
2659                                            .child(
2660                                                div()
2661                                                    .w(DefiniteLength::Fraction(table_fraction))
2662                                                    .h_full()
2663                                                    .min_w_0()
2664                                                    .child(
2665                                                        Table::new(4)
2666                                                            .interactable(&self.table_interaction_state)
2667                                                            .hide_row_borders()
2668                                                            .hide_row_hover()
2669                                                            .width_config(table_width_config)
2670                                                            .map_row(move |(index, row), window, cx| {
2671                                                                let is_selected =
2672                                                                    selected_entry_idx == Some(index);
2673                                                                let is_hovered =
2674                                                                    hovered_entry_idx == Some(index);
2675                                                                let is_focused =
2676                                                                    focus_handle.is_focused(window);
2677                                                                let weak = weak_self.clone();
2678                                                                let weak_for_hover = weak.clone();
2679
2680                                                                let hover_bg = cx
2681                                                                    .theme()
2682                                                                    .colors()
2683                                                                    .element_hover
2684                                                                    .opacity(0.6);
2685                                                                let selected_bg = if is_focused {
2686                                                                    cx.theme().colors().element_selected
2687                                                                } else {
2688                                                                    cx.theme().colors().element_hover
2689                                                                };
2690
2691                                                                row.h(row_height)
2692                                                                    .when(is_selected, |row| row.bg(selected_bg))
2693                                                                    .when(
2694                                                                        is_hovered && !is_selected,
2695                                                                        |row| row.bg(hover_bg),
2696                                                                    )
2697                                                                    .on_hover(move |&is_hovered, _, cx| {
2698                                                                        weak_for_hover
2699                                                                            .update(cx, |this, cx| {
2700                                                                                if is_hovered {
2701                                                                                    if this.hovered_entry_idx
2702                                                                                        != Some(index)
2703                                                                                    {
2704                                                                                        this.hovered_entry_idx =
2705                                                                                            Some(index);
2706                                                                                        cx.notify();
2707                                                                                    }
2708                                                                                } else if this
2709                                                                                    .hovered_entry_idx
2710                                                                                    == Some(index)
2711                                                                                {
2712                                                                                    this.hovered_entry_idx =
2713                                                                                        None;
2714                                                                                    cx.notify();
2715                                                                                }
2716                                                                            })
2717                                                                            .ok();
2718                                                                    })
2719                                                                    .on_click(move |event, window, cx| {
2720                                                                        let click_count = event.click_count();
2721                                                                        weak.update(cx, |this, cx| {
2722                                                                            this.select_entry(
2723                                                                                index,
2724                                                                                ScrollStrategy::Center,
2725                                                                                cx,
2726                                                                            );
2727                                                                            if click_count >= 2 {
2728                                                                                this.open_commit_view(
2729                                                                                    index,
2730                                                                                    window,
2731                                                                                    cx,
2732                                                                                );
2733                                                                            }
2734                                                                        })
2735                                                                        .ok();
2736                                                                    })
2737                                                                    .into_any_element()
2738                                                            })
2739                                                            .uniform_list(
2740                                                                "git-graph-commits",
2741                                                                commit_count,
2742                                                                cx.processor(Self::render_table_rows),
2743                                                            ),
2744                                                    ),
2745                                            ),
2746                                    )
2747                                    .child(render_redistributable_columns_resize_handles(
2748                                        &self.column_widths,
2749                                        window,
2750                                        cx,
2751                                    )),
2752                                self.column_widths.clone(),
2753                            )
2754                        }),
2755                )
2756                .on_drag_move::<DraggedSplitHandle>(cx.listener(|this, event, window, cx| {
2757                    this.commit_details_split_state.update(cx, |state, cx| {
2758                        state.on_drag_move(event, window, cx);
2759                    });
2760                }))
2761                .on_drop::<DraggedSplitHandle>(cx.listener(|this, _event, _window, cx| {
2762                    this.commit_details_split_state.update(cx, |state, _cx| {
2763                        state.commit_ratio();
2764                    });
2765                }))
2766                .when(self.selected_entry_idx.is_some(), |this| {
2767                    this.child(self.render_commit_view_resize_handle(window, cx))
2768                        .child(self.render_commit_detail_panel(window, cx))
2769                })
2770        };
2771
2772        div()
2773            .key_context("GitGraph")
2774            .track_focus(&self.focus_handle)
2775            .size_full()
2776            .bg(cx.theme().colors().editor_background)
2777            .on_action(cx.listener(|this, _: &OpenCommitView, window, cx| {
2778                this.open_selected_commit_view(window, cx);
2779            }))
2780            .on_action(cx.listener(Self::cancel))
2781            .on_action(cx.listener(|this, _: &FocusSearch, window, cx| {
2782                this.search_state
2783                    .editor
2784                    .update(cx, |editor, cx| editor.focus_handle(cx).focus(window, cx));
2785            }))
2786            .on_action(cx.listener(Self::select_first))
2787            .on_action(cx.listener(Self::select_prev))
2788            .on_action(cx.listener(Self::select_next))
2789            .on_action(cx.listener(Self::select_last))
2790            .on_action(cx.listener(Self::confirm))
2791            .on_action(cx.listener(|this, _: &SelectNextMatch, _window, cx| {
2792                this.select_next_match(cx);
2793            }))
2794            .on_action(cx.listener(|this, _: &SelectPreviousMatch, _window, cx| {
2795                this.select_previous_match(cx);
2796            }))
2797            .on_action(cx.listener(|this, _: &ToggleCaseSensitive, _window, cx| {
2798                this.search_state.case_sensitive = !this.search_state.case_sensitive;
2799                this.search_state.state.next_state();
2800                cx.notify();
2801            }))
2802            .child(
2803                v_flex()
2804                    .size_full()
2805                    .child(self.render_search_bar(cx))
2806                    .child(div().flex_1().child(content)),
2807            )
2808            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
2809                deferred(
2810                    anchored()
2811                        .position(*position)
2812                        .anchor(Corner::TopLeft)
2813                        .child(menu.clone()),
2814                )
2815                .with_priority(1)
2816            }))
2817            .on_action(cx.listener(|_, _: &buffer_search::Deploy, window, cx| {
2818                window.dispatch_action(Box::new(FocusSearch), cx);
2819                cx.stop_propagation();
2820            }))
2821    }
2822}
2823
2824impl EventEmitter<ItemEvent> for GitGraph {}
2825
2826impl Focusable for GitGraph {
2827    fn focus_handle(&self, _cx: &App) -> FocusHandle {
2828        self.focus_handle.clone()
2829    }
2830}
2831
2832impl Item for GitGraph {
2833    type Event = ItemEvent;
2834
2835    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
2836        Some(Icon::new(IconName::GitGraph))
2837    }
2838
2839    fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
2840        let repo_name = self.get_repository(cx).and_then(|repo| {
2841            repo.read(cx)
2842                .work_directory_abs_path
2843                .file_name()
2844                .map(|name| name.to_string_lossy().to_string())
2845        });
2846
2847        Some(TabTooltipContent::Custom(Box::new(Tooltip::element({
2848            move |_, _| {
2849                v_flex()
2850                    .child(Label::new("Git Graph"))
2851                    .when_some(repo_name.clone(), |this, name| {
2852                        this.child(Label::new(name).color(Color::Muted).size(LabelSize::Small))
2853                    })
2854                    .into_any_element()
2855            }
2856        }))))
2857    }
2858
2859    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
2860        self.get_repository(cx)
2861            .and_then(|repo| {
2862                repo.read(cx)
2863                    .work_directory_abs_path
2864                    .file_name()
2865                    .map(|name| name.to_string_lossy().to_string())
2866            })
2867            .map_or_else(|| "Git Graph".into(), |name| SharedString::from(name))
2868    }
2869
2870    fn show_toolbar(&self) -> bool {
2871        false
2872    }
2873
2874    fn to_item_events(event: &Self::Event, f: &mut dyn FnMut(ItemEvent)) {
2875        f(*event)
2876    }
2877}
2878
2879impl workspace::SerializableItem for GitGraph {
2880    fn serialized_item_kind() -> &'static str {
2881        "GitGraph"
2882    }
2883
2884    fn cleanup(
2885        workspace_id: workspace::WorkspaceId,
2886        alive_items: Vec<workspace::ItemId>,
2887        _window: &mut Window,
2888        cx: &mut App,
2889    ) -> Task<gpui::Result<()>> {
2890        workspace::delete_unloaded_items(
2891            alive_items,
2892            workspace_id,
2893            "git_graphs",
2894            &persistence::GitGraphsDb::global(cx),
2895            cx,
2896        )
2897    }
2898
2899    fn deserialize(
2900        project: Entity<project::Project>,
2901        workspace: WeakEntity<Workspace>,
2902        workspace_id: workspace::WorkspaceId,
2903        item_id: workspace::ItemId,
2904        window: &mut Window,
2905        cx: &mut App,
2906    ) -> Task<gpui::Result<Entity<Self>>> {
2907        let db = persistence::GitGraphsDb::global(cx);
2908        let Some(repo_work_path) = db.get_git_graph(item_id, workspace_id).ok().flatten() else {
2909            return Task::ready(Err(anyhow::anyhow!("No git graph to deserialize")));
2910        };
2911
2912        let window_handle = window.window_handle();
2913        let project = project.read(cx);
2914        let git_store = project.git_store().clone();
2915        let wait = project.wait_for_initial_scan(cx);
2916
2917        cx.spawn(async move |cx| {
2918            wait.await;
2919
2920            cx.update_window(window_handle, |_, window, cx| {
2921                let path = repo_work_path.as_path();
2922
2923                let repositories = git_store.read(cx).repositories();
2924                let repo_id = repositories.iter().find_map(|(&repo_id, repo)| {
2925                    if repo.read(cx).snapshot().work_directory_abs_path.as_ref() == path {
2926                        Some(repo_id)
2927                    } else {
2928                        None
2929                    }
2930                });
2931
2932                let Some(repo_id) = repo_id else {
2933                    return Err(anyhow::anyhow!("Repository not found for path: {:?}", path));
2934                };
2935
2936                Ok(cx.new(|cx| GitGraph::new(repo_id, git_store, workspace, window, cx)))
2937            })?
2938        })
2939    }
2940
2941    fn serialize(
2942        &mut self,
2943        workspace: &mut Workspace,
2944        item_id: workspace::ItemId,
2945        _closing: bool,
2946        _window: &mut Window,
2947        cx: &mut Context<Self>,
2948    ) -> Option<Task<gpui::Result<()>>> {
2949        let workspace_id = workspace.database_id()?;
2950        let repo = self.get_repository(cx)?;
2951        let repo_working_path = repo
2952            .read(cx)
2953            .snapshot()
2954            .work_directory_abs_path
2955            .to_string_lossy()
2956            .to_string();
2957
2958        let db = persistence::GitGraphsDb::global(cx);
2959        Some(cx.background_spawn(async move {
2960            db.save_git_graph(item_id, workspace_id, repo_working_path)
2961                .await
2962        }))
2963    }
2964
2965    fn should_serialize(&self, event: &Self::Event) -> bool {
2966        event == &ItemEvent::UpdateTab
2967    }
2968}
2969
2970mod persistence {
2971    use std::path::PathBuf;
2972
2973    use db::{
2974        query,
2975        sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
2976        sqlez_macros::sql,
2977    };
2978    use workspace::WorkspaceDb;
2979
2980    pub struct GitGraphsDb(ThreadSafeConnection);
2981
2982    impl Domain for GitGraphsDb {
2983        const NAME: &str = stringify!(GitGraphsDb);
2984
2985        const MIGRATIONS: &[&str] = &[
2986            sql!(
2987                CREATE TABLE git_graphs (
2988                    workspace_id INTEGER,
2989                    item_id INTEGER UNIQUE,
2990                    is_open INTEGER DEFAULT FALSE,
2991
2992                    PRIMARY KEY(workspace_id, item_id),
2993                    FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
2994                    ON DELETE CASCADE
2995                ) STRICT;
2996            ),
2997            sql!(
2998                ALTER TABLE git_graphs ADD COLUMN repo_working_path TEXT;
2999            ),
3000        ];
3001    }
3002
3003    db::static_connection!(GitGraphsDb, [WorkspaceDb]);
3004
3005    impl GitGraphsDb {
3006        query! {
3007            pub async fn save_git_graph(
3008                item_id: workspace::ItemId,
3009                workspace_id: workspace::WorkspaceId,
3010                repo_working_path: String
3011            ) -> Result<()> {
3012                INSERT OR REPLACE INTO git_graphs(item_id, workspace_id, repo_working_path)
3013                VALUES (?, ?, ?)
3014            }
3015        }
3016
3017        query! {
3018            pub fn get_git_graph(
3019                item_id: workspace::ItemId,
3020                workspace_id: workspace::WorkspaceId
3021            ) -> Result<Option<PathBuf>> {
3022                SELECT repo_working_path
3023                FROM git_graphs
3024                WHERE item_id = ? AND workspace_id = ?
3025            }
3026        }
3027    }
3028}
3029
3030#[cfg(test)]
3031mod tests {
3032    use super::*;
3033    use anyhow::{Context, Result, bail};
3034    use collections::{HashMap, HashSet};
3035    use fs::FakeFs;
3036    use git::Oid;
3037    use git::repository::InitialGraphCommitData;
3038    use gpui::TestAppContext;
3039    use project::Project;
3040    use project::git_store::{GitStoreEvent, RepositoryEvent};
3041    use rand::prelude::*;
3042    use serde_json::json;
3043    use settings::SettingsStore;
3044    use smallvec::{SmallVec, smallvec};
3045    use std::path::Path;
3046    use std::sync::{Arc, Mutex};
3047
3048    fn init_test(cx: &mut TestAppContext) {
3049        cx.update(|cx| {
3050            let settings_store = SettingsStore::test(cx);
3051            cx.set_global(settings_store);
3052            theme_settings::init(theme::LoadThemes::JustBase, cx);
3053        });
3054    }
3055
3056    /// Generates a random commit DAG suitable for testing git graph rendering.
3057    ///
3058    /// The commits are ordered newest-first (like git log output), so:
3059    /// - Index 0 = most recent commit (HEAD)
3060    /// - Last index = oldest commit (root, has no parents)
3061    /// - Parents of commit at index I must have index > I
3062    ///
3063    /// When `adversarial` is true, generates complex topologies with many branches
3064    /// and octopus merges. Otherwise generates more realistic linear histories
3065    /// with occasional branches.
3066    fn generate_random_commit_dag(
3067        rng: &mut StdRng,
3068        num_commits: usize,
3069        adversarial: bool,
3070    ) -> Vec<Arc<InitialGraphCommitData>> {
3071        if num_commits == 0 {
3072            return Vec::new();
3073        }
3074
3075        let mut commits: Vec<Arc<InitialGraphCommitData>> = Vec::with_capacity(num_commits);
3076        let oids: Vec<Oid> = (0..num_commits).map(|_| Oid::random(rng)).collect();
3077
3078        for i in 0..num_commits {
3079            let sha = oids[i];
3080
3081            let parents = if i == num_commits - 1 {
3082                smallvec![]
3083            } else {
3084                generate_parents_from_oids(rng, &oids, i, num_commits, adversarial)
3085            };
3086
3087            let ref_names = if i == 0 {
3088                vec!["HEAD".into(), "main".into()]
3089            } else if adversarial && rng.random_bool(0.1) {
3090                vec![format!("branch-{}", i).into()]
3091            } else {
3092                Vec::new()
3093            };
3094
3095            commits.push(Arc::new(InitialGraphCommitData {
3096                sha,
3097                parents,
3098                ref_names,
3099            }));
3100        }
3101
3102        commits
3103    }
3104
3105    fn generate_parents_from_oids(
3106        rng: &mut StdRng,
3107        oids: &[Oid],
3108        current_idx: usize,
3109        num_commits: usize,
3110        adversarial: bool,
3111    ) -> SmallVec<[Oid; 1]> {
3112        let remaining = num_commits - current_idx - 1;
3113        if remaining == 0 {
3114            return smallvec![];
3115        }
3116
3117        if adversarial {
3118            let merge_chance = 0.4;
3119            let octopus_chance = 0.15;
3120
3121            if remaining >= 3 && rng.random_bool(octopus_chance) {
3122                let num_parents = rng.random_range(3..=remaining.min(5));
3123                let mut parent_indices: Vec<usize> = (current_idx + 1..num_commits).collect();
3124                parent_indices.shuffle(rng);
3125                parent_indices
3126                    .into_iter()
3127                    .take(num_parents)
3128                    .map(|idx| oids[idx])
3129                    .collect()
3130            } else if remaining >= 2 && rng.random_bool(merge_chance) {
3131                let mut parent_indices: Vec<usize> = (current_idx + 1..num_commits).collect();
3132                parent_indices.shuffle(rng);
3133                parent_indices
3134                    .into_iter()
3135                    .take(2)
3136                    .map(|idx| oids[idx])
3137                    .collect()
3138            } else {
3139                let parent_idx = rng.random_range(current_idx + 1..num_commits);
3140                smallvec![oids[parent_idx]]
3141            }
3142        } else {
3143            let merge_chance = 0.15;
3144            let skip_chance = 0.1;
3145
3146            if remaining >= 2 && rng.random_bool(merge_chance) {
3147                let first_parent = current_idx + 1;
3148                let second_parent = rng.random_range(current_idx + 2..num_commits);
3149                smallvec![oids[first_parent], oids[second_parent]]
3150            } else if rng.random_bool(skip_chance) && remaining >= 2 {
3151                let skip = rng.random_range(1..remaining.min(3));
3152                smallvec![oids[current_idx + 1 + skip]]
3153            } else {
3154                smallvec![oids[current_idx + 1]]
3155            }
3156        }
3157    }
3158
3159    fn build_oid_to_row_map(graph: &GraphData) -> HashMap<Oid, usize> {
3160        graph
3161            .commits
3162            .iter()
3163            .enumerate()
3164            .map(|(idx, entry)| (entry.data.sha, idx))
3165            .collect()
3166    }
3167
3168    fn verify_commit_order(
3169        graph: &GraphData,
3170        commits: &[Arc<InitialGraphCommitData>],
3171    ) -> Result<()> {
3172        if graph.commits.len() != commits.len() {
3173            bail!(
3174                "Commit count mismatch: graph has {} commits, expected {}",
3175                graph.commits.len(),
3176                commits.len()
3177            );
3178        }
3179
3180        for (idx, (graph_commit, expected_commit)) in
3181            graph.commits.iter().zip(commits.iter()).enumerate()
3182        {
3183            if graph_commit.data.sha != expected_commit.sha {
3184                bail!(
3185                    "Commit order mismatch at index {}: graph has {:?}, expected {:?}",
3186                    idx,
3187                    graph_commit.data.sha,
3188                    expected_commit.sha
3189                );
3190            }
3191        }
3192
3193        Ok(())
3194    }
3195
3196    fn verify_line_endpoints(graph: &GraphData, oid_to_row: &HashMap<Oid, usize>) -> Result<()> {
3197        for line in &graph.lines {
3198            let child_row = *oid_to_row
3199                .get(&line.child)
3200                .context("Line references non-existent child commit")?;
3201
3202            let parent_row = *oid_to_row
3203                .get(&line.parent)
3204                .context("Line references non-existent parent commit")?;
3205
3206            if child_row >= parent_row {
3207                bail!(
3208                    "child_row ({}) must be < parent_row ({})",
3209                    child_row,
3210                    parent_row
3211                );
3212            }
3213
3214            if line.full_interval.start != child_row {
3215                bail!(
3216                    "full_interval.start ({}) != child_row ({})",
3217                    line.full_interval.start,
3218                    child_row
3219                );
3220            }
3221
3222            if line.full_interval.end != parent_row {
3223                bail!(
3224                    "full_interval.end ({}) != parent_row ({})",
3225                    line.full_interval.end,
3226                    parent_row
3227                );
3228            }
3229
3230            if let Some(last_segment) = line.segments.last() {
3231                let segment_end_row = match last_segment {
3232                    CommitLineSegment::Straight { to_row } => *to_row,
3233                    CommitLineSegment::Curve { on_row, .. } => *on_row,
3234                };
3235
3236                if segment_end_row != line.full_interval.end {
3237                    bail!(
3238                        "last segment ends at row {} but full_interval.end is {}",
3239                        segment_end_row,
3240                        line.full_interval.end
3241                    );
3242                }
3243            }
3244        }
3245
3246        Ok(())
3247    }
3248
3249    fn verify_column_correctness(
3250        graph: &GraphData,
3251        oid_to_row: &HashMap<Oid, usize>,
3252    ) -> Result<()> {
3253        for line in &graph.lines {
3254            let child_row = *oid_to_row
3255                .get(&line.child)
3256                .context("Line references non-existent child commit")?;
3257
3258            let parent_row = *oid_to_row
3259                .get(&line.parent)
3260                .context("Line references non-existent parent commit")?;
3261
3262            let child_lane = graph.commits[child_row].lane;
3263            if line.child_column != child_lane {
3264                bail!(
3265                    "child_column ({}) != child's lane ({})",
3266                    line.child_column,
3267                    child_lane
3268                );
3269            }
3270
3271            let mut current_column = line.child_column;
3272            for segment in &line.segments {
3273                if let CommitLineSegment::Curve { to_column, .. } = segment {
3274                    current_column = *to_column;
3275                }
3276            }
3277
3278            let parent_lane = graph.commits[parent_row].lane;
3279            if current_column != parent_lane {
3280                bail!(
3281                    "ending column ({}) != parent's lane ({})",
3282                    current_column,
3283                    parent_lane
3284                );
3285            }
3286        }
3287
3288        Ok(())
3289    }
3290
3291    fn verify_segment_continuity(graph: &GraphData) -> Result<()> {
3292        for line in &graph.lines {
3293            if line.segments.is_empty() {
3294                bail!("Line has no segments");
3295            }
3296
3297            let mut current_row = line.full_interval.start;
3298
3299            for (idx, segment) in line.segments.iter().enumerate() {
3300                let segment_end_row = match segment {
3301                    CommitLineSegment::Straight { to_row } => *to_row,
3302                    CommitLineSegment::Curve { on_row, .. } => *on_row,
3303                };
3304
3305                if segment_end_row < current_row {
3306                    bail!(
3307                        "segment {} ends at row {} which is before current row {}",
3308                        idx,
3309                        segment_end_row,
3310                        current_row
3311                    );
3312                }
3313
3314                current_row = segment_end_row;
3315            }
3316        }
3317
3318        Ok(())
3319    }
3320
3321    fn verify_line_overlaps(graph: &GraphData) -> Result<()> {
3322        for line in &graph.lines {
3323            let child_row = line.full_interval.start;
3324
3325            let mut current_column = line.child_column;
3326            let mut current_row = child_row;
3327
3328            for segment in &line.segments {
3329                match segment {
3330                    CommitLineSegment::Straight { to_row } => {
3331                        for row in (current_row + 1)..*to_row {
3332                            if row < graph.commits.len() {
3333                                let commit_at_row = &graph.commits[row];
3334                                if commit_at_row.lane == current_column {
3335                                    bail!(
3336                                        "straight segment from row {} to {} in column {} passes through commit {:?} at row {}",
3337                                        current_row,
3338                                        to_row,
3339                                        current_column,
3340                                        commit_at_row.data.sha,
3341                                        row
3342                                    );
3343                                }
3344                            }
3345                        }
3346                        current_row = *to_row;
3347                    }
3348                    CommitLineSegment::Curve {
3349                        to_column, on_row, ..
3350                    } => {
3351                        current_column = *to_column;
3352                        current_row = *on_row;
3353                    }
3354                }
3355            }
3356        }
3357
3358        Ok(())
3359    }
3360
3361    fn verify_coverage(graph: &GraphData) -> Result<()> {
3362        let mut expected_edges: HashSet<(Oid, Oid)> = HashSet::default();
3363        for entry in &graph.commits {
3364            for parent in &entry.data.parents {
3365                expected_edges.insert((entry.data.sha, *parent));
3366            }
3367        }
3368
3369        let mut found_edges: HashSet<(Oid, Oid)> = HashSet::default();
3370        for line in &graph.lines {
3371            let edge = (line.child, line.parent);
3372
3373            if !found_edges.insert(edge) {
3374                bail!(
3375                    "Duplicate line found for edge {:?} -> {:?}",
3376                    line.child,
3377                    line.parent
3378                );
3379            }
3380
3381            if !expected_edges.contains(&edge) {
3382                bail!(
3383                    "Orphan line found: {:?} -> {:?} is not in the commit graph",
3384                    line.child,
3385                    line.parent
3386                );
3387            }
3388        }
3389
3390        for (child, parent) in &expected_edges {
3391            if !found_edges.contains(&(*child, *parent)) {
3392                bail!("Missing line for edge {:?} -> {:?}", child, parent);
3393            }
3394        }
3395
3396        assert_eq!(
3397            expected_edges.symmetric_difference(&found_edges).count(),
3398            0,
3399            "The symmetric difference should be zero"
3400        );
3401
3402        Ok(())
3403    }
3404
3405    fn verify_merge_line_optimality(
3406        graph: &GraphData,
3407        oid_to_row: &HashMap<Oid, usize>,
3408    ) -> Result<()> {
3409        for line in &graph.lines {
3410            let first_segment = line.segments.first();
3411            let is_merge_line = matches!(
3412                first_segment,
3413                Some(CommitLineSegment::Curve {
3414                    curve_kind: CurveKind::Merge,
3415                    ..
3416                })
3417            );
3418
3419            if !is_merge_line {
3420                continue;
3421            }
3422
3423            let child_row = *oid_to_row
3424                .get(&line.child)
3425                .context("Line references non-existent child commit")?;
3426
3427            let parent_row = *oid_to_row
3428                .get(&line.parent)
3429                .context("Line references non-existent parent commit")?;
3430
3431            let parent_lane = graph.commits[parent_row].lane;
3432
3433            let Some(CommitLineSegment::Curve { to_column, .. }) = first_segment else {
3434                continue;
3435            };
3436
3437            let curves_directly_to_parent = *to_column == parent_lane;
3438
3439            if !curves_directly_to_parent {
3440                continue;
3441            }
3442
3443            let curve_row = child_row + 1;
3444            let has_commits_in_path = graph.commits[curve_row..parent_row]
3445                .iter()
3446                .any(|c| c.lane == parent_lane);
3447
3448            if has_commits_in_path {
3449                bail!(
3450                    "Merge line from {:?} to {:?} curves directly to parent lane {} but there are commits in that lane between rows {} and {}",
3451                    line.child,
3452                    line.parent,
3453                    parent_lane,
3454                    curve_row,
3455                    parent_row
3456                );
3457            }
3458
3459            let curve_ends_at_parent = curve_row == parent_row;
3460
3461            if curve_ends_at_parent {
3462                if line.segments.len() != 1 {
3463                    bail!(
3464                        "Merge line from {:?} to {:?} curves directly to parent (curve_row == parent_row), but has {} segments instead of 1 [MergeCurve]",
3465                        line.child,
3466                        line.parent,
3467                        line.segments.len()
3468                    );
3469                }
3470            } else {
3471                if line.segments.len() != 2 {
3472                    bail!(
3473                        "Merge line from {:?} to {:?} curves directly to parent lane without overlap, but has {} segments instead of 2 [MergeCurve, Straight]",
3474                        line.child,
3475                        line.parent,
3476                        line.segments.len()
3477                    );
3478                }
3479
3480                let is_straight_segment = matches!(
3481                    line.segments.get(1),
3482                    Some(CommitLineSegment::Straight { .. })
3483                );
3484
3485                if !is_straight_segment {
3486                    bail!(
3487                        "Merge line from {:?} to {:?} curves directly to parent lane without overlap, but second segment is not a Straight segment",
3488                        line.child,
3489                        line.parent
3490                    );
3491                }
3492            }
3493        }
3494
3495        Ok(())
3496    }
3497
3498    fn verify_all_invariants(
3499        graph: &GraphData,
3500        commits: &[Arc<InitialGraphCommitData>],
3501    ) -> Result<()> {
3502        let oid_to_row = build_oid_to_row_map(graph);
3503
3504        verify_commit_order(graph, commits).context("commit order")?;
3505        verify_line_endpoints(graph, &oid_to_row).context("line endpoints")?;
3506        verify_column_correctness(graph, &oid_to_row).context("column correctness")?;
3507        verify_segment_continuity(graph).context("segment continuity")?;
3508        verify_merge_line_optimality(graph, &oid_to_row).context("merge line optimality")?;
3509        verify_coverage(graph).context("coverage")?;
3510        verify_line_overlaps(graph).context("line overlaps")?;
3511        Ok(())
3512    }
3513
3514    #[test]
3515    fn test_git_graph_merge_commits() {
3516        let mut rng = StdRng::seed_from_u64(42);
3517
3518        let oid1 = Oid::random(&mut rng);
3519        let oid2 = Oid::random(&mut rng);
3520        let oid3 = Oid::random(&mut rng);
3521        let oid4 = Oid::random(&mut rng);
3522
3523        let commits = vec![
3524            Arc::new(InitialGraphCommitData {
3525                sha: oid1,
3526                parents: smallvec![oid2, oid3],
3527                ref_names: vec!["HEAD".into()],
3528            }),
3529            Arc::new(InitialGraphCommitData {
3530                sha: oid2,
3531                parents: smallvec![oid4],
3532                ref_names: vec![],
3533            }),
3534            Arc::new(InitialGraphCommitData {
3535                sha: oid3,
3536                parents: smallvec![oid4],
3537                ref_names: vec![],
3538            }),
3539            Arc::new(InitialGraphCommitData {
3540                sha: oid4,
3541                parents: smallvec![],
3542                ref_names: vec![],
3543            }),
3544        ];
3545
3546        let mut graph_data = GraphData::new(8);
3547        graph_data.add_commits(&commits);
3548
3549        if let Err(error) = verify_all_invariants(&graph_data, &commits) {
3550            panic!("Graph invariant violation for merge commits:\n{}", error);
3551        }
3552    }
3553
3554    #[test]
3555    fn test_git_graph_linear_commits() {
3556        let mut rng = StdRng::seed_from_u64(42);
3557
3558        let oid1 = Oid::random(&mut rng);
3559        let oid2 = Oid::random(&mut rng);
3560        let oid3 = Oid::random(&mut rng);
3561
3562        let commits = vec![
3563            Arc::new(InitialGraphCommitData {
3564                sha: oid1,
3565                parents: smallvec![oid2],
3566                ref_names: vec!["HEAD".into()],
3567            }),
3568            Arc::new(InitialGraphCommitData {
3569                sha: oid2,
3570                parents: smallvec![oid3],
3571                ref_names: vec![],
3572            }),
3573            Arc::new(InitialGraphCommitData {
3574                sha: oid3,
3575                parents: smallvec![],
3576                ref_names: vec![],
3577            }),
3578        ];
3579
3580        let mut graph_data = GraphData::new(8);
3581        graph_data.add_commits(&commits);
3582
3583        if let Err(error) = verify_all_invariants(&graph_data, &commits) {
3584            panic!("Graph invariant violation for linear commits:\n{}", error);
3585        }
3586    }
3587
3588    #[test]
3589    fn test_git_graph_random_commits() {
3590        for seed in 0..100 {
3591            let mut rng = StdRng::seed_from_u64(seed);
3592
3593            let adversarial = rng.random_bool(0.2);
3594            let num_commits = if adversarial {
3595                rng.random_range(10..100)
3596            } else {
3597                rng.random_range(5..50)
3598            };
3599
3600            let commits = generate_random_commit_dag(&mut rng, num_commits, adversarial);
3601
3602            assert_eq!(
3603                num_commits,
3604                commits.len(),
3605                "seed={}: Generate random commit dag didn't generate the correct amount of commits",
3606                seed
3607            );
3608
3609            let mut graph_data = GraphData::new(8);
3610            graph_data.add_commits(&commits);
3611
3612            if let Err(error) = verify_all_invariants(&graph_data, &commits) {
3613                panic!(
3614                    "Graph invariant violation (seed={}, adversarial={}, num_commits={}):\n{:#}",
3615                    seed, adversarial, num_commits, error
3616                );
3617            }
3618        }
3619    }
3620
3621    // The full integration test has less iterations because it's significantly slower
3622    // than the random commit test
3623    #[gpui::test(iterations = 10)]
3624    async fn test_git_graph_random_integration(mut rng: StdRng, cx: &mut TestAppContext) {
3625        init_test(cx);
3626
3627        let adversarial = rng.random_bool(0.2);
3628        let num_commits = if adversarial {
3629            rng.random_range(10..100)
3630        } else {
3631            rng.random_range(5..50)
3632        };
3633
3634        let commits = generate_random_commit_dag(&mut rng, num_commits, adversarial);
3635
3636        let fs = FakeFs::new(cx.executor());
3637        fs.insert_tree(
3638            Path::new("/project"),
3639            json!({
3640                ".git": {},
3641                "file.txt": "content",
3642            }),
3643        )
3644        .await;
3645
3646        fs.set_graph_commits(Path::new("/project/.git"), commits.clone());
3647
3648        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
3649        cx.run_until_parked();
3650
3651        let repository = project.read_with(cx, |project, cx| {
3652            project
3653                .active_repository(cx)
3654                .expect("should have a repository")
3655        });
3656
3657        repository.update(cx, |repo, cx| {
3658            repo.graph_data(
3659                crate::LogSource::default(),
3660                crate::LogOrder::default(),
3661                0..usize::MAX,
3662                cx,
3663            );
3664        });
3665        cx.run_until_parked();
3666
3667        let graph_commits: Vec<Arc<InitialGraphCommitData>> = repository.update(cx, |repo, cx| {
3668            repo.graph_data(
3669                crate::LogSource::default(),
3670                crate::LogOrder::default(),
3671                0..usize::MAX,
3672                cx,
3673            )
3674            .commits
3675            .to_vec()
3676        });
3677
3678        let mut graph_data = GraphData::new(8);
3679        graph_data.add_commits(&graph_commits);
3680
3681        if let Err(error) = verify_all_invariants(&graph_data, &commits) {
3682            panic!(
3683                "Graph invariant violation (adversarial={}, num_commits={}):\n{:#}",
3684                adversarial, num_commits, error
3685            );
3686        }
3687    }
3688
3689    #[gpui::test]
3690    async fn test_initial_graph_data_not_cleared_on_initial_loading(cx: &mut TestAppContext) {
3691        init_test(cx);
3692
3693        let fs = FakeFs::new(cx.executor());
3694        fs.insert_tree(
3695            Path::new("/project"),
3696            json!({
3697                ".git": {},
3698                "file.txt": "content",
3699            }),
3700        )
3701        .await;
3702
3703        let mut rng = StdRng::seed_from_u64(42);
3704        let commits = generate_random_commit_dag(&mut rng, 10, false);
3705        fs.set_graph_commits(Path::new("/project/.git"), commits.clone());
3706
3707        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
3708        let observed_repository_events = Arc::new(Mutex::new(Vec::new()));
3709        project.update(cx, |project, cx| {
3710            let observed_repository_events = observed_repository_events.clone();
3711            cx.subscribe(project.git_store(), move |_, _, event, _| {
3712                if let GitStoreEvent::RepositoryUpdated(_, repository_event, true) = event {
3713                    observed_repository_events
3714                        .lock()
3715                        .expect("repository event mutex should be available")
3716                        .push(repository_event.clone());
3717                }
3718            })
3719            .detach();
3720        });
3721
3722        let repository = project.read_with(cx, |project, cx| {
3723            project
3724                .active_repository(cx)
3725                .expect("should have a repository")
3726        });
3727
3728        repository.update(cx, |repo, cx| {
3729            repo.graph_data(
3730                crate::LogSource::default(),
3731                crate::LogOrder::default(),
3732                0..usize::MAX,
3733                cx,
3734            );
3735        });
3736
3737        project
3738            .update(cx, |project, cx| project.git_scans_complete(cx))
3739            .await;
3740        cx.run_until_parked();
3741
3742        let observed_repository_events = observed_repository_events
3743            .lock()
3744            .expect("repository event mutex should be available");
3745        assert!(
3746            observed_repository_events
3747                .iter()
3748                .any(|event| matches!(event, RepositoryEvent::BranchChanged)),
3749            "initial repository scan should emit BranchChanged"
3750        );
3751        let commit_count_after = repository.read_with(cx, |repo, _| {
3752            repo.get_graph_data(crate::LogSource::default(), crate::LogOrder::default())
3753                .map(|data| data.commit_data.len())
3754                .unwrap()
3755        });
3756        assert_eq!(
3757            commits.len(),
3758            commit_count_after,
3759            "initial_graph_data should remain populated after events emitted by initial repository scan"
3760        );
3761    }
3762
3763    #[gpui::test]
3764    async fn test_initial_graph_data_propagates_error(cx: &mut TestAppContext) {
3765        init_test(cx);
3766
3767        let fs = FakeFs::new(cx.executor());
3768        fs.insert_tree(
3769            Path::new("/project"),
3770            json!({
3771                ".git": {},
3772                "file.txt": "content",
3773            }),
3774        )
3775        .await;
3776
3777        fs.set_graph_error(
3778            Path::new("/project/.git"),
3779            Some("fatal: bad default revision 'HEAD'".to_string()),
3780        );
3781
3782        let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;
3783
3784        let repository = project.read_with(cx, |project, cx| {
3785            project
3786                .active_repository(cx)
3787                .expect("should have a repository")
3788        });
3789
3790        repository.update(cx, |repo, cx| {
3791            repo.graph_data(
3792                crate::LogSource::default(),
3793                crate::LogOrder::default(),
3794                0..usize::MAX,
3795                cx,
3796            );
3797        });
3798
3799        cx.run_until_parked();
3800
3801        let error = repository.read_with(cx, |repo, _| {
3802            repo.get_graph_data(crate::LogSource::default(), crate::LogOrder::default())
3803                .and_then(|data| data.error.clone())
3804        });
3805
3806        assert!(
3807            error.is_some(),
3808            "graph data should contain an error after initial_graph_data fails"
3809        );
3810        let error_message = error.unwrap();
3811        assert!(
3812            error_message.contains("bad default revision"),
3813            "error should contain the git error message, got: {}",
3814            error_message
3815        );
3816    }
3817
3818    #[gpui::test]
3819    async fn test_graph_data_repopulated_from_cache_after_repo_switch(cx: &mut TestAppContext) {
3820        init_test(cx);
3821
3822        let fs = FakeFs::new(cx.executor());
3823        fs.insert_tree(
3824            Path::new("/project_a"),
3825            json!({
3826                ".git": {},
3827                "file.txt": "content",
3828            }),
3829        )
3830        .await;
3831        fs.insert_tree(
3832            Path::new("/project_b"),
3833            json!({
3834                ".git": {},
3835                "other.txt": "content",
3836            }),
3837        )
3838        .await;
3839
3840        let mut rng = StdRng::seed_from_u64(42);
3841        let commits = generate_random_commit_dag(&mut rng, 10, false);
3842        fs.set_graph_commits(Path::new("/project_a/.git"), commits.clone());
3843
3844        let project = Project::test(
3845            fs.clone(),
3846            [Path::new("/project_a"), Path::new("/project_b")],
3847            cx,
3848        )
3849        .await;
3850        cx.run_until_parked();
3851
3852        let (first_repository, second_repository) = project.read_with(cx, |project, cx| {
3853            let mut first_repository = None;
3854            let mut second_repository = None;
3855
3856            for repository in project.repositories(cx).values() {
3857                let work_directory_abs_path = &repository.read(cx).work_directory_abs_path;
3858                if work_directory_abs_path.as_ref() == Path::new("/project_a") {
3859                    first_repository = Some(repository.clone());
3860                } else if work_directory_abs_path.as_ref() == Path::new("/project_b") {
3861                    second_repository = Some(repository.clone());
3862                }
3863            }
3864
3865            (
3866                first_repository.expect("should have repository for /project_a"),
3867                second_repository.expect("should have repository for /project_b"),
3868            )
3869        });
3870        first_repository.update(cx, |repository, cx| repository.set_as_active_repository(cx));
3871        cx.run_until_parked();
3872
3873        let (multi_workspace, cx) = cx.add_window_view(|window, cx| {
3874            workspace::MultiWorkspace::test_new(project.clone(), window, cx)
3875        });
3876
3877        let workspace_weak =
3878            multi_workspace.read_with(&*cx, |multi, _| multi.workspace().downgrade());
3879        let git_graph = cx.new_window_entity(|window, cx| {
3880            GitGraph::new(
3881                first_repository.read(cx).id,
3882                project.read(cx).git_store().clone(),
3883                workspace_weak,
3884                window,
3885                cx,
3886            )
3887        });
3888        cx.run_until_parked();
3889
3890        // Verify initial graph data is loaded
3891        let initial_commit_count =
3892            git_graph.read_with(&*cx, |graph, _| graph.graph_data.commits.len());
3893        assert!(
3894            initial_commit_count > 0,
3895            "graph data should have been loaded, got 0 commits"
3896        );
3897
3898        git_graph.update(cx, |graph, cx| {
3899            graph.set_repo_id(second_repository.read(cx).id, cx)
3900        });
3901        cx.run_until_parked();
3902
3903        let commit_count_after_clear =
3904            git_graph.read_with(&*cx, |graph, _| graph.graph_data.commits.len());
3905        assert_eq!(
3906            commit_count_after_clear, 0,
3907            "graph_data should be cleared after switching away"
3908        );
3909
3910        git_graph.update(cx, |graph, cx| {
3911            graph.set_repo_id(first_repository.read(cx).id, cx)
3912        });
3913        cx.run_until_parked();
3914
3915        cx.draw(
3916            point(px(0.), px(0.)),
3917            gpui::size(px(1200.), px(800.)),
3918            |_, _| git_graph.clone().into_any_element(),
3919        );
3920        cx.run_until_parked();
3921
3922        let commit_count_after_switch_back =
3923            git_graph.read_with(&*cx, |graph, _| graph.graph_data.commits.len());
3924        assert_eq!(
3925            initial_commit_count, commit_count_after_switch_back,
3926            "graph_data should be repopulated from cache after switching back to the same repo"
3927        );
3928    }
3929}