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