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