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