1879 lines · 64.9 KB · Rust
RawDownload
use crate::git_panel_settings::StatusStyle;use crate::repository_selector::RepositorySelectorPopoverMenu;use crate::ProjectDiff;use crate::{    git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,};use anyhow::Result;use collections::HashMap;use db::kvp::KEY_VALUE_STORE;use editor::actions::MoveToEnd;use editor::scroll::ScrollbarAutoHide;use editor::{Editor, EditorMode, EditorSettings, MultiBuffer, ShowScrollbar};use git::repository::RepoPath;use git::status::FileStatus;use git::{CommitAllChanges, CommitChanges, ToggleStaged};use gpui::*;use language::{Buffer, File};use menu::{SelectFirst, SelectLast, SelectNext, SelectPrev};use multi_buffer::ExcerptInfo;use panel::PanelHeader;use project::git::{GitEvent, Repository};use project::{Fs, Project, ProjectPath};use serde::{Deserialize, Serialize};use settings::Settings as _;use std::{collections::HashSet, path::PathBuf, sync::Arc, time::Duration, usize};use theme::ThemeSettings;use ui::{    prelude::*, ButtonLike, Checkbox, Divider, DividerColor, ElevationIndex, IndentGuideColors,    ListHeader, ListItem, ListItemSpacing, Scrollbar, ScrollbarState, Tooltip,};use util::{maybe, ResultExt, TryFutureExt};use workspace::notifications::{DetachAndPromptErr, NotificationId};use workspace::Toast;use workspace::{    dock::{DockPosition, Panel, PanelEvent},    Workspace,}; actions!(    git_panel,    [        Close,        ToggleFocus,        OpenMenu,        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, Copy)]enum Section {    Conflict,    Tracked,    New,} #[derive(Debug, PartialEq, Eq, Clone)]struct GitHeaderEntry {    header: Section,} impl GitHeaderEntry {    pub fn contains(&self, status_entry: &GitStatusEntry, repo: &Repository) -> bool {        let this = &self.header;        let status = status_entry.status;        match this {            Section::Conflict => repo.has_conflict(&status_entry.repo_path),            Section::Tracked => !status.is_created(),            Section::New => status.is_created(),        }    }    pub fn title(&self) -> &'static str {        match self.header {            Section::Conflict => "Conflicts",            Section::Tracked => "Changed",            Section::New => "New",        }    }} #[derive(Debug, PartialEq, Eq, Clone)]enum GitListEntry {    GitStatusEntry(GitStatusEntry),    Header(GitHeaderEntry),} impl GitListEntry {    fn status_entry(&self) -> Option<&GitStatusEntry> {        match self {            GitListEntry::GitStatusEntry(entry) => Some(entry),            _ => None,        }    }} #[derive(Debug, PartialEq, Eq, Clone)]pub struct GitStatusEntry {    pub(crate) depth: usize,    pub(crate) display_name: String,    pub(crate) repo_path: RepoPath,    pub(crate) status: FileStatus,    pub(crate) is_staged: Option<bool>,} struct PendingOperation {    finished: bool,    will_become_staged: bool,    repo_paths: HashSet<RepoPath>,    op_id: usize,} 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<Entity<Repository>>,    scroll_handle: UniformListScrollHandle,    scrollbar_state: ScrollbarState,    selected_entry: Option<usize>,    show_scrollbar: bool,    update_visible_entries_task: Task<()>,    repository_selector: Entity<RepositorySelector>,    commit_editor: Entity<Editor>,    entries: Vec<GitListEntry>,    entries_by_path: collections::HashMap<RepoPath, usize>,    width: Option<Pixels>,    pending: Vec<PendingOperation>,    commit_task: Task<Result<()>>,    commit_pending: bool,     conflicted_staged_count: usize,    conflicted_count: usize,    tracked_staged_count: usize,    tracked_count: usize,    new_staged_count: usize,    new_count: usize,} fn commit_message_editor(    commit_message_buffer: Option<Entity<Buffer>>,    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(commit_message_buffer) = commit_message_buffer {        let buffer = cx.new(|cx| MultiBuffer::singleton(commit_message_buffer, 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 new(        workspace: &mut Workspace,        window: &mut Window,        commit_message_buffer: Option<Entity<Buffer>>,        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().clone();        let active_repository = project.read(cx).active_repository(cx);        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(commit_message_buffer, window, cx));            commit_editor.update(cx, |editor, cx| {                editor.clear(window, cx);            });             let scroll_handle = UniformListScrollHandle::new();             cx.subscribe_in(                &git_state,                window,                move |this, git_state, event, window, cx| match event {                    GitEvent::FileSystemUpdated => {                        this.schedule_update(false, window, cx);                    }                    GitEvent::ActiveRepositoryChanged | GitEvent::GitStateUpdated => {                        this.active_repository = git_state.read(cx).active_repository();                        this.schedule_update(true, window, cx);                    }                },            )            .detach();             let repository_selector =                cx.new(|cx| RepositorySelector::new(project.clone(), window, cx));             let mut git_panel = Self {                focus_handle: cx.focus_handle(),                pending_serialization: Task::ready(None),                entries: Vec::new(),                entries_by_path: HashMap::default(),                pending: Vec::new(),                current_modifiers: window.modifiers(),                width: Some(px(360.)),                scrollbar_state: ScrollbarState::new(scroll_handle.clone())                    .parent_entity(&cx.entity()),                repository_selector,                selected_entry: None,                show_scrollbar: false,                hide_scrollbar_task: None,                update_visible_entries_task: Task::ready(()),                commit_task: Task::ready(Ok(())),                commit_pending: false,                active_repository,                scroll_handle,                fs,                commit_editor,                project,                workspace,                conflicted_count: 0,                conflicted_staged_count: 0,                tracked_staged_count: 0,                tracked_count: 0,                new_staged_count: 0,                new_count: 0,            };            git_panel.schedule_update(false, window, cx);            git_panel.show_scrollbar = git_panel.should_show_scrollbar(cx);            git_panel        });         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    }     pub fn set_focused_path(&mut self, path: ProjectPath, _: &mut Window, cx: &mut Context<Self>) {        let Some(git_repo) = self.active_repository.as_ref() else {            return;        };        let Some(repo_path) = git_repo.read(cx).project_path_to_repo_path(&path) else {            return;        };        let Some(ix) = self.entries_by_path.get(&repo_path) else {            return;        };         self.selected_entry = Some(*ix);        cx.notify();    }     fn serialize(&mut self, cx: &mut Context<Self>) {        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.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.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.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 {

Lines 1–500 of 1879.