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