1use std::any::{Any, TypeId};
2
3use ::git::UnstageAndNext;
4use anyhow::Result;
5use buffer_diff::{BufferDiff, DiffHunkSecondaryStatus};
6use collections::HashSet;
7use editor::{
8 actions::{GoToHunk, GoToPrevHunk},
9 scroll::Autoscroll,
10 Editor, EditorEvent, ToPoint,
11};
12use feature_flags::FeatureFlagViewExt;
13use futures::StreamExt;
14use git::{status::FileStatus, Commit, StageAll, StageAndNext, ToggleStaged, UnstageAll};
15use gpui::{
16 actions, Action, AnyElement, AnyView, App, AppContext as _, AsyncWindowContext, Entity,
17 EventEmitter, FocusHandle, Focusable, Render, Subscription, Task, WeakEntity,
18};
19use language::{Anchor, Buffer, Capability, OffsetRangeExt, Point};
20use multi_buffer::{MultiBuffer, PathKey};
21use project::{git::GitStore, Project, ProjectPath};
22use theme::ActiveTheme;
23use ui::{prelude::*, vertical_divider, Tooltip};
24use util::ResultExt as _;
25use workspace::{
26 item::{BreadcrumbText, Item, ItemEvent, ItemHandle, TabContentParams},
27 searchable::SearchableItemHandle,
28 ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
29 Workspace,
30};
31
32use crate::git_panel::{GitPanel, GitPanelAddon, GitStatusEntry};
33
34actions!(git, [Diff]);
35
36pub struct ProjectDiff {
37 multibuffer: Entity<MultiBuffer>,
38 editor: Entity<Editor>,
39 project: Entity<Project>,
40 git_store: Entity<GitStore>,
41 workspace: WeakEntity<Workspace>,
42 focus_handle: FocusHandle,
43 update_needed: postage::watch::Sender<()>,
44 pending_scroll: Option<PathKey>,
45
46 _task: Task<Result<()>>,
47 _subscription: Subscription,
48}
49
50struct DiffBuffer {
51 path_key: PathKey,
52 buffer: Entity<Buffer>,
53 diff: Entity<BufferDiff>,
54 file_status: FileStatus,
55}
56
57const CONFLICT_NAMESPACE: &'static str = "0";
58const TRACKED_NAMESPACE: &'static str = "1";
59const NEW_NAMESPACE: &'static str = "2";
60
61impl ProjectDiff {
62 pub(crate) fn register(
63 _: &mut Workspace,
64 window: Option<&mut Window>,
65 cx: &mut Context<Workspace>,
66 ) {
67 let Some(window) = window else { return };
68 cx.when_flag_enabled::<feature_flags::GitUiFeatureFlag>(window, |workspace, _, _cx| {
69 workspace.register_action(Self::deploy);
70 });
71
72 workspace::register_serializable_item::<ProjectDiff>(cx);
73 }
74
75 fn deploy(
76 workspace: &mut Workspace,
77 _: &Diff,
78 window: &mut Window,
79 cx: &mut Context<Workspace>,
80 ) {
81 Self::deploy_at(workspace, None, window, cx)
82 }
83
84 pub fn deploy_at(
85 workspace: &mut Workspace,
86 entry: Option<GitStatusEntry>,
87 window: &mut Window,
88 cx: &mut Context<Workspace>,
89 ) {
90 let project_diff = if let Some(existing) = workspace.item_of_type::<Self>(cx) {
91 workspace.activate_item(&existing, true, true, window, cx);
92 existing
93 } else {
94 let workspace_handle = cx.entity();
95 let project_diff =
96 cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx));
97 workspace.add_item_to_active_pane(
98 Box::new(project_diff.clone()),
99 None,
100 true,
101 window,
102 cx,
103 );
104 project_diff
105 };
106 if let Some(entry) = entry {
107 project_diff.update(cx, |project_diff, cx| {
108 project_diff.scroll_to(entry, window, cx);
109 })
110 }
111 }
112
113 fn new(
114 project: Entity<Project>,
115 workspace: Entity<Workspace>,
116 window: &mut Window,
117 cx: &mut Context<Self>,
118 ) -> Self {
119 let focus_handle = cx.focus_handle();
120 let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
121
122 let editor = cx.new(|cx| {
123 let mut diff_display_editor = Editor::for_multibuffer(
124 multibuffer.clone(),
125 Some(project.clone()),
126 true,
127 window,
128 cx,
129 );
130 diff_display_editor.set_expand_all_diff_hunks(cx);
131 diff_display_editor.register_addon(GitPanelAddon {
132 workspace: workspace.downgrade(),
133 });
134 diff_display_editor
135 });
136 cx.subscribe_in(&editor, window, Self::handle_editor_event)
137 .detach();
138
139 let git_store = project.read(cx).git_store().clone();
140 let git_store_subscription = cx.subscribe_in(
141 &git_store,
142 window,
143 move |this, _git_store, _event, _window, _cx| {
144 *this.update_needed.borrow_mut() = ();
145 },
146 );
147
148 let (mut send, recv) = postage::watch::channel::<()>();
149 let worker = window.spawn(cx, {
150 let this = cx.weak_entity();
151 |cx| Self::handle_status_updates(this, recv, cx)
152 });
153 // Kick of a refresh immediately
154 *send.borrow_mut() = ();
155
156 Self {
157 project,
158 git_store: git_store.clone(),
159 workspace: workspace.downgrade(),
160 focus_handle,
161 editor,
162 multibuffer,
163 pending_scroll: None,
164 update_needed: send,
165 _task: worker,
166 _subscription: git_store_subscription,
167 }
168 }
169
170 pub fn scroll_to(
171 &mut self,
172 entry: GitStatusEntry,
173 window: &mut Window,
174 cx: &mut Context<Self>,
175 ) {
176 let Some(git_repo) = self.git_store.read(cx).active_repository() else {
177 return;
178 };
179 let repo = git_repo.read(cx);
180
181 let namespace = if repo.has_conflict(&entry.repo_path) {
182 CONFLICT_NAMESPACE
183 } else if entry.status.is_created() {
184 NEW_NAMESPACE
185 } else {
186 TRACKED_NAMESPACE
187 };
188
189 let path_key = PathKey::namespaced(namespace, entry.repo_path.0.clone());
190
191 self.scroll_to_path(path_key, window, cx)
192 }
193
194 fn scroll_to_path(&mut self, path_key: PathKey, window: &mut Window, cx: &mut Context<Self>) {
195 if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {
196 self.editor.update(cx, |editor, cx| {
197 editor.change_selections(Some(Autoscroll::focused()), window, cx, |s| {
198 s.select_ranges([position..position]);
199 })
200 })
201 } else {
202 self.pending_scroll = Some(path_key);
203 }
204 }
205
206 fn button_states(&self, cx: &App) -> ButtonStates {
207 let editor = self.editor.read(cx);
208 let snapshot = self.multibuffer.read(cx).snapshot(cx);
209 let prev_next = snapshot.diff_hunks().skip(1).next().is_some();
210 let mut selection = true;
211
212 let mut ranges = editor
213 .selections
214 .disjoint_anchor_ranges()
215 .collect::<Vec<_>>();
216 if !ranges.iter().any(|range| range.start != range.end) {
217 selection = false;
218 if let Some((excerpt_id, buffer, range)) = self.editor.read(cx).active_excerpt(cx) {
219 ranges = vec![multi_buffer::Anchor::range_in_buffer(
220 excerpt_id,
221 buffer.read(cx).remote_id(),
222 range,
223 )];
224 } else {
225 ranges = Vec::default();
226 }
227 }
228 let mut has_staged_hunks = false;
229 let mut has_unstaged_hunks = false;
230 for hunk in editor.diff_hunks_in_ranges(&ranges, &snapshot) {
231 match hunk.secondary_status {
232 DiffHunkSecondaryStatus::HasSecondaryHunk => {
233 has_unstaged_hunks = true;
234 }
235 DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk => {
236 has_staged_hunks = true;
237 has_unstaged_hunks = true;
238 }
239 DiffHunkSecondaryStatus::None => {
240 has_staged_hunks = true;
241 }
242 }
243 }
244 let mut commit = false;
245 let mut stage_all = false;
246 let mut unstage_all = false;
247 self.workspace
248 .read_with(cx, |workspace, cx| {
249 if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
250 let git_panel = git_panel.read(cx);
251 commit = git_panel.can_commit();
252 stage_all = git_panel.can_stage_all();
253 unstage_all = git_panel.can_unstage_all();
254 }
255 })
256 .ok();
257
258 return ButtonStates {
259 stage: has_unstaged_hunks,
260 unstage: has_staged_hunks,
261 prev_next,
262 selection,
263 commit,
264 stage_all,
265 unstage_all,
266 };
267 }
268
269 fn handle_editor_event(
270 &mut self,
271 editor: &Entity<Editor>,
272 event: &EditorEvent,
273 window: &mut Window,
274 cx: &mut Context<Self>,
275 ) {
276 match event {
277 EditorEvent::ScrollPositionChanged { .. } => editor.update(cx, |editor, cx| {
278 let anchor = editor.scroll_manager.anchor().anchor;
279 let multibuffer = self.multibuffer.read(cx);
280 let snapshot = multibuffer.snapshot(cx);
281 let mut point = anchor.to_point(&snapshot);
282 point.row = (point.row + 1).min(snapshot.max_row().0);
283
284 let Some((_, buffer, _)) = self.multibuffer.read(cx).excerpt_containing(point, cx)
285 else {
286 return;
287 };
288 let Some(project_path) = buffer
289 .read(cx)
290 .file()
291 .map(|file| (file.worktree_id(cx), file.path().clone()))
292 else {
293 return;
294 };
295 self.workspace
296 .update(cx, |workspace, cx| {
297 if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
298 git_panel.update(cx, |git_panel, cx| {
299 git_panel.select_entry_by_path(project_path.into(), window, cx)
300 })
301 }
302 })
303 .ok();
304 }),
305 _ => {}
306 }
307 }
308
309 fn load_buffers(&mut self, cx: &mut Context<Self>) -> Vec<Task<Result<DiffBuffer>>> {
310 let Some(repo) = self.git_store.read(cx).active_repository() else {
311 self.multibuffer.update(cx, |multibuffer, cx| {
312 multibuffer.clear(cx);
313 });
314 return vec![];
315 };
316
317 let mut previous_paths = self.multibuffer.read(cx).paths().collect::<HashSet<_>>();
318
319 let mut result = vec![];
320 repo.update(cx, |repo, cx| {
321 for entry in repo.status() {
322 if !entry.status.has_changes() {
323 continue;
324 }
325 let Some(project_path) = repo.repo_path_to_project_path(&entry.repo_path) else {
326 continue;
327 };
328 let namespace = if repo.has_conflict(&entry.repo_path) {
329 CONFLICT_NAMESPACE
330 } else if entry.status.is_created() {
331 NEW_NAMESPACE
332 } else {
333 TRACKED_NAMESPACE
334 };
335 let path_key = PathKey::namespaced(namespace, entry.repo_path.0.clone());
336
337 previous_paths.remove(&path_key);
338 let load_buffer = self
339 .project
340 .update(cx, |project, cx| project.open_buffer(project_path, cx));
341
342 let project = self.project.clone();
343 result.push(cx.spawn(|_, mut cx| async move {
344 let buffer = load_buffer.await?;
345 let changes = project
346 .update(&mut cx, |project, cx| {
347 project.open_uncommitted_diff(buffer.clone(), cx)
348 })?
349 .await?;
350 Ok(DiffBuffer {
351 path_key,
352 buffer,
353 diff: changes,
354 file_status: entry.status,
355 })
356 }));
357 }
358 });
359 self.multibuffer.update(cx, |multibuffer, cx| {
360 for path in previous_paths {
361 multibuffer.remove_excerpts_for_path(path, cx);
362 }
363 });
364 result
365 }
366
367 fn register_buffer(
368 &mut self,
369 diff_buffer: DiffBuffer,
370 window: &mut Window,
371 cx: &mut Context<Self>,
372 ) {
373 let path_key = diff_buffer.path_key;
374 let buffer = diff_buffer.buffer;
375 let diff = diff_buffer.diff;
376
377 let snapshot = buffer.read(cx).snapshot();
378 let diff = diff.read(cx);
379 let diff_hunk_ranges = if diff.base_text().is_none() {
380 vec![Point::zero()..snapshot.max_point()]
381 } else {
382 diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &snapshot, cx)
383 .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot))
384 .collect::<Vec<_>>()
385 };
386
387 let is_excerpt_newly_added = self.multibuffer.update(cx, |multibuffer, cx| {
388 multibuffer.set_excerpts_for_path(
389 path_key.clone(),
390 buffer,
391 diff_hunk_ranges,
392 editor::DEFAULT_MULTIBUFFER_CONTEXT,
393 cx,
394 )
395 });
396
397 if is_excerpt_newly_added && diff_buffer.file_status.is_deleted() {
398 self.editor.update(cx, |editor, cx| {
399 editor.fold_buffer(snapshot.text.remote_id(), cx)
400 });
401 }
402
403 if self.multibuffer.read(cx).is_empty()
404 && self
405 .editor
406 .read(cx)
407 .focus_handle(cx)
408 .contains_focused(window, cx)
409 {
410 self.focus_handle.focus(window);
411 } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
412 self.editor.update(cx, |editor, cx| {
413 editor.focus_handle(cx).focus(window);
414 });
415 }
416 if self.pending_scroll.as_ref() == Some(&path_key) {
417 self.scroll_to_path(path_key, window, cx);
418 }
419 }
420
421 pub async fn handle_status_updates(
422 this: WeakEntity<Self>,
423 mut recv: postage::watch::Receiver<()>,
424 mut cx: AsyncWindowContext,
425 ) -> Result<()> {
426 while let Some(_) = recv.next().await {
427 let buffers_to_load = this.update(&mut cx, |this, cx| this.load_buffers(cx))?;
428 for buffer_to_load in buffers_to_load {
429 if let Some(buffer) = buffer_to_load.await.log_err() {
430 cx.update(|window, cx| {
431 this.update(cx, |this, cx| this.register_buffer(buffer, window, cx))
432 .ok();
433 })?;
434 }
435 }
436 this.update(&mut cx, |this, _| this.pending_scroll.take())?;
437 }
438
439 Ok(())
440 }
441
442 #[cfg(any(test, feature = "test-support"))]
443 pub fn excerpt_paths(&self, cx: &App) -> Vec<String> {
444 self.multibuffer
445 .read(cx)
446 .excerpt_paths()
447 .map(|key| key.path().to_string_lossy().to_string())
448 .collect()
449 }
450}
451
452impl EventEmitter<EditorEvent> for ProjectDiff {}
453
454impl Focusable for ProjectDiff {
455 fn focus_handle(&self, cx: &App) -> FocusHandle {
456 if self.multibuffer.read(cx).is_empty() {
457 self.focus_handle.clone()
458 } else {
459 self.editor.focus_handle(cx)
460 }
461 }
462}
463
464impl Item for ProjectDiff {
465 type Event = EditorEvent;
466
467 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
468 Some(Icon::new(IconName::GitBranch).color(Color::Muted))
469 }
470
471 fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
472 Editor::to_item_events(event, f)
473 }
474
475 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
476 self.editor
477 .update(cx, |editor, cx| editor.deactivated(window, cx));
478 }
479
480 fn navigate(
481 &mut self,
482 data: Box<dyn Any>,
483 window: &mut Window,
484 cx: &mut Context<Self>,
485 ) -> bool {
486 self.editor
487 .update(cx, |editor, cx| editor.navigate(data, window, cx))
488 }
489
490 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
491 Some("Project Diff".into())
492 }
493
494 fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
495 Label::new("Uncommitted Changes")
496 .color(if params.selected {
497 Color::Default
498 } else {
499 Color::Muted
500 })
501 .into_any_element()
502 }
503
504 fn telemetry_event_text(&self) -> Option<&'static str> {
505 Some("Project Diff Opened")
506 }
507
508 fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
509 Some(Box::new(self.editor.clone()))
510 }
511
512 fn for_each_project_item(
513 &self,
514 cx: &App,
515 f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
516 ) {
517 self.editor.for_each_project_item(cx, f)
518 }
519
520 fn is_singleton(&self, _: &App) -> bool {
521 false
522 }
523
524 fn set_nav_history(
525 &mut self,
526 nav_history: ItemNavHistory,
527 _: &mut Window,
528 cx: &mut Context<Self>,
529 ) {
530 self.editor.update(cx, |editor, _| {
531 editor.set_nav_history(Some(nav_history));
532 });
533 }
534
535 fn clone_on_split(
536 &self,
537 _workspace_id: Option<workspace::WorkspaceId>,
538 window: &mut Window,
539 cx: &mut Context<Self>,
540 ) -> Option<Entity<Self>>
541 where
542 Self: Sized,
543 {
544 let workspace = self.workspace.upgrade()?;
545 Some(cx.new(|cx| ProjectDiff::new(self.project.clone(), workspace, window, cx)))
546 }
547
548 fn is_dirty(&self, cx: &App) -> bool {
549 self.multibuffer.read(cx).is_dirty(cx)
550 }
551
552 fn has_conflict(&self, cx: &App) -> bool {
553 self.multibuffer.read(cx).has_conflict(cx)
554 }
555
556 fn can_save(&self, _: &App) -> bool {
557 true
558 }
559
560 fn save(
561 &mut self,
562 format: bool,
563 project: Entity<Project>,
564 window: &mut Window,
565 cx: &mut Context<Self>,
566 ) -> Task<Result<()>> {
567 self.editor.save(format, project, window, cx)
568 }
569
570 fn save_as(
571 &mut self,
572 _: Entity<Project>,
573 _: ProjectPath,
574 _window: &mut Window,
575 _: &mut Context<Self>,
576 ) -> Task<Result<()>> {
577 unreachable!()
578 }
579
580 fn reload(
581 &mut self,
582 project: Entity<Project>,
583 window: &mut Window,
584 cx: &mut Context<Self>,
585 ) -> Task<Result<()>> {
586 self.editor.reload(project, window, cx)
587 }
588
589 fn act_as_type<'a>(
590 &'a self,
591 type_id: TypeId,
592 self_handle: &'a Entity<Self>,
593 _: &'a App,
594 ) -> Option<AnyView> {
595 if type_id == TypeId::of::<Self>() {
596 Some(self_handle.to_any())
597 } else if type_id == TypeId::of::<Editor>() {
598 Some(self.editor.to_any())
599 } else {
600 None
601 }
602 }
603
604 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
605 ToolbarItemLocation::PrimaryLeft
606 }
607
608 fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
609 self.editor.breadcrumbs(theme, cx)
610 }
611
612 fn added_to_workspace(
613 &mut self,
614 workspace: &mut Workspace,
615 window: &mut Window,
616 cx: &mut Context<Self>,
617 ) {
618 self.editor.update(cx, |editor, cx| {
619 editor.added_to_workspace(workspace, window, cx)
620 });
621 }
622}
623
624impl Render for ProjectDiff {
625 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
626 let is_empty = self.multibuffer.read(cx).is_empty();
627
628 div()
629 .track_focus(&self.focus_handle)
630 .key_context(if is_empty { "EmptyPane" } else { "GitDiff" })
631 .bg(cx.theme().colors().editor_background)
632 .flex()
633 .items_center()
634 .justify_center()
635 .size_full()
636 .when(is_empty, |el| {
637 el.child(Label::new("No uncommitted changes"))
638 })
639 .when(!is_empty, |el| el.child(self.editor.clone()))
640 }
641}
642
643impl SerializableItem for ProjectDiff {
644 fn serialized_item_kind() -> &'static str {
645 "ProjectDiff"
646 }
647
648 fn cleanup(
649 _: workspace::WorkspaceId,
650 _: Vec<workspace::ItemId>,
651 _: &mut Window,
652 _: &mut App,
653 ) -> Task<Result<()>> {
654 Task::ready(Ok(()))
655 }
656
657 fn deserialize(
658 _project: Entity<Project>,
659 workspace: WeakEntity<Workspace>,
660 _workspace_id: workspace::WorkspaceId,
661 _item_id: workspace::ItemId,
662 window: &mut Window,
663 cx: &mut App,
664 ) -> Task<Result<Entity<Self>>> {
665 window.spawn(cx, |mut cx| async move {
666 workspace.update_in(&mut cx, |workspace, window, cx| {
667 let workspace_handle = cx.entity();
668 cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx))
669 })
670 })
671 }
672
673 fn serialize(
674 &mut self,
675 _workspace: &mut Workspace,
676 _item_id: workspace::ItemId,
677 _closing: bool,
678 _window: &mut Window,
679 _cx: &mut Context<Self>,
680 ) -> Option<Task<Result<()>>> {
681 None
682 }
683
684 fn should_serialize(&self, _: &Self::Event) -> bool {
685 false
686 }
687}
688
689pub struct ProjectDiffToolbar {
690 project_diff: Option<WeakEntity<ProjectDiff>>,
691 workspace: WeakEntity<Workspace>,
692}
693
694impl ProjectDiffToolbar {
695 pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
696 Self {
697 project_diff: None,
698 workspace: workspace.weak_handle(),
699 }
700 }
701
702 fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
703 self.project_diff.as_ref()?.upgrade()
704 }
705 fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
706 if let Some(project_diff) = self.project_diff(cx) {
707 project_diff.focus_handle(cx).focus(window);
708 }
709 let action = action.boxed_clone();
710 cx.defer(move |cx| {
711 cx.dispatch_action(action.as_ref());
712 })
713 }
714 fn dispatch_panel_action(
715 &self,
716 action: &dyn Action,
717 window: &mut Window,
718 cx: &mut Context<Self>,
719 ) {
720 self.workspace
721 .read_with(cx, |workspace, cx| {
722 if let Some(panel) = workspace.panel::<GitPanel>(cx) {
723 panel.focus_handle(cx).focus(window)
724 }
725 })
726 .ok();
727 let action = action.boxed_clone();
728 cx.defer(move |cx| {
729 cx.dispatch_action(action.as_ref());
730 })
731 }
732}
733
734impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
735
736impl ToolbarItemView for ProjectDiffToolbar {
737 fn set_active_pane_item(
738 &mut self,
739 active_pane_item: Option<&dyn ItemHandle>,
740 _: &mut Window,
741 cx: &mut Context<Self>,
742 ) -> ToolbarItemLocation {
743 self.project_diff = active_pane_item
744 .and_then(|item| item.act_as::<ProjectDiff>(cx))
745 .map(|entity| entity.downgrade());
746 if self.project_diff.is_some() {
747 ToolbarItemLocation::PrimaryRight
748 } else {
749 ToolbarItemLocation::Hidden
750 }
751 }
752
753 fn pane_focus_update(
754 &mut self,
755 _pane_focused: bool,
756 _window: &mut Window,
757 _cx: &mut Context<Self>,
758 ) {
759 }
760}
761
762struct ButtonStates {
763 stage: bool,
764 unstage: bool,
765 prev_next: bool,
766 selection: bool,
767 stage_all: bool,
768 unstage_all: bool,
769 commit: bool,
770}
771
772impl Render for ProjectDiffToolbar {
773 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
774 let Some(project_diff) = self.project_diff(cx) else {
775 return div();
776 };
777 let focus_handle = project_diff.focus_handle(cx);
778 let button_states = project_diff.read(cx).button_states(cx);
779
780 h_group_xl()
781 .my_neg_1()
782 .items_center()
783 .py_1()
784 .pl_2()
785 .pr_1()
786 .flex_wrap()
787 .justify_between()
788 .child(
789 h_group_sm()
790 .when(button_states.selection, |el| {
791 el.child(
792 Button::new("stage", "Toggle Staged")
793 .tooltip(Tooltip::for_action_title_in(
794 "Toggle Staged",
795 &ToggleStaged,
796 &focus_handle,
797 ))
798 .disabled(!button_states.stage && !button_states.unstage)
799 .on_click(cx.listener(|this, _, window, cx| {
800 this.dispatch_action(&ToggleStaged, window, cx)
801 })),
802 )
803 })
804 .when(!button_states.selection, |el| {
805 el.child(
806 Button::new("stage", "Stage")
807 .tooltip(Tooltip::for_action_title_in(
808 "Stage",
809 &StageAndNext,
810 &focus_handle,
811 ))
812 // don't actually disable the button so it's mashable
813 .color(if button_states.stage {
814 Color::Default
815 } else {
816 Color::Disabled
817 })
818 .on_click(cx.listener(|this, _, window, cx| {
819 this.dispatch_action(&StageAndNext, window, cx)
820 })),
821 )
822 .child(
823 Button::new("unstage", "Unstage")
824 .tooltip(Tooltip::for_action_title_in(
825 "Unstage",
826 &UnstageAndNext,
827 &focus_handle,
828 ))
829 .color(if button_states.unstage {
830 Color::Default
831 } else {
832 Color::Disabled
833 })
834 .on_click(cx.listener(|this, _, window, cx| {
835 this.dispatch_action(&UnstageAndNext, window, cx)
836 })),
837 )
838 }),
839 )
840 // n.b. the only reason these arrows are here is because we don't
841 // support "undo" for staging so we need a way to go back.
842 .child(
843 h_group_sm()
844 .child(
845 IconButton::new("up", IconName::ArrowUp)
846 .shape(ui::IconButtonShape::Square)
847 .tooltip(Tooltip::for_action_title_in(
848 "Go to previous hunk",
849 &GoToPrevHunk,
850 &focus_handle,
851 ))
852 .disabled(!button_states.prev_next)
853 .on_click(cx.listener(|this, _, window, cx| {
854 this.dispatch_action(&GoToPrevHunk, window, cx)
855 })),
856 )
857 .child(
858 IconButton::new("down", IconName::ArrowDown)
859 .shape(ui::IconButtonShape::Square)
860 .tooltip(Tooltip::for_action_title_in(
861 "Go to next hunk",
862 &GoToHunk,
863 &focus_handle,
864 ))
865 .disabled(!button_states.prev_next)
866 .on_click(cx.listener(|this, _, window, cx| {
867 this.dispatch_action(&GoToHunk, window, cx)
868 })),
869 ),
870 )
871 .child(vertical_divider())
872 .child(
873 h_group_sm()
874 .when(
875 button_states.unstage_all && !button_states.stage_all,
876 |el| {
877 el.child(
878 Button::new("unstage-all", "Unstage All")
879 .tooltip(Tooltip::for_action_title_in(
880 "Unstage all changes",
881 &UnstageAll,
882 &focus_handle,
883 ))
884 .on_click(cx.listener(|this, _, window, cx| {
885 this.dispatch_panel_action(&UnstageAll, window, cx)
886 })),
887 )
888 },
889 )
890 .when(
891 !button_states.unstage_all || button_states.stage_all,
892 |el| {
893 el.child(
894 // todo make it so that changing to say "Unstaged"
895 // doesn't change the position.
896 div().child(
897 Button::new("stage-all", "Stage All")
898 .disabled(!button_states.stage_all)
899 .tooltip(Tooltip::for_action_title_in(
900 "Stage all changes",
901 &StageAll,
902 &focus_handle,
903 ))
904 .on_click(cx.listener(|this, _, window, cx| {
905 this.dispatch_panel_action(&StageAll, window, cx)
906 })),
907 ),
908 )
909 },
910 )
911 .child(
912 Button::new("commit", "Commit")
913 .disabled(!button_states.commit)
914 .tooltip(Tooltip::for_action_title_in(
915 "Commit",
916 &Commit,
917 &focus_handle,
918 ))
919 .on_click(cx.listener(|this, _, window, cx| {
920 this.dispatch_action(&Commit, window, cx);
921 })),
922 ),
923 )
924 }
925}