project_diff.rs

  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            .bg(cx.theme().colors().editor_background)
631            .flex()
632            .items_center()
633            .justify_center()
634            .size_full()
635            .when(is_empty, |el| {
636                el.child(Label::new("No uncommitted changes"))
637            })
638            .when(!is_empty, |el| el.child(self.editor.clone()))
639    }
640}
641
642impl SerializableItem for ProjectDiff {
643    fn serialized_item_kind() -> &'static str {
644        "ProjectDiff"
645    }
646
647    fn cleanup(
648        _: workspace::WorkspaceId,
649        _: Vec<workspace::ItemId>,
650        _: &mut Window,
651        _: &mut App,
652    ) -> Task<Result<()>> {
653        Task::ready(Ok(()))
654    }
655
656    fn deserialize(
657        _project: Entity<Project>,
658        workspace: WeakEntity<Workspace>,
659        _workspace_id: workspace::WorkspaceId,
660        _item_id: workspace::ItemId,
661        window: &mut Window,
662        cx: &mut App,
663    ) -> Task<Result<Entity<Self>>> {
664        window.spawn(cx, |mut cx| async move {
665            workspace.update_in(&mut cx, |workspace, window, cx| {
666                let workspace_handle = cx.entity();
667                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx))
668            })
669        })
670    }
671
672    fn serialize(
673        &mut self,
674        _workspace: &mut Workspace,
675        _item_id: workspace::ItemId,
676        _closing: bool,
677        _window: &mut Window,
678        _cx: &mut Context<Self>,
679    ) -> Option<Task<Result<()>>> {
680        None
681    }
682
683    fn should_serialize(&self, _: &Self::Event) -> bool {
684        false
685    }
686}
687
688pub struct ProjectDiffToolbar {
689    project_diff: Option<WeakEntity<ProjectDiff>>,
690    workspace: WeakEntity<Workspace>,
691}
692
693impl ProjectDiffToolbar {
694    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
695        Self {
696            project_diff: None,
697            workspace: workspace.weak_handle(),
698        }
699    }
700
701    fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
702        self.project_diff.as_ref()?.upgrade()
703    }
704    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
705        if let Some(project_diff) = self.project_diff(cx) {
706            project_diff.focus_handle(cx).focus(window);
707        }
708        let action = action.boxed_clone();
709        cx.defer(move |cx| {
710            cx.dispatch_action(action.as_ref());
711        })
712    }
713    fn dispatch_panel_action(
714        &self,
715        action: &dyn Action,
716        window: &mut Window,
717        cx: &mut Context<Self>,
718    ) {
719        self.workspace
720            .read_with(cx, |workspace, cx| {
721                if let Some(panel) = workspace.panel::<GitPanel>(cx) {
722                    panel.focus_handle(cx).focus(window)
723                }
724            })
725            .ok();
726        let action = action.boxed_clone();
727        cx.defer(move |cx| {
728            cx.dispatch_action(action.as_ref());
729        })
730    }
731}
732
733impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
734
735impl ToolbarItemView for ProjectDiffToolbar {
736    fn set_active_pane_item(
737        &mut self,
738        active_pane_item: Option<&dyn ItemHandle>,
739        _: &mut Window,
740        cx: &mut Context<Self>,
741    ) -> ToolbarItemLocation {
742        self.project_diff = active_pane_item
743            .and_then(|item| item.act_as::<ProjectDiff>(cx))
744            .map(|entity| entity.downgrade());
745        if self.project_diff.is_some() {
746            ToolbarItemLocation::PrimaryRight
747        } else {
748            ToolbarItemLocation::Hidden
749        }
750    }
751
752    fn pane_focus_update(
753        &mut self,
754        _pane_focused: bool,
755        _window: &mut Window,
756        _cx: &mut Context<Self>,
757    ) {
758    }
759}
760
761struct ButtonStates {
762    stage: bool,
763    unstage: bool,
764    prev_next: bool,
765    selection: bool,
766    stage_all: bool,
767    unstage_all: bool,
768    commit: bool,
769}
770
771impl Render for ProjectDiffToolbar {
772    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
773        let Some(project_diff) = self.project_diff(cx) else {
774            return div();
775        };
776        let focus_handle = project_diff.focus_handle(cx);
777        let button_states = project_diff.read(cx).button_states(cx);
778
779        h_group_xl()
780            .my_neg_1()
781            .items_center()
782            .py_1()
783            .pl_2()
784            .pr_1()
785            .flex_wrap()
786            .justify_between()
787            .child(
788                h_group_sm()
789                    .when(button_states.selection, |el| {
790                        el.child(
791                            Button::new("stage", "Toggle Staged")
792                                .tooltip(Tooltip::for_action_title_in(
793                                    "Toggle Staged",
794                                    &ToggleStaged,
795                                    &focus_handle,
796                                ))
797                                .disabled(!button_states.stage && !button_states.unstage)
798                                .on_click(cx.listener(|this, _, window, cx| {
799                                    this.dispatch_action(&ToggleStaged, window, cx)
800                                })),
801                        )
802                    })
803                    .when(!button_states.selection, |el| {
804                        el.child(
805                            Button::new("stage", "Stage")
806                                .tooltip(Tooltip::for_action_title_in(
807                                    "Stage",
808                                    &StageAndNext,
809                                    &focus_handle,
810                                ))
811                                // don't actually disable the button so it's mashable
812                                .color(if button_states.stage {
813                                    Color::Default
814                                } else {
815                                    Color::Disabled
816                                })
817                                .on_click(cx.listener(|this, _, window, cx| {
818                                    this.dispatch_action(&StageAndNext, window, cx)
819                                })),
820                        )
821                        .child(
822                            Button::new("unstage", "Unstage")
823                                .tooltip(Tooltip::for_action_title_in(
824                                    "Unstage",
825                                    &UnstageAndNext,
826                                    &focus_handle,
827                                ))
828                                .color(if button_states.unstage {
829                                    Color::Default
830                                } else {
831                                    Color::Disabled
832                                })
833                                .on_click(cx.listener(|this, _, window, cx| {
834                                    this.dispatch_action(&UnstageAndNext, window, cx)
835                                })),
836                        )
837                    }),
838            )
839            // n.b. the only reason these arrows are here is because we don't
840            // support "undo" for staging so we need a way to go back.
841            .child(
842                h_group_sm()
843                    .child(
844                        IconButton::new("up", IconName::ArrowUp)
845                            .shape(ui::IconButtonShape::Square)
846                            .tooltip(Tooltip::for_action_title_in(
847                                "Go to previous hunk",
848                                &GoToPrevHunk,
849                                &focus_handle,
850                            ))
851                            .disabled(!button_states.prev_next)
852                            .on_click(cx.listener(|this, _, window, cx| {
853                                this.dispatch_action(&GoToPrevHunk, window, cx)
854                            })),
855                    )
856                    .child(
857                        IconButton::new("down", IconName::ArrowDown)
858                            .shape(ui::IconButtonShape::Square)
859                            .tooltip(Tooltip::for_action_title_in(
860                                "Go to next hunk",
861                                &GoToHunk,
862                                &focus_handle,
863                            ))
864                            .disabled(!button_states.prev_next)
865                            .on_click(cx.listener(|this, _, window, cx| {
866                                this.dispatch_action(&GoToHunk, window, cx)
867                            })),
868                    ),
869            )
870            .child(vertical_divider())
871            .child(
872                h_group_sm()
873                    .when(
874                        button_states.unstage_all && !button_states.stage_all,
875                        |el| {
876                            el.child(Button::new("unstage-all", "Unstage All").on_click(
877                                cx.listener(|this, _, window, cx| {
878                                    this.dispatch_panel_action(&UnstageAll, window, cx)
879                                }),
880                            ))
881                        },
882                    )
883                    .when(
884                        !button_states.unstage_all || button_states.stage_all,
885                        |el| {
886                            el.child(
887                                // todo make it so that changing to say "Unstaged"
888                                // doesn't change the position.
889                                div().child(
890                                    Button::new("stage-all", "Stage All")
891                                        .disabled(!button_states.stage_all)
892                                        .on_click(cx.listener(|this, _, window, cx| {
893                                            this.dispatch_panel_action(&StageAll, window, cx)
894                                        })),
895                                ),
896                            )
897                        },
898                    )
899                    .child(
900                        Button::new("commit", "Commit")
901                            .disabled(!button_states.commit)
902                            .on_click(cx.listener(|this, _, window, cx| {
903                                // todo this should open modal, not focus panel.
904                                this.dispatch_action(&Commit, window, cx);
905                            })),
906                    ),
907            )
908    }
909}