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