7495 lines · 276.6 KB · Rust
RawDownload
use crate::{    CloseWindow, NewFile, NewTerminal, OpenInTerminal, OpenOptions, OpenTerminal, OpenVisible,    SplitDirection, ToggleFileFinder, ToggleProjectSymbols, ToggleZoom, Workspace,    WorkspaceItemBuilder, ZoomIn, ZoomOut,    invalid_item_view::InvalidItemView,    item::{        ActivateOnClose, ClosePosition, Item, ItemBufferKind, ItemHandle, ItemSettings,        PreviewTabsSettings, ProjectItemKind, SaveOptions, ShowCloseButton, ShowDiagnostics,        TabContentParams, TabTooltipContent, WeakItemHandle,    },    move_item,    notifications::NotifyResultExt,    toolbar::Toolbar,    utility_pane::UtilityPaneSlot,    workspace_settings::{AutosaveSetting, TabBarSettings, WorkspaceSettings},};use anyhow::Result;use collections::{BTreeSet, HashMap, HashSet, VecDeque};use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};use futures::{StreamExt, stream::FuturesUnordered};use gpui::{    Action, AnyElement, App, AsyncWindowContext, ClickEvent, ClipboardItem, Context, Corner, Div,    DragMoveEvent, Entity, EntityId, EventEmitter, ExternalPaths, FocusHandle, FocusOutEvent,    Focusable, KeyContext, MouseButton, MouseDownEvent, NavigationDirection, Pixels, Point,    PromptLevel, Render, ScrollHandle, Subscription, Task, WeakEntity, WeakFocusHandle, Window,    actions, anchored, deferred, prelude::*,};use itertools::Itertools;use language::{Capability, DiagnosticSeverity};use parking_lot::Mutex;use project::{DirectoryLister, Project, ProjectEntryId, ProjectPath, WorktreeId};use schemars::JsonSchema;use serde::Deserialize;use settings::{Settings, SettingsStore};use std::{    any::Any,    cmp, fmt, mem,    num::NonZeroUsize,    ops::ControlFlow,    path::PathBuf,    rc::Rc,    sync::{        Arc,        atomic::{AtomicUsize, Ordering},    },    time::Duration,};use theme::ThemeSettings;use ui::{    ContextMenu, ContextMenuEntry, ContextMenuItem, DecoratedIcon, IconButtonShape, IconDecoration,    IconDecorationKind, Indicator, PopoverMenu, PopoverMenuHandle, Tab, TabBar, TabPosition,    Tooltip, prelude::*, right_click_menu,};use util::{ResultExt, debug_panic, maybe, paths::PathStyle, truncate_and_remove_front}; /// A selected entry in e.g. project panel.#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]pub struct SelectedEntry {    pub worktree_id: WorktreeId,    pub entry_id: ProjectEntryId,} /// A group of selected entries from project panel.#[derive(Debug)]pub struct DraggedSelection {    pub active_selection: SelectedEntry,    pub marked_selections: Arc<[SelectedEntry]>,} impl DraggedSelection {    pub fn items<'a>(&'a self) -> Box<dyn Iterator<Item = &'a SelectedEntry> + 'a> {        if self.marked_selections.contains(&self.active_selection) {            Box::new(self.marked_selections.iter())        } else {            Box::new(std::iter::once(&self.active_selection))        }    }} #[derive(Clone, Copy, PartialEq, Debug, Deserialize, JsonSchema)]#[serde(rename_all = "snake_case")]pub enum SaveIntent {    /// write all files (even if unchanged)    /// prompt before overwriting on-disk changes    Save,    /// same as Save, but without auto formatting    SaveWithoutFormat,    /// write any files that have local changes    /// prompt before overwriting on-disk changes    SaveAll,    /// always prompt for a new path    SaveAs,    /// prompt "you have unsaved changes" before writing    Close,    /// write all dirty files, don't prompt on conflict    Overwrite,    /// skip all save-related behavior    Skip,} /// Activates a specific item in the pane by its index.#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]#[action(namespace = pane)]pub struct ActivateItem(pub usize); /// Closes the currently active item in the pane.#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]#[action(namespace = pane)]#[serde(deny_unknown_fields)]pub struct CloseActiveItem {    #[serde(default)]    pub save_intent: Option<SaveIntent>,    #[serde(default)]    pub close_pinned: bool,} /// Closes all inactive items in the pane.#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]#[action(namespace = pane)]#[serde(deny_unknown_fields)]#[action(deprecated_aliases = ["pane::CloseInactiveItems"])]pub struct CloseOtherItems {    #[serde(default)]    pub save_intent: Option<SaveIntent>,    #[serde(default)]    pub close_pinned: bool,} /// Closes all multibuffers in the pane.#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]#[action(namespace = pane)]#[serde(deny_unknown_fields)]pub struct CloseMultibufferItems {    #[serde(default)]    pub save_intent: Option<SaveIntent>,    #[serde(default)]    pub close_pinned: bool,} /// Closes all items in the pane.#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]#[action(namespace = pane)]#[serde(deny_unknown_fields)]pub struct CloseAllItems {    #[serde(default)]    pub save_intent: Option<SaveIntent>,    #[serde(default)]    pub close_pinned: bool,} /// Closes all items that have no unsaved changes.#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]#[action(namespace = pane)]#[serde(deny_unknown_fields)]pub struct CloseCleanItems {    #[serde(default)]    pub close_pinned: bool,} /// Closes all items to the right of the current item.#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]#[action(namespace = pane)]#[serde(deny_unknown_fields)]pub struct CloseItemsToTheRight {    #[serde(default)]    pub close_pinned: bool,} /// Closes all items to the left of the current item.#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]#[action(namespace = pane)]#[serde(deny_unknown_fields)]pub struct CloseItemsToTheLeft {    #[serde(default)]    pub close_pinned: bool,} /// Reveals the current item in the project panel.#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]#[action(namespace = pane)]#[serde(deny_unknown_fields)]pub struct RevealInProjectPanel {    #[serde(skip)]    pub entry_id: Option<u64>,} /// Opens the search interface with the specified configuration.#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]#[action(namespace = pane)]#[serde(deny_unknown_fields)]pub struct DeploySearch {    #[serde(default)]    pub replace_enabled: bool,    #[serde(default)]    pub included_files: Option<String>,    #[serde(default)]    pub excluded_files: Option<String>,} #[derive(Clone, Copy, PartialEq, Debug, Deserialize, JsonSchema, Default)]#[serde(deny_unknown_fields)]pub enum SplitMode {    /// Clone the current pane.    #[default]    ClonePane,    /// Create an empty new pane.    EmptyPane,    /// Move the item into a new pane. This will map to nop if only one pane exists.    MovePane,} macro_rules! split_structs {    ($($name:ident => $doc:literal),* $(,)?) => {        $(            #[doc = $doc]            #[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]            #[action(namespace = pane)]            #[serde(deny_unknown_fields, default)]            pub struct $name {                pub mode: SplitMode,            }        )*    };} split_structs!(    SplitLeft => "Splits the pane to the left.",    SplitRight => "Splits the pane to the right.",    SplitUp => "Splits the pane upward.",    SplitDown => "Splits the pane downward.",    SplitHorizontal => "Splits the pane horizontally.",    SplitVertical => "Splits the pane vertically."); actions!(    pane,    [        /// Activates the previous item in the pane.        ActivatePreviousItem,        /// Activates the next item in the pane.        ActivateNextItem,        /// Activates the last item in the pane.        ActivateLastItem,        /// Switches to the alternate file.        AlternateFile,        /// Navigates back in history.        GoBack,        /// Navigates forward in history.        GoForward,        /// Joins this pane into the next pane.        JoinIntoNext,        /// Joins all panes into one.        JoinAll,        /// Reopens the most recently closed item.        ReopenClosedItem,        /// Splits the pane to the left, moving the current item.        SplitAndMoveLeft,        /// Splits the pane upward, moving the current item.        SplitAndMoveUp,        /// Splits the pane to the right, moving the current item.        SplitAndMoveRight,        /// Splits the pane downward, moving the current item.        SplitAndMoveDown,        /// Swaps the current item with the one to the left.        SwapItemLeft,        /// Swaps the current item with the one to the right.        SwapItemRight,        /// Toggles preview mode for the current tab.        TogglePreviewTab,        /// Toggles pin status for the current tab.        TogglePinTab,        /// Unpins all tabs in the pane.        UnpinAllTabs,    ]); impl DeploySearch {    pub fn find() -> Self {        Self {            replace_enabled: false,            included_files: None,            excluded_files: None,        }    }} const MAX_NAVIGATION_HISTORY_LEN: usize = 1024; pub enum Event {    AddItem {        item: Box<dyn ItemHandle>,    },    ActivateItem {        local: bool,        focus_changed: bool,    },    Remove {        focus_on_pane: Option<Entity<Pane>>,    },    RemovedItem {        item: Box<dyn ItemHandle>,    },    Split {        direction: SplitDirection,        mode: SplitMode,    },    ItemPinned,    ItemUnpinned,    JoinAll,    JoinIntoNext,    ChangeItemTitle,    Focus,    ZoomIn,    ZoomOut,    UserSavedItem {        item: Box<dyn WeakItemHandle>,        save_intent: SaveIntent,    },} impl fmt::Debug for Event {    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {        match self {            Event::AddItem { item } => f                .debug_struct("AddItem")                .field("item", &item.item_id())                .finish(),            Event::ActivateItem { local, .. } => f                .debug_struct("ActivateItem")                .field("local", local)                .finish(),            Event::Remove { .. } => f.write_str("Remove"),            Event::RemovedItem { item } => f                .debug_struct("RemovedItem")                .field("item", &item.item_id())                .finish(),            Event::Split { direction, mode } => f                .debug_struct("Split")                .field("direction", direction)                .field("mode", mode)                .finish(),            Event::JoinAll => f.write_str("JoinAll"),            Event::JoinIntoNext => f.write_str("JoinIntoNext"),            Event::ChangeItemTitle => f.write_str("ChangeItemTitle"),            Event::Focus => f.write_str("Focus"),            Event::ZoomIn => f.write_str("ZoomIn"),            Event::ZoomOut => f.write_str("ZoomOut"),            Event::UserSavedItem { item, save_intent } => f                .debug_struct("UserSavedItem")                .field("item", &item.id())                .field("save_intent", save_intent)                .finish(),            Event::ItemPinned => f.write_str("ItemPinned"),            Event::ItemUnpinned => f.write_str("ItemUnpinned"),        }    }} /// A container for 0 to many items that are open in the workspace./// Treats all items uniformly via the [`ItemHandle`] trait, whether it's an editor, search results multibuffer, terminal or something else,/// responsible for managing item tabs, focus and zoom states and drag and drop features./// Can be split, see `PaneGroup` for more details.pub struct Pane {    alternate_file_items: (        Option<Box<dyn WeakItemHandle>>,        Option<Box<dyn WeakItemHandle>>,    ),    focus_handle: FocusHandle,    items: Vec<Box<dyn ItemHandle>>,    activation_history: Vec<ActivationHistoryEntry>,    next_activation_timestamp: Arc<AtomicUsize>,    zoomed: bool,    was_focused: bool,    active_item_index: usize,    preview_item_id: Option<EntityId>,    last_focus_handle_by_item: HashMap<EntityId, WeakFocusHandle>,    nav_history: NavHistory,    toolbar: Entity<Toolbar>,    pub(crate) workspace: WeakEntity<Workspace>,    project: WeakEntity<Project>,    pub drag_split_direction: Option<SplitDirection>,    can_drop_predicate: Option<Arc<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool>>,    custom_drop_handle: Option<        Arc<dyn Fn(&mut Pane, &dyn Any, &mut Window, &mut Context<Pane>) -> ControlFlow<(), ()>>,    >,    can_split_predicate:        Option<Arc<dyn Fn(&mut Self, &dyn Any, &mut Window, &mut Context<Self>) -> bool>>,    can_toggle_zoom: bool,    should_display_tab_bar: Rc<dyn Fn(&Window, &mut Context<Pane>) -> bool>,    render_tab_bar_buttons: Rc<        dyn Fn(            &mut Pane,            &mut Window,            &mut Context<Pane>,        ) -> (Option<AnyElement>, Option<AnyElement>),    >,    render_tab_bar: Rc<dyn Fn(&mut Pane, &mut Window, &mut Context<Pane>) -> AnyElement>,    show_tab_bar_buttons: bool,    max_tabs: Option<NonZeroUsize>,    use_max_tabs: bool,    _subscriptions: Vec<Subscription>,    tab_bar_scroll_handle: ScrollHandle,    /// This is set to true if a user scroll has occurred more recently than a system scroll    /// We want to suppress certain system scrolls when the user has intentionally scrolled    suppress_scroll: bool,    /// Is None if navigation buttons are permanently turned off (and should not react to setting changes).    /// Otherwise, when `display_nav_history_buttons` is Some, it determines whether nav buttons should be displayed.    display_nav_history_buttons: Option<bool>,    double_click_dispatch_action: Box<dyn Action>,    save_modals_spawned: HashSet<EntityId>,    close_pane_if_empty: bool,    pub new_item_context_menu_handle: PopoverMenuHandle<ContextMenu>,    pub split_item_context_menu_handle: PopoverMenuHandle<ContextMenu>,    pinned_tab_count: usize,    diagnostics: HashMap<ProjectPath, DiagnosticSeverity>,    zoom_out_on_close: bool,    diagnostic_summary_update: Task<()>,    /// If a certain project item wants to get recreated with specific data, it can persist its data before the recreation here.    pub project_item_restoration_data: HashMap<ProjectItemKind, Box<dyn Any + Send>>,    welcome_page: Option<Entity<crate::welcome::WelcomePage>>,     pub in_center_group: bool,    pub is_upper_left: bool,    pub is_upper_right: bool,} pub struct ActivationHistoryEntry {    pub entity_id: EntityId,    pub timestamp: usize,} pub struct ItemNavHistory {    history: NavHistory,    item: Arc<dyn WeakItemHandle>,    is_preview: bool,} #[derive(Clone)]pub struct NavHistory(Arc<Mutex<NavHistoryState>>); struct NavHistoryState {    mode: NavigationMode,    backward_stack: VecDeque<NavigationEntry>,    forward_stack: VecDeque<NavigationEntry>,    closed_stack: VecDeque<NavigationEntry>,    paths_by_item: HashMap<EntityId, (ProjectPath, Option<PathBuf>)>,    pane: WeakEntity<Pane>,    next_timestamp: Arc<AtomicUsize>,} #[derive(Debug, Default, Copy, Clone)]pub enum NavigationMode {    #[default]    Normal,    GoingBack,    GoingForward,    ClosingItem,    ReopeningClosedItem,    Disabled,} pub struct NavigationEntry {    pub item: Arc<dyn WeakItemHandle>,    pub data: Option<Box<dyn Any + Send>>,    pub timestamp: usize,    pub is_preview: bool,} #[derive(Clone)]pub struct DraggedTab {    pub pane: Entity<Pane>,    pub item: Box<dyn ItemHandle>,    pub ix: usize,    pub detail: usize,    pub is_active: bool,} impl EventEmitter<Event> for Pane {} pub enum Side {    Left,    Right,} #[derive(Copy, Clone)]enum PinOperation {    Pin,    Unpin,} impl Pane {    pub fn new(        workspace: WeakEntity<Workspace>,        project: Entity<Project>,        next_timestamp: Arc<AtomicUsize>,        can_drop_predicate: Option<Arc<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>>,        double_click_dispatch_action: Box<dyn Action>,        use_max_tabs: bool,        window: &mut Window,        cx: &mut Context<Self>,

Lines 1–500 of 7495.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t