1438 lines · 50.4 KB · Rust
RawDownload
use crate::git_panel_settings::StatusStyle;use crate::{git_panel_settings::GitPanelSettings, git_status_icon};use anyhow::Result;use db::kvp::KEY_VALUE_STORE;use editor::actions::MoveToEnd;use editor::scroll::ScrollbarAutoHide;use editor::{Editor, EditorMode, EditorSettings, MultiBuffer, ShowScrollbar};use futures::channel::mpsc;use futures::StreamExt as _;use git::repository::RepoPath;use git::status::FileStatus;use git::{CommitAllChanges, CommitChanges, RevertAll, StageAll, ToggleStaged, UnstageAll};use gpui::*;use menu::{SelectFirst, SelectLast, SelectNext, SelectPrev};use project::git::RepositoryHandle;use project::{Fs, Project, ProjectPath};use serde::{Deserialize, Serialize};use settings::Settings as _;use std::{collections::HashSet, ops::Range, path::PathBuf, sync::Arc, time::Duration, usize};use theme::ThemeSettings;use ui::{    prelude::*, Checkbox, Divider, DividerColor, ElevationIndex, Scrollbar, ScrollbarState, Tooltip,};use util::{ResultExt, TryFutureExt};use workspace::notifications::{DetachAndPromptErr, NotificationId};use workspace::Toast;use workspace::{    dock::{DockPosition, Panel, PanelEvent},    Workspace,}; actions!(    git_panel,    [        Close,        ToggleFocus,        OpenMenu,        OpenSelected,        FocusEditor,        FocusChanges,        FillCoAuthors,    ]); const GIT_PANEL_KEY: &str = "GitPanel"; const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50); pub fn init(cx: &mut App) {    cx.observe_new(        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {            workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {                workspace.toggle_panel_focus::<GitPanel>(window, cx);            });        },    )    .detach();} #[derive(Debug, Clone)]pub enum Event {    Focus,    OpenedEntry { path: ProjectPath },} #[derive(Serialize, Deserialize)]struct SerializedGitPanel {    width: Option<Pixels>,} #[derive(Debug, PartialEq, Eq, Clone)]pub struct GitListEntry {    depth: usize,    display_name: String,    repo_path: RepoPath,    status: FileStatus,    is_staged: Option<bool>,} pub struct GitPanel {    current_modifiers: Modifiers,    focus_handle: FocusHandle,    fs: Arc<dyn Fs>,    hide_scrollbar_task: Option<Task<()>>,    pending_serialization: Task<Option<()>>,    workspace: WeakEntity<Workspace>,    project: Entity<Project>,    active_repository: Option<RepositoryHandle>,    scroll_handle: UniformListScrollHandle,    scrollbar_state: ScrollbarState,    selected_entry: Option<usize>,    show_scrollbar: bool,    update_visible_entries_task: Task<()>,    commit_editor: Entity<Editor>,    visible_entries: Vec<GitListEntry>,    all_staged: Option<bool>,    width: Option<Pixels>,    err_sender: mpsc::Sender<anyhow::Error>,} fn commit_message_editor(    active_repository: Option<&RepositoryHandle>,    window: &mut Window,    cx: &mut Context<'_, Editor>,) -> Editor {    let theme = ThemeSettings::get_global(cx);     let mut text_style = window.text_style();    let refinement = TextStyleRefinement {        font_family: Some(theme.buffer_font.family.clone()),        font_features: Some(FontFeatures::disable_ligatures()),        font_size: Some(px(12.).into()),        color: Some(cx.theme().colors().editor_foreground),        background_color: Some(gpui::transparent_black()),        ..Default::default()    };    text_style.refine(&refinement);     let mut commit_editor = if let Some(active_repository) = active_repository.as_ref() {        let buffer = cx.new(|cx| MultiBuffer::singleton(active_repository.commit_message(), cx));        Editor::new(            EditorMode::AutoHeight { max_lines: 10 },            buffer,            None,            false,            window,            cx,        )    } else {        Editor::auto_height(10, window, cx)    };    commit_editor.set_use_autoclose(false);    commit_editor.set_show_gutter(false, cx);    commit_editor.set_show_wrap_guides(false, cx);    commit_editor.set_show_indent_guides(false, cx);    commit_editor.set_text_style_refinement(refinement);    commit_editor.set_placeholder_text("Enter commit message", cx);    commit_editor} impl GitPanel {    pub fn load(        workspace: WeakEntity<Workspace>,        cx: AsyncWindowContext,    ) -> Task<Result<Entity<Self>>> {        cx.spawn(|mut cx| async move { workspace.update_in(&mut cx, Self::new) })    }     pub fn new(        workspace: &mut Workspace,        window: &mut Window,        cx: &mut Context<Workspace>,    ) -> Entity<Self> {        let fs = workspace.app_state().fs.clone();        let project = workspace.project().clone();        let git_state = project.read(cx).git_state().cloned();        let active_repository = project.read(cx).active_repository(cx);        let (err_sender, mut err_receiver) = mpsc::channel(1);        let workspace = cx.entity().downgrade();         let git_panel = cx.new(|cx| {            let focus_handle = cx.focus_handle();            cx.on_focus(&focus_handle, window, Self::focus_in).detach();            cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {                this.hide_scrollbar(window, cx);            })            .detach();             let commit_editor =                cx.new(|cx| commit_message_editor(active_repository.as_ref(), window, cx));             let scroll_handle = UniformListScrollHandle::new();             if let Some(git_state) = git_state {                cx.subscribe_in(                    &git_state,                    window,                    move |this, git_state, event, window, cx| match event {                        project::git::Event::RepositoriesUpdated => {                            this.active_repository = git_state.read(cx).active_repository();                            this.schedule_update(window, cx);                        }                    },                )                .detach();            }             let mut git_panel = Self {                focus_handle: cx.focus_handle(),                pending_serialization: Task::ready(None),                visible_entries: Vec::new(),                all_staged: None,                current_modifiers: window.modifiers(),                width: Some(px(360.)),                scrollbar_state: ScrollbarState::new(scroll_handle.clone())                    .parent_model(&cx.entity()),                selected_entry: None,                show_scrollbar: false,                hide_scrollbar_task: None,                update_visible_entries_task: Task::ready(()),                active_repository,                scroll_handle,                fs,                commit_editor,                project,                err_sender,                workspace,            };            git_panel.schedule_update(window, cx);            git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);            git_panel        });         let handle = git_panel.downgrade();        cx.spawn(|_, mut cx| async move {            while let Some(e) = err_receiver.next().await {                let Some(this) = handle.upgrade() else {                    break;                };                if this                    .update(&mut cx, |this, cx| {                        this.show_err_toast("git operation error", e, cx);                    })                    .is_err()                {                    break;                }            }        })        .detach();         cx.subscribe_in(            &git_panel,            window,            move |workspace, _, event: &Event, window, cx| match event.clone() {                Event::OpenedEntry { path } => {                    workspace                        .open_path_preview(path, None, false, false, window, cx)                        .detach_and_prompt_err("Failed to open file", window, cx, |e, _, _| {                            Some(format!("{e}"))                        });                }                Event::Focus => { /* TODO */ }            },        )        .detach();         git_panel    }     fn serialize(&mut self, cx: &mut Context<Self>) {        // TODO: we can store stage status here        let width = self.width;        self.pending_serialization = cx.background_executor().spawn(            async move {                KEY_VALUE_STORE                    .write_kvp(                        GIT_PANEL_KEY.into(),                        serde_json::to_string(&SerializedGitPanel { width })?,                    )                    .await?;                anyhow::Ok(())            }            .log_err(),        );    }     fn dispatch_context(&self, window: &mut Window, cx: &Context<Self>) -> KeyContext {        let mut dispatch_context = KeyContext::new_with_defaults();        dispatch_context.add("GitPanel");         if self.is_focused(window, cx) {            dispatch_context.add("menu");            dispatch_context.add("ChangesList");        }         if self.commit_editor.read(cx).is_focused(window) {            dispatch_context.add("CommitEditor");        }         dispatch_context    }     fn is_focused(&self, window: &Window, cx: &Context<Self>) -> bool {        window            .focused(cx)            .map_or(false, |focused| self.focus_handle == focused)    }     fn close_panel(&mut self, _: &Close, _window: &mut Window, cx: &mut Context<Self>) {        cx.emit(PanelEvent::Close);    }     fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {        if !self.focus_handle.contains_focused(window, cx) {            cx.emit(Event::Focus);        }    }     fn show_scrollbar(&self, cx: &mut Context<Self>) -> ShowScrollbar {        GitPanelSettings::get_global(cx)            .scrollbar            .show            .unwrap_or_else(|| EditorSettings::get_global(cx).scrollbar.show)    }     fn should_show_scrollbar(&self, cx: &mut Context<Self>) -> bool {        let show = self.show_scrollbar(cx);        match show {            ShowScrollbar::Auto => true,            ShowScrollbar::System => true,            ShowScrollbar::Always => true,            ShowScrollbar::Never => false,        }    }     fn should_autohide_scrollbar(&self, cx: &mut Context<Self>) -> bool {        let show = self.show_scrollbar(cx);        match show {            ShowScrollbar::Auto => true,            ShowScrollbar::System => cx                .try_global::<ScrollbarAutoHide>()                .map_or_else(|| cx.should_auto_hide_scrollbars(), |autohide| autohide.0),            ShowScrollbar::Always => false,            ShowScrollbar::Never => true,        }    }     fn hide_scrollbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {        const SCROLLBAR_SHOW_INTERVAL: Duration = Duration::from_secs(1);        if !self.should_autohide_scrollbar(cx) {            return;        }        self.hide_scrollbar_task = Some(cx.spawn_in(window, |panel, mut cx| async move {            cx.background_executor()                .timer(SCROLLBAR_SHOW_INTERVAL)                .await;            panel                .update(&mut cx, |panel, cx| {                    panel.show_scrollbar = false;                    cx.notify();                })                .log_err();        }))    }     fn handle_modifiers_changed(        &mut self,        event: &ModifiersChangedEvent,        _: &mut Window,        cx: &mut Context<Self>,    ) {        self.current_modifiers = event.modifiers;        cx.notify();    }     fn calculate_depth_and_difference(        repo_path: &RepoPath,        visible_entries: &HashSet<RepoPath>,    ) -> (usize, usize) {        let ancestors = repo_path.ancestors().skip(1);        for ancestor in ancestors {            if let Some(parent_entry) = visible_entries.get(ancestor) {                let entry_component_count = repo_path.components().count();                let parent_component_count = parent_entry.components().count();                 let difference = entry_component_count - parent_component_count;                 let parent_depth = parent_entry                    .ancestors()                    .skip(1) // Skip the parent itself                    .filter(|ancestor| visible_entries.contains(*ancestor))                    .count();                 return (parent_depth + 1, difference);            }        }         (0, 0)    }     fn scroll_to_selected_entry(&mut self, cx: &mut Context<Self>) {        if let Some(selected_entry) = self.selected_entry {            self.scroll_handle                .scroll_to_item(selected_entry, ScrollStrategy::Center);        }         cx.notify();    }     fn select_first(&mut self, _: &SelectFirst, _window: &mut Window, cx: &mut Context<Self>) {        if self.visible_entries.first().is_some() {            self.selected_entry = Some(0);            self.scroll_to_selected_entry(cx);        }    }     fn select_prev(&mut self, _: &SelectPrev, _window: &mut Window, cx: &mut Context<Self>) {        let item_count = self.visible_entries.len();        if item_count == 0 {            return;        }         if let Some(selected_entry) = self.selected_entry {            let new_selected_entry = if selected_entry > 0 {                selected_entry - 1            } else {                selected_entry            };             self.selected_entry = Some(new_selected_entry);             self.scroll_to_selected_entry(cx);        }         cx.notify();    }     fn select_next(&mut self, _: &SelectNext, _window: &mut Window, cx: &mut Context<Self>) {        let item_count = self.visible_entries.len();        if item_count == 0 {            return;        }         if let Some(selected_entry) = self.selected_entry {            let new_selected_entry = if selected_entry < item_count - 1 {                selected_entry + 1            } else {                selected_entry            };             self.selected_entry = Some(new_selected_entry);             self.scroll_to_selected_entry(cx);        }         cx.notify();    }     fn select_last(&mut self, _: &SelectLast, _window: &mut Window, cx: &mut Context<Self>) {        if self.visible_entries.last().is_some() {            self.selected_entry = Some(self.visible_entries.len() - 1);            self.scroll_to_selected_entry(cx);        }    }     fn focus_editor(&mut self, _: &FocusEditor, window: &mut Window, cx: &mut Context<Self>) {        self.commit_editor.update(cx, |editor, cx| {            window.focus(&editor.focus_handle(cx));        });        cx.notify();    }     fn select_first_entry_if_none(&mut self, cx: &mut Context<Self>) {        let have_entries = self            .active_repository            .as_ref()            .map_or(false, |active_repository| {                active_repository.entry_count() > 0            });        if have_entries && self.selected_entry.is_none() {            self.selected_entry = Some(0);            self.scroll_to_selected_entry(cx);            cx.notify();        }    }     fn focus_changes_list(        &mut self,        _: &FocusChanges,        window: &mut Window,        cx: &mut Context<Self>,    ) {        self.select_first_entry_if_none(cx);         cx.focus_self(window);        cx.notify();    }     fn get_selected_entry(&self) -> Option<&GitListEntry> {        self.selected_entry            .and_then(|i| self.visible_entries.get(i))    }     fn open_selected(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {        if let Some(entry) = self            .selected_entry            .and_then(|i| self.visible_entries.get(i))        {            self.open_entry(entry, cx);        }    }     fn toggle_staged_for_entry(        &mut self,        entry: &GitListEntry,        _window: &mut Window,        cx: &mut Context<Self>,    ) {        let Some(active_repository) = self.active_repository.as_ref() else {

Lines 1–500 of 1438.