git_graph.rs

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