1use crate::branch_picker::{self};
2use crate::git_panel_settings::StatusStyle;
3use crate::remote_output_toast::{RemoteAction, RemoteOutputToast};
4use crate::{
5 git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
6};
7use crate::{picker_prompt, project_diff, ProjectDiff};
8use db::kvp::KEY_VALUE_STORE;
9use editor::commit_tooltip::CommitTooltip;
10
11use editor::{
12 scroll::ScrollbarAutoHide, Editor, EditorElement, EditorMode, EditorSettings, MultiBuffer,
13 ShowScrollbar,
14};
15use git::repository::{
16 Branch, CommitDetails, CommitSummary, PushOptions, Remote, RemoteCommandOutput, ResetMode,
17 Upstream, UpstreamTracking, UpstreamTrackingStatus,
18};
19use git::{repository::RepoPath, status::FileStatus, Commit, ToggleStaged};
20use git::{RestoreTrackedFiles, StageAll, TrashUntrackedFiles, UnstageAll};
21use gpui::*;
22use itertools::Itertools;
23use language::{Buffer, File};
24use menu::{Confirm, SecondaryConfirm, SelectFirst, SelectLast, SelectNext, SelectPrevious};
25use multi_buffer::ExcerptInfo;
26use panel::{
27 panel_editor_container, panel_editor_style, panel_filled_button, panel_icon_button, PanelHeader,
28};
29use project::{
30 git::{GitEvent, Repository},
31 Fs, Project, ProjectPath,
32};
33use serde::{Deserialize, Serialize};
34use settings::Settings as _;
35use smallvec::smallvec;
36use std::cell::RefCell;
37use std::future::Future;
38use std::rc::Rc;
39use std::{collections::HashSet, sync::Arc, time::Duration, usize};
40use strum::{IntoEnumIterator, VariantNames};
41use time::OffsetDateTime;
42use ui::{
43 prelude::*, ButtonLike, Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar,
44 ScrollbarState, Tooltip,
45};
46use util::{maybe, post_inc, ResultExt, TryFutureExt};
47
48use workspace::{
49 dock::{DockPosition, Panel, PanelEvent},
50 notifications::{DetachAndPromptErr, NotificationId},
51 Toast, Workspace,
52};
53
54actions!(
55 git_panel,
56 [
57 Close,
58 ToggleFocus,
59 OpenMenu,
60 FocusEditor,
61 FocusChanges,
62 ToggleFillCoAuthors,
63 ]
64);
65
66fn prompt<T>(msg: &str, detail: Option<&str>, window: &mut Window, cx: &mut App) -> Task<Result<T>>
67where
68 T: IntoEnumIterator + VariantNames + 'static,
69{
70 let rx = window.prompt(PromptLevel::Info, msg, detail, &T::VARIANTS, cx);
71 cx.spawn(|_| async move { Ok(T::iter().nth(rx.await?).unwrap()) })
72}
73
74#[derive(strum::EnumIter, strum::VariantNames)]
75#[strum(serialize_all = "title_case")]
76enum TrashCancel {
77 Trash,
78 Cancel,
79}
80
81fn git_panel_context_menu(window: &mut Window, cx: &mut App) -> Entity<ContextMenu> {
82 ContextMenu::build(window, cx, |context_menu, _, _| {
83 context_menu
84 .action("Stage All", StageAll.boxed_clone())
85 .action("Unstage All", UnstageAll.boxed_clone())
86 .separator()
87 .action("Open Diff", project_diff::Diff.boxed_clone())
88 .separator()
89 .action("Discard Tracked Changes", RestoreTrackedFiles.boxed_clone())
90 .action("Trash Untracked Files", TrashUntrackedFiles.boxed_clone())
91 })
92}
93
94const GIT_PANEL_KEY: &str = "GitPanel";
95
96const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
97
98pub fn init(cx: &mut App) {
99 cx.observe_new(
100 |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
101 workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
102 workspace.toggle_panel_focus::<GitPanel>(window, cx);
103 });
104 },
105 )
106 .detach();
107}
108
109#[derive(Debug, Clone)]
110pub enum Event {
111 Focus,
112}
113
114#[derive(Serialize, Deserialize)]
115struct SerializedGitPanel {
116 width: Option<Pixels>,
117}
118
119#[derive(Debug, PartialEq, Eq, Clone, Copy)]
120enum Section {
121 Conflict,
122 Tracked,
123 New,
124}
125
126#[derive(Debug, PartialEq, Eq, Clone)]
127struct GitHeaderEntry {
128 header: Section,
129}
130
131impl GitHeaderEntry {
132 pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {
133 let this = &self.header;
134 let status = status_entry.status;
135 match this {
136 Section::Conflict => repo.has_conflict(&status_entry.repo_path),
137 Section::Tracked => !status.is_created(),
138 Section::New => status.is_created(),
139 }
140 }
141 pub fn title(&self) -> &'static str {
142 match self.header {
143 Section::Conflict => "Conflicts",
144 Section::Tracked => "Tracked",
145 Section::New => "Untracked",
146 }
147 }
148}
149
150#[derive(Debug, PartialEq, Eq, Clone)]
151enum GitListEntry {
152 GitStatusEntry(GitStatusEntry),
153 Header(GitHeaderEntry),
154}
155
156impl GitListEntry {
157 fn status_entry(&self) -> Option<&GitStatusEntry> {
158 match self {
159 GitListEntry::GitStatusEntry(entry) => Some(entry),
160 _ => None,
161 }
162 }
163}
164
165#[derive(Debug, PartialEq, Eq, Clone)]
166pub struct GitStatusEntry {
167 pub(crate) repo_path: RepoPath,
168 pub(crate) status: FileStatus,
169 pub(crate) is_staged: Option<bool>,
170}
171
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173enum TargetStatus {
174 Staged,
175 Unstaged,
176 Reverted,
177 Unchanged,
178}
179
180struct PendingOperation {
181 finished: bool,
182 target_status: TargetStatus,
183 repo_paths: HashSet<RepoPath>,
184 op_id: usize,
185}
186
187type RemoteOperations = Rc<RefCell<HashSet<u32>>>;
188
189pub struct GitPanel {
190 remote_operation_id: u32,
191 pending_remote_operations: RemoteOperations,
192 pub(crate) active_repository: Option<Entity<Repository>>,
193 pub(crate) commit_editor: Entity<Editor>,
194 conflicted_count: usize,
195 conflicted_staged_count: usize,
196 current_modifiers: Modifiers,
197 add_coauthors: bool,
198 entries: Vec<GitListEntry>,
199 focus_handle: FocusHandle,
200 fs: Arc<dyn Fs>,
201 hide_scrollbar_task: Option<Task<()>>,
202 new_count: usize,
203 new_staged_count: usize,
204 pending: Vec<PendingOperation>,
205 pending_commit: Option<Task<()>>,
206 pending_serialization: Task<Option<()>>,
207 pub(crate) project: Entity<Project>,
208 scroll_handle: UniformListScrollHandle,
209 scrollbar_state: ScrollbarState,
210 selected_entry: Option<usize>,
211 marked_entries: Vec<usize>,
212 show_scrollbar: bool,
213 tracked_count: usize,
214 tracked_staged_count: usize,
215 update_visible_entries_task: Task<()>,
216 width: Option<Pixels>,
217 workspace: WeakEntity<Workspace>,
218 context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
219 modal_open: bool,
220}
221
222struct RemoteOperationGuard {
223 id: u32,
224 pending_remote_operations: RemoteOperations,
225}
226
227impl Drop for RemoteOperationGuard {
228 fn drop(&mut self) {
229 self.pending_remote_operations.borrow_mut().remove(&self.id);
230 }
231}
232
233pub(crate) fn commit_message_editor(
234 commit_message_buffer: Entity<Buffer>,
235 placeholder: Option<&str>,
236 project: Entity<Project>,
237 in_panel: bool,
238 window: &mut Window,
239 cx: &mut Context<'_, Editor>,
240) -> Editor {
241 let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, cx));
242 let max_lines = if in_panel { 6 } else { 18 };
243 let mut commit_editor = Editor::new(
244 EditorMode::AutoHeight { max_lines },
245 buffer,
246 None,
247 false,
248 window,
249 cx,
250 );
251 commit_editor.set_collaboration_hub(Box::new(project));
252 commit_editor.set_use_autoclose(false);
253 commit_editor.set_show_gutter(false, cx);
254 commit_editor.set_show_wrap_guides(false, cx);
255 commit_editor.set_show_indent_guides(false, cx);
256 let placeholder = placeholder.unwrap_or("Enter commit message");
257 commit_editor.set_placeholder_text(placeholder, cx);
258 commit_editor
259}
260
261impl GitPanel {
262 pub fn new(
263 workspace: &mut Workspace,
264 window: &mut Window,
265 cx: &mut Context<Workspace>,
266 ) -> Entity<Self> {
267 let fs = workspace.app_state().fs.clone();
268 let project = workspace.project().clone();
269 let git_store = project.read(cx).git_store().clone();
270 let active_repository = project.read(cx).active_repository(cx);
271 let workspace = cx.entity().downgrade();
272
273 cx.new(|cx| {
274 let focus_handle = cx.focus_handle();
275 cx.on_focus(&focus_handle, window, Self::focus_in).detach();
276 cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
277 this.hide_scrollbar(window, cx);
278 })
279 .detach();
280
281 // just to let us render a placeholder editor.
282 // Once the active git repo is set, this buffer will be replaced.
283 let temporary_buffer = cx.new(|cx| Buffer::local("", cx));
284 let commit_editor = cx.new(|cx| {
285 commit_message_editor(temporary_buffer, None, project.clone(), true, window, cx)
286 });
287
288 commit_editor.update(cx, |editor, cx| {
289 editor.clear(window, cx);
290 });
291
292 let scroll_handle = UniformListScrollHandle::new();
293
294 cx.subscribe_in(
295 &git_store,
296 window,
297 move |this, git_store, event, window, cx| match event {
298 GitEvent::FileSystemUpdated => {
299 this.schedule_update(false, window, cx);
300 }
301 GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {
302 this.active_repository = git_store.read(cx).active_repository();
303 this.schedule_update(true, window, cx);
304 }
305 },
306 )
307 .detach();
308
309 let scrollbar_state =
310 ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity());
311
312 let mut git_panel = Self {
313 pending_remote_operations: Default::default(),
314 remote_operation_id: 0,
315 active_repository,
316 commit_editor,
317 conflicted_count: 0,
318 conflicted_staged_count: 0,
319 current_modifiers: window.modifiers(),
320 add_coauthors: true,
321 entries: Vec::new(),
322 focus_handle: cx.focus_handle(),
323 fs,
324 hide_scrollbar_task: None,
325 new_count: 0,
326 new_staged_count: 0,
327 pending: Vec::new(),
328 pending_commit: None,
329 pending_serialization: Task::ready(None),
330 project,
331 scroll_handle,
332 scrollbar_state,
333 selected_entry: None,
334 marked_entries: Vec::new(),
335 show_scrollbar: false,
336 tracked_count: 0,
337 tracked_staged_count: 0,
338 update_visible_entries_task: Task::ready(()),
339 width: Some(px(360.)),
340 context_menu: None,
341 workspace,
342 modal_open: false,
343 };
344 git_panel.schedule_update(false, window, cx);
345 git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);
346 git_panel
347 })
348 }
349
350 pub fn entry_by_path(&self, path: &RepoPath) -> Option<usize> {
351 fn binary_search<F>(mut low: usize, mut high: usize, is_target: F) -> Option<usize>
352 where
353 F: Fn(usize) -> std::cmp::Ordering,
354 {
355 while low < high {
356 let mid = low + (high - low) / 2;
357 match is_target(mid) {
358 std::cmp::Ordering::Equal => return Some(mid),
359 std::cmp::Ordering::Less => low = mid + 1,
360 std::cmp::Ordering::Greater => high = mid,
361 }
362 }
363 None
364 }
365 if self.conflicted_count > 0 {
366 let conflicted_start = 1;
367 if let Some(ix) = binary_search(
368 conflicted_start,
369 conflicted_start + self.conflicted_count,
370 |ix| {
371 self.entries[ix]
372 .status_entry()
373 .unwrap()
374 .repo_path
375 .cmp(&path)
376 },
377 ) {
378 return Some(ix);
379 }
380 }
381 if self.tracked_count > 0 {
382 let tracked_start = if self.conflicted_count > 0 {
383 1 + self.conflicted_count
384 } else {
385 0
386 } + 1;
387 if let Some(ix) =
388 binary_search(tracked_start, tracked_start + self.tracked_count, |ix| {
389 self.entries[ix]
390 .status_entry()
391 .unwrap()
392 .repo_path
393 .cmp(&path)
394 })
395 {
396 return Some(ix);
397 }
398 }
399 if self.new_count > 0 {
400 let untracked_start = if self.conflicted_count > 0 {
401 1 + self.conflicted_count
402 } else {
403 0
404 } + if self.tracked_count > 0 {
405 1 + self.tracked_count
406 } else {
407 0
408 } + 1;
409 if let Some(ix) =
410 binary_search(untracked_start, untracked_start + self.new_count, |ix| {
411 self.entries[ix]
412 .status_entry()
413 .unwrap()
414 .repo_path
415 .cmp(&path)
416 })
417 {
418 return Some(ix);
419 }
420 }
421 None
422 }
423
424 pub fn select_entry_by_path(
425 &mut self,
426 path: ProjectPath,
427 _: &mut Window,
428 cx: &mut Context<Self>,
429 ) {
430 let Some(git_repo) = self.active_repository.as_ref() else {
431 return;
432 };
433 let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {
434 return;
435 };
436 let Some(ix) = self.entry_by_path(&repo_path) else {
437 return;
438 };
439 self.selected_entry = Some(ix);
440 cx.notify();
441 }
442
443 fn start_remote_operation(&mut self) -> RemoteOperationGuard {
444 let id = post_inc(&mut self.remote_operation_id);
445 self.pending_remote_operations.borrow_mut().insert(id);
446
447 RemoteOperationGuard {
448 id,
449 pending_remote_operations: self.pending_remote_operations.clone(),
450 }
451 }
452
453 fn serialize(&mut self, cx: &mut Context<Self>) {
454 let width = self.width;
455 self.pending_serialization = cx.background_spawn(
456 async move {
457 KEY_VALUE_STORE
458 .write_kvp(
459 GIT_PANEL_KEY.into(),
460 serde_json::to_string(&SerializedGitPanel { width })?,
461 )
462 .await?;
463 anyhow::Ok(())
464 }
465 .log_err(),
466 );
467 }
468
469 pub(crate) fn set_modal_open(&mut self, open: bool, cx: &mut Context<Self>) {
470 self.modal_open = open;
471 cx.notify();
472 }
473
474 fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {
475 let mut dispatch_context = KeyContext::new_with_defaults();
476 dispatch_context.add("GitPanel");
477
478 if self.is_focused(window, cx) {
479 dispatch_context.add("menu");
480 dispatch_context.add("ChangesList");
481 }
482
483 if self.commit_editor.read(cx).is_focused(window) {
484 dispatch_context.add("CommitEditor");
485 }
486
487 dispatch_context
488 }
489
490 fn is_focused(&self, window: &Window, cx: &Context<Self>) -> bool {
491 window
492 .focused(cx)
493 .map_or(false, |focused| self.focus_handle == focused)
494 }
495
496 fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {
497 cx.emit(PanelEvent::Close);
498 }
499
500 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
501 if !self.focus_handle.contains_focused(window, cx) {
502 cx.emit(Event::Focus);
503 }
504 }
505
506 fn show_scrollbar(&self, cx: &mut Context<Self>) -> ShowScrollbar {
507 GitPanelSettings::get_global(cx)
508 .scrollbar
509 .show
510 .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
511 }
512
513 fn should_show_scrollbar(&self, cx: &mut Context<Self>) -> bool {
514 let show = self.show_scrollbar(cx);
515 match show {
516 ShowScrollbar::Auto => true,
517 ShowScrollbar::System => true,
518 ShowScrollbar::Always => true,
519 ShowScrollbar::Never => false,
520 }
521 }
522
523 fn should_autohide_scrollbar(&self, cx: &mut Context<Self>) -> bool {
524 let show = self.show_scrollbar(cx);
525 match show {
526 ShowScrollbar::Auto => true,
527 ShowScrollbar::System => cx
528 .try_global::<ScrollbarAutoHide>()
529 .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
530 ShowScrollbar::Always => false,
531 ShowScrollbar::Never => true,
532 }
533 }
534
535 fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
536 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
537 if !self.should_autohide_scrollbar(cx) {
538 return;
539 }
540 self.hide_scrollbar_task = Some(cx.spawn_in(window, |panel, mut cx| async move {
541 cx.background_executor()
542 .timer(SCROLLBAR_SHOW_INTERVAL)
543 .await;
544 panel
545 .update(&mut cx, |panel, cx| {
546 panel.show_scrollbar = false;
547 cx.notify();
548 })
549 .log_err();
550 }))
551 }
552
553 fn handle_modifiers_changed(
554 &mut self,
555 event: &ModifiersChangedEvent,
556 _: &mut Window,
557 cx: &mut Context<Self>,
558 ) {
559 self.current_modifiers = event.modifiers;
560 cx.notify();
561 }
562
563 fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {
564 if let Some(selected_entry) = self.selected_entry {
565 self.scroll_handle
566 .scroll_to_item(selected_entry, ScrollStrategy::Center);
567 }
568
569 cx.notify();
570 }
571
572 fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {
573 if !self.entries.is_empty() {
574 self.selected_entry = Some(1);
575 self.scroll_to_selected_entry(cx);
576 }
577 }
578
579 fn select_previous(
580 &mut self,
581 _: &SelectPrevious,
582 _window: &mut Window,
583 cx: &mut Context<Self>,
584 ) {
585 let item_count = self.entries.len();
586 if item_count == 0 {
587 return;
588 }
589
590 if let Some(selected_entry) = self.selected_entry {
591 let new_selected_entry = if selected_entry > 0 {
592 selected_entry - 1
593 } else {
594 selected_entry
595 };
596
597 if matches!(
598 self.entries.get(new_selected_entry),
599 Some(GitListEntry::Header(..))
600 ) {
601 if new_selected_entry > 0 {
602 self.selected_entry = Some(new_selected_entry - 1)
603 }
604 } else {
605 self.selected_entry = Some(new_selected_entry);
606 }
607
608 self.scroll_to_selected_entry(cx);
609 }
610
611 cx.notify();
612 }
613
614 fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
615 let item_count = self.entries.len();
616 if item_count == 0 {
617 return;
618 }
619
620 if let Some(selected_entry) = self.selected_entry {
621 let new_selected_entry = if selected_entry < item_count - 1 {
622 selected_entry + 1
623 } else {
624 selected_entry
625 };
626 if matches!(
627 self.entries.get(new_selected_entry),
628 Some(GitListEntry::Header(..))
629 ) {
630 self.selected_entry = Some(new_selected_entry + 1);
631 } else {
632 self.selected_entry = Some(new_selected_entry);
633 }
634
635 self.scroll_to_selected_entry(cx);
636 }
637
638 cx.notify();
639 }
640
641 fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
642 if self.entries.last().is_some() {
643 self.selected_entry = Some(self.entries.len() - 1);
644 self.scroll_to_selected_entry(cx);
645 }
646 }
647
648 pub(crate) fn editor_focus_handle(&self, cx: &mut Context<Self>) -> FocusHandle {
649 self.commit_editor.focus_handle(cx).clone()
650 }
651
652 fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {
653 self.commit_editor.update(cx, |editor, cx| {
654 window.focus(&editor.focus_handle(cx));
655 });
656 cx.notify();
657 }
658
659 fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {
660 let have_entries = self
661 .active_repository
662 .as_ref()
663 .map_or(false, |active_repository| {
664 active_repository.read(cx).entry_count() > 0
665 });
666 if have_entries && self.selected_entry.is_none() {
667 self.selected_entry = Some(1);
668 self.scroll_to_selected_entry(cx);
669 cx.notify();
670 }
671 }
672
673 fn focus_changes_list(
674 &mut self,
675 _: &FocusChanges,
676 window: &mut Window,
677 cx: &mut Context<Self>,
678 ) {
679 self.select_first_entry_if_none(cx);
680
681 cx.focus_self(window);
682 cx.notify();
683 }
684
685 fn get_selected_entry(&self) -> Option<&GitListEntry> {
686 self.selected_entry.and_then(|i| self.entries.get(i))
687 }
688
689 fn open_diff(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
690 maybe!({
691 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
692 let workspace = self.workspace.upgrade()?;
693 let git_repo = self.active_repository.as_ref()?;
694
695 if let Some(project_diff) = workspace.read(cx).active_item_as::<ProjectDiff>(cx) {
696 if let Some(project_path) = project_diff.read(cx).active_path(cx) {
697 if Some(&entry.repo_path)
698 == git_repo
699 .read(cx)
700 .project_path_to_repo_path(&project_path)
701 .as_ref()
702 {
703 project_diff.focus_handle(cx).focus(window);
704 return None;
705 }
706 }
707 };
708
709 self.workspace
710 .update(cx, |workspace, cx| {
711 ProjectDiff::deploy_at(workspace, Some(entry.clone()), window, cx);
712 })
713 .ok();
714 self.focus_handle.focus(window);
715
716 Some(())
717 });
718 }
719
720 fn open_file(
721 &mut self,
722 _: &menu::SecondaryConfirm,
723 window: &mut Window,
724 cx: &mut Context<Self>,
725 ) {
726 maybe!({
727 let entry = self.entries.get(self.selected_entry?)?.status_entry()?;
728 let active_repo = self.active_repository.as_ref()?;
729 let path = active_repo
730 .read(cx)
731 .repo_path_to_project_path(&entry.repo_path)?;
732 if entry.status.is_deleted() {
733 return None;
734 }
735
736 self.workspace
737 .update(cx, |workspace, cx| {
738 workspace
739 .open_path_preview(path, None, false, false, true, window, cx)
740 .detach_and_prompt_err("Failed to open file", window, cx, |e, _, _| {
741 Some(format!("{e}"))
742 });
743 })
744 .ok()
745 });
746 }
747
748 fn revert_selected(
749 &mut self,
750 _: &git::RestoreFile,
751 window: &mut Window,
752 cx: &mut Context<Self>,
753 ) {
754 maybe!({
755 let list_entry = self.entries.get(self.selected_entry?)?.clone();
756 let entry = list_entry.status_entry()?;
757 self.revert_entry(&entry, window, cx);
758 Some(())
759 });
760 }
761
762 fn revert_entry(
763 &mut self,
764 entry: &GitStatusEntry,
765 window: &mut Window,
766 cx: &mut Context<Self>,
767 ) {
768 maybe!({
769 let active_repo = self.active_repository.clone()?;
770 let path = active_repo
771 .read(cx)
772 .repo_path_to_project_path(&entry.repo_path)?;
773 let workspace = self.workspace.clone();
774
775 if entry.status.is_staged() != Some(false) {
776 self.perform_stage(false, vec![entry.repo_path.clone()], cx);
777 }
778 let filename = path.path.file_name()?.to_string_lossy();
779
780 if !entry.status.is_created() {
781 self.perform_checkout(vec![entry.repo_path.clone()], cx);
782 } else {
783 let prompt = prompt(&format!("Trash {}?", filename), None, window, cx);
784 cx.spawn_in(window, |_, mut cx| async move {
785 match prompt.await? {
786 TrashCancel::Trash => {}
787 TrashCancel::Cancel => return Ok(()),
788 }
789 let task = workspace.update(&mut cx, |workspace, cx| {
790 workspace
791 .project()
792 .update(cx, |project, cx| project.delete_file(path, true, cx))
793 })?;
794 if let Some(task) = task {
795 task.await?;
796 }
797 Ok(())
798 })
799 .detach_and_prompt_err(
800 "Failed to trash file",
801 window,
802 cx,
803 |e, _, _| Some(format!("{e}")),
804 );
805 }
806 Some(())
807 });
808 }
809
810 fn perform_checkout(&mut self, repo_paths: Vec<RepoPath>, cx: &mut Context<Self>) {
811 let workspace = self.workspace.clone();
812 let Some(active_repository) = self.active_repository.clone() else {
813 return;
814 };
815
816 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
817 self.pending.push(PendingOperation {
818 op_id,
819 target_status: TargetStatus::Reverted,
820 repo_paths: repo_paths.iter().cloned().collect(),
821 finished: false,
822 });
823 self.update_visible_entries(cx);
824 let task = cx.spawn(|_, mut cx| async move {
825 let tasks: Vec<_> = workspace.update(&mut cx, |workspace, cx| {
826 workspace.project().update(cx, |project, cx| {
827 repo_paths
828 .iter()
829 .filter_map(|repo_path| {
830 let path = active_repository
831 .read(cx)
832 .repo_path_to_project_path(&repo_path)?;
833 Some(project.open_buffer(path, cx))
834 })
835 .collect()
836 })
837 })?;
838
839 let buffers = futures::future::join_all(tasks).await;
840
841 active_repository
842 .update(&mut cx, |repo, _| repo.checkout_files("HEAD", repo_paths))?
843 .await??;
844
845 let tasks: Vec<_> = cx.update(|cx| {
846 buffers
847 .iter()
848 .filter_map(|buffer| {
849 buffer.as_ref().ok()?.update(cx, |buffer, cx| {
850 buffer.is_dirty().then(|| buffer.reload(cx))
851 })
852 })
853 .collect()
854 })?;
855
856 futures::future::join_all(tasks).await;
857
858 Ok(())
859 });
860
861 cx.spawn(|this, mut cx| async move {
862 let result = task.await;
863
864 this.update(&mut cx, |this, cx| {
865 for pending in this.pending.iter_mut() {
866 if pending.op_id == op_id {
867 pending.finished = true;
868 if result.is_err() {
869 pending.target_status = TargetStatus::Unchanged;
870 this.update_visible_entries(cx);
871 }
872 break;
873 }
874 }
875 result
876 .map_err(|e| {
877 this.show_err_toast(e, cx);
878 })
879 .ok();
880 })
881 .ok();
882 })
883 .detach();
884 }
885
886 fn restore_tracked_files(
887 &mut self,
888 _: &RestoreTrackedFiles,
889 window: &mut Window,
890 cx: &mut Context<Self>,
891 ) {
892 let entries = self
893 .entries
894 .iter()
895 .filter_map(|entry| entry.status_entry().cloned())
896 .filter(|status_entry| !status_entry.status.is_created())
897 .collect::<Vec<_>>();
898
899 match entries.len() {
900 0 => return,
901 1 => return self.revert_entry(&entries[0], window, cx),
902 _ => {}
903 }
904 let mut details = entries
905 .iter()
906 .filter_map(|entry| entry.repo_path.0.file_name())
907 .map(|filename| filename.to_string_lossy())
908 .take(5)
909 .join("\n");
910 if entries.len() > 5 {
911 details.push_str(&format!("\nand {} more…", entries.len() - 5))
912 }
913
914 #[derive(strum::EnumIter, strum::VariantNames)]
915 #[strum(serialize_all = "title_case")]
916 enum RestoreCancel {
917 RestoreTrackedFiles,
918 Cancel,
919 }
920 let prompt = prompt(
921 "Discard changes to these files?",
922 Some(&details),
923 window,
924 cx,
925 );
926 cx.spawn(|this, mut cx| async move {
927 match prompt.await {
928 Ok(RestoreCancel::RestoreTrackedFiles) => {
929 this.update(&mut cx, |this, cx| {
930 let repo_paths = entries.into_iter().map(|entry| entry.repo_path).collect();
931 this.perform_checkout(repo_paths, cx);
932 })
933 .ok();
934 }
935 _ => {
936 return;
937 }
938 }
939 })
940 .detach();
941 }
942
943 fn clean_all(&mut self, _: &TrashUntrackedFiles, window: &mut Window, cx: &mut Context<Self>) {
944 let workspace = self.workspace.clone();
945 let Some(active_repo) = self.active_repository.clone() else {
946 return;
947 };
948 let to_delete = self
949 .entries
950 .iter()
951 .filter_map(|entry| entry.status_entry())
952 .filter(|status_entry| status_entry.status.is_created())
953 .cloned()
954 .collect::<Vec<_>>();
955
956 match to_delete.len() {
957 0 => return,
958 1 => return self.revert_entry(&to_delete[0], window, cx),
959 _ => {}
960 };
961
962 let mut details = to_delete
963 .iter()
964 .map(|entry| {
965 entry
966 .repo_path
967 .0
968 .file_name()
969 .map(|f| f.to_string_lossy())
970 .unwrap_or_default()
971 })
972 .take(5)
973 .join("\n");
974
975 if to_delete.len() > 5 {
976 details.push_str(&format!("\nand {} more…", to_delete.len() - 5))
977 }
978
979 let prompt = prompt("Trash these files?", Some(&details), window, cx);
980 cx.spawn_in(window, |this, mut cx| async move {
981 match prompt.await? {
982 TrashCancel::Trash => {}
983 TrashCancel::Cancel => return Ok(()),
984 }
985 let tasks = workspace.update(&mut cx, |workspace, cx| {
986 to_delete
987 .iter()
988 .filter_map(|entry| {
989 workspace.project().update(cx, |project, cx| {
990 let project_path = active_repo
991 .read(cx)
992 .repo_path_to_project_path(&entry.repo_path)?;
993 project.delete_file(project_path, true, cx)
994 })
995 })
996 .collect::<Vec<_>>()
997 })?;
998 let to_unstage = to_delete
999 .into_iter()
1000 .filter_map(|entry| {
1001 if entry.status.is_staged() != Some(false) {
1002 Some(entry.repo_path.clone())
1003 } else {
1004 None
1005 }
1006 })
1007 .collect();
1008 this.update(&mut cx, |this, cx| {
1009 this.perform_stage(false, to_unstage, cx)
1010 })?;
1011 for task in tasks {
1012 task.await?;
1013 }
1014 Ok(())
1015 })
1016 .detach_and_prompt_err("Failed to trash files", window, cx, |e, _, _| {
1017 Some(format!("{e}"))
1018 });
1019 }
1020
1021 fn stage_all(&mut self, _: &StageAll, _window: &mut Window, cx: &mut Context<Self>) {
1022 let repo_paths = self
1023 .entries
1024 .iter()
1025 .filter_map(|entry| entry.status_entry())
1026 .filter(|status_entry| status_entry.is_staged != Some(true))
1027 .map(|status_entry| status_entry.repo_path.clone())
1028 .collect::<Vec<_>>();
1029 self.perform_stage(true, repo_paths, cx);
1030 }
1031
1032 fn unstage_all(&mut self, _: &UnstageAll, _window: &mut Window, cx: &mut Context<Self>) {
1033 let repo_paths = self
1034 .entries
1035 .iter()
1036 .filter_map(|entry| entry.status_entry())
1037 .filter(|status_entry| status_entry.is_staged != Some(false))
1038 .map(|status_entry| status_entry.repo_path.clone())
1039 .collect::<Vec<_>>();
1040 self.perform_stage(false, repo_paths, cx);
1041 }
1042
1043 fn toggle_staged_for_entry(
1044 &mut self,
1045 entry: &GitListEntry,
1046 _window: &mut Window,
1047 cx: &mut Context<Self>,
1048 ) {
1049 let Some(active_repository) = self.active_repository.as_ref() else {
1050 return;
1051 };
1052 let (stage, repo_paths) = match entry {
1053 GitListEntry::GitStatusEntry(status_entry) => {
1054 if status_entry.status.is_staged().unwrap_or(false) {
1055 (false, vec![status_entry.repo_path.clone()])
1056 } else {
1057 (true, vec![status_entry.repo_path.clone()])
1058 }
1059 }
1060 GitListEntry::Header(section) => {
1061 let goal_staged_state = !self.header_state(section.header).selected();
1062 let repository = active_repository.read(cx);
1063 let entries = self
1064 .entries
1065 .iter()
1066 .filter_map(|entry| entry.status_entry())
1067 .filter(|status_entry| {
1068 section.contains(&status_entry, repository)
1069 && status_entry.is_staged != Some(goal_staged_state)
1070 })
1071 .map(|status_entry| status_entry.repo_path.clone())
1072 .collect::<Vec<_>>();
1073
1074 (goal_staged_state, entries)
1075 }
1076 };
1077 self.perform_stage(stage, repo_paths, cx);
1078 }
1079
1080 fn perform_stage(&mut self, stage: bool, repo_paths: Vec<RepoPath>, cx: &mut Context<Self>) {
1081 let Some(active_repository) = self.active_repository.clone() else {
1082 return;
1083 };
1084 let op_id = self.pending.iter().map(|p| p.op_id).max().unwrap_or(0) + 1;
1085 self.pending.push(PendingOperation {
1086 op_id,
1087 target_status: if stage {
1088 TargetStatus::Staged
1089 } else {
1090 TargetStatus::Unstaged
1091 },
1092 repo_paths: repo_paths.iter().cloned().collect(),
1093 finished: false,
1094 });
1095 let repo_paths = repo_paths.clone();
1096 let repository = active_repository.read(cx);
1097 self.update_counts(repository);
1098 cx.notify();
1099
1100 cx.spawn({
1101 |this, mut cx| async move {
1102 let result = cx
1103 .update(|cx| {
1104 if stage {
1105 active_repository
1106 .update(cx, |repo, cx| repo.stage_entries(repo_paths.clone(), cx))
1107 } else {
1108 active_repository
1109 .update(cx, |repo, cx| repo.unstage_entries(repo_paths.clone(), cx))
1110 }
1111 })?
1112 .await;
1113
1114 this.update(&mut cx, |this, cx| {
1115 for pending in this.pending.iter_mut() {
1116 if pending.op_id == op_id {
1117 pending.finished = true
1118 }
1119 }
1120 result
1121 .map_err(|e| {
1122 this.show_err_toast(e, cx);
1123 })
1124 .ok();
1125 cx.notify();
1126 })
1127 }
1128 })
1129 .detach();
1130 }
1131
1132 pub fn total_staged_count(&self) -> usize {
1133 self.tracked_staged_count + self.new_staged_count + self.conflicted_staged_count
1134 }
1135
1136 pub fn commit_message_buffer(&self, cx: &App) -> Entity<Buffer> {
1137 self.commit_editor
1138 .read(cx)
1139 .buffer()
1140 .read(cx)
1141 .as_singleton()
1142 .unwrap()
1143 .clone()
1144 }
1145
1146 fn toggle_staged_for_selected(
1147 &mut self,
1148 _: &git::ToggleStaged,
1149 window: &mut Window,
1150 cx: &mut Context<Self>,
1151 ) {
1152 if let Some(selected_entry) = self.get_selected_entry().cloned() {
1153 self.toggle_staged_for_entry(&selected_entry, window, cx);
1154 }
1155 }
1156
1157 fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
1158 if self
1159 .commit_editor
1160 .focus_handle(cx)
1161 .contains_focused(window, cx)
1162 {
1163 self.commit_changes(window, cx)
1164 } else {
1165 cx.propagate();
1166 }
1167 }
1168
1169 fn custom_or_suggested_commit_message(&self, cx: &mut Context<Self>) -> Option<String> {
1170 let message = self.commit_editor.read(cx).text(cx);
1171
1172 if !message.trim().is_empty() {
1173 return Some(message.to_string());
1174 }
1175
1176 self.suggest_commit_message()
1177 .filter(|message| !message.trim().is_empty())
1178 }
1179
1180 pub(crate) fn commit_changes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1181 let Some(active_repository) = self.active_repository.clone() else {
1182 return;
1183 };
1184 let error_spawn = |message, window: &mut Window, cx: &mut App| {
1185 let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
1186 cx.spawn(|_| async move {
1187 prompt.await.ok();
1188 })
1189 .detach();
1190 };
1191
1192 if self.has_unstaged_conflicts() {
1193 error_spawn(
1194 "There are still conflicts. You must stage these before committing",
1195 window,
1196 cx,
1197 );
1198 return;
1199 }
1200
1201 let commit_message = self.custom_or_suggested_commit_message(cx);
1202
1203 let Some(mut message) = commit_message else {
1204 self.commit_editor.read(cx).focus_handle(cx).focus(window);
1205 return;
1206 };
1207
1208 if self.add_coauthors {
1209 self.fill_co_authors(&mut message, cx);
1210 }
1211
1212 let task = if self.has_staged_changes() {
1213 // Repository serializes all git operations, so we can just send a commit immediately
1214 let commit_task = active_repository.read(cx).commit(message.into(), None);
1215 cx.background_spawn(async move { commit_task.await? })
1216 } else {
1217 let changed_files = self
1218 .entries
1219 .iter()
1220 .filter_map(|entry| entry.status_entry())
1221 .filter(|status_entry| !status_entry.status.is_created())
1222 .map(|status_entry| status_entry.repo_path.clone())
1223 .collect::<Vec<_>>();
1224
1225 if changed_files.is_empty() {
1226 error_spawn("No changes to commit", window, cx);
1227 return;
1228 }
1229
1230 let stage_task =
1231 active_repository.update(cx, |repo, cx| repo.stage_entries(changed_files, cx));
1232 cx.spawn(|_, mut cx| async move {
1233 stage_task.await?;
1234 let commit_task = active_repository
1235 .update(&mut cx, |repo, _| repo.commit(message.into(), None))?;
1236 commit_task.await?
1237 })
1238 };
1239 let task = cx.spawn_in(window, |this, mut cx| async move {
1240 let result = task.await;
1241 this.update_in(&mut cx, |this, window, cx| {
1242 this.pending_commit.take();
1243 match result {
1244 Ok(()) => {
1245 this.commit_editor
1246 .update(cx, |editor, cx| editor.clear(window, cx));
1247 }
1248 Err(e) => this.show_err_toast(e, cx),
1249 }
1250 })
1251 .ok();
1252 });
1253
1254 self.pending_commit = Some(task);
1255 }
1256
1257 fn uncommit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1258 let Some(repo) = self.active_repository.clone() else {
1259 return;
1260 };
1261
1262 // TODO: Use git merge-base to find the upstream and main branch split
1263 let confirmation = Task::ready(true);
1264 // let confirmation = if self.commit_editor.read(cx).is_empty(cx) {
1265 // Task::ready(true)
1266 // } else {
1267 // let prompt = window.prompt(
1268 // PromptLevel::Warning,
1269 // "Uncomitting will replace the current commit message with the previous commit's message",
1270 // None,
1271 // &["Ok", "Cancel"],
1272 // cx,
1273 // );
1274 // cx.spawn(|_, _| async move { prompt.await.is_ok_and(|i| i == 0) })
1275 // };
1276
1277 let prior_head = self.load_commit_details("HEAD", cx);
1278
1279 let task = cx.spawn_in(window, |this, mut cx| async move {
1280 let result = maybe!(async {
1281 if !confirmation.await {
1282 Ok(None)
1283 } else {
1284 let prior_head = prior_head.await?;
1285
1286 repo.update(&mut cx, |repo, _| repo.reset("HEAD^", ResetMode::Soft))?
1287 .await??;
1288
1289 Ok(Some(prior_head))
1290 }
1291 })
1292 .await;
1293
1294 this.update_in(&mut cx, |this, window, cx| {
1295 this.pending_commit.take();
1296 match result {
1297 Ok(None) => {}
1298 Ok(Some(prior_commit)) => {
1299 this.commit_editor.update(cx, |editor, cx| {
1300 editor.set_text(prior_commit.message, window, cx)
1301 });
1302 }
1303 Err(e) => this.show_err_toast(e, cx),
1304 }
1305 })
1306 .ok();
1307 });
1308
1309 self.pending_commit = Some(task);
1310 }
1311
1312 /// Suggests a commit message based on the changed files and their statuses
1313 pub fn suggest_commit_message(&self) -> Option<String> {
1314 if self.total_staged_count() != 1 {
1315 return None;
1316 }
1317
1318 let entry = self
1319 .entries
1320 .iter()
1321 .find(|entry| match entry.status_entry() {
1322 Some(entry) => entry.is_staged.unwrap_or(false),
1323 _ => false,
1324 })?;
1325
1326 let GitListEntry::GitStatusEntry(git_status_entry) = entry.clone() else {
1327 return None;
1328 };
1329
1330 let action_text = if git_status_entry.status.is_deleted() {
1331 Some("Delete")
1332 } else if git_status_entry.status.is_created() {
1333 Some("Create")
1334 } else if git_status_entry.status.is_modified() {
1335 Some("Update")
1336 } else {
1337 None
1338 }?;
1339
1340 let file_name = git_status_entry
1341 .repo_path
1342 .file_name()
1343 .unwrap_or_default()
1344 .to_string_lossy();
1345
1346 Some(format!("{} {}", action_text, file_name))
1347 }
1348
1349 fn update_editor_placeholder(&mut self, cx: &mut Context<Self>) {
1350 let suggested_commit_message = self.suggest_commit_message();
1351 let placeholder_text = suggested_commit_message
1352 .as_deref()
1353 .unwrap_or("Enter commit message");
1354
1355 self.commit_editor.update(cx, |editor, cx| {
1356 editor.set_placeholder_text(Arc::from(placeholder_text), cx)
1357 });
1358
1359 cx.notify();
1360 }
1361
1362 pub(crate) fn fetch(&mut self, _: &git::Fetch, _window: &mut Window, cx: &mut Context<Self>) {
1363 let Some(repo) = self.active_repository.clone() else {
1364 return;
1365 };
1366 let guard = self.start_remote_operation();
1367 let fetch = repo.read(cx).fetch();
1368 cx.spawn(|this, mut cx| async move {
1369 let remote_message = fetch.await?;
1370 drop(guard);
1371 this.update(&mut cx, |this, cx| {
1372 match remote_message {
1373 Ok(remote_message) => {
1374 this.show_remote_output(RemoteAction::Fetch, remote_message, cx);
1375 }
1376 Err(e) => {
1377 this.show_err_toast(e, cx);
1378 }
1379 }
1380
1381 anyhow::Ok(())
1382 })
1383 .ok();
1384 anyhow::Ok(())
1385 })
1386 .detach_and_log_err(cx);
1387 }
1388
1389 pub(crate) fn pull(&mut self, _: &git::Pull, window: &mut Window, cx: &mut Context<Self>) {
1390 let Some(repo) = self.active_repository.clone() else {
1391 return;
1392 };
1393 let Some(branch) = repo.read(cx).current_branch() else {
1394 return;
1395 };
1396 let branch = branch.clone();
1397 let remote = self.get_current_remote(window, cx);
1398 cx.spawn(move |this, mut cx| async move {
1399 let remote = match remote.await {
1400 Ok(Some(remote)) => remote,
1401 Ok(None) => {
1402 return Ok(());
1403 }
1404 Err(e) => {
1405 log::error!("Failed to get current remote: {}", e);
1406 this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1407 .ok();
1408 return Ok(());
1409 }
1410 };
1411
1412 let guard = this
1413 .update(&mut cx, |this, _| this.start_remote_operation())
1414 .ok();
1415
1416 let pull = repo.update(&mut cx, |repo, _cx| {
1417 repo.pull(branch.name.clone(), remote.name.clone())
1418 })?;
1419
1420 let remote_message = pull.await?;
1421 drop(guard);
1422
1423 this.update(&mut cx, |this, cx| match remote_message {
1424 Ok(remote_message) => {
1425 this.show_remote_output(RemoteAction::Pull, remote_message, cx)
1426 }
1427 Err(err) => this.show_err_toast(err, cx),
1428 })
1429 .ok();
1430
1431 anyhow::Ok(())
1432 })
1433 .detach_and_log_err(cx);
1434 }
1435
1436 pub(crate) fn push(&mut self, action: &git::Push, window: &mut Window, cx: &mut Context<Self>) {
1437 let Some(repo) = self.active_repository.clone() else {
1438 return;
1439 };
1440 let Some(branch) = repo.read(cx).current_branch() else {
1441 return;
1442 };
1443 let branch = branch.clone();
1444 let options = action.options;
1445 let remote = self.get_current_remote(window, cx);
1446
1447 cx.spawn(move |this, mut cx| async move {
1448 let remote = match remote.await {
1449 Ok(Some(remote)) => remote,
1450 Ok(None) => {
1451 return Ok(());
1452 }
1453 Err(e) => {
1454 log::error!("Failed to get current remote: {}", e);
1455 this.update(&mut cx, |this, cx| this.show_err_toast(e, cx))
1456 .ok();
1457 return Ok(());
1458 }
1459 };
1460
1461 let guard = this
1462 .update(&mut cx, |this, _| this.start_remote_operation())
1463 .ok();
1464
1465 let push = repo.update(&mut cx, |repo, _cx| {
1466 repo.push(branch.name.clone(), remote.name.clone(), options)
1467 })?;
1468
1469 let remote_output = push.await?;
1470
1471 drop(guard);
1472
1473 this.update(&mut cx, |this, cx| match remote_output {
1474 Ok(remote_message) => {
1475 this.show_remote_output(RemoteAction::Push(remote), remote_message, cx);
1476 }
1477 Err(e) => {
1478 this.show_err_toast(e, cx);
1479 }
1480 })?;
1481
1482 anyhow::Ok(())
1483 })
1484 .detach_and_log_err(cx);
1485 }
1486
1487 fn get_current_remote(
1488 &mut self,
1489 window: &mut Window,
1490 cx: &mut Context<Self>,
1491 ) -> impl Future<Output = Result<Option<Remote>>> {
1492 let repo = self.active_repository.clone();
1493 let workspace = self.workspace.clone();
1494 let mut cx = window.to_async(cx);
1495
1496 async move {
1497 let Some(repo) = repo else {
1498 return Err(anyhow::anyhow!("No active repository"));
1499 };
1500
1501 let mut current_remotes: Vec<Remote> = repo
1502 .update(&mut cx, |repo, _| {
1503 let Some(current_branch) = repo.current_branch() else {
1504 return Err(anyhow::anyhow!("No active branch"));
1505 };
1506
1507 Ok(repo.get_remotes(Some(current_branch.name.to_string())))
1508 })??
1509 .await??;
1510
1511 if current_remotes.len() == 0 {
1512 return Err(anyhow::anyhow!("No active remote"));
1513 } else if current_remotes.len() == 1 {
1514 return Ok(Some(current_remotes.pop().unwrap()));
1515 } else {
1516 let current_remotes: Vec<_> = current_remotes
1517 .into_iter()
1518 .map(|remotes| remotes.name)
1519 .collect();
1520 let selection = cx
1521 .update(|window, cx| {
1522 picker_prompt::prompt(
1523 "Pick which remote to push to",
1524 current_remotes.clone(),
1525 workspace,
1526 window,
1527 cx,
1528 )
1529 })?
1530 .await?;
1531
1532 Ok(selection.map(|selection| Remote {
1533 name: current_remotes[selection].clone(),
1534 }))
1535 }
1536 }
1537 }
1538
1539 fn potential_co_authors(&self, cx: &App) -> Vec<(String, String)> {
1540 let mut new_co_authors = Vec::new();
1541 let project = self.project.read(cx);
1542
1543 let Some(room) = self
1544 .workspace
1545 .upgrade()
1546 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1547 else {
1548 return Vec::default();
1549 };
1550
1551 let room = room.read(cx);
1552
1553 for (peer_id, collaborator) in project.collaborators() {
1554 if collaborator.is_host {
1555 continue;
1556 }
1557
1558 let Some(participant) = room.remote_participant_for_peer_id(*peer_id) else {
1559 continue;
1560 };
1561 if participant.can_write() && participant.user.email.is_some() {
1562 let email = participant.user.email.clone().unwrap();
1563
1564 new_co_authors.push((
1565 participant
1566 .user
1567 .name
1568 .clone()
1569 .unwrap_or_else(|| participant.user.github_login.clone()),
1570 email,
1571 ))
1572 }
1573 }
1574 if !project.is_local() && !project.is_read_only(cx) {
1575 if let Some(user) = room.local_participant_user(cx) {
1576 if let Some(email) = user.email.clone() {
1577 new_co_authors.push((
1578 user.name
1579 .clone()
1580 .unwrap_or_else(|| user.github_login.clone()),
1581 email.clone(),
1582 ))
1583 }
1584 }
1585 }
1586 new_co_authors
1587 }
1588
1589 fn toggle_fill_co_authors(
1590 &mut self,
1591 _: &ToggleFillCoAuthors,
1592 _: &mut Window,
1593 cx: &mut Context<Self>,
1594 ) {
1595 self.add_coauthors = !self.add_coauthors;
1596 cx.notify();
1597 }
1598
1599 fn fill_co_authors(&mut self, message: &mut String, cx: &mut Context<Self>) {
1600 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
1601
1602 let existing_text = message.to_ascii_lowercase();
1603 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
1604 let mut ends_with_co_authors = false;
1605 let existing_co_authors = existing_text
1606 .lines()
1607 .filter_map(|line| {
1608 let line = line.trim();
1609 if line.starts_with(&lowercase_co_author_prefix) {
1610 ends_with_co_authors = true;
1611 Some(line)
1612 } else {
1613 ends_with_co_authors = false;
1614 None
1615 }
1616 })
1617 .collect::<HashSet<_>>();
1618
1619 let new_co_authors = self
1620 .potential_co_authors(cx)
1621 .into_iter()
1622 .filter(|(_, email)| {
1623 !existing_co_authors
1624 .iter()
1625 .any(|existing| existing.contains(email.as_str()))
1626 })
1627 .collect::<Vec<_>>();
1628
1629 if new_co_authors.is_empty() {
1630 return;
1631 }
1632
1633 if !ends_with_co_authors {
1634 message.push('\n');
1635 }
1636 for (name, email) in new_co_authors {
1637 message.push('\n');
1638 message.push_str(CO_AUTHOR_PREFIX);
1639 message.push_str(&name);
1640 message.push_str(" <");
1641 message.push_str(&email);
1642 message.push('>');
1643 }
1644 message.push('\n');
1645 }
1646
1647 fn schedule_update(
1648 &mut self,
1649 clear_pending: bool,
1650 window: &mut Window,
1651 cx: &mut Context<Self>,
1652 ) {
1653 let handle = cx.entity().downgrade();
1654 self.reopen_commit_buffer(window, cx);
1655 self.update_visible_entries_task = cx.spawn_in(window, |_, mut cx| async move {
1656 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
1657 if let Some(git_panel) = handle.upgrade() {
1658 git_panel
1659 .update_in(&mut cx, |git_panel, _, cx| {
1660 if clear_pending {
1661 git_panel.clear_pending();
1662 }
1663 git_panel.update_visible_entries(cx);
1664 git_panel.update_editor_placeholder(cx);
1665 })
1666 .ok();
1667 }
1668 });
1669 }
1670
1671 fn reopen_commit_buffer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1672 let Some(active_repo) = self.active_repository.as_ref() else {
1673 return;
1674 };
1675 let load_buffer = active_repo.update(cx, |active_repo, cx| {
1676 let project = self.project.read(cx);
1677 active_repo.open_commit_buffer(
1678 Some(project.languages().clone()),
1679 project.buffer_store().clone(),
1680 cx,
1681 )
1682 });
1683
1684 cx.spawn_in(window, |git_panel, mut cx| async move {
1685 let buffer = load_buffer.await?;
1686 git_panel.update_in(&mut cx, |git_panel, window, cx| {
1687 if git_panel
1688 .commit_editor
1689 .read(cx)
1690 .buffer()
1691 .read(cx)
1692 .as_singleton()
1693 .as_ref()
1694 != Some(&buffer)
1695 {
1696 git_panel.commit_editor = cx.new(|cx| {
1697 commit_message_editor(
1698 buffer,
1699 git_panel.suggest_commit_message().as_deref(),
1700 git_panel.project.clone(),
1701 true,
1702 window,
1703 cx,
1704 )
1705 });
1706 }
1707 })
1708 })
1709 .detach_and_log_err(cx);
1710 }
1711
1712 fn clear_pending(&mut self) {
1713 self.pending.retain(|v| !v.finished)
1714 }
1715
1716 fn update_visible_entries(&mut self, cx: &mut Context<Self>) {
1717 self.entries.clear();
1718 let mut changed_entries = Vec::new();
1719 let mut new_entries = Vec::new();
1720 let mut conflict_entries = Vec::new();
1721
1722 let Some(repo) = self.active_repository.as_ref() else {
1723 // Just clear entries if no repository is active.
1724 cx.notify();
1725 return;
1726 };
1727
1728 // First pass - collect all paths
1729 let repo = repo.read(cx);
1730
1731 // Second pass - create entries with proper depth calculation
1732 for entry in repo.status() {
1733 let is_conflict = repo.has_conflict(&entry.repo_path);
1734 let is_new = entry.status.is_created();
1735 let is_staged = entry.status.is_staged();
1736
1737 if self.pending.iter().any(|pending| {
1738 pending.target_status == TargetStatus::Reverted
1739 && !pending.finished
1740 && pending.repo_paths.contains(&entry.repo_path)
1741 }) {
1742 continue;
1743 }
1744
1745 let entry = GitStatusEntry {
1746 repo_path: entry.repo_path.clone(),
1747 status: entry.status,
1748 is_staged,
1749 };
1750
1751 if is_conflict {
1752 conflict_entries.push(entry);
1753 } else if is_new {
1754 new_entries.push(entry);
1755 } else {
1756 changed_entries.push(entry);
1757 }
1758 }
1759
1760 if conflict_entries.len() > 0 {
1761 self.entries.push(GitListEntry::Header(GitHeaderEntry {
1762 header: Section::Conflict,
1763 }));
1764 self.entries.extend(
1765 conflict_entries
1766 .into_iter()
1767 .map(GitListEntry::GitStatusEntry),
1768 );
1769 }
1770
1771 if changed_entries.len() > 0 {
1772 self.entries.push(GitListEntry::Header(GitHeaderEntry {
1773 header: Section::Tracked,
1774 }));
1775 self.entries.extend(
1776 changed_entries
1777 .into_iter()
1778 .map(GitListEntry::GitStatusEntry),
1779 );
1780 }
1781 if new_entries.len() > 0 {
1782 self.entries.push(GitListEntry::Header(GitHeaderEntry {
1783 header: Section::New,
1784 }));
1785 self.entries
1786 .extend(new_entries.into_iter().map(GitListEntry::GitStatusEntry));
1787 }
1788
1789 self.update_counts(repo);
1790
1791 self.select_first_entry_if_none(cx);
1792
1793 cx.notify();
1794 }
1795
1796 fn header_state(&self, header_type: Section) -> ToggleState {
1797 let (staged_count, count) = match header_type {
1798 Section::New => (self.new_staged_count, self.new_count),
1799 Section::Tracked => (self.tracked_staged_count, self.tracked_count),
1800 Section::Conflict => (self.conflicted_staged_count, self.conflicted_count),
1801 };
1802 if staged_count == 0 {
1803 ToggleState::Unselected
1804 } else if count == staged_count {
1805 ToggleState::Selected
1806 } else {
1807 ToggleState::Indeterminate
1808 }
1809 }
1810
1811 fn update_counts(&mut self, repo: &Repository) {
1812 self.conflicted_count = 0;
1813 self.conflicted_staged_count = 0;
1814 self.new_count = 0;
1815 self.tracked_count = 0;
1816 self.new_staged_count = 0;
1817 self.tracked_staged_count = 0;
1818 for entry in &self.entries {
1819 let Some(status_entry) = entry.status_entry() else {
1820 continue;
1821 };
1822 if repo.has_conflict(&status_entry.repo_path) {
1823 self.conflicted_count += 1;
1824 if self.entry_is_staged(status_entry) != Some(false) {
1825 self.conflicted_staged_count += 1;
1826 }
1827 } else if status_entry.status.is_created() {
1828 self.new_count += 1;
1829 if self.entry_is_staged(status_entry) != Some(false) {
1830 self.new_staged_count += 1;
1831 }
1832 } else {
1833 self.tracked_count += 1;
1834 if self.entry_is_staged(status_entry) != Some(false) {
1835 self.tracked_staged_count += 1;
1836 }
1837 }
1838 }
1839 }
1840
1841 fn entry_is_staged(&self, entry: &GitStatusEntry) -> Option<bool> {
1842 for pending in self.pending.iter().rev() {
1843 if pending.repo_paths.contains(&entry.repo_path) {
1844 match pending.target_status {
1845 TargetStatus::Staged => return Some(true),
1846 TargetStatus::Unstaged => return Some(false),
1847 TargetStatus::Reverted => continue,
1848 TargetStatus::Unchanged => continue,
1849 }
1850 }
1851 }
1852 entry.is_staged
1853 }
1854
1855 pub(crate) fn has_staged_changes(&self) -> bool {
1856 self.tracked_staged_count > 0
1857 || self.new_staged_count > 0
1858 || self.conflicted_staged_count > 0
1859 }
1860
1861 pub(crate) fn has_unstaged_changes(&self) -> bool {
1862 self.tracked_count > self.tracked_staged_count
1863 || self.new_count > self.new_staged_count
1864 || self.conflicted_count > self.conflicted_staged_count
1865 }
1866
1867 fn has_conflicts(&self) -> bool {
1868 self.conflicted_count > 0
1869 }
1870
1871 fn has_tracked_changes(&self) -> bool {
1872 self.tracked_count > 0
1873 }
1874
1875 pub fn has_unstaged_conflicts(&self) -> bool {
1876 self.conflicted_count > 0 && self.conflicted_count != self.conflicted_staged_count
1877 }
1878
1879 fn show_err_toast(&self, e: anyhow::Error, cx: &mut App) {
1880 let Some(workspace) = self.workspace.upgrade() else {
1881 return;
1882 };
1883 let notif_id = NotificationId::Named("git-operation-error".into());
1884
1885 let mut message = e.to_string().trim().to_string();
1886 let toast;
1887 if message.matches("Authentication failed").count() >= 1 {
1888 message = format!(
1889 "{}\n\n{}",
1890 message, "Please set your credentials via the CLI"
1891 );
1892 toast = Toast::new(notif_id, message);
1893 } else {
1894 toast = Toast::new(notif_id, message).on_click("Open Zed Log", |window, cx| {
1895 window.dispatch_action(workspace::OpenLog.boxed_clone(), cx);
1896 });
1897 }
1898 workspace.update(cx, |workspace, cx| {
1899 workspace.show_toast(toast, cx);
1900 });
1901 }
1902
1903 fn show_remote_output(&self, action: RemoteAction, info: RemoteCommandOutput, cx: &mut App) {
1904 let Some(workspace) = self.workspace.upgrade() else {
1905 return;
1906 };
1907
1908 let notification_id = NotificationId::Named("git-remote-info".into());
1909
1910 workspace.update(cx, |workspace, cx| {
1911 workspace.show_notification(notification_id.clone(), cx, |cx| {
1912 let workspace = cx.weak_entity();
1913 cx.new(|cx| RemoteOutputToast::new(action, info, notification_id, workspace, cx))
1914 });
1915 });
1916 }
1917
1918 pub fn render_spinner(&self) -> Option<impl IntoElement> {
1919 (!self.pending_remote_operations.borrow().is_empty()).then(|| {
1920 Icon::new(IconName::ArrowCircle)
1921 .size(IconSize::XSmall)
1922 .color(Color::Info)
1923 .with_animation(
1924 "arrow-circle",
1925 Animation::new(Duration::from_secs(2)).repeat(),
1926 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
1927 )
1928 .into_any_element()
1929 })
1930 }
1931
1932 pub fn can_commit(&self) -> bool {
1933 (self.has_staged_changes() || self.has_tracked_changes()) && !self.has_unstaged_conflicts()
1934 }
1935
1936 pub fn can_stage_all(&self) -> bool {
1937 self.has_unstaged_changes()
1938 }
1939
1940 pub fn can_unstage_all(&self) -> bool {
1941 self.has_staged_changes()
1942 }
1943
1944 pub(crate) fn render_co_authors(&self, cx: &Context<Self>) -> Option<AnyElement> {
1945 let potential_co_authors = self.potential_co_authors(cx);
1946 if potential_co_authors.is_empty() {
1947 None
1948 } else {
1949 Some(
1950 IconButton::new("co-authors", IconName::Person)
1951 .icon_color(Color::Disabled)
1952 .selected_icon_color(Color::Selected)
1953 .toggle_state(self.add_coauthors)
1954 .tooltip(move |_, cx| {
1955 let title = format!(
1956 "Add co-authored-by:{}{}",
1957 if potential_co_authors.len() == 1 {
1958 ""
1959 } else {
1960 "\n"
1961 },
1962 potential_co_authors
1963 .iter()
1964 .map(|(name, email)| format!(" {} <{}>", name, email))
1965 .join("\n")
1966 );
1967 Tooltip::simple(title, cx)
1968 })
1969 .on_click(cx.listener(|this, _, _, cx| {
1970 this.add_coauthors = !this.add_coauthors;
1971 cx.notify();
1972 }))
1973 .into_any_element(),
1974 )
1975 }
1976 }
1977
1978 pub fn configure_commit_button(&self, cx: &mut Context<Self>) -> (bool, &'static str) {
1979 if self.has_unstaged_conflicts() {
1980 (false, "You must resolve conflicts before committing")
1981 } else if !self.has_staged_changes() && !self.has_tracked_changes() {
1982 (
1983 false,
1984 "You must have either staged changes or tracked files to commit",
1985 )
1986 } else if self.pending_commit.is_some() {
1987 (false, "Commit in progress")
1988 } else if self.custom_or_suggested_commit_message(cx).is_none() {
1989 (false, "No commit message")
1990 } else if !self.has_write_access(cx) {
1991 (false, "You do not have write access to this project")
1992 } else {
1993 (true, self.commit_button_title())
1994 }
1995 }
1996
1997 pub fn commit_button_title(&self) -> &'static str {
1998 if self.has_staged_changes() {
1999 "Commit"
2000 } else {
2001 "Commit Tracked"
2002 }
2003 }
2004
2005 pub fn render_footer(
2006 &self,
2007 window: &mut Window,
2008 cx: &mut Context<Self>,
2009 ) -> Option<impl IntoElement> {
2010 let active_repository = self.active_repository.clone()?;
2011 let (can_commit, tooltip) = self.configure_commit_button(cx);
2012 let project = self.project.clone().read(cx);
2013 let panel_editor_style = panel_editor_style(true, window, cx);
2014
2015 let enable_coauthors = self.render_co_authors(cx);
2016
2017 let title = self.commit_button_title();
2018 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2019
2020 let branch = active_repository.read(cx).current_branch().cloned();
2021
2022 let footer_size = px(32.);
2023 let gap = px(8.0);
2024
2025 let max_height = window.line_height() * 5. + gap + footer_size;
2026
2027 let expand_button_size = px(16.);
2028
2029 let git_panel = cx.entity().clone();
2030 let display_name = SharedString::from(Arc::from(
2031 active_repository
2032 .read(cx)
2033 .display_name(project, cx)
2034 .trim_end_matches("/"),
2035 ));
2036
2037 let footer = v_flex()
2038 .child(PanelRepoFooter::new(
2039 "footer-button",
2040 display_name,
2041 branch,
2042 Some(git_panel),
2043 ))
2044 .child(
2045 panel_editor_container(window, cx)
2046 .id("commit-editor-container")
2047 .relative()
2048 .h(max_height)
2049 // .w_full()
2050 // .border_t_1()
2051 // .border_color(cx.theme().colors().border)
2052 .bg(cx.theme().colors().editor_background)
2053 .cursor_text()
2054 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2055 window.focus(&this.commit_editor.focus_handle(cx));
2056 }))
2057 .child(
2058 h_flex()
2059 .id("commit-footer")
2060 .absolute()
2061 .bottom_0()
2062 .right_2()
2063 .h(footer_size)
2064 .flex_none()
2065 .children(enable_coauthors)
2066 .child(
2067 panel_filled_button(title)
2068 .tooltip(move |window, cx| {
2069 if can_commit {
2070 Tooltip::for_action_in(
2071 tooltip,
2072 &Commit,
2073 &editor_focus_handle,
2074 window,
2075 cx,
2076 )
2077 } else {
2078 Tooltip::simple(tooltip, cx)
2079 }
2080 })
2081 .disabled(!can_commit || self.modal_open)
2082 .on_click({
2083 cx.listener(move |this, _: &ClickEvent, window, cx| {
2084 this.commit_changes(window, cx)
2085 })
2086 }),
2087 ),
2088 )
2089 // .when(!self.modal_open, |el| {
2090 .child(EditorElement::new(&self.commit_editor, panel_editor_style))
2091 .child(
2092 div()
2093 .absolute()
2094 .top_1()
2095 .right_2()
2096 .opacity(0.5)
2097 .hover(|this| this.opacity(1.0))
2098 .w(expand_button_size)
2099 .child(
2100 panel_icon_button("expand-commit-editor", IconName::Maximize)
2101 .icon_size(IconSize::Small)
2102 .style(ButtonStyle::Transparent)
2103 .width(expand_button_size.into())
2104 .on_click(cx.listener({
2105 move |_, _, window, cx| {
2106 window.dispatch_action(
2107 git::ShowCommitEditor.boxed_clone(),
2108 cx,
2109 )
2110 }
2111 })),
2112 ),
2113 ),
2114 );
2115
2116 Some(footer)
2117 }
2118
2119 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2120 let active_repository = self.active_repository.as_ref()?;
2121 let branch = active_repository.read(cx).current_branch()?;
2122 let commit = branch.most_recent_commit.as_ref()?.clone();
2123
2124 let this = cx.entity();
2125 Some(
2126 h_flex()
2127 .items_center()
2128 .py_2()
2129 .px(px(8.))
2130 // .bg(cx.theme().colors().background)
2131 // .border_t_1()
2132 .border_color(cx.theme().colors().border)
2133 .gap_1p5()
2134 .child(
2135 div()
2136 .flex_grow()
2137 .overflow_hidden()
2138 .max_w(relative(0.6))
2139 .h_full()
2140 .child(
2141 Label::new(commit.subject.clone())
2142 .size(LabelSize::Small)
2143 .truncate(),
2144 )
2145 .id("commit-msg-hover")
2146 .hoverable_tooltip(move |window, cx| {
2147 GitPanelMessageTooltip::new(
2148 this.clone(),
2149 commit.sha.clone(),
2150 window,
2151 cx,
2152 )
2153 .into()
2154 }),
2155 )
2156 .child(div().flex_1())
2157 .child(
2158 panel_icon_button("undo", IconName::Undo)
2159 .icon_size(IconSize::Small)
2160 .icon_color(Color::Muted)
2161 .tooltip(Tooltip::for_action_title(
2162 if self.has_staged_changes() {
2163 "git reset HEAD^ --soft"
2164 } else {
2165 "git reset HEAD^"
2166 },
2167 &git::Uncommit,
2168 ))
2169 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2170 ),
2171 )
2172 }
2173
2174 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2175 h_flex()
2176 .h_full()
2177 .flex_grow()
2178 .justify_center()
2179 .items_center()
2180 .child(
2181 v_flex()
2182 .gap_3()
2183 .child(if self.active_repository.is_some() {
2184 "No changes to commit"
2185 } else {
2186 "No Git repositories"
2187 })
2188 .text_ui_sm(cx)
2189 .mx_auto()
2190 .text_color(Color::Placeholder.color(cx)),
2191 )
2192 }
2193
2194 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2195 let scroll_bar_style = self.show_scrollbar(cx);
2196 let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2197
2198 if !self.should_show_scrollbar(cx)
2199 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2200 {
2201 return None;
2202 }
2203
2204 Some(
2205 div()
2206 .id("git-panel-vertical-scroll")
2207 .occlude()
2208 .flex_none()
2209 .h_full()
2210 .cursor_default()
2211 .when(show_container, |this| this.pl_1().px_1p5())
2212 .when(!show_container, |this| {
2213 this.absolute().right_1().top_1().bottom_1().w(px(12.))
2214 })
2215 .on_mouse_move(cx.listener(|_, _, _, cx| {
2216 cx.notify();
2217 cx.stop_propagation()
2218 }))
2219 .on_hover(|_, _, cx| {
2220 cx.stop_propagation();
2221 })
2222 .on_any_mouse_down(|_, _, cx| {
2223 cx.stop_propagation();
2224 })
2225 .on_mouse_up(
2226 MouseButton::Left,
2227 cx.listener(|this, _, window, cx| {
2228 if !this.scrollbar_state.is_dragging()
2229 && !this.focus_handle.contains_focused(window, cx)
2230 {
2231 this.hide_scrollbar(window, cx);
2232 cx.notify();
2233 }
2234
2235 cx.stop_propagation();
2236 }),
2237 )
2238 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2239 cx.notify();
2240 }))
2241 .children(Scrollbar::vertical(
2242 // percentage as f32..end_offset as f32,
2243 self.scrollbar_state.clone(),
2244 )),
2245 )
2246 }
2247
2248 fn render_buffer_header_controls(
2249 &self,
2250 entity: &Entity<Self>,
2251 file: &Arc<dyn File>,
2252 _: &Window,
2253 cx: &App,
2254 ) -> Option<AnyElement> {
2255 let repo = self.active_repository.as_ref()?.read(cx);
2256 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2257 let ix = self.entry_by_path(&repo_path)?;
2258 let entry = self.entries.get(ix)?;
2259
2260 let is_staged = self.entry_is_staged(entry.status_entry()?);
2261
2262 let checkbox = Checkbox::new("stage-file", is_staged.into())
2263 .disabled(!self.has_write_access(cx))
2264 .fill()
2265 .elevation(ElevationIndex::Surface)
2266 .on_click({
2267 let entry = entry.clone();
2268 let git_panel = entity.downgrade();
2269 move |_, window, cx| {
2270 git_panel
2271 .update(cx, |this, cx| {
2272 this.toggle_staged_for_entry(&entry, window, cx);
2273 cx.stop_propagation();
2274 })
2275 .ok();
2276 }
2277 });
2278 Some(
2279 h_flex()
2280 .id("start-slot")
2281 .text_lg()
2282 .child(checkbox)
2283 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2284 // prevent the list item active state triggering when toggling checkbox
2285 cx.stop_propagation();
2286 })
2287 .into_any_element(),
2288 )
2289 }
2290
2291 fn render_entries(
2292 &self,
2293 has_write_access: bool,
2294 _: &Window,
2295 cx: &mut Context<Self>,
2296 ) -> impl IntoElement {
2297 let entry_count = self.entries.len();
2298
2299 h_flex()
2300 .size_full()
2301 .flex_grow()
2302 .overflow_hidden()
2303 .child(
2304 uniform_list(cx.entity().clone(), "entries", entry_count, {
2305 move |this, range, window, cx| {
2306 let mut items = Vec::with_capacity(range.end - range.start);
2307
2308 for ix in range {
2309 match &this.entries.get(ix) {
2310 Some(GitListEntry::GitStatusEntry(entry)) => {
2311 items.push(this.render_entry(
2312 ix,
2313 entry,
2314 has_write_access,
2315 window,
2316 cx,
2317 ));
2318 }
2319 Some(GitListEntry::Header(header)) => {
2320 items.push(this.render_list_header(
2321 ix,
2322 header,
2323 has_write_access,
2324 window,
2325 cx,
2326 ));
2327 }
2328 None => {}
2329 }
2330 }
2331
2332 items
2333 }
2334 })
2335 .size_full()
2336 .with_sizing_behavior(ListSizingBehavior::Auto)
2337 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2338 .track_scroll(self.scroll_handle.clone()),
2339 )
2340 .on_mouse_down(
2341 MouseButton::Right,
2342 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2343 this.deploy_panel_context_menu(event.position, window, cx)
2344 }),
2345 )
2346 .children(self.render_scrollbar(cx))
2347 }
2348
2349 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2350 Label::new(label.into()).color(color).single_line()
2351 }
2352
2353 fn list_item_height(&self) -> Rems {
2354 rems(1.75)
2355 }
2356
2357 fn render_list_header(
2358 &self,
2359 ix: usize,
2360 header: &GitHeaderEntry,
2361 _: bool,
2362 _: &Window,
2363 _: &Context<Self>,
2364 ) -> AnyElement {
2365 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2366
2367 h_flex()
2368 .id(id)
2369 .h(self.list_item_height())
2370 .w_full()
2371 .items_end()
2372 .px(rems(0.75)) // ~12px
2373 .pb(rems(0.3125)) // ~ 5px
2374 .child(
2375 Label::new(header.title())
2376 .color(Color::Muted)
2377 .size(LabelSize::Small)
2378 .line_height_style(LineHeightStyle::UiLabel)
2379 .single_line(),
2380 )
2381 .into_any_element()
2382 }
2383
2384 fn load_commit_details(
2385 &self,
2386 sha: &str,
2387 cx: &mut Context<Self>,
2388 ) -> Task<Result<CommitDetails>> {
2389 let Some(repo) = self.active_repository.clone() else {
2390 return Task::ready(Err(anyhow::anyhow!("no active repo")));
2391 };
2392 repo.update(cx, |repo, cx| {
2393 let show = repo.show(sha);
2394 cx.spawn(|_, _| async move { show.await? })
2395 })
2396 }
2397
2398 fn deploy_entry_context_menu(
2399 &mut self,
2400 position: Point<Pixels>,
2401 ix: usize,
2402 window: &mut Window,
2403 cx: &mut Context<Self>,
2404 ) {
2405 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2406 return;
2407 };
2408 let stage_title = if entry.status.is_staged() == Some(true) {
2409 "Unstage File"
2410 } else {
2411 "Stage File"
2412 };
2413 let restore_title = if entry.status.is_created() {
2414 "Trash File"
2415 } else {
2416 "Restore File"
2417 };
2418 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2419 context_menu
2420 .action(stage_title, ToggleStaged.boxed_clone())
2421 .action(restore_title, git::RestoreFile.boxed_clone())
2422 .separator()
2423 .action("Open Diff", Confirm.boxed_clone())
2424 .action("Open File", SecondaryConfirm.boxed_clone())
2425 });
2426 self.selected_entry = Some(ix);
2427 self.set_context_menu(context_menu, position, window, cx);
2428 }
2429
2430 fn deploy_panel_context_menu(
2431 &mut self,
2432 position: Point<Pixels>,
2433 window: &mut Window,
2434 cx: &mut Context<Self>,
2435 ) {
2436 let context_menu = git_panel_context_menu(window, cx);
2437 self.set_context_menu(context_menu, position, window, cx);
2438 }
2439
2440 fn set_context_menu(
2441 &mut self,
2442 context_menu: Entity<ContextMenu>,
2443 position: Point<Pixels>,
2444 window: &Window,
2445 cx: &mut Context<Self>,
2446 ) {
2447 let subscription = cx.subscribe_in(
2448 &context_menu,
2449 window,
2450 |this, _, _: &DismissEvent, window, cx| {
2451 if this.context_menu.as_ref().is_some_and(|context_menu| {
2452 context_menu.0.focus_handle(cx).contains_focused(window, cx)
2453 }) {
2454 cx.focus_self(window);
2455 }
2456 this.context_menu.take();
2457 cx.notify();
2458 },
2459 );
2460 self.context_menu = Some((context_menu, position, subscription));
2461 cx.notify();
2462 }
2463
2464 fn render_entry(
2465 &self,
2466 ix: usize,
2467 entry: &GitStatusEntry,
2468 has_write_access: bool,
2469 window: &Window,
2470 cx: &Context<Self>,
2471 ) -> AnyElement {
2472 let display_name = entry
2473 .repo_path
2474 .file_name()
2475 .map(|name| name.to_string_lossy().into_owned())
2476 .unwrap_or_else(|| entry.repo_path.to_string_lossy().into_owned());
2477
2478 let repo_path = entry.repo_path.clone();
2479 let selected = self.selected_entry == Some(ix);
2480 let marked = self.marked_entries.contains(&ix);
2481 let status_style = GitPanelSettings::get_global(cx).status_style;
2482 let status = entry.status;
2483 let has_conflict = status.is_conflicted();
2484 let is_modified = status.is_modified();
2485 let is_deleted = status.is_deleted();
2486
2487 let label_color = if status_style == StatusStyle::LabelColor {
2488 if has_conflict {
2489 Color::Conflict
2490 } else if is_modified {
2491 Color::Modified
2492 } else if is_deleted {
2493 // We don't want a bunch of red labels in the list
2494 Color::Disabled
2495 } else {
2496 Color::Created
2497 }
2498 } else {
2499 Color::Default
2500 };
2501
2502 let path_color = if status.is_deleted() {
2503 Color::Disabled
2504 } else {
2505 Color::Muted
2506 };
2507
2508 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
2509 let checkbox_wrapper_id: ElementId =
2510 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
2511 let checkbox_id: ElementId =
2512 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
2513
2514 let is_entry_staged = self.entry_is_staged(entry);
2515 let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
2516
2517 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2518 is_staged = ToggleState::Selected;
2519 }
2520
2521 let handle = cx.weak_entity();
2522
2523 let selected_bg_alpha = 0.08;
2524 let marked_bg_alpha = 0.12;
2525 let state_opacity_step = 0.04;
2526
2527 let base_bg = match (selected, marked) {
2528 (true, true) => cx
2529 .theme()
2530 .status()
2531 .info
2532 .alpha(selected_bg_alpha + marked_bg_alpha),
2533 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
2534 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
2535 _ => cx.theme().colors().ghost_element_background,
2536 };
2537
2538 let hover_bg = if selected {
2539 cx.theme()
2540 .status()
2541 .info
2542 .alpha(selected_bg_alpha + state_opacity_step)
2543 } else {
2544 cx.theme().colors().ghost_element_hover
2545 };
2546
2547 let active_bg = if selected {
2548 cx.theme()
2549 .status()
2550 .info
2551 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
2552 } else {
2553 cx.theme().colors().ghost_element_active
2554 };
2555
2556 h_flex()
2557 .id(id)
2558 .h(self.list_item_height())
2559 .w_full()
2560 .items_center()
2561 .border_1()
2562 .when(selected && self.focus_handle.is_focused(window), |el| {
2563 el.border_color(cx.theme().colors().border_focused)
2564 })
2565 .px(rems(0.75)) // ~12px
2566 .overflow_hidden()
2567 .flex_none()
2568 .gap(DynamicSpacing::Base04.rems(cx))
2569 .bg(base_bg)
2570 .hover(|this| this.bg(hover_bg))
2571 .active(|this| this.bg(active_bg))
2572 .on_click({
2573 cx.listener(move |this, event: &ClickEvent, window, cx| {
2574 this.selected_entry = Some(ix);
2575 cx.notify();
2576 if event.modifiers().secondary() {
2577 this.open_file(&Default::default(), window, cx)
2578 } else {
2579 this.open_diff(&Default::default(), window, cx);
2580 this.focus_handle.focus(window);
2581 }
2582 })
2583 })
2584 .on_mouse_down(
2585 MouseButton::Right,
2586 move |event: &MouseDownEvent, window, cx| {
2587 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
2588 if event.button != MouseButton::Right {
2589 return;
2590 }
2591
2592 let Some(this) = handle.upgrade() else {
2593 return;
2594 };
2595 this.update(cx, |this, cx| {
2596 this.deploy_entry_context_menu(event.position, ix, window, cx);
2597 });
2598 cx.stop_propagation();
2599 },
2600 )
2601 // .on_secondary_mouse_down(cx.listener(
2602 // move |this, event: &MouseDownEvent, window, cx| {
2603 // this.deploy_entry_context_menu(event.position, ix, window, cx);
2604 // cx.stop_propagation();
2605 // },
2606 // ))
2607 .child(
2608 div()
2609 .id(checkbox_wrapper_id)
2610 .flex_none()
2611 .occlude()
2612 .cursor_pointer()
2613 .child(
2614 Checkbox::new(checkbox_id, is_staged)
2615 .disabled(!has_write_access)
2616 .fill()
2617 .placeholder(!self.has_staged_changes() && !self.has_conflicts())
2618 .elevation(ElevationIndex::Surface)
2619 .on_click({
2620 let entry = entry.clone();
2621 cx.listener(move |this, _, window, cx| {
2622 if !has_write_access {
2623 return;
2624 }
2625 this.toggle_staged_for_entry(
2626 &GitListEntry::GitStatusEntry(entry.clone()),
2627 window,
2628 cx,
2629 );
2630 cx.stop_propagation();
2631 })
2632 })
2633 .tooltip(move |window, cx| {
2634 let tooltip_name = if is_entry_staged.unwrap_or(false) {
2635 "Unstage"
2636 } else {
2637 "Stage"
2638 };
2639
2640 Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
2641 }),
2642 ),
2643 )
2644 .child(git_status_icon(status, cx))
2645 .child(
2646 h_flex()
2647 .items_center()
2648 .overflow_hidden()
2649 .when_some(repo_path.parent(), |this, parent| {
2650 let parent_str = parent.to_string_lossy();
2651 if !parent_str.is_empty() {
2652 this.child(
2653 self.entry_label(format!("{}/", parent_str), path_color)
2654 .when(status.is_deleted(), |this| this.strikethrough()),
2655 )
2656 } else {
2657 this
2658 }
2659 })
2660 .child(
2661 self.entry_label(display_name.clone(), label_color)
2662 .when(status.is_deleted(), |this| this.strikethrough()),
2663 ),
2664 )
2665 .into_any_element()
2666 }
2667
2668 fn has_write_access(&self, cx: &App) -> bool {
2669 !self.project.read(cx).is_read_only(cx)
2670 }
2671}
2672
2673impl Render for GitPanel {
2674 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2675 let project = self.project.read(cx);
2676 let has_entries = self.entries.len() > 0;
2677 let room = self
2678 .workspace
2679 .upgrade()
2680 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
2681
2682 let has_write_access = self.has_write_access(cx);
2683
2684 let has_co_authors = room.map_or(false, |room| {
2685 room.read(cx)
2686 .remote_participants()
2687 .values()
2688 .any(|remote_participant| remote_participant.can_write())
2689 });
2690
2691 v_flex()
2692 .id("git_panel")
2693 .key_context(self.dispatch_context(window, cx))
2694 .track_focus(&self.focus_handle)
2695 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
2696 .when(has_write_access && !project.is_read_only(cx), |this| {
2697 this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
2698 this.toggle_staged_for_selected(&ToggleStaged, window, cx)
2699 }))
2700 .on_action(cx.listener(GitPanel::commit))
2701 })
2702 .on_action(cx.listener(Self::select_first))
2703 .on_action(cx.listener(Self::select_next))
2704 .on_action(cx.listener(Self::select_previous))
2705 .on_action(cx.listener(Self::select_last))
2706 .on_action(cx.listener(Self::close_panel))
2707 .on_action(cx.listener(Self::open_diff))
2708 .on_action(cx.listener(Self::open_file))
2709 .on_action(cx.listener(Self::revert_selected))
2710 .on_action(cx.listener(Self::focus_changes_list))
2711 .on_action(cx.listener(Self::focus_editor))
2712 .on_action(cx.listener(Self::toggle_staged_for_selected))
2713 .on_action(cx.listener(Self::stage_all))
2714 .on_action(cx.listener(Self::unstage_all))
2715 .on_action(cx.listener(Self::restore_tracked_files))
2716 .on_action(cx.listener(Self::clean_all))
2717 .when(has_write_access && has_co_authors, |git_panel| {
2718 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
2719 })
2720 // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
2721 .on_hover(cx.listener(|this, hovered, window, cx| {
2722 if *hovered {
2723 this.show_scrollbar = true;
2724 this.hide_scrollbar_task.take();
2725 cx.notify();
2726 } else if !this.focus_handle.contains_focused(window, cx) {
2727 this.hide_scrollbar(window, cx);
2728 }
2729 }))
2730 .size_full()
2731 .overflow_hidden()
2732 .bg(ElevationIndex::Surface.bg(cx))
2733 .child(
2734 v_flex()
2735 .size_full()
2736 .map(|this| {
2737 if has_entries {
2738 this.child(self.render_entries(has_write_access, window, cx))
2739 } else {
2740 this.child(self.render_empty_state(cx).into_any_element())
2741 }
2742 })
2743 .children(self.render_footer(window, cx))
2744 .children(self.render_previous_commit(cx))
2745 .into_any_element(),
2746 )
2747 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
2748 deferred(
2749 anchored()
2750 .position(*position)
2751 .anchor(gpui::Corner::TopLeft)
2752 .child(menu.clone()),
2753 )
2754 .with_priority(1)
2755 }))
2756 }
2757}
2758
2759impl Focusable for GitPanel {
2760 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
2761 self.focus_handle.clone()
2762 }
2763}
2764
2765impl EventEmitter<Event> for GitPanel {}
2766
2767impl EventEmitter<PanelEvent> for GitPanel {}
2768
2769pub(crate) struct GitPanelAddon {
2770 pub(crate) workspace: WeakEntity<Workspace>,
2771}
2772
2773impl editor::Addon for GitPanelAddon {
2774 fn to_any(&self) -> &dyn std::any::Any {
2775 self
2776 }
2777
2778 fn render_buffer_header_controls(
2779 &self,
2780 excerpt_info: &ExcerptInfo,
2781 window: &Window,
2782 cx: &App,
2783 ) -> Option<AnyElement> {
2784 let file = excerpt_info.buffer.file()?;
2785 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
2786
2787 git_panel
2788 .read(cx)
2789 .render_buffer_header_controls(&git_panel, &file, window, cx)
2790 }
2791}
2792
2793impl Panel for GitPanel {
2794 fn persistent_name() -> &'static str {
2795 "GitPanel"
2796 }
2797
2798 fn position(&self, _: &Window, cx: &App) -> DockPosition {
2799 GitPanelSettings::get_global(cx).dock
2800 }
2801
2802 fn position_is_valid(&self, position: DockPosition) -> bool {
2803 matches!(position, DockPosition::Left | DockPosition::Right)
2804 }
2805
2806 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
2807 settings::update_settings_file::<GitPanelSettings>(
2808 self.fs.clone(),
2809 cx,
2810 move |settings, _| settings.dock = Some(position),
2811 );
2812 }
2813
2814 fn size(&self, _: &Window, cx: &App) -> Pixels {
2815 self.width
2816 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
2817 }
2818
2819 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
2820 self.width = size;
2821 self.serialize(cx);
2822 cx.notify();
2823 }
2824
2825 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
2826 Some(ui::IconName::GitBranch).filter(|_| GitPanelSettings::get_global(cx).button)
2827 }
2828
2829 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
2830 Some("Git Panel")
2831 }
2832
2833 fn toggle_action(&self) -> Box<dyn Action> {
2834 Box::new(ToggleFocus)
2835 }
2836
2837 fn activation_priority(&self) -> u32 {
2838 2
2839 }
2840}
2841
2842impl PanelHeader for GitPanel {}
2843
2844struct GitPanelMessageTooltip {
2845 commit_tooltip: Option<Entity<CommitTooltip>>,
2846}
2847
2848impl GitPanelMessageTooltip {
2849 fn new(
2850 git_panel: Entity<GitPanel>,
2851 sha: SharedString,
2852 window: &mut Window,
2853 cx: &mut App,
2854 ) -> Entity<Self> {
2855 cx.new(|cx| {
2856 cx.spawn_in(window, |this, mut cx| async move {
2857 let details = git_panel
2858 .update(&mut cx, |git_panel, cx| {
2859 git_panel.load_commit_details(&sha, cx)
2860 })?
2861 .await?;
2862
2863 let commit_details = editor::commit_tooltip::CommitDetails {
2864 sha: details.sha.clone(),
2865 committer_name: details.committer_name.clone(),
2866 committer_email: details.committer_email.clone(),
2867 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
2868 message: Some(editor::commit_tooltip::ParsedCommitMessage {
2869 message: details.message.clone(),
2870 ..Default::default()
2871 }),
2872 };
2873
2874 this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
2875 this.commit_tooltip =
2876 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
2877 cx.notify();
2878 })
2879 })
2880 .detach();
2881
2882 Self {
2883 commit_tooltip: None,
2884 }
2885 })
2886 }
2887}
2888
2889impl Render for GitPanelMessageTooltip {
2890 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
2891 if let Some(commit_tooltip) = &self.commit_tooltip {
2892 commit_tooltip.clone().into_any_element()
2893 } else {
2894 gpui::Empty.into_any_element()
2895 }
2896 }
2897}
2898
2899fn git_action_tooltip(
2900 label: impl Into<SharedString>,
2901 action: &dyn Action,
2902 command: impl Into<SharedString>,
2903 focus_handle: Option<FocusHandle>,
2904 window: &mut Window,
2905 cx: &mut App,
2906) -> AnyView {
2907 let label = label.into();
2908 let command = command.into();
2909
2910 if let Some(handle) = focus_handle {
2911 Tooltip::with_meta_in(
2912 label.clone(),
2913 Some(action),
2914 command.clone(),
2915 &handle,
2916 window,
2917 cx,
2918 )
2919 } else {
2920 Tooltip::with_meta(label.clone(), Some(action), command.clone(), window, cx)
2921 }
2922}
2923
2924#[derive(IntoElement)]
2925struct SplitButton {
2926 pub left: ButtonLike,
2927 pub right: AnyElement,
2928}
2929
2930impl SplitButton {
2931 fn new(
2932 id: impl Into<SharedString>,
2933 left_label: impl Into<SharedString>,
2934 ahead_count: usize,
2935 behind_count: usize,
2936 left_icon: Option<IconName>,
2937 left_on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
2938 tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
2939 ) -> Self {
2940 let id = id.into();
2941
2942 fn count(count: usize) -> impl IntoElement {
2943 h_flex()
2944 .ml_neg_px()
2945 .h(rems(0.875))
2946 .items_center()
2947 .overflow_hidden()
2948 .px_0p5()
2949 .child(
2950 Label::new(count.to_string())
2951 .size(LabelSize::XSmall)
2952 .line_height_style(LineHeightStyle::UiLabel),
2953 )
2954 }
2955
2956 let should_render_counts = left_icon.is_none() && (ahead_count > 0 || behind_count > 0);
2957
2958 let left = ui::ButtonLike::new_rounded_left(ElementId::Name(
2959 format!("split-button-left-{}", id).into(),
2960 ))
2961 .layer(ui::ElevationIndex::ModalSurface)
2962 .size(ui::ButtonSize::Compact)
2963 .when(should_render_counts, |this| {
2964 this.child(
2965 h_flex()
2966 .ml_neg_0p5()
2967 .mr_1()
2968 .when(behind_count > 0, |this| {
2969 this.child(Icon::new(IconName::ArrowDown).size(IconSize::XSmall))
2970 .child(count(behind_count))
2971 })
2972 .when(ahead_count > 0, |this| {
2973 this.child(Icon::new(IconName::ArrowUp).size(IconSize::XSmall))
2974 .child(count(ahead_count))
2975 }),
2976 )
2977 })
2978 .when_some(left_icon, |this, left_icon| {
2979 this.child(
2980 h_flex()
2981 .ml_neg_0p5()
2982 .mr_1()
2983 .child(Icon::new(left_icon).size(IconSize::XSmall)),
2984 )
2985 })
2986 .child(
2987 div()
2988 .child(Label::new(left_label).size(LabelSize::Small))
2989 .mr_0p5(),
2990 )
2991 .on_click(left_on_click)
2992 .tooltip(tooltip);
2993
2994 let right =
2995 render_git_action_menu(ElementId::Name(format!("split-button-right-{}", id).into()))
2996 .into_any_element();
2997 // .on_click(right_on_click);
2998
2999 Self { left, right }
3000 }
3001}
3002
3003impl RenderOnce for SplitButton {
3004 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3005 h_flex()
3006 .rounded_md()
3007 .border_1()
3008 .border_color(cx.theme().colors().text_muted.alpha(0.12))
3009 .child(self.left)
3010 .child(
3011 div()
3012 .h_full()
3013 .w_px()
3014 .bg(cx.theme().colors().text_muted.alpha(0.16)),
3015 )
3016 .child(self.right)
3017 .bg(ElevationIndex::Surface.on_elevation_bg(cx))
3018 .shadow(smallvec![BoxShadow {
3019 color: hsla(0.0, 0.0, 0.0, 0.16),
3020 offset: point(px(0.), px(1.)),
3021 blur_radius: px(0.),
3022 spread_radius: px(0.),
3023 }])
3024 }
3025}
3026
3027fn render_git_action_menu(id: impl Into<ElementId>) -> impl IntoElement {
3028 PopoverMenu::new(id.into())
3029 .trigger(
3030 ui::ButtonLike::new_rounded_right("split-button-right")
3031 .layer(ui::ElevationIndex::ModalSurface)
3032 .size(ui::ButtonSize::None)
3033 .child(
3034 div()
3035 .px_1()
3036 .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
3037 ),
3038 )
3039 .menu(move |window, cx| {
3040 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3041 context_menu
3042 .action("Fetch", git::Fetch.boxed_clone())
3043 .action("Pull", git::Pull.boxed_clone())
3044 .separator()
3045 .action("Push", git::Push { options: None }.boxed_clone())
3046 .action(
3047 "Force Push",
3048 git::Push {
3049 options: Some(PushOptions::Force),
3050 }
3051 .boxed_clone(),
3052 )
3053 }))
3054 })
3055 .anchor(Corner::TopRight)
3056}
3057
3058#[derive(IntoElement, IntoComponent)]
3059#[component(scope = "git_panel")]
3060pub struct PanelRepoFooter {
3061 id: SharedString,
3062 active_repository: SharedString,
3063 branch: Option<Branch>,
3064 // Getting a GitPanel in previews will be difficult.
3065 //
3066 // For now just take an option here, and we won't bind handlers to buttons in previews.
3067 git_panel: Option<Entity<GitPanel>>,
3068}
3069
3070impl PanelRepoFooter {
3071 pub fn new(
3072 id: impl Into<SharedString>,
3073 active_repository: SharedString,
3074 branch: Option<Branch>,
3075 git_panel: Option<Entity<GitPanel>>,
3076 ) -> Self {
3077 Self {
3078 id: id.into(),
3079 active_repository,
3080 branch,
3081 git_panel,
3082 }
3083 }
3084
3085 pub fn new_preview(
3086 id: impl Into<SharedString>,
3087 active_repository: SharedString,
3088 branch: Option<Branch>,
3089 ) -> Self {
3090 Self {
3091 id: id.into(),
3092 active_repository,
3093 branch,
3094 git_panel: None,
3095 }
3096 }
3097
3098 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3099 PopoverMenu::new(id.into())
3100 .trigger(
3101 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3102 .icon_size(IconSize::Small)
3103 .icon_color(Color::Muted),
3104 )
3105 .menu(move |window, cx| Some(git_panel_context_menu(window, cx)))
3106 .anchor(Corner::TopRight)
3107 }
3108
3109 fn panel_focus_handle(&self, cx: &App) -> Option<FocusHandle> {
3110 if let Some(git_panel) = self.git_panel.clone() {
3111 Some(git_panel.focus_handle(cx))
3112 } else {
3113 None
3114 }
3115 }
3116
3117 fn render_push_button(&self, id: SharedString, ahead: u32, cx: &mut App) -> SplitButton {
3118 let panel = self.git_panel.clone();
3119 let panel_focus_handle = self.panel_focus_handle(cx);
3120
3121 SplitButton::new(
3122 id,
3123 "Push",
3124 ahead as usize,
3125 0,
3126 None,
3127 move |_, window, cx| {
3128 if let Some(panel) = panel.as_ref() {
3129 panel.update(cx, |panel, cx| {
3130 panel.push(&git::Push { options: None }, window, cx);
3131 });
3132 }
3133 },
3134 move |window, cx| {
3135 git_action_tooltip(
3136 "Push committed changes to remote",
3137 &git::Push { options: None },
3138 "git push",
3139 panel_focus_handle.clone(),
3140 window,
3141 cx,
3142 )
3143 },
3144 )
3145 }
3146
3147 fn render_pull_button(
3148 &self,
3149 id: SharedString,
3150 ahead: u32,
3151 behind: u32,
3152 cx: &mut App,
3153 ) -> SplitButton {
3154 let panel = self.git_panel.clone();
3155 let panel_focus_handle = self.panel_focus_handle(cx);
3156
3157 SplitButton::new(
3158 id,
3159 "Pull",
3160 ahead as usize,
3161 behind as usize,
3162 None,
3163 move |_, window, cx| {
3164 if let Some(panel) = panel.as_ref() {
3165 panel.update(cx, |panel, cx| {
3166 panel.pull(&git::Pull, window, cx);
3167 });
3168 }
3169 },
3170 move |window, cx| {
3171 git_action_tooltip(
3172 "Pull",
3173 &git::Pull,
3174 "git pull",
3175 panel_focus_handle.clone(),
3176 window,
3177 cx,
3178 )
3179 },
3180 )
3181 }
3182
3183 fn render_fetch_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3184 let panel = self.git_panel.clone();
3185 let panel_focus_handle = self.panel_focus_handle(cx);
3186
3187 SplitButton::new(
3188 id,
3189 "Fetch",
3190 0,
3191 0,
3192 Some(IconName::ArrowCircle),
3193 move |_, window, cx| {
3194 if let Some(panel) = panel.as_ref() {
3195 panel.update(cx, |panel, cx| {
3196 panel.fetch(&git::Fetch, window, cx);
3197 });
3198 }
3199 },
3200 move |window, cx| {
3201 git_action_tooltip(
3202 "Fetch updates from remote",
3203 &git::Fetch,
3204 "git fetch",
3205 panel_focus_handle.clone(),
3206 window,
3207 cx,
3208 )
3209 },
3210 )
3211 }
3212
3213 fn render_publish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3214 let panel = self.git_panel.clone();
3215 let panel_focus_handle = self.panel_focus_handle(cx);
3216
3217 SplitButton::new(
3218 id,
3219 "Publish",
3220 0,
3221 0,
3222 Some(IconName::ArrowUpFromLine),
3223 move |_, window, cx| {
3224 if let Some(panel) = panel.as_ref() {
3225 panel.update(cx, |panel, cx| {
3226 panel.push(
3227 &git::Push {
3228 options: Some(PushOptions::SetUpstream),
3229 },
3230 window,
3231 cx,
3232 );
3233 });
3234 }
3235 },
3236 move |window, cx| {
3237 git_action_tooltip(
3238 "Publish branch to remote",
3239 &git::Push {
3240 options: Some(PushOptions::SetUpstream),
3241 },
3242 "git push --set-upstream",
3243 panel_focus_handle.clone(),
3244 window,
3245 cx,
3246 )
3247 },
3248 )
3249 }
3250
3251 fn render_republish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3252 let panel = self.git_panel.clone();
3253 let panel_focus_handle = self.panel_focus_handle(cx);
3254
3255 SplitButton::new(
3256 id,
3257 "Republish",
3258 0,
3259 0,
3260 Some(IconName::ArrowUpFromLine),
3261 move |_, window, cx| {
3262 if let Some(panel) = panel.as_ref() {
3263 panel.update(cx, |panel, cx| {
3264 panel.push(
3265 &git::Push {
3266 options: Some(PushOptions::SetUpstream),
3267 },
3268 window,
3269 cx,
3270 );
3271 });
3272 }
3273 },
3274 move |window, cx| {
3275 git_action_tooltip(
3276 "Re-publish branch to remote",
3277 &git::Push {
3278 options: Some(PushOptions::SetUpstream),
3279 },
3280 "git push --set-upstream",
3281 panel_focus_handle.clone(),
3282 window,
3283 cx,
3284 )
3285 },
3286 )
3287 }
3288
3289 fn render_relevant_button(
3290 &self,
3291 id: impl Into<SharedString>,
3292 branch: &Branch,
3293 cx: &mut App,
3294 ) -> impl IntoElement {
3295 let id = id.into();
3296 let upstream = branch.upstream.as_ref();
3297 match upstream {
3298 Some(Upstream {
3299 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus { ahead, behind }),
3300 ..
3301 }) => match (*ahead, *behind) {
3302 (0, 0) => self.render_fetch_button(id, cx),
3303 (ahead, 0) => self.render_push_button(id, ahead, cx),
3304 (ahead, behind) => self.render_pull_button(id, ahead, behind, cx),
3305 },
3306 Some(Upstream {
3307 tracking: UpstreamTracking::Gone,
3308 ..
3309 }) => self.render_republish_button(id, cx),
3310 None => self.render_publish_button(id, cx),
3311 }
3312 }
3313}
3314
3315impl RenderOnce for PanelRepoFooter {
3316 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3317 let active_repo = self.active_repository.clone();
3318 let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3319 let repo_selector_trigger = Button::new("repo-selector", active_repo)
3320 .style(ButtonStyle::Transparent)
3321 .size(ButtonSize::None)
3322 .label_size(LabelSize::Small)
3323 .color(Color::Muted);
3324
3325 let project = self
3326 .git_panel
3327 .as_ref()
3328 .map(|panel| panel.read(cx).project.clone());
3329
3330 let single_repo = project
3331 .as_ref()
3332 .map(|project| project.read(cx).all_repositories(cx).len() == 1)
3333 .unwrap_or(true);
3334
3335 let repo_selector = PopoverMenu::new("repository-switcher")
3336 .menu({
3337 let project = project.clone();
3338 move |window, cx| {
3339 let project = project.clone()?;
3340 Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
3341 }
3342 })
3343 .trigger_with_tooltip(
3344 repo_selector_trigger.disabled(single_repo).truncate(true),
3345 Tooltip::text("Switch active repository"),
3346 )
3347 .attach(gpui::Corner::BottomLeft)
3348 .into_any_element();
3349
3350 let branch = self.branch.clone();
3351 let branch_name = branch
3352 .as_ref()
3353 .map_or(" (no branch)".into(), |branch| branch.name.clone());
3354
3355 let branch_selector_button = Button::new("branch-selector", branch_name)
3356 .style(ButtonStyle::Transparent)
3357 .size(ButtonSize::None)
3358 .label_size(LabelSize::Small)
3359 .truncate(true)
3360 .tooltip(Tooltip::for_action_title(
3361 "Switch Branch",
3362 &zed_actions::git::Branch,
3363 ))
3364 .on_click(|_, window, cx| {
3365 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3366 });
3367
3368 let branch_selector = PopoverMenu::new("popover-button")
3369 .menu(move |window, cx| Some(branch_picker::popover(project.clone()?, window, cx)))
3370 .trigger_with_tooltip(
3371 branch_selector_button,
3372 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3373 )
3374 .anchor(Corner::TopLeft)
3375 .offset(gpui::Point {
3376 x: px(0.0),
3377 y: px(-2.0),
3378 });
3379
3380 let spinner = self
3381 .git_panel
3382 .as_ref()
3383 .and_then(|git_panel| git_panel.read(cx).render_spinner());
3384
3385 h_flex()
3386 .w_full()
3387 .px_2()
3388 .h(px(36.))
3389 .items_center()
3390 .justify_between()
3391 .child(
3392 h_flex()
3393 .flex_1()
3394 .overflow_hidden()
3395 .items_center()
3396 .child(
3397 div().child(
3398 Icon::new(IconName::GitBranchSmall)
3399 .size(IconSize::Small)
3400 .color(Color::Muted),
3401 ),
3402 )
3403 .child(repo_selector)
3404 .when_some(branch.clone(), |this, _| {
3405 this.child(
3406 div()
3407 .text_color(cx.theme().colors().text_muted)
3408 .text_sm()
3409 .child("/"),
3410 )
3411 })
3412 .child(branch_selector),
3413 )
3414 .child(
3415 h_flex()
3416 .gap_1()
3417 .flex_shrink_0()
3418 .children(spinner)
3419 .child(self.render_overflow_menu(overflow_menu_id))
3420 .when_some(branch, |this, branch| {
3421 let button = self.render_relevant_button(self.id.clone(), &branch, cx);
3422 this.child(button)
3423 }),
3424 )
3425 }
3426}
3427
3428impl ComponentPreview for PanelRepoFooter {
3429 fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3430 let unknown_upstream = None;
3431 let no_remote_upstream = Some(UpstreamTracking::Gone);
3432 let ahead_of_upstream = Some(
3433 UpstreamTrackingStatus {
3434 ahead: 2,
3435 behind: 0,
3436 }
3437 .into(),
3438 );
3439 let behind_upstream = Some(
3440 UpstreamTrackingStatus {
3441 ahead: 0,
3442 behind: 2,
3443 }
3444 .into(),
3445 );
3446 let ahead_and_behind_upstream = Some(
3447 UpstreamTrackingStatus {
3448 ahead: 3,
3449 behind: 1,
3450 }
3451 .into(),
3452 );
3453
3454 let not_ahead_or_behind_upstream = Some(
3455 UpstreamTrackingStatus {
3456 ahead: 0,
3457 behind: 0,
3458 }
3459 .into(),
3460 );
3461
3462 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3463 Branch {
3464 is_head: true,
3465 name: "some-branch".into(),
3466 upstream: upstream.map(|tracking| Upstream {
3467 ref_name: "origin/some-branch".into(),
3468 tracking,
3469 }),
3470 most_recent_commit: Some(CommitSummary {
3471 sha: "abc123".into(),
3472 subject: "Modify stuff".into(),
3473 commit_timestamp: 1710932954,
3474 }),
3475 }
3476 }
3477
3478 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3479 Branch {
3480 is_head: true,
3481 name: branch_name.to_string().into(),
3482 upstream: upstream.map(|tracking| Upstream {
3483 ref_name: format!("zed/{}", branch_name).into(),
3484 tracking,
3485 }),
3486 most_recent_commit: Some(CommitSummary {
3487 sha: "abc123".into(),
3488 subject: "Modify stuff".into(),
3489 commit_timestamp: 1710932954,
3490 }),
3491 }
3492 }
3493
3494 fn active_repository(id: usize) -> SharedString {
3495 format!("repo-{}", id).into()
3496 }
3497
3498 let example_width = px(340.);
3499
3500 v_flex()
3501 .gap_6()
3502 .w_full()
3503 .flex_none()
3504 .children(vec![example_group_with_title(
3505 "Action Button States",
3506 vec![
3507 single_example(
3508 "No Branch",
3509 div()
3510 .w(example_width)
3511 .overflow_hidden()
3512 .child(PanelRepoFooter::new_preview(
3513 "no-branch",
3514 active_repository(1).clone(),
3515 None,
3516 ))
3517 .into_any_element(),
3518 )
3519 .grow(),
3520 single_example(
3521 "Remote status unknown",
3522 div()
3523 .w(example_width)
3524 .overflow_hidden()
3525 .child(PanelRepoFooter::new_preview(
3526 "unknown-upstream",
3527 active_repository(2).clone(),
3528 Some(branch(unknown_upstream)),
3529 ))
3530 .into_any_element(),
3531 )
3532 .grow(),
3533 single_example(
3534 "No Remote Upstream",
3535 div()
3536 .w(example_width)
3537 .overflow_hidden()
3538 .child(PanelRepoFooter::new_preview(
3539 "no-remote-upstream",
3540 active_repository(3).clone(),
3541 Some(branch(no_remote_upstream)),
3542 ))
3543 .into_any_element(),
3544 )
3545 .grow(),
3546 single_example(
3547 "Not Ahead or Behind",
3548 div()
3549 .w(example_width)
3550 .overflow_hidden()
3551 .child(PanelRepoFooter::new_preview(
3552 "not-ahead-or-behind",
3553 active_repository(4).clone(),
3554 Some(branch(not_ahead_or_behind_upstream)),
3555 ))
3556 .into_any_element(),
3557 )
3558 .grow(),
3559 single_example(
3560 "Behind remote",
3561 div()
3562 .w(example_width)
3563 .overflow_hidden()
3564 .child(PanelRepoFooter::new_preview(
3565 "behind-remote",
3566 active_repository(5).clone(),
3567 Some(branch(behind_upstream)),
3568 ))
3569 .into_any_element(),
3570 )
3571 .grow(),
3572 single_example(
3573 "Ahead of remote",
3574 div()
3575 .w(example_width)
3576 .overflow_hidden()
3577 .child(PanelRepoFooter::new_preview(
3578 "ahead-of-remote",
3579 active_repository(6).clone(),
3580 Some(branch(ahead_of_upstream)),
3581 ))
3582 .into_any_element(),
3583 )
3584 .grow(),
3585 single_example(
3586 "Ahead and behind remote",
3587 div()
3588 .w(example_width)
3589 .overflow_hidden()
3590 .child(PanelRepoFooter::new_preview(
3591 "ahead-and-behind",
3592 active_repository(7).clone(),
3593 Some(branch(ahead_and_behind_upstream)),
3594 ))
3595 .into_any_element(),
3596 )
3597 .grow(),
3598 ],
3599 )
3600 .grow()
3601 .vertical()])
3602 .children(vec![example_group_with_title(
3603 "Labels",
3604 vec![
3605 single_example(
3606 "Short Branch & Repo",
3607 div()
3608 .w(example_width)
3609 .overflow_hidden()
3610 .child(PanelRepoFooter::new_preview(
3611 "short-branch",
3612 SharedString::from("zed"),
3613 Some(custom("main", behind_upstream)),
3614 ))
3615 .into_any_element(),
3616 )
3617 .grow(),
3618 single_example(
3619 "Long Branch",
3620 div()
3621 .w(example_width)
3622 .overflow_hidden()
3623 .child(PanelRepoFooter::new_preview(
3624 "long-branch",
3625 SharedString::from("zed"),
3626 Some(custom(
3627 "redesign-and-update-git-ui-list-entry-style",
3628 behind_upstream,
3629 )),
3630 ))
3631 .into_any_element(),
3632 )
3633 .grow(),
3634 single_example(
3635 "Long Repo",
3636 div()
3637 .w(example_width)
3638 .overflow_hidden()
3639 .child(PanelRepoFooter::new_preview(
3640 "long-repo",
3641 SharedString::from("zed-industries-community-examples"),
3642 Some(custom("gpui", ahead_of_upstream)),
3643 ))
3644 .into_any_element(),
3645 )
3646 .grow(),
3647 single_example(
3648 "Long Repo & Branch",
3649 div()
3650 .w(example_width)
3651 .overflow_hidden()
3652 .child(PanelRepoFooter::new_preview(
3653 "long-repo-and-branch",
3654 SharedString::from("zed-industries-community-examples"),
3655 Some(custom(
3656 "redesign-and-update-git-ui-list-entry-style",
3657 behind_upstream,
3658 )),
3659 ))
3660 .into_any_element(),
3661 )
3662 .grow(),
3663 single_example(
3664 "Uppercase Repo",
3665 div()
3666 .w(example_width)
3667 .overflow_hidden()
3668 .child(PanelRepoFooter::new_preview(
3669 "uppercase-repo",
3670 SharedString::from("LICENSES"),
3671 Some(custom("main", ahead_of_upstream)),
3672 ))
3673 .into_any_element(),
3674 )
3675 .grow(),
3676 single_example(
3677 "Uppercase Branch",
3678 div()
3679 .w(example_width)
3680 .overflow_hidden()
3681 .child(PanelRepoFooter::new_preview(
3682 "uppercase-branch",
3683 SharedString::from("zed"),
3684 Some(custom("update-README", behind_upstream)),
3685 ))
3686 .into_any_element(),
3687 )
3688 .grow(),
3689 ],
3690 )
3691 .grow()
3692 .vertical()])
3693 .into_any_element()
3694 }
3695}