git_graph.rs

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