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