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