1use crate::git_panel_settings::StatusStyle;
2use crate::{git_panel_settings::GitPanelSettings, git_status_icon};
3use anyhow::Result;
4use db::kvp::KEY_VALUE_STORE;
5use editor::actions::MoveToEnd;
6use editor::scroll::ScrollbarAutoHide;
7use editor::{Editor, EditorMode, EditorSettings, MultiBuffer, ShowScrollbar};
8use futures::channel::mpsc;
9use futures::StreamExt as _;
10use git::repository::RepoPath;
11use git::status::FileStatus;
12use git::{CommitAllChanges, CommitChanges, RevertAll, StageAll, ToggleStaged, UnstageAll};
13use gpui::*;
14use menu::{SelectFirst, SelectLast, SelectNext, SelectPrev};
15use project::git::RepositoryHandle;
16use project::{Fs, Project, ProjectPath};
17use serde::{Deserialize, Serialize};
18use settings::Settings as _;
19use std::{collections::HashSet, ops::Range, path::PathBuf, sync::Arc, time::Duration, usize};
20use theme::ThemeSettings;
21use ui::{
22 prelude::*, Checkbox, Divider, DividerColor, ElevationIndex, Scrollbar, ScrollbarState, Tooltip,
23};
24use util::{ResultExt, TryFutureExt};
25use workspace::notifications::{DetachAndPromptErr, NotificationId};
26use workspace::Toast;
27use workspace::{
28 dock::{DockPosition, Panel, PanelEvent},
29 Workspace,
30};
31
32actions!(
33 git_panel,
34 [
35 Close,
36 ToggleFocus,
37 OpenMenu,
38 OpenSelected,
39 FocusEditor,
40 FocusChanges,
41 FillCoAuthors,
42 ]
43);
44
45const GIT_PANEL_KEY: &str = "GitPanel";
46
47const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
48
49pub fn init(cx: &mut AppContext) {
50 cx.observe_new_views(
51 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
52 workspace.register_action(|workspace, _: &ToggleFocus, cx| {
53 workspace.toggle_panel_focus::<GitPanel>(cx);
54 });
55 },
56 )
57 .detach();
58}
59
60#[derive(Debug, Clone)]
61pub enum Event {
62 Focus,
63 OpenedEntry { path: ProjectPath },
64}
65
66#[derive(Serialize, Deserialize)]
67struct SerializedGitPanel {
68 width: Option<Pixels>,
69}
70
71#[derive(Debug, PartialEq, Eq, Clone)]
72pub struct GitListEntry {
73 depth: usize,
74 display_name: String,
75 repo_path: RepoPath,
76 status: FileStatus,
77 is_staged: Option<bool>,
78}
79
80pub struct GitPanel {
81 current_modifiers: Modifiers,
82 focus_handle: FocusHandle,
83 fs: Arc<dyn Fs>,
84 hide_scrollbar_task: Option<Task<()>>,
85 pending_serialization: Task<Option<()>>,
86 workspace: WeakView<Workspace>,
87 project: Model<Project>,
88 active_repository: Option<RepositoryHandle>,
89 scroll_handle: UniformListScrollHandle,
90 scrollbar_state: ScrollbarState,
91 selected_entry: Option<usize>,
92 show_scrollbar: bool,
93 update_visible_entries_task: Task<()>,
94 commit_editor: View<Editor>,
95 visible_entries: Vec<GitListEntry>,
96 all_staged: Option<bool>,
97 width: Option<Pixels>,
98 err_sender: mpsc::Sender<anyhow::Error>,
99}
100
101fn commit_message_editor(
102 active_repository: Option<&RepositoryHandle>,
103 cx: &mut ViewContext<'_, Editor>,
104) -> Editor {
105 let theme = ThemeSettings::get_global(cx);
106
107 let mut text_style = cx.text_style();
108 let refinement = TextStyleRefinement {
109 font_family: Some(theme.buffer_font.family.clone()),
110 font_features: Some(FontFeatures::disable_ligatures()),
111 font_size: Some(px(12.).into()),
112 color: Some(cx.theme().colors().editor_foreground),
113 background_color: Some(gpui::transparent_black()),
114 ..Default::default()
115 };
116 text_style.refine(&refinement);
117
118 let mut commit_editor = if let Some(active_repository) = active_repository.as_ref() {
119 let buffer =
120 cx.new_model(|cx| MultiBuffer::singleton(active_repository.commit_message(), cx));
121 Editor::new(
122 EditorMode::AutoHeight { max_lines: 10 },
123 buffer,
124 None,
125 false,
126 cx,
127 )
128 } else {
129 Editor::auto_height(10, cx)
130 };
131 commit_editor.set_use_autoclose(false);
132 commit_editor.set_show_gutter(false, cx);
133 commit_editor.set_show_wrap_guides(false, cx);
134 commit_editor.set_show_indent_guides(false, cx);
135 commit_editor.set_text_style_refinement(refinement);
136 commit_editor.set_placeholder_text("Enter commit message", cx);
137 commit_editor
138}
139
140impl GitPanel {
141 pub fn load(
142 workspace: WeakView<Workspace>,
143 cx: AsyncWindowContext,
144 ) -> Task<Result<View<Self>>> {
145 cx.spawn(|mut cx| async move { workspace.update(&mut cx, Self::new) })
146 }
147
148 pub fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> View<Self> {
149 let fs = workspace.app_state().fs.clone();
150 let project = workspace.project().clone();
151 let git_state = project.read(cx).git_state().cloned();
152 let active_repository = project.read(cx).active_repository(cx);
153 let (err_sender, mut err_receiver) = mpsc::channel(1);
154 let workspace = cx.view().downgrade();
155
156 let git_panel = cx.new_view(|cx: &mut ViewContext<Self>| {
157 let focus_handle = cx.focus_handle();
158 cx.on_focus(&focus_handle, Self::focus_in).detach();
159 cx.on_focus_out(&focus_handle, |this, _, cx| {
160 this.hide_scrollbar(cx);
161 })
162 .detach();
163
164 let commit_editor =
165 cx.new_view(|cx| commit_message_editor(active_repository.as_ref(), cx));
166
167 let scroll_handle = UniformListScrollHandle::new();
168
169 if let Some(git_state) = git_state {
170 cx.subscribe(&git_state, move |this, git_state, event, cx| match event {
171 project::git::Event::RepositoriesUpdated => {
172 this.active_repository = git_state.read(cx).active_repository();
173 this.schedule_update(cx);
174 }
175 })
176 .detach();
177 }
178
179 let mut git_panel = Self {
180 focus_handle: cx.focus_handle(),
181 pending_serialization: Task::ready(None),
182 visible_entries: Vec::new(),
183 all_staged: None,
184 current_modifiers: cx.modifiers(),
185 width: Some(px(360.)),
186 scrollbar_state: ScrollbarState::new(scroll_handle.clone()).parent_view(cx.view()),
187 selected_entry: None,
188 show_scrollbar: false,
189 hide_scrollbar_task: None,
190 update_visible_entries_task: Task::ready(()),
191 active_repository,
192 scroll_handle,
193 fs,
194 commit_editor,
195 project,
196 err_sender,
197 workspace,
198 };
199 git_panel.schedule_update(cx);
200 git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);
201 git_panel
202 });
203
204 let handle = git_panel.downgrade();
205 cx.spawn(|_, mut cx| async move {
206 while let Some(e) = err_receiver.next().await {
207 let Some(this) = handle.upgrade() else {
208 break;
209 };
210 if this
211 .update(&mut cx, |this, cx| {
212 this.show_err_toast("git operation error", e, cx);
213 })
214 .is_err()
215 {
216 break;
217 }
218 }
219 })
220 .detach();
221
222 cx.subscribe(
223 &git_panel,
224 move |workspace, _, event: &Event, cx| match event.clone() {
225 Event::OpenedEntry { path } => {
226 workspace
227 .open_path_preview(path, None, false, false, cx)
228 .detach_and_prompt_err("Failed to open file", cx, |e, _| {
229 Some(format!("{e}"))
230 });
231 }
232 Event::Focus => { /* TODO */ }
233 },
234 )
235 .detach();
236
237 git_panel
238 }
239
240 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
241 // TODO: we can store stage status here
242 let width = self.width;
243 self.pending_serialization = cx.background_executor().spawn(
244 async move {
245 KEY_VALUE_STORE
246 .write_kvp(
247 GIT_PANEL_KEY.into(),
248 serde_json::to_string(&SerializedGitPanel { width })?,
249 )
250 .await?;
251 anyhow::Ok(())
252 }
253 .log_err(),
254 );
255 }
256
257 fn dispatch_context(&self, cx: &ViewContext<Self>) -> KeyContext {
258 let mut dispatch_context = KeyContext::new_with_defaults();
259 dispatch_context.add("GitPanel");
260
261 if self.is_focused(cx) {
262 dispatch_context.add("menu");
263 dispatch_context.add("ChangesList");
264 }
265
266 if self.commit_editor.read(cx).is_focused(cx) {
267 dispatch_context.add("CommitEditor");
268 }
269
270 dispatch_context
271 }
272
273 fn is_focused(&self, cx: &ViewContext<Self>) -> bool {
274 cx.focused()
275 .map_or(false, |focused| self.focus_handle == focused)
276 }
277
278 fn close_panel(&mut self, _: &Close, cx: &mut ViewContext<Self>) {
279 cx.emit(PanelEvent::Close);
280 }
281
282 fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
283 if !self.focus_handle.contains_focused(cx) {
284 cx.emit(Event::Focus);
285 }
286 }
287
288 fn show_scrollbar(&self, cx: &mut ViewContext<Self>) -> ShowScrollbar {
289 GitPanelSettings::get_global(cx)
290 .scrollbar
291 .show
292 .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)
293 }
294
295 fn should_show_scrollbar(&self, cx: &mut ViewContext<Self>) -> bool {
296 let show = self.show_scrollbar(cx);
297 match show {
298 ShowScrollbar::Auto => true,
299 ShowScrollbar::System => true,
300 ShowScrollbar::Always => true,
301 ShowScrollbar::Never => false,
302 }
303 }
304
305 fn should_autohide_scrollbar(&self, cx: &mut ViewContext<Self>) -> bool {
306 let show = self.show_scrollbar(cx);
307 match show {
308 ShowScrollbar::Auto => true,
309 ShowScrollbar::System => cx
310 .try_global::<ScrollbarAutoHide>()
311 .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),
312 ShowScrollbar::Always => false,
313 ShowScrollbar::Never => true,
314 }
315 }
316
317 fn hide_scrollbar(&mut self, cx: &mut ViewContext<Self>) {
318 const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);
319 if !self.should_autohide_scrollbar(cx) {
320 return;
321 }
322 self.hide_scrollbar_task = Some(cx.spawn(|panel, mut cx| async move {
323 cx.background_executor()
324 .timer(SCROLLBAR_SHOW_INTERVAL)
325 .await;
326 panel
327 .update(&mut cx, |panel, cx| {
328 panel.show_scrollbar = false;
329 cx.notify();
330 })
331 .log_err();
332 }))
333 }
334
335 fn handle_modifiers_changed(
336 &mut self,
337 event: &ModifiersChangedEvent,
338 cx: &mut ViewContext<Self>,
339 ) {
340 self.current_modifiers = event.modifiers;
341 cx.notify();
342 }
343
344 fn calculate_depth_and_difference(
345 repo_path: &RepoPath,
346 visible_entries: &HashSet<RepoPath>,
347 ) -> (usize, usize) {
348 let ancestors = repo_path.ancestors().skip(1);
349 for ancestor in ancestors {
350 if let Some(parent_entry) = visible_entries.get(ancestor) {
351 let entry_component_count = repo_path.components().count();
352 let parent_component_count = parent_entry.components().count();
353
354 let difference = entry_component_count - parent_component_count;
355
356 let parent_depth = parent_entry
357 .ancestors()
358 .skip(1) // Skip the parent itself
359 .filter(|ancestor| visible_entries.contains(*ancestor))
360 .count();
361
362 return (parent_depth + 1, difference);
363 }
364 }
365
366 (0, 0)
367 }
368
369 fn scroll_to_selected_entry(&mut self, cx: &mut ViewContext<Self>) {
370 if let Some(selected_entry) = self.selected_entry {
371 self.scroll_handle
372 .scroll_to_item(selected_entry, ScrollStrategy::Center);
373 }
374
375 cx.notify();
376 }
377
378 fn select_first(&mut self, _: &SelectFirst, cx: &mut ViewContext<Self>) {
379 if self.visible_entries.first().is_some() {
380 self.selected_entry = Some(0);
381 self.scroll_to_selected_entry(cx);
382 }
383 }
384
385 fn select_prev(&mut self, _: &SelectPrev, cx: &mut ViewContext<Self>) {
386 let item_count = self.visible_entries.len();
387 if item_count == 0 {
388 return;
389 }
390
391 if let Some(selected_entry) = self.selected_entry {
392 let new_selected_entry = if selected_entry > 0 {
393 selected_entry - 1
394 } else {
395 selected_entry
396 };
397
398 self.selected_entry = Some(new_selected_entry);
399
400 self.scroll_to_selected_entry(cx);
401 }
402
403 cx.notify();
404 }
405
406 fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
407 let item_count = self.visible_entries.len();
408 if item_count == 0 {
409 return;
410 }
411
412 if let Some(selected_entry) = self.selected_entry {
413 let new_selected_entry = if selected_entry < item_count - 1 {
414 selected_entry + 1
415 } else {
416 selected_entry
417 };
418
419 self.selected_entry = Some(new_selected_entry);
420
421 self.scroll_to_selected_entry(cx);
422 }
423
424 cx.notify();
425 }
426
427 fn select_last(&mut self, _: &SelectLast, cx: &mut ViewContext<Self>) {
428 if self.visible_entries.last().is_some() {
429 self.selected_entry = Some(self.visible_entries.len() - 1);
430 self.scroll_to_selected_entry(cx);
431 }
432 }
433
434 fn focus_editor(&mut self, _: &FocusEditor, cx: &mut ViewContext<Self>) {
435 self.commit_editor.update(cx, |editor, cx| {
436 editor.focus(cx);
437 });
438 cx.notify();
439 }
440
441 fn select_first_entry_if_none(&mut self, cx: &mut ViewContext<Self>) {
442 let have_entries = self
443 .active_repository
444 .as_ref()
445 .map_or(false, |active_repository| {
446 active_repository.entry_count() > 0
447 });
448 if have_entries && self.selected_entry.is_none() {
449 self.selected_entry = Some(0);
450 self.scroll_to_selected_entry(cx);
451 cx.notify();
452 }
453 }
454
455 fn focus_changes_list(&mut self, _: &FocusChanges, cx: &mut ViewContext<Self>) {
456 self.select_first_entry_if_none(cx);
457
458 cx.focus_self();
459 cx.notify();
460 }
461
462 fn get_selected_entry(&self) -> Option<&GitListEntry> {
463 self.selected_entry
464 .and_then(|i| self.visible_entries.get(i))
465 }
466
467 fn open_selected(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
468 if let Some(entry) = self
469 .selected_entry
470 .and_then(|i| self.visible_entries.get(i))
471 {
472 self.open_entry(entry, cx);
473 }
474 }
475
476 fn toggle_staged_for_entry(&mut self, entry: &GitListEntry, cx: &mut ViewContext<Self>) {
477 let Some(active_repository) = self.active_repository.as_ref() else {
478 return;
479 };
480 let result = if entry.status.is_staged().unwrap_or(false) {
481 active_repository
482 .unstage_entries(vec![entry.repo_path.clone()], self.err_sender.clone())
483 } else {
484 active_repository.stage_entries(vec![entry.repo_path.clone()], self.err_sender.clone())
485 };
486 if let Err(e) = result {
487 self.show_err_toast("toggle staged error", e, cx);
488 }
489 cx.notify();
490 }
491
492 fn toggle_staged_for_selected(&mut self, _: &git::ToggleStaged, cx: &mut ViewContext<Self>) {
493 if let Some(selected_entry) = self.get_selected_entry().cloned() {
494 self.toggle_staged_for_entry(&selected_entry, cx);
495 }
496 }
497
498 fn open_entry(&self, entry: &GitListEntry, cx: &mut ViewContext<Self>) {
499 let Some(active_repository) = self.active_repository.as_ref() else {
500 return;
501 };
502 let Some(path) = active_repository.unrelativize(&entry.repo_path) else {
503 return;
504 };
505 let path_exists = self.project.update(cx, |project, cx| {
506 project.entry_for_path(&path, cx).is_some()
507 });
508 if !path_exists {
509 return;
510 }
511 // TODO maybe move all of this into project?
512 cx.emit(Event::OpenedEntry { path });
513 }
514
515 fn stage_all(&mut self, _: &git::StageAll, cx: &mut ViewContext<Self>) {
516 let Some(active_repository) = self.active_repository.as_ref() else {
517 return;
518 };
519 for entry in &mut self.visible_entries {
520 entry.is_staged = Some(true);
521 }
522 self.all_staged = Some(true);
523
524 if let Err(e) = active_repository.stage_all(self.err_sender.clone()) {
525 self.show_err_toast("stage all error", e, cx);
526 };
527 }
528
529 fn unstage_all(&mut self, _: &git::UnstageAll, cx: &mut ViewContext<Self>) {
530 let Some(active_repository) = self.active_repository.as_ref() else {
531 return;
532 };
533 for entry in &mut self.visible_entries {
534 entry.is_staged = Some(false);
535 }
536 self.all_staged = Some(false);
537 if let Err(e) = active_repository.unstage_all(self.err_sender.clone()) {
538 self.show_err_toast("unstage all error", e, cx);
539 };
540 }
541
542 fn discard_all(&mut self, _: &git::RevertAll, _cx: &mut ViewContext<Self>) {
543 // TODO: Implement discard all
544 println!("Discard all triggered");
545 }
546
547 /// Commit all staged changes
548 fn commit_changes(&mut self, _: &git::CommitChanges, cx: &mut ViewContext<Self>) {
549 let Some(active_repository) = self.active_repository.as_ref() else {
550 return;
551 };
552 if let Err(e) = active_repository.commit(self.err_sender.clone(), cx) {
553 self.show_err_toast("commit error", e, cx);
554 };
555 self.commit_editor
556 .update(cx, |editor, cx| editor.set_text("", cx));
557 }
558
559 /// Commit all changes, regardless of whether they are staged or not
560 fn commit_all_changes(&mut self, _: &git::CommitAllChanges, cx: &mut ViewContext<Self>) {
561 let Some(active_repository) = self.active_repository.as_ref() else {
562 return;
563 };
564 if let Err(e) = active_repository.commit_all(self.err_sender.clone(), cx) {
565 self.show_err_toast("commit all error", e, cx);
566 };
567 self.commit_editor
568 .update(cx, |editor, cx| editor.set_text("", cx));
569 }
570
571 fn fill_co_authors(&mut self, _: &FillCoAuthors, cx: &mut ViewContext<Self>) {
572 const CO_AUTHOR_PREFIX: &str = "Co-authored-by: ";
573
574 let Some(room) = self
575 .workspace
576 .upgrade()
577 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
578 else {
579 return;
580 };
581
582 let mut existing_text = self.commit_editor.read(cx).text(cx);
583 existing_text.make_ascii_lowercase();
584 let lowercase_co_author_prefix = CO_AUTHOR_PREFIX.to_lowercase();
585 let mut ends_with_co_authors = false;
586 let existing_co_authors = existing_text
587 .lines()
588 .filter_map(|line| {
589 let line = line.trim();
590 if line.starts_with(&lowercase_co_author_prefix) {
591 ends_with_co_authors = true;
592 Some(line)
593 } else {
594 ends_with_co_authors = false;
595 None
596 }
597 })
598 .collect::<HashSet<_>>();
599
600 let new_co_authors = room
601 .read(cx)
602 .remote_participants()
603 .values()
604 .filter(|participant| participant.can_write())
605 .map(|participant| participant.user.clone())
606 .filter_map(|user| {
607 let email = user.email.as_deref()?;
608 let name = user.name.as_deref().unwrap_or(&user.github_login);
609 Some(format!("{CO_AUTHOR_PREFIX}{name} <{email}>"))
610 })
611 .filter(|co_author| {
612 !existing_co_authors.contains(co_author.to_ascii_lowercase().as_str())
613 })
614 .collect::<Vec<_>>();
615 if new_co_authors.is_empty() {
616 return;
617 }
618
619 self.commit_editor.update(cx, |editor, cx| {
620 let editor_end = editor.buffer().read(cx).read(cx).len();
621 let mut edit = String::new();
622 if !ends_with_co_authors {
623 edit.push('\n');
624 }
625 for co_author in new_co_authors {
626 edit.push('\n');
627 edit.push_str(&co_author);
628 }
629
630 editor.edit(Some((editor_end..editor_end, edit)), cx);
631 editor.move_to_end(&MoveToEnd, cx);
632 editor.focus(cx);
633 });
634 }
635
636 fn for_each_visible_entry(
637 &self,
638 range: Range<usize>,
639 cx: &mut ViewContext<Self>,
640 mut callback: impl FnMut(usize, GitListEntry, &mut ViewContext<Self>),
641 ) {
642 let visible_entries = &self.visible_entries;
643
644 for (ix, entry) in visible_entries
645 .iter()
646 .enumerate()
647 .skip(range.start)
648 .take(range.end - range.start)
649 {
650 let status = entry.status;
651 let filename = entry
652 .repo_path
653 .file_name()
654 .map(|name| name.to_string_lossy().into_owned())
655 .unwrap_or_else(|| entry.repo_path.to_string_lossy().into_owned());
656
657 let details = GitListEntry {
658 repo_path: entry.repo_path.clone(),
659 status,
660 depth: 0,
661 display_name: filename,
662 is_staged: entry.is_staged,
663 };
664
665 callback(ix, details, cx);
666 }
667 }
668
669 fn schedule_update(&mut self, cx: &mut ViewContext<Self>) {
670 let handle = cx.view().downgrade();
671 self.update_visible_entries_task = cx.spawn(|_, mut cx| async move {
672 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
673 if let Some(this) = handle.upgrade() {
674 this.update(&mut cx, |this, cx| {
675 this.update_visible_entries(cx);
676 let active_repository = this.active_repository.as_ref();
677 this.commit_editor =
678 cx.new_view(|cx| commit_message_editor(active_repository, cx));
679 })
680 .ok();
681 }
682 });
683 }
684
685 fn update_visible_entries(&mut self, cx: &mut ViewContext<Self>) {
686 self.visible_entries.clear();
687
688 let Some(repo) = self.active_repository.as_ref() else {
689 // Just clear entries if no repository is active.
690 cx.notify();
691 return;
692 };
693
694 // First pass - collect all paths
695 let path_set = HashSet::from_iter(repo.status().map(|entry| entry.repo_path));
696
697 // Second pass - create entries with proper depth calculation
698 let mut all_staged = None;
699 for (ix, entry) in repo.status().enumerate() {
700 let (depth, difference) =
701 Self::calculate_depth_and_difference(&entry.repo_path, &path_set);
702 let is_staged = entry.status.is_staged();
703 all_staged = if ix == 0 {
704 is_staged
705 } else {
706 match (all_staged, is_staged) {
707 (None, _) | (_, None) => None,
708 (Some(a), Some(b)) => (a == b).then_some(a),
709 }
710 };
711
712 let display_name = if difference > 1 {
713 // Show partial path for deeply nested files
714 entry
715 .repo_path
716 .as_ref()
717 .iter()
718 .skip(entry.repo_path.components().count() - difference)
719 .collect::<PathBuf>()
720 .to_string_lossy()
721 .into_owned()
722 } else {
723 // Just show filename
724 entry
725 .repo_path
726 .file_name()
727 .map(|name| name.to_string_lossy().into_owned())
728 .unwrap_or_default()
729 };
730
731 let entry = GitListEntry {
732 depth,
733 display_name,
734 repo_path: entry.repo_path.clone(),
735 status: entry.status,
736 is_staged,
737 };
738
739 self.visible_entries.push(entry);
740 }
741 self.all_staged = all_staged;
742
743 // Sort entries by path to maintain consistent order
744 self.visible_entries
745 .sort_by(|a, b| a.repo_path.cmp(&b.repo_path));
746
747 self.select_first_entry_if_none(cx);
748
749 cx.notify();
750 }
751
752 fn show_err_toast(&self, id: &'static str, e: anyhow::Error, cx: &mut ViewContext<Self>) {
753 let Some(workspace) = self.workspace.upgrade() else {
754 return;
755 };
756 let notif_id = NotificationId::Named(id.into());
757 let message = e.to_string();
758 workspace.update(cx, |workspace, cx| {
759 let toast = Toast::new(notif_id, message).on_click("Open Zed Log", |cx| {
760 cx.dispatch_action(workspace::OpenLog.boxed_clone());
761 });
762 workspace.show_toast(toast, cx);
763 });
764 }
765}
766
767// GitPanel –– Render
768impl GitPanel {
769 pub fn panel_button(
770 &self,
771 id: impl Into<SharedString>,
772 label: impl Into<SharedString>,
773 ) -> Button {
774 let id = id.into().clone();
775 let label = label.into().clone();
776
777 Button::new(id, label)
778 .label_size(LabelSize::Small)
779 .layer(ElevationIndex::ElevatedSurface)
780 .size(ButtonSize::Compact)
781 .style(ButtonStyle::Filled)
782 }
783
784 pub fn render_divider(&self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
785 h_flex()
786 .items_center()
787 .h(px(8.))
788 .child(Divider::horizontal_dashed().color(DividerColor::Border))
789 }
790
791 pub fn render_panel_header(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
792 let focus_handle = self.focus_handle(cx).clone();
793 let entry_count = self
794 .active_repository
795 .as_ref()
796 .map_or(0, RepositoryHandle::entry_count);
797
798 let changes_string = match entry_count {
799 0 => "No changes".to_string(),
800 1 => "1 change".to_string(),
801 n => format!("{} changes", n),
802 };
803
804 // for our use case treat None as false
805 let all_staged = self.all_staged.unwrap_or(false);
806
807 h_flex()
808 .h(px(32.))
809 .items_center()
810 .px_2()
811 .bg(ElevationIndex::Surface.bg(cx))
812 .child(
813 h_flex()
814 .gap_2()
815 .child(
816 Checkbox::new(
817 "all-changes",
818 if entry_count == 0 {
819 ToggleState::Selected
820 } else {
821 self.all_staged
822 .map_or(ToggleState::Indeterminate, ToggleState::from)
823 },
824 )
825 .fill()
826 .elevation(ElevationIndex::Surface)
827 .tooltip(move |cx| {
828 if all_staged {
829 Tooltip::text("Unstage all changes", cx)
830 } else {
831 Tooltip::text("Stage all changes", cx)
832 }
833 })
834 .on_click(cx.listener(move |git_panel, _, cx| match all_staged {
835 true => git_panel.unstage_all(&UnstageAll, cx),
836 false => git_panel.stage_all(&StageAll, cx),
837 })),
838 )
839 .child(div().text_buffer(cx).text_ui_sm(cx).child(changes_string)),
840 )
841 .child(div().flex_grow())
842 .child(
843 h_flex()
844 .gap_2()
845 // TODO: Re-add once revert all is added
846 // .child(
847 // IconButton::new("discard-changes", IconName::Undo)
848 // .tooltip({
849 // let focus_handle = focus_handle.clone();
850 // move |cx| {
851 // Tooltip::for_action_in(
852 // "Discard all changes",
853 // &RevertAll,
854 // &focus_handle,
855 // cx,
856 // )
857 // }
858 // })
859 // .icon_size(IconSize::Small)
860 // .disabled(true),
861 // )
862 .child(if self.all_staged.unwrap_or(false) {
863 self.panel_button("unstage-all", "Unstage All")
864 .tooltip({
865 let focus_handle = focus_handle.clone();
866 move |cx| {
867 Tooltip::for_action_in(
868 "Unstage all changes",
869 &UnstageAll,
870 &focus_handle,
871 cx,
872 )
873 }
874 })
875 .key_binding(ui::KeyBinding::for_action_in(
876 &UnstageAll,
877 &focus_handle,
878 cx,
879 ))
880 .on_click(
881 cx.listener(move |this, _, cx| this.unstage_all(&UnstageAll, cx)),
882 )
883 } else {
884 self.panel_button("stage-all", "Stage All")
885 .tooltip({
886 let focus_handle = focus_handle.clone();
887 move |cx| {
888 Tooltip::for_action_in(
889 "Stage all changes",
890 &StageAll,
891 &focus_handle,
892 cx,
893 )
894 }
895 })
896 .key_binding(ui::KeyBinding::for_action_in(
897 &StageAll,
898 &focus_handle,
899 cx,
900 ))
901 .on_click(cx.listener(move |this, _, cx| this.stage_all(&StageAll, cx)))
902 }),
903 )
904 }
905
906 pub fn render_commit_editor(&self, cx: &ViewContext<Self>) -> impl IntoElement {
907 let editor = self.commit_editor.clone();
908 let editor_focus_handle = editor.read(cx).focus_handle(cx).clone();
909 let (can_commit, can_commit_all) = self.active_repository.as_ref().map_or_else(
910 || (false, false),
911 |active_repository| {
912 (
913 active_repository.can_commit(false, cx),
914 active_repository.can_commit(true, cx),
915 )
916 },
917 );
918
919 let focus_handle_1 = self.focus_handle(cx).clone();
920 let focus_handle_2 = self.focus_handle(cx).clone();
921
922 let commit_staged_button = self
923 .panel_button("commit-staged-changes", "Commit")
924 .tooltip(move |cx| {
925 let focus_handle = focus_handle_1.clone();
926 Tooltip::for_action_in(
927 "Commit all staged changes",
928 &CommitChanges,
929 &focus_handle,
930 cx,
931 )
932 })
933 .disabled(!can_commit)
934 .on_click(
935 cx.listener(|this, _: &ClickEvent, cx| this.commit_changes(&CommitChanges, cx)),
936 );
937
938 let commit_all_button = self
939 .panel_button("commit-all-changes", "Commit All")
940 .tooltip(move |cx| {
941 let focus_handle = focus_handle_2.clone();
942 Tooltip::for_action_in(
943 "Commit all changes, including unstaged changes",
944 &CommitAllChanges,
945 &focus_handle,
946 cx,
947 )
948 })
949 .disabled(!can_commit_all)
950 .on_click(cx.listener(|this, _: &ClickEvent, cx| {
951 this.commit_all_changes(&CommitAllChanges, cx)
952 }));
953
954 div().w_full().h(px(140.)).px_2().pt_1().pb_2().child(
955 v_flex()
956 .id("commit-editor-container")
957 .relative()
958 .h_full()
959 .py_2p5()
960 .px_3()
961 .bg(cx.theme().colors().editor_background)
962 .on_click(cx.listener(move |_, _: &ClickEvent, cx| cx.focus(&editor_focus_handle)))
963 .child(self.commit_editor.clone())
964 .child(
965 h_flex()
966 .absolute()
967 .bottom_2p5()
968 .right_3()
969 .child(div().gap_1().flex_grow())
970 .child(if self.current_modifiers.alt {
971 commit_all_button
972 } else {
973 commit_staged_button
974 }),
975 ),
976 )
977 }
978
979 fn render_empty_state(&self, cx: &ViewContext<Self>) -> impl IntoElement {
980 h_flex()
981 .h_full()
982 .flex_1()
983 .justify_center()
984 .items_center()
985 .child(
986 v_flex()
987 .gap_3()
988 .child("No changes to commit")
989 .text_ui_sm(cx)
990 .mx_auto()
991 .text_color(Color::Placeholder.color(cx)),
992 )
993 }
994
995 fn render_scrollbar(&self, cx: &mut ViewContext<Self>) -> Option<Stateful<Div>> {
996 let scroll_bar_style = self.show_scrollbar(cx);
997 let show_container = matches!(scroll_bar_style, ShowScrollbar::Always);
998
999 if !self.should_show_scrollbar(cx)
1000 || !(self.show_scrollbar || self.scrollbar_state.is_dragging())
1001 {
1002 return None;
1003 }
1004
1005 Some(
1006 div()
1007 .id("git-panel-vertical-scroll")
1008 .occlude()
1009 .flex_none()
1010 .h_full()
1011 .cursor_default()
1012 .when(show_container, |this| this.pl_1().px_1p5())
1013 .when(!show_container, |this| {
1014 this.absolute().right_1().top_1().bottom_1().w(px(12.))
1015 })
1016 .on_mouse_move(cx.listener(|_, _, cx| {
1017 cx.notify();
1018 cx.stop_propagation()
1019 }))
1020 .on_hover(|_, cx| {
1021 cx.stop_propagation();
1022 })
1023 .on_any_mouse_down(|_, cx| {
1024 cx.stop_propagation();
1025 })
1026 .on_mouse_up(
1027 MouseButton::Left,
1028 cx.listener(|this, _, cx| {
1029 if !this.scrollbar_state.is_dragging()
1030 && !this.focus_handle.contains_focused(cx)
1031 {
1032 this.hide_scrollbar(cx);
1033 cx.notify();
1034 }
1035
1036 cx.stop_propagation();
1037 }),
1038 )
1039 .on_scroll_wheel(cx.listener(|_, _, cx| {
1040 cx.notify();
1041 }))
1042 .children(Scrollbar::vertical(
1043 // percentage as f32..end_offset as f32,
1044 self.scrollbar_state.clone(),
1045 )),
1046 )
1047 }
1048
1049 fn render_entries(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1050 let entry_count = self.visible_entries.len();
1051
1052 h_flex()
1053 .size_full()
1054 .overflow_hidden()
1055 .child(
1056 uniform_list(cx.view().clone(), "entries", entry_count, {
1057 move |git_panel, range, cx| {
1058 let mut items = Vec::with_capacity(range.end - range.start);
1059 git_panel.for_each_visible_entry(range, cx, |ix, details, cx| {
1060 items.push(git_panel.render_entry(ix, details, cx));
1061 });
1062 items
1063 }
1064 })
1065 .size_full()
1066 .with_sizing_behavior(ListSizingBehavior::Infer)
1067 .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
1068 // .with_width_from_item(self.max_width_item_index)
1069 .track_scroll(self.scroll_handle.clone()),
1070 )
1071 .children(self.render_scrollbar(cx))
1072 }
1073
1074 fn render_entry(
1075 &self,
1076 ix: usize,
1077 entry_details: GitListEntry,
1078 cx: &ViewContext<Self>,
1079 ) -> impl IntoElement {
1080 let repo_path = entry_details.repo_path.clone();
1081 let selected = self.selected_entry == Some(ix);
1082 let status_style = GitPanelSettings::get_global(cx).status_style;
1083 let status = entry_details.status;
1084
1085 let mut label_color = cx.theme().colors().text;
1086 if status_style == StatusStyle::LabelColor {
1087 label_color = if status.is_conflicted() {
1088 cx.theme().status().conflict
1089 } else if status.is_modified() {
1090 cx.theme().status().modified
1091 } else if status.is_deleted() {
1092 cx.theme().colors().text_disabled
1093 } else {
1094 cx.theme().status().created
1095 }
1096 }
1097
1098 let path_color = status
1099 .is_deleted()
1100 .then_some(cx.theme().colors().text_disabled)
1101 .unwrap_or(cx.theme().colors().text_muted);
1102
1103 let entry_id = ElementId::Name(format!("entry_{}", entry_details.display_name).into());
1104 let checkbox_id =
1105 ElementId::Name(format!("checkbox_{}", entry_details.display_name).into());
1106 let is_tree_view = false;
1107 let handle = cx.view().downgrade();
1108
1109 let end_slot = h_flex()
1110 .invisible()
1111 .when(selected, |this| this.visible())
1112 .when(!selected, |this| {
1113 this.group_hover("git-panel-entry", |this| this.visible())
1114 })
1115 .gap_1()
1116 .items_center()
1117 .child(
1118 IconButton::new("more", IconName::EllipsisVertical)
1119 .icon_color(Color::Placeholder)
1120 .icon_size(IconSize::Small),
1121 );
1122
1123 let mut entry = h_flex()
1124 .id(entry_id)
1125 .group("git-panel-entry")
1126 .h(px(28.))
1127 .w_full()
1128 .pr(px(4.))
1129 .items_center()
1130 .gap_2()
1131 .font_buffer(cx)
1132 .text_ui_sm(cx)
1133 .when(!selected, |this| {
1134 this.hover(|this| this.bg(cx.theme().colors().ghost_element_hover))
1135 });
1136
1137 if is_tree_view {
1138 entry = entry.pl(px(8. + 12. * entry_details.depth as f32))
1139 } else {
1140 entry = entry.pl(px(8.))
1141 }
1142
1143 if selected {
1144 entry = entry.bg(cx.theme().status().info_background);
1145 }
1146
1147 entry = entry
1148 .child(
1149 Checkbox::new(
1150 checkbox_id,
1151 entry_details
1152 .is_staged
1153 .map_or(ToggleState::Indeterminate, ToggleState::from),
1154 )
1155 .fill()
1156 .elevation(ElevationIndex::Surface)
1157 .on_click({
1158 let handle = handle.clone();
1159 let repo_path = repo_path.clone();
1160 move |toggle, cx| {
1161 let Some(this) = handle.upgrade() else {
1162 return;
1163 };
1164 this.update(cx, |this, cx| {
1165 this.visible_entries[ix].is_staged = match *toggle {
1166 ToggleState::Selected => Some(true),
1167 ToggleState::Unselected => Some(false),
1168 ToggleState::Indeterminate => None,
1169 };
1170 let repo_path = repo_path.clone();
1171 let Some(active_repository) = this.active_repository.as_ref() else {
1172 return;
1173 };
1174 let result = match toggle {
1175 ToggleState::Selected | ToggleState::Indeterminate => {
1176 active_repository
1177 .stage_entries(vec![repo_path], this.err_sender.clone())
1178 }
1179 ToggleState::Unselected => active_repository
1180 .unstage_entries(vec![repo_path], this.err_sender.clone()),
1181 };
1182 if let Err(e) = result {
1183 this.show_err_toast("toggle staged error", e, cx);
1184 }
1185 });
1186 }
1187 }),
1188 )
1189 .when(status_style == StatusStyle::Icon, |this| {
1190 this.child(git_status_icon(status))
1191 })
1192 .child(
1193 h_flex()
1194 .text_color(label_color)
1195 .when(status.is_deleted(), |this| this.line_through())
1196 .when_some(repo_path.parent(), |this, parent| {
1197 let parent_str = parent.to_string_lossy();
1198 if !parent_str.is_empty() {
1199 this.child(
1200 div()
1201 .text_color(path_color)
1202 .child(format!("{}/", parent_str)),
1203 )
1204 } else {
1205 this
1206 }
1207 })
1208 .child(div().child(entry_details.display_name.clone())),
1209 )
1210 .child(div().flex_1())
1211 .child(end_slot)
1212 .on_click(move |_, cx| {
1213 // TODO: add `select_entry` method then do after that
1214 cx.dispatch_action(Box::new(OpenSelected));
1215
1216 handle
1217 .update(cx, |git_panel, _| {
1218 git_panel.selected_entry = Some(ix);
1219 })
1220 .ok();
1221 });
1222
1223 entry
1224 }
1225}
1226
1227impl Render for GitPanel {
1228 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1229 let project = self.project.read(cx);
1230 let has_entries = self
1231 .active_repository
1232 .as_ref()
1233 .map_or(false, |active_repository| {
1234 active_repository.entry_count() > 0
1235 });
1236 let has_co_authors = self
1237 .workspace
1238 .upgrade()
1239 .and_then(|workspace| workspace.read(cx).active_call()?.read(cx).room().cloned())
1240 .map(|room| {
1241 let room = room.read(cx);
1242 room.local_participant().can_write()
1243 && room
1244 .remote_participants()
1245 .values()
1246 .any(|remote_participant| remote_participant.can_write())
1247 })
1248 .unwrap_or(false);
1249
1250 v_flex()
1251 .id("git_panel")
1252 .key_context(self.dispatch_context(cx))
1253 .track_focus(&self.focus_handle)
1254 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
1255 .when(!project.is_read_only(cx), |this| {
1256 this.on_action(cx.listener(|this, &ToggleStaged, cx| {
1257 this.toggle_staged_for_selected(&ToggleStaged, cx)
1258 }))
1259 .on_action(cx.listener(|this, &StageAll, cx| this.stage_all(&StageAll, cx)))
1260 .on_action(cx.listener(|this, &UnstageAll, cx| this.unstage_all(&UnstageAll, cx)))
1261 .on_action(cx.listener(|this, &RevertAll, cx| this.discard_all(&RevertAll, cx)))
1262 .on_action(
1263 cx.listener(|this, &CommitChanges, cx| this.commit_changes(&CommitChanges, cx)),
1264 )
1265 .on_action(cx.listener(|this, &CommitAllChanges, cx| {
1266 this.commit_all_changes(&CommitAllChanges, cx)
1267 }))
1268 })
1269 .when(self.is_focused(cx), |this| {
1270 this.on_action(cx.listener(Self::select_first))
1271 .on_action(cx.listener(Self::select_next))
1272 .on_action(cx.listener(Self::select_prev))
1273 .on_action(cx.listener(Self::select_last))
1274 .on_action(cx.listener(Self::close_panel))
1275 })
1276 .on_action(cx.listener(Self::open_selected))
1277 .on_action(cx.listener(Self::focus_changes_list))
1278 .on_action(cx.listener(Self::focus_editor))
1279 .on_action(cx.listener(Self::toggle_staged_for_selected))
1280 .when(has_co_authors, |git_panel| {
1281 git_panel.on_action(cx.listener(Self::fill_co_authors))
1282 })
1283 // .on_action(cx.listener(|this, &OpenSelected, cx| this.open_selected(&OpenSelected, cx)))
1284 .on_hover(cx.listener(|this, hovered, cx| {
1285 if *hovered {
1286 this.show_scrollbar = true;
1287 this.hide_scrollbar_task.take();
1288 cx.notify();
1289 } else if !this.focus_handle.contains_focused(cx) {
1290 this.hide_scrollbar(cx);
1291 }
1292 }))
1293 .size_full()
1294 .overflow_hidden()
1295 .font_buffer(cx)
1296 .py_1()
1297 .bg(ElevationIndex::Surface.bg(cx))
1298 .child(self.render_panel_header(cx))
1299 .child(self.render_divider(cx))
1300 .child(if has_entries {
1301 self.render_entries(cx).into_any_element()
1302 } else {
1303 self.render_empty_state(cx).into_any_element()
1304 })
1305 .child(self.render_divider(cx))
1306 .child(self.render_commit_editor(cx))
1307 }
1308}
1309
1310impl FocusableView for GitPanel {
1311 fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
1312 self.focus_handle.clone()
1313 }
1314}
1315
1316impl EventEmitter<Event> for GitPanel {}
1317
1318impl EventEmitter<PanelEvent> for GitPanel {}
1319
1320impl Panel for GitPanel {
1321 fn persistent_name() -> &'static str {
1322 "GitPanel"
1323 }
1324
1325 fn position(&self, cx: &WindowContext) -> DockPosition {
1326 GitPanelSettings::get_global(cx).dock
1327 }
1328
1329 fn position_is_valid(&self, position: DockPosition) -> bool {
1330 matches!(position, DockPosition::Left | DockPosition::Right)
1331 }
1332
1333 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1334 settings::update_settings_file::<GitPanelSettings>(
1335 self.fs.clone(),
1336 cx,
1337 move |settings, _| settings.dock = Some(position),
1338 );
1339 }
1340
1341 fn size(&self, cx: &WindowContext) -> Pixels {
1342 self.width
1343 .unwrap_or_else(|| GitPanelSettings::get_global(cx).default_width)
1344 }
1345
1346 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1347 self.width = size;
1348 self.serialize(cx);
1349 cx.notify();
1350 }
1351
1352 fn icon(&self, cx: &WindowContext) -> Option<ui::IconName> {
1353 Some(ui::IconName::GitBranch).filter(|_| GitPanelSettings::get_global(cx).button)
1354 }
1355
1356 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1357 Some("Git Panel")
1358 }
1359
1360 fn toggle_action(&self) -> Box<dyn Action> {
1361 Box::new(ToggleFocus)
1362 }
1363
1364 fn activation_priority(&self) -> u32 {
1365 2
1366 }
1367}