git_graph.rs

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