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_commit(&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_commit, tooltip) = self.configure_commit_button(cx);
2004
2005 let enable_coauthors = self.render_co_authors(cx);
2006
2007 let title = self.commit_button_title();
2008 let editor_focus_handle = self.commit_editor.focus_handle(cx);
2009
2010 let branch = active_repo.read(cx).current_branch().cloned();
2011
2012 let footer_size = px(32.);
2013 let gap = px(8.0);
2014
2015 let max_height = window.line_height() * 5. + gap + footer_size;
2016
2017 let expand_button_size = px(16.);
2018
2019 let git_panel = cx.entity().clone();
2020 let display_name = SharedString::from(Arc::from(
2021 active_repo
2022 .read(cx)
2023 .display_name(project, cx)
2024 .trim_end_matches("/"),
2025 ));
2026 let branches = branch_picker::popover(self.project.clone(), window, cx);
2027 let footer = v_flex()
2028 .child(PanelRepoFooter::new(
2029 "footer-button",
2030 display_name,
2031 branch,
2032 Some(git_panel),
2033 Some(branches),
2034 ))
2035 .child(
2036 panel_editor_container(window, cx)
2037 .id("commit-editor-container")
2038 .relative()
2039 .h(max_height)
2040 // .w_full()
2041 // .border_t_1()
2042 // .border_color(cx.theme().colors().border)
2043 .bg(cx.theme().colors().editor_background)
2044 .cursor_text()
2045 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
2046 window.focus(&this.commit_editor.focus_handle(cx));
2047 }))
2048 .child(
2049 h_flex()
2050 .id("commit-footer")
2051 .absolute()
2052 .bottom_0()
2053 .right_2()
2054 .h(footer_size)
2055 .flex_none()
2056 .children(enable_coauthors)
2057 .child(
2058 panel_filled_button(title)
2059 .tooltip(move |window, cx| {
2060 if can_commit {
2061 Tooltip::for_action_in(
2062 tooltip,
2063 &Commit,
2064 &editor_focus_handle,
2065 window,
2066 cx,
2067 )
2068 } else {
2069 Tooltip::simple(tooltip, cx)
2070 }
2071 })
2072 .disabled(!can_commit || self.modal_open)
2073 .on_click({
2074 cx.listener(move |this, _: &ClickEvent, window, cx| {
2075 this.commit_changes(window, cx)
2076 })
2077 }),
2078 ),
2079 )
2080 // .when(!self.modal_open, |el| {
2081 .child(EditorElement::new(&self.commit_editor, panel_editor_style))
2082 .child(
2083 div()
2084 .absolute()
2085 .top_1()
2086 .right_2()
2087 .opacity(0.5)
2088 .hover(|this| this.opacity(1.0))
2089 .w(expand_button_size)
2090 .child(
2091 panel_icon_button("expand-commit-editor", IconName::Maximize)
2092 .icon_size(IconSize::Small)
2093 .style(ButtonStyle::Transparent)
2094 .width(expand_button_size.into())
2095 .on_click(cx.listener({
2096 move |_, _, window, cx| {
2097 window.dispatch_action(
2098 git::ShowCommitEditor.boxed_clone(),
2099 cx,
2100 )
2101 }
2102 })),
2103 ),
2104 ),
2105 );
2106
2107 Some(footer)
2108 } else {
2109 None
2110 }
2111 }
2112
2113 fn render_previous_commit(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2114 let active_repository = self.active_repository.as_ref()?;
2115 let branch = active_repository.read(cx).current_branch()?;
2116 let commit = branch.most_recent_commit.as_ref()?.clone();
2117
2118 let this = cx.entity();
2119 Some(
2120 h_flex()
2121 .items_center()
2122 .py_2()
2123 .px(px(8.))
2124 // .bg(cx.theme().colors().background)
2125 // .border_t_1()
2126 .border_color(cx.theme().colors().border)
2127 .gap_1p5()
2128 .child(
2129 div()
2130 .flex_grow()
2131 .overflow_hidden()
2132 .max_w(relative(0.6))
2133 .h_full()
2134 .child(
2135 Label::new(commit.subject.clone())
2136 .size(LabelSize::Small)
2137 .truncate(),
2138 )
2139 .id("commit-msg-hover")
2140 .hoverable_tooltip(move |window, cx| {
2141 GitPanelMessageTooltip::new(
2142 this.clone(),
2143 commit.sha.clone(),
2144 window,
2145 cx,
2146 )
2147 .into()
2148 }),
2149 )
2150 .child(div().flex_1())
2151 .child(
2152 panel_icon_button("undo", IconName::Undo)
2153 .icon_size(IconSize::Small)
2154 .icon_color(Color::Muted)
2155 .tooltip(Tooltip::for_action_title(
2156 if self.has_staged_changes() {
2157 "git reset HEAD^ --soft"
2158 } else {
2159 "git reset HEAD^"
2160 },
2161 &git::Uncommit,
2162 ))
2163 .on_click(cx.listener(|this, _, window, cx| this.uncommit(window, cx))),
2164 ),
2165 )
2166 }
2167
2168 fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
2169 h_flex()
2170 .h_full()
2171 .flex_grow()
2172 .justify_center()
2173 .items_center()
2174 .child(
2175 v_flex()
2176 .gap_3()
2177 .child(if self.active_repository.is_some() {
2178 "No changes to commit"
2179 } else {
2180 "No Git repositories"
2181 })
2182 .text_ui_sm(cx)
2183 .mx_auto()
2184 .text_color(Color::Placeholder.color(cx)),
2185 )
2186 }
2187
2188 fn render_scrollbar(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
2189 let scroll_bar_style = self.show_scrollbar(cx);
2190 let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
2191
2192 if !self.should_show_scrollbar(cx)
2193 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
2194 {
2195 return None;
2196 }
2197
2198 Some(
2199 div()
2200 .id("git-panel-vertical-scroll")
2201 .occlude()
2202 .flex_none()
2203 .h_full()
2204 .cursor_default()
2205 .when(show_container, |this| this.pl_1().px_1p5())
2206 .when(!show_container, |this| {
2207 this.absolute().right_1().top_1().bottom_1().w(px(12.))
2208 })
2209 .on_mouse_move(cx.listener(|_, _, _, cx| {
2210 cx.notify();
2211 cx.stop_propagation()
2212 }))
2213 .on_hover(|_, _, cx| {
2214 cx.stop_propagation();
2215 })
2216 .on_any_mouse_down(|_, _, cx| {
2217 cx.stop_propagation();
2218 })
2219 .on_mouse_up(
2220 MouseButton::Left,
2221 cx.listener(|this, _, window, cx| {
2222 if !this.scrollbar_state.is_dragging()
2223 && !this.focus_handle.contains_focused(window, cx)
2224 {
2225 this.hide_scrollbar(window, cx);
2226 cx.notify();
2227 }
2228
2229 cx.stop_propagation();
2230 }),
2231 )
2232 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
2233 cx.notify();
2234 }))
2235 .children(Scrollbar::vertical(
2236 // percentage as f32..end_offset as f32,
2237 self.scrollbar_state.clone(),
2238 )),
2239 )
2240 }
2241
2242 fn render_buffer_header_controls(
2243 &self,
2244 entity: &Entity<Self>,
2245 file: &Arc<dyn File>,
2246 _: &Window,
2247 cx: &App,
2248 ) -> Option<AnyElement> {
2249 let repo = self.active_repository.as_ref()?.read(cx);
2250 let repo_path = repo.worktree_id_path_to_repo_path(file.worktree_id(cx), file.path())?;
2251 let ix = self.entry_by_path(&repo_path)?;
2252 let entry = self.entries.get(ix)?;
2253
2254 let is_staged = self.entry_is_staged(entry.status_entry()?);
2255
2256 let checkbox = Checkbox::new("stage-file", is_staged.into())
2257 .disabled(!self.has_write_access(cx))
2258 .fill()
2259 .elevation(ElevationIndex::Surface)
2260 .on_click({
2261 let entry = entry.clone();
2262 let git_panel = entity.downgrade();
2263 move |_, window, cx| {
2264 git_panel
2265 .update(cx, |this, cx| {
2266 this.toggle_staged_for_entry(&entry, window, cx);
2267 cx.stop_propagation();
2268 })
2269 .ok();
2270 }
2271 });
2272 Some(
2273 h_flex()
2274 .id("start-slot")
2275 .text_lg()
2276 .child(checkbox)
2277 .on_mouse_down(MouseButton::Left, |_, _, cx| {
2278 // prevent the list item active state triggering when toggling checkbox
2279 cx.stop_propagation();
2280 })
2281 .into_any_element(),
2282 )
2283 }
2284
2285 fn render_entries(
2286 &self,
2287 has_write_access: bool,
2288 _: &Window,
2289 cx: &mut Context<Self>,
2290 ) -> impl IntoElement {
2291 let entry_count = self.entries.len();
2292
2293 h_flex()
2294 .size_full()
2295 .flex_grow()
2296 .overflow_hidden()
2297 .child(
2298 uniform_list(cx.entity().clone(), "entries", entry_count, {
2299 move |this, range, window, cx| {
2300 let mut items = Vec::with_capacity(range.end - range.start);
2301
2302 for ix in range {
2303 match &this.entries.get(ix) {
2304 Some(GitListEntry::GitStatusEntry(entry)) => {
2305 items.push(this.render_entry(
2306 ix,
2307 entry,
2308 has_write_access,
2309 window,
2310 cx,
2311 ));
2312 }
2313 Some(GitListEntry::Header(header)) => {
2314 items.push(this.render_list_header(
2315 ix,
2316 header,
2317 has_write_access,
2318 window,
2319 cx,
2320 ));
2321 }
2322 None => {}
2323 }
2324 }
2325
2326 items
2327 }
2328 })
2329 .size_full()
2330 .with_sizing_behavior(ListSizingBehavior::Auto)
2331 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
2332 .track_scroll(self.scroll_handle.clone()),
2333 )
2334 .on_mouse_down(
2335 MouseButton::Right,
2336 cx.listener(move |this, event: &MouseDownEvent, window, cx| {
2337 this.deploy_panel_context_menu(event.position, window, cx)
2338 }),
2339 )
2340 .children(self.render_scrollbar(cx))
2341 }
2342
2343 fn entry_label(&self, label: impl Into<SharedString>, color: Color) -> Label {
2344 Label::new(label.into()).color(color).single_line()
2345 }
2346
2347 fn list_item_height(&self) -> Rems {
2348 rems(1.75)
2349 }
2350
2351 fn render_list_header(
2352 &self,
2353 ix: usize,
2354 header: &GitHeaderEntry,
2355 _: bool,
2356 _: &Window,
2357 _: &Context<Self>,
2358 ) -> AnyElement {
2359 let id: ElementId = ElementId::Name(format!("header_{}", ix).into());
2360
2361 h_flex()
2362 .id(id)
2363 .h(self.list_item_height())
2364 .w_full()
2365 .items_end()
2366 .px(rems(0.75)) // ~12px
2367 .pb(rems(0.3125)) // ~ 5px
2368 .child(
2369 Label::new(header.title())
2370 .color(Color::Muted)
2371 .size(LabelSize::Small)
2372 .line_height_style(LineHeightStyle::UiLabel)
2373 .single_line(),
2374 )
2375 .into_any_element()
2376 }
2377
2378 fn load_commit_details(
2379 &self,
2380 sha: &str,
2381 cx: &mut Context<Self>,
2382 ) -> Task<Result<CommitDetails>> {
2383 let Some(repo) = self.active_repository.clone() else {
2384 return Task::ready(Err(anyhow::anyhow!("no active repo")));
2385 };
2386 repo.update(cx, |repo, cx| {
2387 let show = repo.show(sha);
2388 cx.spawn(|_, _| async move { show.await? })
2389 })
2390 }
2391
2392 fn deploy_entry_context_menu(
2393 &mut self,
2394 position: Point<Pixels>,
2395 ix: usize,
2396 window: &mut Window,
2397 cx: &mut Context<Self>,
2398 ) {
2399 let Some(entry) = self.entries.get(ix).and_then(|e| e.status_entry()) else {
2400 return;
2401 };
2402 let stage_title = if entry.status.is_staged() == Some(true) {
2403 "Unstage File"
2404 } else {
2405 "Stage File"
2406 };
2407 let restore_title = if entry.status.is_created() {
2408 "Trash File"
2409 } else {
2410 "Restore File"
2411 };
2412 let context_menu = ContextMenu::build(window, cx, |context_menu, _, _| {
2413 context_menu
2414 .action(stage_title, ToggleStaged.boxed_clone())
2415 .action(restore_title, git::RestoreFile.boxed_clone())
2416 .separator()
2417 .action("Open Diff", Confirm.boxed_clone())
2418 .action("Open File", SecondaryConfirm.boxed_clone())
2419 });
2420 self.selected_entry = Some(ix);
2421 self.set_context_menu(context_menu, position, window, cx);
2422 }
2423
2424 fn deploy_panel_context_menu(
2425 &mut self,
2426 position: Point<Pixels>,
2427 window: &mut Window,
2428 cx: &mut Context<Self>,
2429 ) {
2430 let context_menu = git_panel_context_menu(window, cx);
2431 self.set_context_menu(context_menu, position, window, cx);
2432 }
2433
2434 fn set_context_menu(
2435 &mut self,
2436 context_menu: Entity<ContextMenu>,
2437 position: Point<Pixels>,
2438 window: &Window,
2439 cx: &mut Context<Self>,
2440 ) {
2441 let subscription = cx.subscribe_in(
2442 &context_menu,
2443 window,
2444 |this, _, _: &DismissEvent, window, cx| {
2445 if this.context_menu.as_ref().is_some_and(|context_menu| {
2446 context_menu.0.focus_handle(cx).contains_focused(window, cx)
2447 }) {
2448 cx.focus_self(window);
2449 }
2450 this.context_menu.take();
2451 cx.notify();
2452 },
2453 );
2454 self.context_menu = Some((context_menu, position, subscription));
2455 cx.notify();
2456 }
2457
2458 fn render_entry(
2459 &self,
2460 ix: usize,
2461 entry: &GitStatusEntry,
2462 has_write_access: bool,
2463 window: &Window,
2464 cx: &Context<Self>,
2465 ) -> AnyElement {
2466 let display_name = entry
2467 .repo_path
2468 .file_name()
2469 .map(|name| name.to_string_lossy().into_owned())
2470 .unwrap_or_else(|| entry.repo_path.to_string_lossy().into_owned());
2471
2472 let repo_path = entry.repo_path.clone();
2473 let selected = self.selected_entry == Some(ix);
2474 let marked = self.marked_entries.contains(&ix);
2475 let status_style = GitPanelSettings::get_global(cx).status_style;
2476 let status = entry.status;
2477 let has_conflict = status.is_conflicted();
2478 let is_modified = status.is_modified();
2479 let is_deleted = status.is_deleted();
2480
2481 let label_color = if status_style == StatusStyle::LabelColor {
2482 if has_conflict {
2483 Color::Conflict
2484 } else if is_modified {
2485 Color::Modified
2486 } else if is_deleted {
2487 // We don't want a bunch of red labels in the list
2488 Color::Disabled
2489 } else {
2490 Color::Created
2491 }
2492 } else {
2493 Color::Default
2494 };
2495
2496 let path_color = if status.is_deleted() {
2497 Color::Disabled
2498 } else {
2499 Color::Muted
2500 };
2501
2502 let id: ElementId = ElementId::Name(format!("entry_{}_{}", display_name, ix).into());
2503 let checkbox_wrapper_id: ElementId =
2504 ElementId::Name(format!("entry_{}_{}_checkbox_wrapper", display_name, ix).into());
2505 let checkbox_id: ElementId =
2506 ElementId::Name(format!("entry_{}_{}_checkbox", display_name, ix).into());
2507
2508 let is_entry_staged = self.entry_is_staged(entry);
2509 let mut is_staged: ToggleState = self.entry_is_staged(entry).into();
2510
2511 if !self.has_staged_changes() && !self.has_conflicts() && !entry.status.is_created() {
2512 is_staged = ToggleState::Selected;
2513 }
2514
2515 let handle = cx.weak_entity();
2516
2517 let selected_bg_alpha = 0.08;
2518 let marked_bg_alpha = 0.12;
2519 let state_opacity_step = 0.04;
2520
2521 let base_bg = match (selected, marked) {
2522 (true, true) => cx
2523 .theme()
2524 .status()
2525 .info
2526 .alpha(selected_bg_alpha + marked_bg_alpha),
2527 (true, false) => cx.theme().status().info.alpha(selected_bg_alpha),
2528 (false, true) => cx.theme().status().info.alpha(marked_bg_alpha),
2529 _ => cx.theme().colors().ghost_element_background,
2530 };
2531
2532 let hover_bg = if selected {
2533 cx.theme()
2534 .status()
2535 .info
2536 .alpha(selected_bg_alpha + state_opacity_step)
2537 } else {
2538 cx.theme().colors().ghost_element_hover
2539 };
2540
2541 let active_bg = if selected {
2542 cx.theme()
2543 .status()
2544 .info
2545 .alpha(selected_bg_alpha + state_opacity_step * 2.0)
2546 } else {
2547 cx.theme().colors().ghost_element_active
2548 };
2549
2550 h_flex()
2551 .id(id)
2552 .h(self.list_item_height())
2553 .w_full()
2554 .items_center()
2555 .border_1()
2556 .when(selected && self.focus_handle.is_focused(window), |el| {
2557 el.border_color(cx.theme().colors().border_focused)
2558 })
2559 .px(rems(0.75)) // ~12px
2560 .overflow_hidden()
2561 .flex_none()
2562 .gap(DynamicSpacing::Base04.rems(cx))
2563 .bg(base_bg)
2564 .hover(|this| this.bg(hover_bg))
2565 .active(|this| this.bg(active_bg))
2566 .on_click({
2567 cx.listener(move |this, event: &ClickEvent, window, cx| {
2568 this.selected_entry = Some(ix);
2569 cx.notify();
2570 if event.modifiers().secondary() {
2571 this.open_file(&Default::default(), window, cx)
2572 } else {
2573 this.open_diff(&Default::default(), window, cx);
2574 this.focus_handle.focus(window);
2575 }
2576 })
2577 })
2578 .on_mouse_down(
2579 MouseButton::Right,
2580 move |event: &MouseDownEvent, window, cx| {
2581 // why isn't this happening automatically? we are passing MouseButton::Right to `on_mouse_down`?
2582 if event.button != MouseButton::Right {
2583 return;
2584 }
2585
2586 let Some(this) = handle.upgrade() else {
2587 return;
2588 };
2589 this.update(cx, |this, cx| {
2590 this.deploy_entry_context_menu(event.position, ix, window, cx);
2591 });
2592 cx.stop_propagation();
2593 },
2594 )
2595 // .on_secondary_mouse_down(cx.listener(
2596 // move |this, event: &MouseDownEvent, window, cx| {
2597 // this.deploy_entry_context_menu(event.position, ix, window, cx);
2598 // cx.stop_propagation();
2599 // },
2600 // ))
2601 .child(
2602 div()
2603 .id(checkbox_wrapper_id)
2604 .flex_none()
2605 .occlude()
2606 .cursor_pointer()
2607 .child(
2608 Checkbox::new(checkbox_id, is_staged)
2609 .disabled(!has_write_access)
2610 .fill()
2611 .placeholder(!self.has_staged_changes() && !self.has_conflicts())
2612 .elevation(ElevationIndex::Surface)
2613 .on_click({
2614 let entry = entry.clone();
2615 cx.listener(move |this, _, window, cx| {
2616 if !has_write_access {
2617 return;
2618 }
2619 this.toggle_staged_for_entry(
2620 &GitListEntry::GitStatusEntry(entry.clone()),
2621 window,
2622 cx,
2623 );
2624 cx.stop_propagation();
2625 })
2626 })
2627 .tooltip(move |window, cx| {
2628 let tooltip_name = if is_entry_staged.unwrap_or(false) {
2629 "Unstage"
2630 } else {
2631 "Stage"
2632 };
2633
2634 Tooltip::for_action(tooltip_name, &ToggleStaged, window, cx)
2635 }),
2636 ),
2637 )
2638 .child(git_status_icon(status, cx))
2639 .child(
2640 h_flex()
2641 .items_center()
2642 .overflow_hidden()
2643 .when_some(repo_path.parent(), |this, parent| {
2644 let parent_str = parent.to_string_lossy();
2645 if !parent_str.is_empty() {
2646 this.child(
2647 self.entry_label(format!("{}/", parent_str), path_color)
2648 .when(status.is_deleted(), |this| this.strikethrough()),
2649 )
2650 } else {
2651 this
2652 }
2653 })
2654 .child(
2655 self.entry_label(display_name.clone(), label_color)
2656 .when(status.is_deleted(), |this| this.strikethrough()),
2657 ),
2658 )
2659 .into_any_element()
2660 }
2661
2662 fn has_write_access(&self, cx: &App) -> bool {
2663 !self.project.read(cx).is_read_only(cx)
2664 }
2665}
2666
2667impl Render for GitPanel {
2668 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2669 let project = self.project.read(cx);
2670 let has_entries = self.entries.len() > 0;
2671 let room = self
2672 .workspace
2673 .upgrade()
2674 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned());
2675
2676 let has_write_access = self.has_write_access(cx);
2677
2678 let has_co_authors = room.map_or(false, |room| {
2679 room.read(cx)
2680 .remote_participants()
2681 .values()
2682 .any(|remote_participant| remote_participant.can_write())
2683 });
2684
2685 v_flex()
2686 .id("git_panel")
2687 .key_context(self.dispatch_context(window, cx))
2688 .track_focus(&self.focus_handle)
2689 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
2690 .when(has_write_access && !project.is_read_only(cx), |this| {
2691 this.on_action(cx.listener(|this, &ToggleStaged, window, cx| {
2692 this.toggle_staged_for_selected(&ToggleStaged, window, cx)
2693 }))
2694 .on_action(cx.listener(GitPanel::commit))
2695 })
2696 .on_action(cx.listener(Self::select_first))
2697 .on_action(cx.listener(Self::select_next))
2698 .on_action(cx.listener(Self::select_previous))
2699 .on_action(cx.listener(Self::select_last))
2700 .on_action(cx.listener(Self::close_panel))
2701 .on_action(cx.listener(Self::open_diff))
2702 .on_action(cx.listener(Self::open_file))
2703 .on_action(cx.listener(Self::revert_selected))
2704 .on_action(cx.listener(Self::focus_changes_list))
2705 .on_action(cx.listener(Self::focus_editor))
2706 .on_action(cx.listener(Self::toggle_staged_for_selected))
2707 .on_action(cx.listener(Self::stage_all))
2708 .on_action(cx.listener(Self::unstage_all))
2709 .on_action(cx.listener(Self::restore_tracked_files))
2710 .on_action(cx.listener(Self::clean_all))
2711 .on_action(cx.listener(Self::fetch))
2712 .on_action(cx.listener(Self::pull))
2713 .on_action(cx.listener(Self::push))
2714 .when(has_write_access && has_co_authors, |git_panel| {
2715 git_panel.on_action(cx.listener(Self::toggle_fill_co_authors))
2716 })
2717 // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
2718 .on_hover(cx.listener(|this, hovered, window, cx| {
2719 if *hovered {
2720 this.show_scrollbar = true;
2721 this.hide_scrollbar_task.take();
2722 cx.notify();
2723 } else if !this.focus_handle.contains_focused(window, cx) {
2724 this.hide_scrollbar(window, cx);
2725 }
2726 }))
2727 .size_full()
2728 .overflow_hidden()
2729 .bg(ElevationIndex::Surface.bg(cx))
2730 .child(
2731 v_flex()
2732 .size_full()
2733 .map(|this| {
2734 if has_entries {
2735 this.child(self.render_entries(has_write_access, window, cx))
2736 } else {
2737 this.child(self.render_empty_state(cx).into_any_element())
2738 }
2739 })
2740 .children(self.render_footer(window, cx))
2741 .children(self.render_previous_commit(cx))
2742 .into_any_element(),
2743 )
2744 .children(self.context_menu.as_ref().map(|(menu, position, _)| {
2745 deferred(
2746 anchored()
2747 .position(*position)
2748 .anchor(gpui::Corner::TopLeft)
2749 .child(menu.clone()),
2750 )
2751 .with_priority(1)
2752 }))
2753 }
2754}
2755
2756impl Focusable for GitPanel {
2757 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
2758 self.focus_handle.clone()
2759 }
2760}
2761
2762impl EventEmitter<Event> for GitPanel {}
2763
2764impl EventEmitter<PanelEvent> for GitPanel {}
2765
2766pub(crate) struct GitPanelAddon {
2767 pub(crate) workspace: WeakEntity<Workspace>,
2768}
2769
2770impl editor::Addon for GitPanelAddon {
2771 fn to_any(&self) -> &dyn std::any::Any {
2772 self
2773 }
2774
2775 fn render_buffer_header_controls(
2776 &self,
2777 excerpt_info: &ExcerptInfo,
2778 window: &Window,
2779 cx: &App,
2780 ) -> Option<AnyElement> {
2781 let file = excerpt_info.buffer.file()?;
2782 let git_panel = self.workspace.upgrade()?.read(cx).panel::<GitPanel>(cx)?;
2783
2784 git_panel
2785 .read(cx)
2786 .render_buffer_header_controls(&git_panel, &file, window, cx)
2787 }
2788}
2789
2790impl Panel for GitPanel {
2791 fn persistent_name() -> &'static str {
2792 "GitPanel"
2793 }
2794
2795 fn position(&self, _: &Window, cx: &App) -> DockPosition {
2796 GitPanelSettings::get_global(cx).dock
2797 }
2798
2799 fn position_is_valid(&self, position: DockPosition) -> bool {
2800 matches!(position, DockPosition::Left | DockPosition::Right)
2801 }
2802
2803 fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
2804 settings::update_settings_file::<GitPanelSettings>(
2805 self.fs.clone(),
2806 cx,
2807 move |settings, _| settings.dock = Some(position),
2808 );
2809 }
2810
2811 fn size(&self, _: &Window, cx: &App) -> Pixels {
2812 self.width
2813 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
2814 }
2815
2816 fn set_size(&mut self, size: Option<Pixels>, _: &mut Window, cx: &mut Context<Self>) {
2817 self.width = size;
2818 self.serialize(cx);
2819 cx.notify();
2820 }
2821
2822 fn icon(&self, _: &Window, cx: &App) -> Option<ui::IconName> {
2823 Some(ui::IconName::GitBranch).filter(|_| GitPanelSettings::get_global(cx).button)
2824 }
2825
2826 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
2827 Some("Git Panel")
2828 }
2829
2830 fn toggle_action(&self) -> Box<dyn Action> {
2831 Box::new(ToggleFocus)
2832 }
2833
2834 fn activation_priority(&self) -> u32 {
2835 2
2836 }
2837}
2838
2839impl PanelHeader for GitPanel {}
2840
2841struct GitPanelMessageTooltip {
2842 commit_tooltip: Option<Entity<CommitTooltip>>,
2843}
2844
2845impl GitPanelMessageTooltip {
2846 fn new(
2847 git_panel: Entity<GitPanel>,
2848 sha: SharedString,
2849 window: &mut Window,
2850 cx: &mut App,
2851 ) -> Entity<Self> {
2852 cx.new(|cx| {
2853 cx.spawn_in(window, |this, mut cx| async move {
2854 let details = git_panel
2855 .update(&mut cx, |git_panel, cx| {
2856 git_panel.load_commit_details(&sha, cx)
2857 })?
2858 .await?;
2859
2860 let commit_details = editor::commit_tooltip::CommitDetails {
2861 sha: details.sha.clone(),
2862 committer_name: details.committer_name.clone(),
2863 committer_email: details.committer_email.clone(),
2864 commit_time: OffsetDateTime::from_unix_timestamp(details.commit_timestamp)?,
2865 message: Some(editor::commit_tooltip::ParsedCommitMessage {
2866 message: details.message.clone(),
2867 ..Default::default()
2868 }),
2869 };
2870
2871 this.update_in(&mut cx, |this: &mut GitPanelMessageTooltip, window, cx| {
2872 this.commit_tooltip =
2873 Some(cx.new(move |cx| CommitTooltip::new(commit_details, window, cx)));
2874 cx.notify();
2875 })
2876 })
2877 .detach();
2878
2879 Self {
2880 commit_tooltip: None,
2881 }
2882 })
2883 }
2884}
2885
2886impl Render for GitPanelMessageTooltip {
2887 fn render(&mut self, _window: &mut Window, _cx: &mut Context<'_, Self>) -> impl IntoElement {
2888 if let Some(commit_tooltip) = &self.commit_tooltip {
2889 commit_tooltip.clone().into_any_element()
2890 } else {
2891 gpui::Empty.into_any_element()
2892 }
2893 }
2894}
2895
2896fn git_action_tooltip(
2897 label: impl Into<SharedString>,
2898 action: &dyn Action,
2899 command: impl Into<SharedString>,
2900 focus_handle: Option<FocusHandle>,
2901 window: &mut Window,
2902 cx: &mut App,
2903) -> AnyView {
2904 let label = label.into();
2905 let command = command.into();
2906
2907 if let Some(handle) = focus_handle {
2908 Tooltip::with_meta_in(
2909 label.clone(),
2910 Some(action),
2911 command.clone(),
2912 &handle,
2913 window,
2914 cx,
2915 )
2916 } else {
2917 Tooltip::with_meta(label.clone(), Some(action), command.clone(), window, cx)
2918 }
2919}
2920
2921#[derive(IntoElement)]
2922struct SplitButton {
2923 pub left: ButtonLike,
2924 pub right: AnyElement,
2925}
2926
2927impl SplitButton {
2928 fn new(
2929 id: impl Into<SharedString>,
2930 left_label: impl Into<SharedString>,
2931 ahead_count: usize,
2932 behind_count: usize,
2933 left_icon: Option<IconName>,
2934 left_on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
2935 tooltip: impl Fn(&mut Window, &mut App) -> AnyView + 'static,
2936 ) -> Self {
2937 let id = id.into();
2938
2939 fn count(count: usize) -> impl IntoElement {
2940 h_flex()
2941 .ml_neg_px()
2942 .h(rems(0.875))
2943 .items_center()
2944 .overflow_hidden()
2945 .px_0p5()
2946 .child(
2947 Label::new(count.to_string())
2948 .size(LabelSize::XSmall)
2949 .line_height_style(LineHeightStyle::UiLabel),
2950 )
2951 }
2952
2953 let should_render_counts = left_icon.is_none() && (ahead_count > 0 || behind_count > 0);
2954
2955 let left = ui::ButtonLike::new_rounded_left(ElementId::Name(
2956 format!("split-button-left-{}", id).into(),
2957 ))
2958 .layer(ui::ElevationIndex::ModalSurface)
2959 .size(ui::ButtonSize::Compact)
2960 .when(should_render_counts, |this| {
2961 this.child(
2962 h_flex()
2963 .ml_neg_0p5()
2964 .mr_1()
2965 .when(behind_count > 0, |this| {
2966 this.child(Icon::new(IconName::ArrowDown).size(IconSize::XSmall))
2967 .child(count(behind_count))
2968 })
2969 .when(ahead_count > 0, |this| {
2970 this.child(Icon::new(IconName::ArrowUp).size(IconSize::XSmall))
2971 .child(count(ahead_count))
2972 }),
2973 )
2974 })
2975 .when_some(left_icon, |this, left_icon| {
2976 this.child(
2977 h_flex()
2978 .ml_neg_0p5()
2979 .mr_1()
2980 .child(Icon::new(left_icon).size(IconSize::XSmall)),
2981 )
2982 })
2983 .child(
2984 div()
2985 .child(Label::new(left_label).size(LabelSize::Small))
2986 .mr_0p5(),
2987 )
2988 .on_click(left_on_click)
2989 .tooltip(tooltip);
2990
2991 let right =
2992 render_git_action_menu(ElementId::Name(format!("split-button-right-{}", id).into()))
2993 .into_any_element();
2994 // .on_click(right_on_click);
2995
2996 Self { left, right }
2997 }
2998}
2999
3000impl RenderOnce for SplitButton {
3001 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
3002 h_flex()
3003 .rounded_md()
3004 .border_1()
3005 .border_color(cx.theme().colors().text_muted.alpha(0.12))
3006 .child(self.left)
3007 .child(
3008 div()
3009 .h_full()
3010 .w_px()
3011 .bg(cx.theme().colors().text_muted.alpha(0.16)),
3012 )
3013 .child(self.right)
3014 .bg(ElevationIndex::Surface.on_elevation_bg(cx))
3015 .shadow(smallvec![BoxShadow {
3016 color: hsla(0.0, 0.0, 0.0, 0.16),
3017 offset: point(px(0.), px(1.)),
3018 blur_radius: px(0.),
3019 spread_radius: px(0.),
3020 }])
3021 }
3022}
3023
3024fn render_git_action_menu(id: impl Into<ElementId>) -> impl IntoElement {
3025 PopoverMenu::new(id.into())
3026 .trigger(
3027 ui::ButtonLike::new_rounded_right("split-button-right")
3028 .layer(ui::ElevationIndex::ModalSurface)
3029 .size(ui::ButtonSize::None)
3030 .child(
3031 div()
3032 .px_1()
3033 .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
3034 ),
3035 )
3036 .menu(move |window, cx| {
3037 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
3038 context_menu
3039 .action("Fetch", git::Fetch.boxed_clone())
3040 .action("Pull", git::Pull.boxed_clone())
3041 .separator()
3042 .action("Push", git::Push { options: None }.boxed_clone())
3043 .action(
3044 "Force Push",
3045 git::Push {
3046 options: Some(PushOptions::Force),
3047 }
3048 .boxed_clone(),
3049 )
3050 }))
3051 })
3052 .anchor(Corner::TopRight)
3053}
3054
3055#[derive(IntoElement, IntoComponent)]
3056#[component(scope = "git_panel")]
3057pub struct PanelRepoFooter {
3058 id: SharedString,
3059 active_repository: SharedString,
3060 branch: Option<Branch>,
3061 // Getting a GitPanel in previews will be difficult.
3062 //
3063 // For now just take an option here, and we won't bind handlers to buttons in previews.
3064 git_panel: Option<Entity<GitPanel>>,
3065 branches: Option<Entity<BranchList>>,
3066}
3067
3068impl PanelRepoFooter {
3069 pub fn new(
3070 id: impl Into<SharedString>,
3071 active_repository: SharedString,
3072 branch: Option<Branch>,
3073 git_panel: Option<Entity<GitPanel>>,
3074 branches: Option<Entity<BranchList>>,
3075 ) -> Self {
3076 Self {
3077 id: id.into(),
3078 active_repository,
3079 branch,
3080 git_panel,
3081 branches,
3082 }
3083 }
3084
3085 pub fn new_preview(
3086 id: impl Into<SharedString>,
3087 active_repository: SharedString,
3088 branch: Option<Branch>,
3089 ) -> Self {
3090 Self {
3091 id: id.into(),
3092 active_repository,
3093 branch,
3094 git_panel: None,
3095 branches: None,
3096 }
3097 }
3098
3099 fn render_overflow_menu(&self, id: impl Into<ElementId>) -> impl IntoElement {
3100 PopoverMenu::new(id.into())
3101 .trigger(
3102 IconButton::new("overflow-menu-trigger", IconName::EllipsisVertical)
3103 .icon_size(IconSize::Small)
3104 .icon_color(Color::Muted),
3105 )
3106 .menu(move |window, cx| Some(git_panel_context_menu(window, cx)))
3107 .anchor(Corner::TopRight)
3108 }
3109
3110 fn panel_focus_handle(&self, cx: &App) -> Option<FocusHandle> {
3111 if let Some(git_panel) = self.git_panel.clone() {
3112 Some(git_panel.focus_handle(cx))
3113 } else {
3114 None
3115 }
3116 }
3117
3118 fn render_push_button(&self, id: SharedString, ahead: u32, cx: &mut App) -> SplitButton {
3119 let panel = self.git_panel.clone();
3120 let panel_focus_handle = self.panel_focus_handle(cx);
3121
3122 SplitButton::new(
3123 id,
3124 "Push",
3125 ahead as usize,
3126 0,
3127 None,
3128 move |_, window, cx| {
3129 if let Some(panel) = panel.as_ref() {
3130 panel.update(cx, |panel, cx| {
3131 panel.push(&git::Push { options: None }, window, cx);
3132 });
3133 }
3134 },
3135 move |window, cx| {
3136 git_action_tooltip(
3137 "Push committed changes to remote",
3138 &git::Push { options: None },
3139 "git push",
3140 panel_focus_handle.clone(),
3141 window,
3142 cx,
3143 )
3144 },
3145 )
3146 }
3147
3148 fn render_pull_button(
3149 &self,
3150 id: SharedString,
3151 ahead: u32,
3152 behind: u32,
3153 cx: &mut App,
3154 ) -> SplitButton {
3155 let panel = self.git_panel.clone();
3156 let panel_focus_handle = self.panel_focus_handle(cx);
3157
3158 SplitButton::new(
3159 id,
3160 "Pull",
3161 ahead as usize,
3162 behind as usize,
3163 None,
3164 move |_, window, cx| {
3165 if let Some(panel) = panel.as_ref() {
3166 panel.update(cx, |panel, cx| {
3167 panel.pull(&git::Pull, window, cx);
3168 });
3169 }
3170 },
3171 move |window, cx| {
3172 git_action_tooltip(
3173 "Pull",
3174 &git::Pull,
3175 "git pull",
3176 panel_focus_handle.clone(),
3177 window,
3178 cx,
3179 )
3180 },
3181 )
3182 }
3183
3184 fn render_fetch_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3185 let panel = self.git_panel.clone();
3186 let panel_focus_handle = self.panel_focus_handle(cx);
3187
3188 SplitButton::new(
3189 id,
3190 "Fetch",
3191 0,
3192 0,
3193 Some(IconName::ArrowCircle),
3194 move |_, window, cx| {
3195 if let Some(panel) = panel.as_ref() {
3196 panel.update(cx, |panel, cx| {
3197 panel.fetch(&git::Fetch, window, cx);
3198 });
3199 }
3200 },
3201 move |window, cx| {
3202 git_action_tooltip(
3203 "Fetch updates from remote",
3204 &git::Fetch,
3205 "git fetch",
3206 panel_focus_handle.clone(),
3207 window,
3208 cx,
3209 )
3210 },
3211 )
3212 }
3213
3214 fn render_publish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3215 let panel = self.git_panel.clone();
3216 let panel_focus_handle = self.panel_focus_handle(cx);
3217
3218 SplitButton::new(
3219 id,
3220 "Publish",
3221 0,
3222 0,
3223 Some(IconName::ArrowUpFromLine),
3224 move |_, window, cx| {
3225 if let Some(panel) = panel.as_ref() {
3226 panel.update(cx, |panel, cx| {
3227 panel.push(
3228 &git::Push {
3229 options: Some(PushOptions::SetUpstream),
3230 },
3231 window,
3232 cx,
3233 );
3234 });
3235 }
3236 },
3237 move |window, cx| {
3238 git_action_tooltip(
3239 "Publish branch to remote",
3240 &git::Push {
3241 options: Some(PushOptions::SetUpstream),
3242 },
3243 "git push --set-upstream",
3244 panel_focus_handle.clone(),
3245 window,
3246 cx,
3247 )
3248 },
3249 )
3250 }
3251
3252 fn render_republish_button(&self, id: SharedString, cx: &mut App) -> SplitButton {
3253 let panel = self.git_panel.clone();
3254 let panel_focus_handle = self.panel_focus_handle(cx);
3255
3256 SplitButton::new(
3257 id,
3258 "Republish",
3259 0,
3260 0,
3261 Some(IconName::ArrowUpFromLine),
3262 move |_, window, cx| {
3263 if let Some(panel) = panel.as_ref() {
3264 panel.update(cx, |panel, cx| {
3265 panel.push(
3266 &git::Push {
3267 options: Some(PushOptions::SetUpstream),
3268 },
3269 window,
3270 cx,
3271 );
3272 });
3273 }
3274 },
3275 move |window, cx| {
3276 git_action_tooltip(
3277 "Re-publish branch to remote",
3278 &git::Push {
3279 options: Some(PushOptions::SetUpstream),
3280 },
3281 "git push --set-upstream",
3282 panel_focus_handle.clone(),
3283 window,
3284 cx,
3285 )
3286 },
3287 )
3288 }
3289
3290 fn render_relevant_button(
3291 &self,
3292 id: impl Into<SharedString>,
3293 branch: &Branch,
3294 cx: &mut App,
3295 ) -> impl IntoElement {
3296 let id = id.into();
3297 let upstream = branch.upstream.as_ref();
3298 match upstream {
3299 Some(Upstream {
3300 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus { ahead, behind }),
3301 ..
3302 }) => match (*ahead, *behind) {
3303 (0, 0) => self.render_fetch_button(id, cx),
3304 (ahead, 0) => self.render_push_button(id, ahead, cx),
3305 (ahead, behind) => self.render_pull_button(id, ahead, behind, cx),
3306 },
3307 Some(Upstream {
3308 tracking: UpstreamTracking::Gone,
3309 ..
3310 }) => self.render_republish_button(id, cx),
3311 None => self.render_publish_button(id, cx),
3312 }
3313 }
3314}
3315
3316impl RenderOnce for PanelRepoFooter {
3317 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
3318 let active_repo = self.active_repository.clone();
3319 let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
3320 let repo_selector_trigger = Button::new("repo-selector", active_repo)
3321 .style(ButtonStyle::Transparent)
3322 .size(ButtonSize::None)
3323 .label_size(LabelSize::Small)
3324 .color(Color::Muted);
3325
3326 let repo_selector = if let Some(panel) = self.git_panel.clone() {
3327 let repo_selector = panel.read(cx).repository_selector.clone();
3328 let repo_count = repo_selector.read(cx).repositories_len(cx);
3329 let single_repo = repo_count == 1;
3330
3331 RepositorySelectorPopoverMenu::new(
3332 panel.read(cx).repository_selector.clone(),
3333 repo_selector_trigger.disabled(single_repo).truncate(true),
3334 Tooltip::text("Switch active repository"),
3335 )
3336 .into_any_element()
3337 } else {
3338 // for rendering preview, we don't have git_panel there
3339 repo_selector_trigger.into_any_element()
3340 };
3341
3342 let branch = self.branch.clone();
3343 let branch_name = branch
3344 .as_ref()
3345 .map_or(" (no branch)".into(), |branch| branch.name.clone());
3346
3347 let branches = self.branches.clone();
3348
3349 let branch_selector_button = Button::new("branch-selector", branch_name)
3350 .style(ButtonStyle::Transparent)
3351 .size(ButtonSize::None)
3352 .label_size(LabelSize::Small)
3353 .truncate(true)
3354 .tooltip(Tooltip::for_action_title(
3355 "Switch Branch",
3356 &zed_actions::git::Branch,
3357 ))
3358 .on_click(|_, window, cx| {
3359 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
3360 });
3361
3362 let branch_selector = if let Some(branches) = branches {
3363 PopoverButton::new(
3364 branches,
3365 Corner::BottomLeft,
3366 branch_selector_button,
3367 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
3368 )
3369 .render(window, cx)
3370 .into_any_element()
3371 } else {
3372 branch_selector_button.into_any_element()
3373 };
3374
3375 let spinner = self
3376 .git_panel
3377 .as_ref()
3378 .and_then(|git_panel| git_panel.read(cx).render_spinner());
3379
3380 h_flex()
3381 .w_full()
3382 .px_2()
3383 .h(px(36.))
3384 .items_center()
3385 .justify_between()
3386 .child(
3387 h_flex()
3388 .flex_1()
3389 .overflow_hidden()
3390 .items_center()
3391 .child(
3392 div().child(
3393 Icon::new(IconName::GitBranchSmall)
3394 .size(IconSize::Small)
3395 .color(Color::Muted),
3396 ),
3397 )
3398 .child(repo_selector)
3399 .when_some(branch.clone(), |this, _| {
3400 this.child(
3401 div()
3402 .text_color(cx.theme().colors().text_muted)
3403 .text_sm()
3404 .child("/"),
3405 )
3406 })
3407 .child(branch_selector),
3408 )
3409 .child(
3410 h_flex()
3411 .gap_1()
3412 .flex_shrink_0()
3413 .children(spinner)
3414 .child(self.render_overflow_menu(overflow_menu_id))
3415 .when_some(branch, |this, branch| {
3416 let button = self.render_relevant_button(self.id.clone(), &branch, cx);
3417 this.child(button)
3418 }),
3419 )
3420 }
3421}
3422
3423impl ComponentPreview for PanelRepoFooter {
3424 fn preview(_window: &mut Window, _cx: &mut App) -> AnyElement {
3425 let unknown_upstream = None;
3426 let no_remote_upstream = Some(UpstreamTracking::Gone);
3427 let ahead_of_upstream = Some(
3428 UpstreamTrackingStatus {
3429 ahead: 2,
3430 behind: 0,
3431 }
3432 .into(),
3433 );
3434 let behind_upstream = Some(
3435 UpstreamTrackingStatus {
3436 ahead: 0,
3437 behind: 2,
3438 }
3439 .into(),
3440 );
3441 let ahead_and_behind_upstream = Some(
3442 UpstreamTrackingStatus {
3443 ahead: 3,
3444 behind: 1,
3445 }
3446 .into(),
3447 );
3448
3449 let not_ahead_or_behind_upstream = Some(
3450 UpstreamTrackingStatus {
3451 ahead: 0,
3452 behind: 0,
3453 }
3454 .into(),
3455 );
3456
3457 fn branch(upstream: Option<UpstreamTracking>) -> Branch {
3458 Branch {
3459 is_head: true,
3460 name: "some-branch".into(),
3461 upstream: upstream.map(|tracking| Upstream {
3462 ref_name: "origin/some-branch".into(),
3463 tracking,
3464 }),
3465 most_recent_commit: Some(CommitSummary {
3466 sha: "abc123".into(),
3467 subject: "Modify stuff".into(),
3468 commit_timestamp: 1710932954,
3469 }),
3470 }
3471 }
3472
3473 fn custom(branch_name: &str, upstream: Option<UpstreamTracking>) -> Branch {
3474 Branch {
3475 is_head: true,
3476 name: branch_name.to_string().into(),
3477 upstream: upstream.map(|tracking| Upstream {
3478 ref_name: format!("zed/{}", branch_name).into(),
3479 tracking,
3480 }),
3481 most_recent_commit: Some(CommitSummary {
3482 sha: "abc123".into(),
3483 subject: "Modify stuff".into(),
3484 commit_timestamp: 1710932954,
3485 }),
3486 }
3487 }
3488
3489 fn active_repository(id: usize) -> SharedString {
3490 format!("repo-{}", id).into()
3491 }
3492
3493 let example_width = px(340.);
3494
3495 v_flex()
3496 .gap_6()
3497 .w_full()
3498 .flex_none()
3499 .children(vec![example_group_with_title(
3500 "Action Button States",
3501 vec![
3502 single_example(
3503 "No Branch",
3504 div()
3505 .w(example_width)
3506 .overflow_hidden()
3507 .child(PanelRepoFooter::new_preview(
3508 "no-branch",
3509 active_repository(1).clone(),
3510 None,
3511 ))
3512 .into_any_element(),
3513 )
3514 .grow(),
3515 single_example(
3516 "Remote status unknown",
3517 div()
3518 .w(example_width)
3519 .overflow_hidden()
3520 .child(PanelRepoFooter::new_preview(
3521 "unknown-upstream",
3522 active_repository(2).clone(),
3523 Some(branch(unknown_upstream)),
3524 ))
3525 .into_any_element(),
3526 )
3527 .grow(),
3528 single_example(
3529 "No Remote Upstream",
3530 div()
3531 .w(example_width)
3532 .overflow_hidden()
3533 .child(PanelRepoFooter::new_preview(
3534 "no-remote-upstream",
3535 active_repository(3).clone(),
3536 Some(branch(no_remote_upstream)),
3537 ))
3538 .into_any_element(),
3539 )
3540 .grow(),
3541 single_example(
3542 "Not Ahead or Behind",
3543 div()
3544 .w(example_width)
3545 .overflow_hidden()
3546 .child(PanelRepoFooter::new_preview(
3547 "not-ahead-or-behind",
3548 active_repository(4).clone(),
3549 Some(branch(not_ahead_or_behind_upstream)),
3550 ))
3551 .into_any_element(),
3552 )
3553 .grow(),
3554 single_example(
3555 "Behind remote",
3556 div()
3557 .w(example_width)
3558 .overflow_hidden()
3559 .child(PanelRepoFooter::new_preview(
3560 "behind-remote",
3561 active_repository(5).clone(),
3562 Some(branch(behind_upstream)),
3563 ))
3564 .into_any_element(),
3565 )
3566 .grow(),
3567 single_example(
3568 "Ahead of remote",
3569 div()
3570 .w(example_width)
3571 .overflow_hidden()
3572 .child(PanelRepoFooter::new_preview(
3573 "ahead-of-remote",
3574 active_repository(6).clone(),
3575 Some(branch(ahead_of_upstream)),
3576 ))
3577 .into_any_element(),
3578 )
3579 .grow(),
3580 single_example(
3581 "Ahead and behind remote",
3582 div()
3583 .w(example_width)
3584 .overflow_hidden()
3585 .child(PanelRepoFooter::new_preview(
3586 "ahead-and-behind",
3587 active_repository(7).clone(),
3588 Some(branch(ahead_and_behind_upstream)),
3589 ))
3590 .into_any_element(),
3591 )
3592 .grow(),
3593 ],
3594 )
3595 .grow()
3596 .vertical()])
3597 .children(vec![example_group_with_title(
3598 "Labels",
3599 vec![
3600 single_example(
3601 "Short Branch & Repo",
3602 div()
3603 .w(example_width)
3604 .overflow_hidden()
3605 .child(PanelRepoFooter::new_preview(
3606 "short-branch",
3607 SharedString::from("zed"),
3608 Some(custom("main", behind_upstream)),
3609 ))
3610 .into_any_element(),
3611 )
3612 .grow(),
3613 single_example(
3614 "Long Branch",
3615 div()
3616 .w(example_width)
3617 .overflow_hidden()
3618 .child(PanelRepoFooter::new_preview(
3619 "long-branch",
3620 SharedString::from("zed"),
3621 Some(custom(
3622 "redesign-and-update-git-ui-list-entry-style",
3623 behind_upstream,
3624 )),
3625 ))
3626 .into_any_element(),
3627 )
3628 .grow(),
3629 single_example(
3630 "Long Repo",
3631 div()
3632 .w(example_width)
3633 .overflow_hidden()
3634 .child(PanelRepoFooter::new_preview(
3635 "long-repo",
3636 SharedString::from("zed-industries-community-examples"),
3637 Some(custom("gpui", ahead_of_upstream)),
3638 ))
3639 .into_any_element(),
3640 )
3641 .grow(),
3642 single_example(
3643 "Long Repo & Branch",
3644 div()
3645 .w(example_width)
3646 .overflow_hidden()
3647 .child(PanelRepoFooter::new_preview(
3648 "long-repo-and-branch",
3649 SharedString::from("zed-industries-community-examples"),
3650 Some(custom(
3651 "redesign-and-update-git-ui-list-entry-style",
3652 behind_upstream,
3653 )),
3654 ))
3655 .into_any_element(),
3656 )
3657 .grow(),
3658 single_example(
3659 "Uppercase Repo",
3660 div()
3661 .w(example_width)
3662 .overflow_hidden()
3663 .child(PanelRepoFooter::new_preview(
3664 "uppercase-repo",
3665 SharedString::from("LICENSES"),
3666 Some(custom("main", ahead_of_upstream)),
3667 ))
3668 .into_any_element(),
3669 )
3670 .grow(),
3671 single_example(
3672 "Uppercase Branch",
3673 div()
3674 .w(example_width)
3675 .overflow_hidden()
3676 .child(PanelRepoFooter::new_preview(
3677 "uppercase-branch",
3678 SharedString::from("zed"),
3679 Some(custom("update-README", behind_upstream)),
3680 ))
3681 .into_any_element(),
3682 )
3683 .grow(),
3684 ],
3685 )
3686 .grow()
3687 .vertical()])
3688 .into_any_element()
3689 }
3690}