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(crate) 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
443impl EventEmitter<EditorEvent> for ProjectDiff {}
444
445impl Focusable for ProjectDiff {
446    fn focus_handle(&self, cx: &App) -> FocusHandle {
447        if self.multibuffer.read(cx).is_empty() {
448            self.focus_handle.clone()
449        } else {
450            self.editor.focus_handle(cx)
451        }
452    }
453}
454
455impl Item for ProjectDiff {
456    type Event = EditorEvent;
457
458    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
459        Some(Icon::new(IconName::GitBranch).color(Color::Muted))
460    }
461
462    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
463        Editor::to_item_events(event, f)
464    }
465
466    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
467        self.editor
468            .update(cx, |editor, cx| editor.deactivated(window, cx));
469    }
470
471    fn navigate(
472        &mut self,
473        data: Box<dyn Any>,
474        window: &mut Window,
475        cx: &mut Context<Self>,
476    ) -> bool {
477        self.editor
478            .update(cx, |editor, cx| editor.navigate(data, window, cx))
479    }
480
481    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
482        Some("Project Diff".into())
483    }
484
485    fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
486        Label::new("Uncommitted Changes")
487            .color(if params.selected {
488                Color::Default
489            } else {
490                Color::Muted
491            })
492            .into_any_element()
493    }
494
495    fn telemetry_event_text(&self) -> Option<&'static str> {
496        Some("Project Diff Opened")
497    }
498
499    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
500        Some(Box::new(self.editor.clone()))
501    }
502
503    fn for_each_project_item(
504        &self,
505        cx: &App,
506        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
507    ) {
508        self.editor.for_each_project_item(cx, f)
509    }
510
511    fn is_singleton(&self, _: &App) -> bool {
512        false
513    }
514
515    fn set_nav_history(
516        &mut self,
517        nav_history: ItemNavHistory,
518        _: &mut Window,
519        cx: &mut Context<Self>,
520    ) {
521        self.editor.update(cx, |editor, _| {
522            editor.set_nav_history(Some(nav_history));
523        });
524    }
525
526    fn clone_on_split(
527        &self,
528        _workspace_id: Option<workspace::WorkspaceId>,
529        window: &mut Window,
530        cx: &mut Context<Self>,
531    ) -> Option<Entity<Self>>
532    where
533        Self: Sized,
534    {
535        let workspace = self.workspace.upgrade()?;
536        Some(cx.new(|cx| ProjectDiff::new(self.project.clone(), workspace, window, cx)))
537    }
538
539    fn is_dirty(&self, cx: &App) -> bool {
540        self.multibuffer.read(cx).is_dirty(cx)
541    }
542
543    fn has_conflict(&self, cx: &App) -> bool {
544        self.multibuffer.read(cx).has_conflict(cx)
545    }
546
547    fn can_save(&self, _: &App) -> bool {
548        true
549    }
550
551    fn save(
552        &mut self,
553        format: bool,
554        project: Entity<Project>,
555        window: &mut Window,
556        cx: &mut Context<Self>,
557    ) -> Task<Result<()>> {
558        self.editor.save(format, project, window, cx)
559    }
560
561    fn save_as(
562        &mut self,
563        _: Entity<Project>,
564        _: ProjectPath,
565        _window: &mut Window,
566        _: &mut Context<Self>,
567    ) -> Task<Result<()>> {
568        unreachable!()
569    }
570
571    fn reload(
572        &mut self,
573        project: Entity<Project>,
574        window: &mut Window,
575        cx: &mut Context<Self>,
576    ) -> Task<Result<()>> {
577        self.editor.reload(project, window, cx)
578    }
579
580    fn act_as_type<'a>(
581        &'a self,
582        type_id: TypeId,
583        self_handle: &'a Entity<Self>,
584        _: &'a App,
585    ) -> Option<AnyView> {
586        if type_id == TypeId::of::<Self>() {
587            Some(self_handle.to_any())
588        } else if type_id == TypeId::of::<Editor>() {
589            Some(self.editor.to_any())
590        } else {
591            None
592        }
593    }
594
595    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
596        ToolbarItemLocation::PrimaryLeft
597    }
598
599    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
600        self.editor.breadcrumbs(theme, cx)
601    }
602
603    fn added_to_workspace(
604        &mut self,
605        workspace: &mut Workspace,
606        window: &mut Window,
607        cx: &mut Context<Self>,
608    ) {
609        self.editor.update(cx, |editor, cx| {
610            editor.added_to_workspace(workspace, window, cx)
611        });
612    }
613}
614
615impl Render for ProjectDiff {
616    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
617        let is_empty = self.multibuffer.read(cx).is_empty();
618
619        div()
620            .track_focus(&self.focus_handle)
621            .bg(cx.theme().colors().editor_background)
622            .flex()
623            .items_center()
624            .justify_center()
625            .size_full()
626            .when(is_empty, |el| {
627                el.child(Label::new("No uncommitted changes"))
628            })
629            .when(!is_empty, |el| el.child(self.editor.clone()))
630    }
631}
632
633impl SerializableItem for ProjectDiff {
634    fn serialized_item_kind() -> &'static str {
635        "ProjectDiff"
636    }
637
638    fn cleanup(
639        _: workspace::WorkspaceId,
640        _: Vec<workspace::ItemId>,
641        _: &mut Window,
642        _: &mut App,
643    ) -> Task<Result<()>> {
644        Task::ready(Ok(()))
645    }
646
647    fn deserialize(
648        _project: Entity<Project>,
649        workspace: WeakEntity<Workspace>,
650        _workspace_id: workspace::WorkspaceId,
651        _item_id: workspace::ItemId,
652        window: &mut Window,
653        cx: &mut App,
654    ) -> Task<Result<Entity<Self>>> {
655        window.spawn(cx, |mut cx| async move {
656            workspace.update_in(&mut cx, |workspace, window, cx| {
657                let workspace_handle = cx.entity();
658                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx))
659            })
660        })
661    }
662
663    fn serialize(
664        &mut self,
665        _workspace: &mut Workspace,
666        _item_id: workspace::ItemId,
667        _closing: bool,
668        _window: &mut Window,
669        _cx: &mut Context<Self>,
670    ) -> Option<Task<Result<()>>> {
671        None
672    }
673
674    fn should_serialize(&self, _: &Self::Event) -> bool {
675        false
676    }
677}
678
679pub struct ProjectDiffToolbar {
680    project_diff: Option<WeakEntity<ProjectDiff>>,
681    workspace: WeakEntity<Workspace>,
682}
683
684impl ProjectDiffToolbar {
685    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
686        Self {
687            project_diff: None,
688            workspace: workspace.weak_handle(),
689        }
690    }
691
692    fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
693        self.project_diff.as_ref()?.upgrade()
694    }
695    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
696        if let Some(project_diff) = self.project_diff(cx) {
697            project_diff.focus_handle(cx).focus(window);
698        }
699        let action = action.boxed_clone();
700        cx.defer(move |cx| {
701            cx.dispatch_action(action.as_ref());
702        })
703    }
704    fn dispatch_panel_action(
705        &self,
706        action: &dyn Action,
707        window: &mut Window,
708        cx: &mut Context<Self>,
709    ) {
710        self.workspace
711            .read_with(cx, |workspace, cx| {
712                if let Some(panel) = workspace.panel::<GitPanel>(cx) {
713                    panel.focus_handle(cx).focus(window)
714                }
715            })
716            .ok();
717        let action = action.boxed_clone();
718        cx.defer(move |cx| {
719            cx.dispatch_action(action.as_ref());
720        })
721    }
722}
723
724impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
725
726impl ToolbarItemView for ProjectDiffToolbar {
727    fn set_active_pane_item(
728        &mut self,
729        active_pane_item: Option<&dyn ItemHandle>,
730        _: &mut Window,
731        cx: &mut Context<Self>,
732    ) -> ToolbarItemLocation {
733        self.project_diff = active_pane_item
734            .and_then(|item| item.act_as::<ProjectDiff>(cx))
735            .map(|entity| entity.downgrade());
736        if self.project_diff.is_some() {
737            ToolbarItemLocation::PrimaryRight
738        } else {
739            ToolbarItemLocation::Hidden
740        }
741    }
742
743    fn pane_focus_update(
744        &mut self,
745        _pane_focused: bool,
746        _window: &mut Window,
747        _cx: &mut Context<Self>,
748    ) {
749    }
750}
751
752struct ButtonStates {
753    stage: bool,
754    unstage: bool,
755    prev_next: bool,
756    selection: bool,
757    stage_all: bool,
758    unstage_all: bool,
759    commit: bool,
760}
761
762impl Render for ProjectDiffToolbar {
763    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
764        let Some(project_diff) = self.project_diff(cx) else {
765            return div();
766        };
767        let focus_handle = project_diff.focus_handle(cx);
768        let button_states = project_diff.read(cx).button_states(cx);
769
770        h_group_xl()
771            .my_neg_1()
772            .items_center()
773            .py_1()
774            .pl_2()
775            .pr_1()
776            .flex_wrap()
777            .justify_between()
778            .child(
779                h_group_sm()
780                    .when(button_states.selection, |el| {
781                        el.child(
782                            Button::new("stage", "Toggle Staged")
783                                .tooltip(Tooltip::for_action_title_in(
784                                    "Toggle Staged",
785                                    &ToggleStaged,
786                                    &focus_handle,
787                                ))
788                                .disabled(!button_states.stage && !button_states.unstage)
789                                .on_click(cx.listener(|this, _, window, cx| {
790                                    this.dispatch_action(&ToggleStaged, window, cx)
791                                })),
792                        )
793                    })
794                    .when(!button_states.selection, |el| {
795                        el.child(
796                            Button::new("stage", "Stage")
797                                .tooltip(Tooltip::for_action_title_in(
798                                    "Stage",
799                                    &StageAndNext,
800                                    &focus_handle,
801                                ))
802                                // don't actually disable the button so it's mashable
803                                .color(if button_states.stage {
804                                    Color::Default
805                                } else {
806                                    Color::Disabled
807                                })
808                                .on_click(cx.listener(|this, _, window, cx| {
809                                    this.dispatch_action(&StageAndNext, window, cx)
810                                })),
811                        )
812                        .child(
813                            Button::new("unstage", "Unstage")
814                                .tooltip(Tooltip::for_action_title_in(
815                                    "Unstage",
816                                    &UnstageAndNext,
817                                    &focus_handle,
818                                ))
819                                .color(if button_states.unstage {
820                                    Color::Default
821                                } else {
822                                    Color::Disabled
823                                })
824                                .on_click(cx.listener(|this, _, window, cx| {
825                                    this.dispatch_action(&UnstageAndNext, window, cx)
826                                })),
827                        )
828                    }),
829            )
830            // n.b. the only reason these arrows are here is because we don't
831            // support "undo" for staging so we need a way to go back.
832            .child(
833                h_group_sm()
834                    .child(
835                        IconButton::new("up", IconName::ArrowUp)
836                            .shape(ui::IconButtonShape::Square)
837                            .tooltip(Tooltip::for_action_title_in(
838                                "Go to previous hunk",
839                                &GoToPrevHunk,
840                                &focus_handle,
841                            ))
842                            .disabled(!button_states.prev_next)
843                            .on_click(cx.listener(|this, _, window, cx| {
844                                this.dispatch_action(&GoToPrevHunk, window, cx)
845                            })),
846                    )
847                    .child(
848                        IconButton::new("down", IconName::ArrowDown)
849                            .shape(ui::IconButtonShape::Square)
850                            .tooltip(Tooltip::for_action_title_in(
851                                "Go to next hunk",
852                                &GoToHunk,
853                                &focus_handle,
854                            ))
855                            .disabled(!button_states.prev_next)
856                            .on_click(cx.listener(|this, _, window, cx| {
857                                this.dispatch_action(&GoToHunk, window, cx)
858                            })),
859                    ),
860            )
861            .child(vertical_divider())
862            .child(
863                h_group_sm()
864                    .when(
865                        button_states.unstage_all && !button_states.stage_all,
866                        |el| {
867                            el.child(Button::new("unstage-all", "Unstage All").on_click(
868                                cx.listener(|this, _, window, cx| {
869                                    this.dispatch_panel_action(&UnstageAll, window, cx)
870                                }),
871                            ))
872                        },
873                    )
874                    .when(
875                        !button_states.unstage_all || button_states.stage_all,
876                        |el| {
877                            el.child(
878                                // todo make it so that changing to say "Unstaged"
879                                // doesn't change the position.
880                                div().child(
881                                    Button::new("stage-all", "Stage All")
882                                        .disabled(!button_states.stage_all)
883                                        .on_click(cx.listener(|this, _, window, cx| {
884                                            this.dispatch_panel_action(&StageAll, window, cx)
885                                        })),
886                                ),
887                            )
888                        },
889                    )
890                    .child(
891                        Button::new("commit", "Commit")
892                            .disabled(!button_states.commit)
893                            .on_click(cx.listener(|this, _, window, cx| {
894                                // todo this should open modal, not focus panel.
895                                this.dispatch_action(&Commit, window, cx);
896                            })),
897                    ),
898            )
899    }
900}