git_graph.rs

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