pane.rs

   1use crate::{
   2    CloseWindow, NewFile, NewTerminal, OpenInTerminal, OpenOptions, OpenTerminal, OpenVisible,
   3    SplitDirection, ToggleFileFinder, ToggleProjectSymbols, ToggleZoom, Workspace,
   4    WorkspaceItemBuilder, ZoomIn, ZoomOut,
   5    invalid_item_view::InvalidItemView,
   6    item::{
   7        ActivateOnClose, ClosePosition, Item, ItemBufferKind, ItemHandle, ItemSettings,
   8        PreviewTabsSettings, ProjectItemKind, SaveOptions, ShowCloseButton, ShowDiagnostics,
   9        TabContentParams, TabTooltipContent, WeakItemHandle,
  10    },
  11    move_item,
  12    notifications::NotifyResultExt,
  13    toolbar::Toolbar,
  14    utility_pane::UtilityPaneSlot,
  15    workspace_settings::{AutosaveSetting, TabBarSettings, WorkspaceSettings},
  16};
  17use anyhow::Result;
  18use collections::{BTreeSet, HashMap, HashSet, VecDeque};
  19use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
  20use futures::{StreamExt, stream::FuturesUnordered};
  21use gpui::{
  22    Action, AnyElement, App, AsyncWindowContext, ClickEvent, ClipboardItem, Context, Corner, Div,
  23    DragMoveEvent, Entity, EntityId, EventEmitter, ExternalPaths, FocusHandle, FocusOutEvent,
  24    Focusable, KeyContext, MouseButton, MouseDownEvent, NavigationDirection, Pixels, Point,
  25    PromptLevel, Render, ScrollHandle, Subscription, Task, WeakEntity, WeakFocusHandle, Window,
  26    actions, anchored, deferred, prelude::*,
  27};
  28use itertools::Itertools;
  29use language::{Capability, DiagnosticSeverity};
  30use parking_lot::Mutex;
  31use project::{DirectoryLister, Project, ProjectEntryId, ProjectPath, WorktreeId};
  32use schemars::JsonSchema;
  33use serde::Deserialize;
  34use settings::{Settings, SettingsStore};
  35use std::{
  36    any::Any,
  37    cmp, fmt, mem,
  38    num::NonZeroUsize,
  39    ops::ControlFlow,
  40    path::PathBuf,
  41    rc::Rc,
  42    sync::{
  43        Arc,
  44        atomic::{AtomicUsize, Ordering},
  45    },
  46    time::Duration,
  47};
  48use theme::ThemeSettings;
  49use ui::{
  50    ContextMenu, ContextMenuEntry, ContextMenuItem, DecoratedIcon, IconButtonShape, IconDecoration,
  51    IconDecorationKind, Indicator, PopoverMenu, PopoverMenuHandle, Tab, TabBar, TabPosition,
  52    Tooltip, prelude::*, right_click_menu,
  53};
  54use util::{ResultExt, debug_panic, maybe, paths::PathStyle, truncate_and_remove_front};
  55
  56/// A selected entry in e.g. project panel.
  57#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  58pub struct SelectedEntry {
  59    pub worktree_id: WorktreeId,
  60    pub entry_id: ProjectEntryId,
  61}
  62
  63/// A group of selected entries from project panel.
  64#[derive(Debug)]
  65pub struct DraggedSelection {
  66    pub active_selection: SelectedEntry,
  67    pub marked_selections: Arc<[SelectedEntry]>,
  68}
  69
  70impl DraggedSelection {
  71    pub fn items<'a>(&'a self) -> Box<dyn Iterator<Item = &'a SelectedEntry> + 'a> {
  72        if self.marked_selections.contains(&self.active_selection) {
  73            Box::new(self.marked_selections.iter())
  74        } else {
  75            Box::new(std::iter::once(&self.active_selection))
  76        }
  77    }
  78}
  79
  80#[derive(Clone, Copy, PartialEq, Debug, Deserialize, JsonSchema)]
  81#[serde(rename_all = "snake_case")]
  82pub enum SaveIntent {
  83    /// write all files (even if unchanged)
  84    /// prompt before overwriting on-disk changes
  85    Save,
  86    /// same as Save, but without auto formatting
  87    SaveWithoutFormat,
  88    /// write any files that have local changes
  89    /// prompt before overwriting on-disk changes
  90    SaveAll,
  91    /// always prompt for a new path
  92    SaveAs,
  93    /// prompt "you have unsaved changes" before writing
  94    Close,
  95    /// write all dirty files, don't prompt on conflict
  96    Overwrite,
  97    /// skip all save-related behavior
  98    Skip,
  99}
 100
 101/// Activates a specific item in the pane by its index.
 102#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 103#[action(namespace = pane)]
 104pub struct ActivateItem(pub usize);
 105
 106/// Closes the currently active item in the pane.
 107#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 108#[action(namespace = pane)]
 109#[serde(deny_unknown_fields)]
 110pub struct CloseActiveItem {
 111    #[serde(default)]
 112    pub save_intent: Option<SaveIntent>,
 113    #[serde(default)]
 114    pub close_pinned: bool,
 115}
 116
 117/// Closes all inactive items in the pane.
 118#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 119#[action(namespace = pane)]
 120#[serde(deny_unknown_fields)]
 121#[action(deprecated_aliases = ["pane::CloseInactiveItems"])]
 122pub struct CloseOtherItems {
 123    #[serde(default)]
 124    pub save_intent: Option<SaveIntent>,
 125    #[serde(default)]
 126    pub close_pinned: bool,
 127}
 128
 129/// Closes all multibuffers in the pane.
 130#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 131#[action(namespace = pane)]
 132#[serde(deny_unknown_fields)]
 133pub struct CloseMultibufferItems {
 134    #[serde(default)]
 135    pub save_intent: Option<SaveIntent>,
 136    #[serde(default)]
 137    pub close_pinned: bool,
 138}
 139
 140/// Closes all items in the pane.
 141#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 142#[action(namespace = pane)]
 143#[serde(deny_unknown_fields)]
 144pub struct CloseAllItems {
 145    #[serde(default)]
 146    pub save_intent: Option<SaveIntent>,
 147    #[serde(default)]
 148    pub close_pinned: bool,
 149}
 150
 151/// Closes all items that have no unsaved changes.
 152#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 153#[action(namespace = pane)]
 154#[serde(deny_unknown_fields)]
 155pub struct CloseCleanItems {
 156    #[serde(default)]
 157    pub close_pinned: bool,
 158}
 159
 160/// Closes all items to the right of the current item.
 161#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 162#[action(namespace = pane)]
 163#[serde(deny_unknown_fields)]
 164pub struct CloseItemsToTheRight {
 165    #[serde(default)]
 166    pub close_pinned: bool,
 167}
 168
 169/// Closes all items to the left of the current item.
 170#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 171#[action(namespace = pane)]
 172#[serde(deny_unknown_fields)]
 173pub struct CloseItemsToTheLeft {
 174    #[serde(default)]
 175    pub close_pinned: bool,
 176}
 177
 178/// Reveals the current item in the project panel.
 179#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 180#[action(namespace = pane)]
 181#[serde(deny_unknown_fields)]
 182pub struct RevealInProjectPanel {
 183    #[serde(skip)]
 184    pub entry_id: Option<u64>,
 185}
 186
 187/// Opens the search interface with the specified configuration.
 188#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 189#[action(namespace = pane)]
 190#[serde(deny_unknown_fields)]
 191pub struct DeploySearch {
 192    #[serde(default)]
 193    pub replace_enabled: bool,
 194    #[serde(default)]
 195    pub included_files: Option<String>,
 196    #[serde(default)]
 197    pub excluded_files: Option<String>,
 198}
 199
 200#[derive(Clone, Copy, PartialEq, Debug, Deserialize, JsonSchema, Default)]
 201#[serde(deny_unknown_fields)]
 202pub enum SplitMode {
 203    /// Clone the current pane.
 204    #[default]
 205    ClonePane,
 206    /// Create an empty new pane.
 207    EmptyPane,
 208    /// Move the item into a new pane. This will map to nop if only one pane exists.
 209    MovePane,
 210}
 211
 212macro_rules! split_structs {
 213    ($($name:ident => $doc:literal),* $(,)?) => {
 214        $(
 215            #[doc = $doc]
 216            #[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 217            #[action(namespace = pane)]
 218            #[serde(deny_unknown_fields, default)]
 219            pub struct $name {
 220                pub mode: SplitMode,
 221            }
 222        )*
 223    };
 224}
 225
 226split_structs!(
 227    SplitLeft => "Splits the pane to the left.",
 228    SplitRight => "Splits the pane to the right.",
 229    SplitUp => "Splits the pane upward.",
 230    SplitDown => "Splits the pane downward.",
 231    SplitHorizontal => "Splits the pane horizontally.",
 232    SplitVertical => "Splits the pane vertically."
 233);
 234
 235actions!(
 236    pane,
 237    [
 238        /// Activates the previous item in the pane.
 239        ActivatePreviousItem,
 240        /// Activates the next item in the pane.
 241        ActivateNextItem,
 242        /// Activates the last item in the pane.
 243        ActivateLastItem,
 244        /// Switches to the alternate file.
 245        AlternateFile,
 246        /// Navigates back in history.
 247        GoBack,
 248        /// Navigates forward in history.
 249        GoForward,
 250        /// Joins this pane into the next pane.
 251        JoinIntoNext,
 252        /// Joins all panes into one.
 253        JoinAll,
 254        /// Reopens the most recently closed item.
 255        ReopenClosedItem,
 256        /// Splits the pane to the left, moving the current item.
 257        SplitAndMoveLeft,
 258        /// Splits the pane upward, moving the current item.
 259        SplitAndMoveUp,
 260        /// Splits the pane to the right, moving the current item.
 261        SplitAndMoveRight,
 262        /// Splits the pane downward, moving the current item.
 263        SplitAndMoveDown,
 264        /// Swaps the current item with the one to the left.
 265        SwapItemLeft,
 266        /// Swaps the current item with the one to the right.
 267        SwapItemRight,
 268        /// Toggles preview mode for the current tab.
 269        TogglePreviewTab,
 270        /// Toggles pin status for the current tab.
 271        TogglePinTab,
 272        /// Unpins all tabs in the pane.
 273        UnpinAllTabs,
 274    ]
 275);
 276
 277impl DeploySearch {
 278    pub fn find() -> Self {
 279        Self {
 280            replace_enabled: false,
 281            included_files: None,
 282            excluded_files: None,
 283        }
 284    }
 285}
 286
 287const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
 288
 289pub enum Event {
 290    AddItem {
 291        item: Box<dyn ItemHandle>,
 292    },
 293    ActivateItem {
 294        local: bool,
 295        focus_changed: bool,
 296    },
 297    Remove {
 298        focus_on_pane: Option<Entity<Pane>>,
 299    },
 300    RemovedItem {
 301        item: Box<dyn ItemHandle>,
 302    },
 303    Split {
 304        direction: SplitDirection,
 305        mode: SplitMode,
 306    },
 307    ItemPinned,
 308    ItemUnpinned,
 309    JoinAll,
 310    JoinIntoNext,
 311    ChangeItemTitle,
 312    Focus,
 313    ZoomIn,
 314    ZoomOut,
 315    UserSavedItem {
 316        item: Box<dyn WeakItemHandle>,
 317        save_intent: SaveIntent,
 318    },
 319}
 320
 321impl fmt::Debug for Event {
 322    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 323        match self {
 324            Event::AddItem { item } => f
 325                .debug_struct("AddItem")
 326                .field("item", &item.item_id())
 327                .finish(),
 328            Event::ActivateItem { local, .. } => f
 329                .debug_struct("ActivateItem")
 330                .field("local", local)
 331                .finish(),
 332            Event::Remove { .. } => f.write_str("Remove"),
 333            Event::RemovedItem { item } => f
 334                .debug_struct("RemovedItem")
 335                .field("item", &item.item_id())
 336                .finish(),
 337            Event::Split { direction, mode } => f
 338                .debug_struct("Split")
 339                .field("direction", direction)
 340                .field("mode", mode)
 341                .finish(),
 342            Event::JoinAll => f.write_str("JoinAll"),
 343            Event::JoinIntoNext => f.write_str("JoinIntoNext"),
 344            Event::ChangeItemTitle => f.write_str("ChangeItemTitle"),
 345            Event::Focus => f.write_str("Focus"),
 346            Event::ZoomIn => f.write_str("ZoomIn"),
 347            Event::ZoomOut => f.write_str("ZoomOut"),
 348            Event::UserSavedItem { item, save_intent } => f
 349                .debug_struct("UserSavedItem")
 350                .field("item", &item.id())
 351                .field("save_intent", save_intent)
 352                .finish(),
 353            Event::ItemPinned => f.write_str("ItemPinned"),
 354            Event::ItemUnpinned => f.write_str("ItemUnpinned"),
 355        }
 356    }
 357}
 358
 359/// A container for 0 to many items that are open in the workspace.
 360/// Treats all items uniformly via the [`ItemHandle`] trait, whether it's an editor, search results multibuffer, terminal or something else,
 361/// responsible for managing item tabs, focus and zoom states and drag and drop features.
 362/// Can be split, see `PaneGroup` for more details.
 363pub struct Pane {
 364    alternate_file_items: (
 365        Option<Box<dyn WeakItemHandle>>,
 366        Option<Box<dyn WeakItemHandle>>,
 367    ),
 368    focus_handle: FocusHandle,
 369    items: Vec<Box<dyn ItemHandle>>,
 370    activation_history: Vec<ActivationHistoryEntry>,
 371    next_activation_timestamp: Arc<AtomicUsize>,
 372    zoomed: bool,
 373    was_focused: bool,
 374    active_item_index: usize,
 375    preview_item_id: Option<EntityId>,
 376    last_focus_handle_by_item: HashMap<EntityId, WeakFocusHandle>,
 377    nav_history: NavHistory,
 378    toolbar: Entity<Toolbar>,
 379    pub(crate) workspace: WeakEntity<Workspace>,
 380    project: WeakEntity<Project>,
 381    pub drag_split_direction: Option<SplitDirection>,
 382    can_drop_predicate: Option<Arc<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool>>,
 383    custom_drop_handle: Option<
 384        Arc<dyn Fn(&mut Pane, &dyn Any, &mut Window, &mut Context<Pane>) -> ControlFlow<(), ()>>,
 385    >,
 386    can_split_predicate:
 387        Option<Arc<dyn Fn(&mut Self, &dyn Any, &mut Window, &mut Context<Self>) -> bool>>,
 388    can_toggle_zoom: bool,
 389    should_display_tab_bar: Rc<dyn Fn(&Window, &mut Context<Pane>) -> bool>,
 390    render_tab_bar_buttons: Rc<
 391        dyn Fn(
 392            &mut Pane,
 393            &mut Window,
 394            &mut Context<Pane>,
 395        ) -> (Option<AnyElement>, Option<AnyElement>),
 396    >,
 397    render_tab_bar: Rc<dyn Fn(&mut Pane, &mut Window, &mut Context<Pane>) -> AnyElement>,
 398    show_tab_bar_buttons: bool,
 399    max_tabs: Option<NonZeroUsize>,
 400    use_max_tabs: bool,
 401    _subscriptions: Vec<Subscription>,
 402    tab_bar_scroll_handle: ScrollHandle,
 403    /// This is set to true if a user scroll has occurred more recently than a system scroll
 404    /// We want to suppress certain system scrolls when the user has intentionally scrolled
 405    suppress_scroll: bool,
 406    /// Is None if navigation buttons are permanently turned off (and should not react to setting changes).
 407    /// Otherwise, when `display_nav_history_buttons` is Some, it determines whether nav buttons should be displayed.
 408    display_nav_history_buttons: Option<bool>,
 409    double_click_dispatch_action: Box<dyn Action>,
 410    save_modals_spawned: HashSet<EntityId>,
 411    close_pane_if_empty: bool,
 412    pub new_item_context_menu_handle: PopoverMenuHandle<ContextMenu>,
 413    pub split_item_context_menu_handle: PopoverMenuHandle<ContextMenu>,
 414    pinned_tab_count: usize,
 415    diagnostics: HashMap<ProjectPath, DiagnosticSeverity>,
 416    zoom_out_on_close: bool,
 417    diagnostic_summary_update: Task<()>,
 418    /// If a certain project item wants to get recreated with specific data, it can persist its data before the recreation here.
 419    pub project_item_restoration_data: HashMap<ProjectItemKind, Box<dyn Any + Send>>,
 420    welcome_page: Option<Entity<crate::welcome::WelcomePage>>,
 421
 422    pub in_center_group: bool,
 423    pub is_upper_left: bool,
 424    pub is_upper_right: bool,
 425}
 426
 427pub struct ActivationHistoryEntry {
 428    pub entity_id: EntityId,
 429    pub timestamp: usize,
 430}
 431
 432pub struct ItemNavHistory {
 433    history: NavHistory,
 434    item: Arc<dyn WeakItemHandle>,
 435    is_preview: bool,
 436}
 437
 438#[derive(Clone)]
 439pub struct NavHistory(Arc<Mutex<NavHistoryState>>);
 440
 441struct NavHistoryState {
 442    mode: NavigationMode,
 443    backward_stack: VecDeque<NavigationEntry>,
 444    forward_stack: VecDeque<NavigationEntry>,
 445    closed_stack: VecDeque<NavigationEntry>,
 446    paths_by_item: HashMap<EntityId, (ProjectPath, Option<PathBuf>)>,
 447    pane: WeakEntity<Pane>,
 448    next_timestamp: Arc<AtomicUsize>,
 449}
 450
 451#[derive(Debug, Default, Copy, Clone)]
 452pub enum NavigationMode {
 453    #[default]
 454    Normal,
 455    GoingBack,
 456    GoingForward,
 457    ClosingItem,
 458    ReopeningClosedItem,
 459    Disabled,
 460}
 461
 462pub struct NavigationEntry {
 463    pub item: Arc<dyn WeakItemHandle>,
 464    pub data: Option<Box<dyn Any + Send>>,
 465    pub timestamp: usize,
 466    pub is_preview: bool,
 467}
 468
 469#[derive(Clone)]
 470pub struct DraggedTab {
 471    pub pane: Entity<Pane>,
 472    pub item: Box<dyn ItemHandle>,
 473    pub ix: usize,
 474    pub detail: usize,
 475    pub is_active: bool,
 476}
 477
 478impl EventEmitter<Event> for Pane {}
 479
 480pub enum Side {
 481    Left,
 482    Right,
 483}
 484
 485#[derive(Copy, Clone)]
 486enum PinOperation {
 487    Pin,
 488    Unpin,
 489}
 490
 491impl Pane {
 492    pub fn new(
 493        workspace: WeakEntity<Workspace>,
 494        project: Entity<Project>,
 495        next_timestamp: Arc<AtomicUsize>,
 496        can_drop_predicate: Option<Arc<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>>,
 497        double_click_dispatch_action: Box<dyn Action>,
 498        use_max_tabs: bool,
 499        window: &mut Window,
 500        cx: &mut Context<Self>,
 501    ) -> Self {
 502        let focus_handle = cx.focus_handle();
 503        let max_tabs = if use_max_tabs {
 504            WorkspaceSettings::get_global(cx).max_tabs
 505        } else {
 506            None
 507        };
 508
 509        let subscriptions = vec![
 510            cx.on_focus(&focus_handle, window, Pane::focus_in),
 511            cx.on_focus_in(&focus_handle, window, Pane::focus_in),
 512            cx.on_focus_out(&focus_handle, window, Pane::focus_out),
 513            cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 514            cx.subscribe(&project, Self::project_events),
 515        ];
 516
 517        let handle = cx.entity().downgrade();
 518
 519        Self {
 520            alternate_file_items: (None, None),
 521            focus_handle,
 522            items: Vec::new(),
 523            activation_history: Vec::new(),
 524            next_activation_timestamp: next_timestamp.clone(),
 525            was_focused: false,
 526            zoomed: false,
 527            active_item_index: 0,
 528            preview_item_id: None,
 529            max_tabs,
 530            use_max_tabs,
 531            last_focus_handle_by_item: Default::default(),
 532            nav_history: NavHistory(Arc::new(Mutex::new(NavHistoryState {
 533                mode: NavigationMode::Normal,
 534                backward_stack: Default::default(),
 535                forward_stack: Default::default(),
 536                closed_stack: Default::default(),
 537                paths_by_item: Default::default(),
 538                pane: handle,
 539                next_timestamp,
 540            }))),
 541            toolbar: cx.new(|_| Toolbar::new()),
 542            tab_bar_scroll_handle: ScrollHandle::new(),
 543            suppress_scroll: false,
 544            drag_split_direction: None,
 545            workspace,
 546            project: project.downgrade(),
 547            can_drop_predicate,
 548            custom_drop_handle: None,
 549            can_split_predicate: None,
 550            can_toggle_zoom: true,
 551            should_display_tab_bar: Rc::new(|_, cx| TabBarSettings::get_global(cx).show),
 552            render_tab_bar_buttons: Rc::new(default_render_tab_bar_buttons),
 553            render_tab_bar: Rc::new(Self::render_tab_bar),
 554            show_tab_bar_buttons: TabBarSettings::get_global(cx).show_tab_bar_buttons,
 555            display_nav_history_buttons: Some(
 556                TabBarSettings::get_global(cx).show_nav_history_buttons,
 557            ),
 558            _subscriptions: subscriptions,
 559            double_click_dispatch_action,
 560            save_modals_spawned: HashSet::default(),
 561            close_pane_if_empty: true,
 562            split_item_context_menu_handle: Default::default(),
 563            new_item_context_menu_handle: Default::default(),
 564            pinned_tab_count: 0,
 565            diagnostics: Default::default(),
 566            zoom_out_on_close: true,
 567            diagnostic_summary_update: Task::ready(()),
 568            project_item_restoration_data: HashMap::default(),
 569            welcome_page: None,
 570            in_center_group: false,
 571            is_upper_left: false,
 572            is_upper_right: false,
 573        }
 574    }
 575
 576    fn alternate_file(&mut self, _: &AlternateFile, window: &mut Window, cx: &mut Context<Pane>) {
 577        let (_, alternative) = &self.alternate_file_items;
 578        if let Some(alternative) = alternative {
 579            let existing = self
 580                .items()
 581                .find_position(|item| item.item_id() == alternative.id());
 582            if let Some((ix, _)) = existing {
 583                self.activate_item(ix, true, true, window, cx);
 584            } else if let Some(upgraded) = alternative.upgrade() {
 585                self.add_item(upgraded, true, true, None, window, cx);
 586            }
 587        }
 588    }
 589
 590    pub fn track_alternate_file_items(&mut self) {
 591        if let Some(item) = self.active_item().map(|item| item.downgrade_item()) {
 592            let (current, _) = &self.alternate_file_items;
 593            match current {
 594                Some(current) => {
 595                    if current.id() != item.id() {
 596                        self.alternate_file_items =
 597                            (Some(item), self.alternate_file_items.0.take());
 598                    }
 599                }
 600                None => {
 601                    self.alternate_file_items = (Some(item), None);
 602                }
 603            }
 604        }
 605    }
 606
 607    pub fn has_focus(&self, window: &Window, cx: &App) -> bool {
 608        // We not only check whether our focus handle contains focus, but also
 609        // whether the active item might have focus, because we might have just activated an item
 610        // that hasn't rendered yet.
 611        // Before the next render, we might transfer focus
 612        // to the item, and `focus_handle.contains_focus` returns false because the `active_item`
 613        // is not hooked up to us in the dispatch tree.
 614        self.focus_handle.contains_focused(window, cx)
 615            || self
 616                .active_item()
 617                .is_some_and(|item| item.item_focus_handle(cx).contains_focused(window, cx))
 618    }
 619
 620    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 621        if !self.was_focused {
 622            self.was_focused = true;
 623            self.update_history(self.active_item_index);
 624            if !self.suppress_scroll && self.items.get(self.active_item_index).is_some() {
 625                self.update_active_tab(self.active_item_index);
 626            }
 627            cx.emit(Event::Focus);
 628            cx.notify();
 629        }
 630
 631        self.toolbar.update(cx, |toolbar, cx| {
 632            toolbar.focus_changed(true, window, cx);
 633        });
 634
 635        if let Some(active_item) = self.active_item() {
 636            if self.focus_handle.is_focused(window) {
 637                // Schedule a redraw next frame, so that the focus changes below take effect
 638                cx.on_next_frame(window, |_, _, cx| {
 639                    cx.notify();
 640                });
 641
 642                // Pane was focused directly. We need to either focus a view inside the active item,
 643                // or focus the active item itself
 644                if let Some(weak_last_focus_handle) =
 645                    self.last_focus_handle_by_item.get(&active_item.item_id())
 646                    && let Some(focus_handle) = weak_last_focus_handle.upgrade()
 647                {
 648                    focus_handle.focus(window, cx);
 649                    return;
 650                }
 651
 652                active_item.item_focus_handle(cx).focus(window, cx);
 653            } else if let Some(focused) = window.focused(cx)
 654                && !self.context_menu_focused(window, cx)
 655            {
 656                self.last_focus_handle_by_item
 657                    .insert(active_item.item_id(), focused.downgrade());
 658            }
 659        } else if let Some(welcome_page) = self.welcome_page.as_ref() {
 660            if self.focus_handle.is_focused(window) {
 661                welcome_page.read(cx).focus_handle(cx).focus(window, cx);
 662            }
 663        }
 664    }
 665
 666    pub fn context_menu_focused(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
 667        self.new_item_context_menu_handle.is_focused(window, cx)
 668            || self.split_item_context_menu_handle.is_focused(window, cx)
 669    }
 670
 671    fn focus_out(&mut self, _event: FocusOutEvent, window: &mut Window, cx: &mut Context<Self>) {
 672        self.was_focused = false;
 673        self.toolbar.update(cx, |toolbar, cx| {
 674            toolbar.focus_changed(false, window, cx);
 675        });
 676
 677        cx.notify();
 678    }
 679
 680    fn project_events(
 681        &mut self,
 682        _project: Entity<Project>,
 683        event: &project::Event,
 684        cx: &mut Context<Self>,
 685    ) {
 686        match event {
 687            project::Event::DiskBasedDiagnosticsFinished { .. }
 688            | project::Event::DiagnosticsUpdated { .. } => {
 689                if ItemSettings::get_global(cx).show_diagnostics != ShowDiagnostics::Off {
 690                    self.diagnostic_summary_update = cx.spawn(async move |this, cx| {
 691                        cx.background_executor()
 692                            .timer(Duration::from_millis(30))
 693                            .await;
 694                        this.update(cx, |this, cx| {
 695                            this.update_diagnostics(cx);
 696                            cx.notify();
 697                        })
 698                        .log_err();
 699                    });
 700                }
 701            }
 702            _ => {}
 703        }
 704    }
 705
 706    fn update_diagnostics(&mut self, cx: &mut Context<Self>) {
 707        let Some(project) = self.project.upgrade() else {
 708            return;
 709        };
 710        let show_diagnostics = ItemSettings::get_global(cx).show_diagnostics;
 711        self.diagnostics = if show_diagnostics != ShowDiagnostics::Off {
 712            project
 713                .read(cx)
 714                .diagnostic_summaries(false, cx)
 715                .filter_map(|(project_path, _, diagnostic_summary)| {
 716                    if diagnostic_summary.error_count > 0 {
 717                        Some((project_path, DiagnosticSeverity::ERROR))
 718                    } else if diagnostic_summary.warning_count > 0
 719                        && show_diagnostics != ShowDiagnostics::Errors
 720                    {
 721                        Some((project_path, DiagnosticSeverity::WARNING))
 722                    } else {
 723                        None
 724                    }
 725                })
 726                .collect()
 727        } else {
 728            HashMap::default()
 729        }
 730    }
 731
 732    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 733        let tab_bar_settings = TabBarSettings::get_global(cx);
 734        let new_max_tabs = WorkspaceSettings::get_global(cx).max_tabs;
 735
 736        if let Some(display_nav_history_buttons) = self.display_nav_history_buttons.as_mut() {
 737            *display_nav_history_buttons = tab_bar_settings.show_nav_history_buttons;
 738        }
 739
 740        self.show_tab_bar_buttons = tab_bar_settings.show_tab_bar_buttons;
 741
 742        if !PreviewTabsSettings::get_global(cx).enabled {
 743            self.preview_item_id = None;
 744        }
 745
 746        if self.use_max_tabs && new_max_tabs != self.max_tabs {
 747            self.max_tabs = new_max_tabs;
 748            self.close_items_on_settings_change(window, cx);
 749        }
 750
 751        self.update_diagnostics(cx);
 752        cx.notify();
 753    }
 754
 755    pub fn active_item_index(&self) -> usize {
 756        self.active_item_index
 757    }
 758
 759    pub fn activation_history(&self) -> &[ActivationHistoryEntry] {
 760        &self.activation_history
 761    }
 762
 763    pub fn set_should_display_tab_bar<F>(&mut self, should_display_tab_bar: F)
 764    where
 765        F: 'static + Fn(&Window, &mut Context<Pane>) -> bool,
 766    {
 767        self.should_display_tab_bar = Rc::new(should_display_tab_bar);
 768    }
 769
 770    pub fn set_can_split(
 771        &mut self,
 772        can_split_predicate: Option<
 773            Arc<dyn Fn(&mut Self, &dyn Any, &mut Window, &mut Context<Self>) -> bool + 'static>,
 774        >,
 775    ) {
 776        self.can_split_predicate = can_split_predicate;
 777    }
 778
 779    pub fn set_can_toggle_zoom(&mut self, can_toggle_zoom: bool, cx: &mut Context<Self>) {
 780        self.can_toggle_zoom = can_toggle_zoom;
 781        cx.notify();
 782    }
 783
 784    pub fn set_close_pane_if_empty(&mut self, close_pane_if_empty: bool, cx: &mut Context<Self>) {
 785        self.close_pane_if_empty = close_pane_if_empty;
 786        cx.notify();
 787    }
 788
 789    pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut Context<Self>) {
 790        self.toolbar.update(cx, |toolbar, cx| {
 791            toolbar.set_can_navigate(can_navigate, cx);
 792        });
 793        cx.notify();
 794    }
 795
 796    pub fn set_render_tab_bar<F>(&mut self, cx: &mut Context<Self>, render: F)
 797    where
 798        F: 'static + Fn(&mut Pane, &mut Window, &mut Context<Pane>) -> AnyElement,
 799    {
 800        self.render_tab_bar = Rc::new(render);
 801        cx.notify();
 802    }
 803
 804    pub fn set_render_tab_bar_buttons<F>(&mut self, cx: &mut Context<Self>, render: F)
 805    where
 806        F: 'static
 807            + Fn(
 808                &mut Pane,
 809                &mut Window,
 810                &mut Context<Pane>,
 811            ) -> (Option<AnyElement>, Option<AnyElement>),
 812    {
 813        self.render_tab_bar_buttons = Rc::new(render);
 814        cx.notify();
 815    }
 816
 817    pub fn set_custom_drop_handle<F>(&mut self, cx: &mut Context<Self>, handle: F)
 818    where
 819        F: 'static
 820            + Fn(&mut Pane, &dyn Any, &mut Window, &mut Context<Pane>) -> ControlFlow<(), ()>,
 821    {
 822        self.custom_drop_handle = Some(Arc::new(handle));
 823        cx.notify();
 824    }
 825
 826    pub fn nav_history_for_item<T: Item>(&self, item: &Entity<T>) -> ItemNavHistory {
 827        ItemNavHistory {
 828            history: self.nav_history.clone(),
 829            item: Arc::new(item.downgrade()),
 830            is_preview: self.preview_item_id == Some(item.item_id()),
 831        }
 832    }
 833
 834    pub fn nav_history(&self) -> &NavHistory {
 835        &self.nav_history
 836    }
 837
 838    pub fn nav_history_mut(&mut self) -> &mut NavHistory {
 839        &mut self.nav_history
 840    }
 841
 842    pub fn disable_history(&mut self) {
 843        self.nav_history.disable();
 844    }
 845
 846    pub fn enable_history(&mut self) {
 847        self.nav_history.enable();
 848    }
 849
 850    pub fn can_navigate_backward(&self) -> bool {
 851        !self.nav_history.0.lock().backward_stack.is_empty()
 852    }
 853
 854    pub fn can_navigate_forward(&self) -> bool {
 855        !self.nav_history.0.lock().forward_stack.is_empty()
 856    }
 857
 858    pub fn navigate_backward(&mut self, _: &GoBack, window: &mut Window, cx: &mut Context<Self>) {
 859        if let Some(workspace) = self.workspace.upgrade() {
 860            let pane = cx.entity().downgrade();
 861            window.defer(cx, move |window, cx| {
 862                workspace.update(cx, |workspace, cx| {
 863                    workspace.go_back(pane, window, cx).detach_and_log_err(cx)
 864                })
 865            })
 866        }
 867    }
 868
 869    fn navigate_forward(&mut self, _: &GoForward, window: &mut Window, cx: &mut Context<Self>) {
 870        if let Some(workspace) = self.workspace.upgrade() {
 871            let pane = cx.entity().downgrade();
 872            window.defer(cx, move |window, cx| {
 873                workspace.update(cx, |workspace, cx| {
 874                    workspace
 875                        .go_forward(pane, window, cx)
 876                        .detach_and_log_err(cx)
 877                })
 878            })
 879        }
 880    }
 881
 882    fn history_updated(&mut self, cx: &mut Context<Self>) {
 883        self.toolbar.update(cx, |_, cx| cx.notify());
 884    }
 885
 886    pub fn preview_item_id(&self) -> Option<EntityId> {
 887        self.preview_item_id
 888    }
 889
 890    pub fn preview_item(&self) -> Option<Box<dyn ItemHandle>> {
 891        self.preview_item_id
 892            .and_then(|id| self.items.iter().find(|item| item.item_id() == id))
 893            .cloned()
 894    }
 895
 896    pub fn preview_item_idx(&self) -> Option<usize> {
 897        if let Some(preview_item_id) = self.preview_item_id {
 898            self.items
 899                .iter()
 900                .position(|item| item.item_id() == preview_item_id)
 901        } else {
 902            None
 903        }
 904    }
 905
 906    pub fn is_active_preview_item(&self, item_id: EntityId) -> bool {
 907        self.preview_item_id == Some(item_id)
 908    }
 909
 910    /// Promotes the item with the given ID to not be a preview item.
 911    /// This does nothing if it wasn't already a preview item.
 912    pub fn unpreview_item_if_preview(&mut self, item_id: EntityId) {
 913        if self.is_active_preview_item(item_id) {
 914            self.preview_item_id = None;
 915        }
 916    }
 917
 918    /// Marks the item with the given ID as the preview item.
 919    /// This will be ignored if the global setting `preview_tabs` is disabled.
 920    ///
 921    /// The old preview item (if there was one) is closed and its index is returned.
 922    pub fn replace_preview_item_id(
 923        &mut self,
 924        item_id: EntityId,
 925        window: &mut Window,
 926        cx: &mut Context<Self>,
 927    ) -> Option<usize> {
 928        let idx = self.close_current_preview_item(window, cx);
 929        self.set_preview_item_id(Some(item_id), cx);
 930        idx
 931    }
 932
 933    /// Marks the item with the given ID as the preview item.
 934    /// This will be ignored if the global setting `preview_tabs` is disabled.
 935    ///
 936    /// This is a low-level method. Prefer `unpreview_item_if_preview()` or `set_new_preview_item()`.
 937    pub(crate) fn set_preview_item_id(&mut self, item_id: Option<EntityId>, cx: &App) {
 938        if item_id.is_none() || PreviewTabsSettings::get_global(cx).enabled {
 939            self.preview_item_id = item_id;
 940        }
 941    }
 942
 943    /// Should only be used when deserializing a pane.
 944    pub fn set_pinned_count(&mut self, count: usize) {
 945        self.pinned_tab_count = count;
 946    }
 947
 948    pub fn pinned_count(&self) -> usize {
 949        self.pinned_tab_count
 950    }
 951
 952    pub fn handle_item_edit(&mut self, item_id: EntityId, cx: &App) {
 953        if let Some(preview_item) = self.preview_item()
 954            && preview_item.item_id() == item_id
 955            && !preview_item.preserve_preview(cx)
 956        {
 957            self.unpreview_item_if_preview(item_id);
 958        }
 959    }
 960
 961    pub(crate) fn open_item(
 962        &mut self,
 963        project_entry_id: Option<ProjectEntryId>,
 964        project_path: ProjectPath,
 965        focus_item: bool,
 966        allow_preview: bool,
 967        activate: bool,
 968        suggested_position: Option<usize>,
 969        window: &mut Window,
 970        cx: &mut Context<Self>,
 971        build_item: WorkspaceItemBuilder,
 972    ) -> Box<dyn ItemHandle> {
 973        let mut existing_item = None;
 974        if let Some(project_entry_id) = project_entry_id {
 975            for (index, item) in self.items.iter().enumerate() {
 976                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 977                    && item.project_entry_ids(cx).as_slice() == [project_entry_id]
 978                {
 979                    let item = item.boxed_clone();
 980                    existing_item = Some((index, item));
 981                    break;
 982                }
 983            }
 984        } else {
 985            for (index, item) in self.items.iter().enumerate() {
 986                if item.buffer_kind(cx) == ItemBufferKind::Singleton
 987                    && item.project_path(cx).as_ref() == Some(&project_path)
 988                {
 989                    let item = item.boxed_clone();
 990                    existing_item = Some((index, item));
 991                    break;
 992                }
 993            }
 994        }
 995
 996        let set_up_existing_item =
 997            |index: usize, pane: &mut Self, window: &mut Window, cx: &mut Context<Self>| {
 998                if !allow_preview && let Some(item) = pane.items.get(index) {
 999                    pane.unpreview_item_if_preview(item.item_id());
1000                }
1001                if activate {
1002                    pane.activate_item(index, focus_item, focus_item, window, cx);
1003                }
1004            };
1005        let set_up_new_item = |new_item: Box<dyn ItemHandle>,
1006                               destination_index: Option<usize>,
1007                               pane: &mut Self,
1008                               window: &mut Window,
1009                               cx: &mut Context<Self>| {
1010            if allow_preview {
1011                pane.replace_preview_item_id(new_item.item_id(), window, cx);
1012            }
1013
1014            if let Some(text) = new_item.telemetry_event_text(cx) {
1015                telemetry::event!(text);
1016            }
1017
1018            pane.add_item_inner(
1019                new_item,
1020                true,
1021                focus_item,
1022                activate,
1023                destination_index,
1024                window,
1025                cx,
1026            );
1027        };
1028
1029        if let Some((index, existing_item)) = existing_item {
1030            set_up_existing_item(index, self, window, cx);
1031            existing_item
1032        } else {
1033            // If the item is being opened as preview and we have an existing preview tab,
1034            // open the new item in the position of the existing preview tab.
1035            let destination_index = if allow_preview {
1036                self.close_current_preview_item(window, cx)
1037            } else {
1038                suggested_position
1039            };
1040
1041            let new_item = build_item(self, window, cx);
1042            // A special case that won't ever get a `project_entry_id` but has to be deduplicated nonetheless.
1043            if let Some(invalid_buffer_view) = new_item.downcast::<InvalidItemView>() {
1044                let mut already_open_view = None;
1045                let mut views_to_close = HashSet::default();
1046                for existing_error_view in self
1047                    .items_of_type::<InvalidItemView>()
1048                    .filter(|item| item.read(cx).abs_path == invalid_buffer_view.read(cx).abs_path)
1049                {
1050                    if already_open_view.is_none()
1051                        && existing_error_view.read(cx).error == invalid_buffer_view.read(cx).error
1052                    {
1053                        already_open_view = Some(existing_error_view);
1054                    } else {
1055                        views_to_close.insert(existing_error_view.item_id());
1056                    }
1057                }
1058
1059                let resulting_item = match already_open_view {
1060                    Some(already_open_view) => {
1061                        if let Some(index) = self.index_for_item_id(already_open_view.item_id()) {
1062                            set_up_existing_item(index, self, window, cx);
1063                        }
1064                        Box::new(already_open_view) as Box<_>
1065                    }
1066                    None => {
1067                        set_up_new_item(new_item.clone(), destination_index, self, window, cx);
1068                        new_item
1069                    }
1070                };
1071
1072                self.close_items(window, cx, SaveIntent::Skip, |existing_item| {
1073                    views_to_close.contains(&existing_item)
1074                })
1075                .detach();
1076
1077                resulting_item
1078            } else {
1079                set_up_new_item(new_item.clone(), destination_index, self, window, cx);
1080                new_item
1081            }
1082        }
1083    }
1084
1085    pub fn close_current_preview_item(
1086        &mut self,
1087        window: &mut Window,
1088        cx: &mut Context<Self>,
1089    ) -> Option<usize> {
1090        let item_idx = self.preview_item_idx()?;
1091        let id = self.preview_item_id()?;
1092        self.set_preview_item_id(None, cx);
1093
1094        let prev_active_item_index = self.active_item_index;
1095        self.remove_item(id, false, false, window, cx);
1096        self.active_item_index = prev_active_item_index;
1097
1098        if item_idx < self.items.len() {
1099            Some(item_idx)
1100        } else {
1101            None
1102        }
1103    }
1104
1105    pub fn add_item_inner(
1106        &mut self,
1107        item: Box<dyn ItemHandle>,
1108        activate_pane: bool,
1109        focus_item: bool,
1110        activate: bool,
1111        destination_index: Option<usize>,
1112        window: &mut Window,
1113        cx: &mut Context<Self>,
1114    ) {
1115        let item_already_exists = self
1116            .items
1117            .iter()
1118            .any(|existing_item| existing_item.item_id() == item.item_id());
1119
1120        if !item_already_exists {
1121            self.close_items_on_item_open(window, cx);
1122        }
1123
1124        if item.buffer_kind(cx) == ItemBufferKind::Singleton
1125            && let Some(&entry_id) = item.project_entry_ids(cx).first()
1126        {
1127            let Some(project) = self.project.upgrade() else {
1128                return;
1129            };
1130
1131            let project = project.read(cx);
1132            if let Some(project_path) = project.path_for_entry(entry_id, cx) {
1133                let abs_path = project.absolute_path(&project_path, cx);
1134                self.nav_history
1135                    .0
1136                    .lock()
1137                    .paths_by_item
1138                    .insert(item.item_id(), (project_path, abs_path));
1139            }
1140        }
1141        // If no destination index is specified, add or move the item after the
1142        // active item (or at the start of tab bar, if the active item is pinned)
1143        let mut insertion_index = {
1144            cmp::min(
1145                if let Some(destination_index) = destination_index {
1146                    destination_index
1147                } else {
1148                    cmp::max(self.active_item_index + 1, self.pinned_count())
1149                },
1150                self.items.len(),
1151            )
1152        };
1153
1154        // Does the item already exist?
1155        let project_entry_id = if item.buffer_kind(cx) == ItemBufferKind::Singleton {
1156            item.project_entry_ids(cx).first().copied()
1157        } else {
1158            None
1159        };
1160
1161        let existing_item_index = self.items.iter().position(|existing_item| {
1162            if existing_item.item_id() == item.item_id() {
1163                true
1164            } else if existing_item.buffer_kind(cx) == ItemBufferKind::Singleton {
1165                existing_item
1166                    .project_entry_ids(cx)
1167                    .first()
1168                    .is_some_and(|existing_entry_id| {
1169                        Some(existing_entry_id) == project_entry_id.as_ref()
1170                    })
1171            } else {
1172                false
1173            }
1174        });
1175        if let Some(existing_item_index) = existing_item_index {
1176            // If the item already exists, move it to the desired destination and activate it
1177
1178            if existing_item_index != insertion_index {
1179                let existing_item_is_active = existing_item_index == self.active_item_index;
1180
1181                // If the caller didn't specify a destination and the added item is already
1182                // the active one, don't move it
1183                if existing_item_is_active && destination_index.is_none() {
1184                    insertion_index = existing_item_index;
1185                } else {
1186                    self.items.remove(existing_item_index);
1187                    if existing_item_index < self.active_item_index {
1188                        self.active_item_index -= 1;
1189                    }
1190                    insertion_index = insertion_index.min(self.items.len());
1191
1192                    self.items.insert(insertion_index, item.clone());
1193
1194                    if existing_item_is_active {
1195                        self.active_item_index = insertion_index;
1196                    } else if insertion_index <= self.active_item_index {
1197                        self.active_item_index += 1;
1198                    }
1199                }
1200
1201                cx.notify();
1202            }
1203
1204            if activate {
1205                self.activate_item(insertion_index, activate_pane, focus_item, window, cx);
1206            }
1207        } else {
1208            self.items.insert(insertion_index, item.clone());
1209            cx.notify();
1210
1211            if activate {
1212                if insertion_index <= self.active_item_index
1213                    && self.preview_item_idx() != Some(self.active_item_index)
1214                {
1215                    self.active_item_index += 1;
1216                }
1217
1218                self.activate_item(insertion_index, activate_pane, focus_item, window, cx);
1219            }
1220        }
1221
1222        cx.emit(Event::AddItem { item });
1223    }
1224
1225    pub fn add_item(
1226        &mut self,
1227        item: Box<dyn ItemHandle>,
1228        activate_pane: bool,
1229        focus_item: bool,
1230        destination_index: Option<usize>,
1231        window: &mut Window,
1232        cx: &mut Context<Self>,
1233    ) {
1234        if let Some(text) = item.telemetry_event_text(cx) {
1235            telemetry::event!(text);
1236        }
1237
1238        self.add_item_inner(
1239            item,
1240            activate_pane,
1241            focus_item,
1242            true,
1243            destination_index,
1244            window,
1245            cx,
1246        )
1247    }
1248
1249    pub fn items_len(&self) -> usize {
1250        self.items.len()
1251    }
1252
1253    pub fn items(&self) -> impl DoubleEndedIterator<Item = &Box<dyn ItemHandle>> {
1254        self.items.iter()
1255    }
1256
1257    pub fn items_of_type<T: Render>(&self) -> impl '_ + Iterator<Item = Entity<T>> {
1258        self.items
1259            .iter()
1260            .filter_map(|item| item.to_any_view().downcast().ok())
1261    }
1262
1263    pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
1264        self.items.get(self.active_item_index).cloned()
1265    }
1266
1267    fn active_item_id(&self) -> EntityId {
1268        self.items[self.active_item_index].item_id()
1269    }
1270
1271    pub fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>> {
1272        self.items
1273            .get(self.active_item_index)?
1274            .pixel_position_of_cursor(cx)
1275    }
1276
1277    pub fn item_for_entry(
1278        &self,
1279        entry_id: ProjectEntryId,
1280        cx: &App,
1281    ) -> Option<Box<dyn ItemHandle>> {
1282        self.items.iter().find_map(|item| {
1283            if item.buffer_kind(cx) == ItemBufferKind::Singleton
1284                && (item.project_entry_ids(cx).as_slice() == [entry_id])
1285            {
1286                Some(item.boxed_clone())
1287            } else {
1288                None
1289            }
1290        })
1291    }
1292
1293    pub fn item_for_path(
1294        &self,
1295        project_path: ProjectPath,
1296        cx: &App,
1297    ) -> Option<Box<dyn ItemHandle>> {
1298        self.items.iter().find_map(move |item| {
1299            if item.buffer_kind(cx) == ItemBufferKind::Singleton
1300                && (item.project_path(cx).as_slice() == [project_path.clone()])
1301            {
1302                Some(item.boxed_clone())
1303            } else {
1304                None
1305            }
1306        })
1307    }
1308
1309    pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
1310        self.index_for_item_id(item.item_id())
1311    }
1312
1313    fn index_for_item_id(&self, item_id: EntityId) -> Option<usize> {
1314        self.items.iter().position(|i| i.item_id() == item_id)
1315    }
1316
1317    pub fn item_for_index(&self, ix: usize) -> Option<&dyn ItemHandle> {
1318        self.items.get(ix).map(|i| i.as_ref())
1319    }
1320
1321    pub fn toggle_zoom(&mut self, _: &ToggleZoom, window: &mut Window, cx: &mut Context<Self>) {
1322        if !self.can_toggle_zoom {
1323            cx.propagate();
1324        } else if self.zoomed {
1325            cx.emit(Event::ZoomOut);
1326        } else if !self.items.is_empty() {
1327            if !self.focus_handle.contains_focused(window, cx) {
1328                cx.focus_self(window);
1329            }
1330            cx.emit(Event::ZoomIn);
1331        }
1332    }
1333
1334    pub fn zoom_in(&mut self, _: &ZoomIn, window: &mut Window, cx: &mut Context<Self>) {
1335        if !self.can_toggle_zoom {
1336            cx.propagate();
1337        } else if !self.zoomed && !self.items.is_empty() {
1338            if !self.focus_handle.contains_focused(window, cx) {
1339                cx.focus_self(window);
1340            }
1341            cx.emit(Event::ZoomIn);
1342        }
1343    }
1344
1345    pub fn zoom_out(&mut self, _: &ZoomOut, _window: &mut Window, cx: &mut Context<Self>) {
1346        if !self.can_toggle_zoom {
1347            cx.propagate();
1348        } else if self.zoomed {
1349            cx.emit(Event::ZoomOut);
1350        }
1351    }
1352
1353    pub fn activate_item(
1354        &mut self,
1355        index: usize,
1356        activate_pane: bool,
1357        focus_item: bool,
1358        window: &mut Window,
1359        cx: &mut Context<Self>,
1360    ) {
1361        use NavigationMode::{GoingBack, GoingForward};
1362        if index < self.items.len() {
1363            let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
1364            if (prev_active_item_ix != self.active_item_index
1365                || matches!(self.nav_history.mode(), GoingBack | GoingForward))
1366                && let Some(prev_item) = self.items.get(prev_active_item_ix)
1367            {
1368                prev_item.deactivated(window, cx);
1369            }
1370            self.update_history(index);
1371            self.update_toolbar(window, cx);
1372            self.update_status_bar(window, cx);
1373
1374            if focus_item {
1375                self.focus_active_item(window, cx);
1376            }
1377
1378            cx.emit(Event::ActivateItem {
1379                local: activate_pane,
1380                focus_changed: focus_item,
1381            });
1382
1383            self.update_active_tab(index);
1384            cx.notify();
1385        }
1386    }
1387
1388    fn update_active_tab(&mut self, index: usize) {
1389        if !self.is_tab_pinned(index) {
1390            self.suppress_scroll = false;
1391            self.tab_bar_scroll_handle.scroll_to_item(index);
1392        }
1393    }
1394
1395    fn update_history(&mut self, index: usize) {
1396        if let Some(newly_active_item) = self.items.get(index) {
1397            self.activation_history
1398                .retain(|entry| entry.entity_id != newly_active_item.item_id());
1399            self.activation_history.push(ActivationHistoryEntry {
1400                entity_id: newly_active_item.item_id(),
1401                timestamp: self
1402                    .next_activation_timestamp
1403                    .fetch_add(1, Ordering::SeqCst),
1404            });
1405        }
1406    }
1407
1408    pub fn activate_previous_item(
1409        &mut self,
1410        _: &ActivatePreviousItem,
1411        window: &mut Window,
1412        cx: &mut Context<Self>,
1413    ) {
1414        let mut index = self.active_item_index;
1415        if index > 0 {
1416            index -= 1;
1417        } else if !self.items.is_empty() {
1418            index = self.items.len() - 1;
1419        }
1420        self.activate_item(index, true, true, window, cx);
1421    }
1422
1423    pub fn activate_next_item(
1424        &mut self,
1425        _: &ActivateNextItem,
1426        window: &mut Window,
1427        cx: &mut Context<Self>,
1428    ) {
1429        let mut index = self.active_item_index;
1430        if index + 1 < self.items.len() {
1431            index += 1;
1432        } else {
1433            index = 0;
1434        }
1435        self.activate_item(index, true, true, window, cx);
1436    }
1437
1438    pub fn swap_item_left(
1439        &mut self,
1440        _: &SwapItemLeft,
1441        window: &mut Window,
1442        cx: &mut Context<Self>,
1443    ) {
1444        let index = self.active_item_index;
1445        if index == 0 {
1446            return;
1447        }
1448
1449        self.items.swap(index, index - 1);
1450        self.activate_item(index - 1, true, true, window, cx);
1451    }
1452
1453    pub fn swap_item_right(
1454        &mut self,
1455        _: &SwapItemRight,
1456        window: &mut Window,
1457        cx: &mut Context<Self>,
1458    ) {
1459        let index = self.active_item_index;
1460        if index + 1 >= self.items.len() {
1461            return;
1462        }
1463
1464        self.items.swap(index, index + 1);
1465        self.activate_item(index + 1, true, true, window, cx);
1466    }
1467
1468    pub fn activate_last_item(
1469        &mut self,
1470        _: &ActivateLastItem,
1471        window: &mut Window,
1472        cx: &mut Context<Self>,
1473    ) {
1474        let index = self.items.len().saturating_sub(1);
1475        self.activate_item(index, true, true, window, cx);
1476    }
1477
1478    pub fn close_active_item(
1479        &mut self,
1480        action: &CloseActiveItem,
1481        window: &mut Window,
1482        cx: &mut Context<Self>,
1483    ) -> Task<Result<()>> {
1484        if self.items.is_empty() {
1485            // Close the window when there's no active items to close, if configured
1486            if WorkspaceSettings::get_global(cx)
1487                .when_closing_with_no_tabs
1488                .should_close()
1489            {
1490                window.dispatch_action(Box::new(CloseWindow), cx);
1491            }
1492
1493            return Task::ready(Ok(()));
1494        }
1495        if self.is_tab_pinned(self.active_item_index) && !action.close_pinned {
1496            // Activate any non-pinned tab in same pane
1497            let non_pinned_tab_index = self
1498                .items()
1499                .enumerate()
1500                .find(|(index, _item)| !self.is_tab_pinned(*index))
1501                .map(|(index, _item)| index);
1502            if let Some(index) = non_pinned_tab_index {
1503                self.activate_item(index, false, false, window, cx);
1504                return Task::ready(Ok(()));
1505            }
1506
1507            // Activate any non-pinned tab in different pane
1508            let current_pane = cx.entity();
1509            self.workspace
1510                .update(cx, |workspace, cx| {
1511                    let panes = workspace.center.panes();
1512                    let pane_with_unpinned_tab = panes.iter().find(|pane| {
1513                        if **pane == &current_pane {
1514                            return false;
1515                        }
1516                        pane.read(cx).has_unpinned_tabs()
1517                    });
1518                    if let Some(pane) = pane_with_unpinned_tab {
1519                        pane.update(cx, |pane, cx| pane.activate_unpinned_tab(window, cx));
1520                    }
1521                })
1522                .ok();
1523
1524            return Task::ready(Ok(()));
1525        };
1526
1527        let active_item_id = self.active_item_id();
1528
1529        self.close_item_by_id(
1530            active_item_id,
1531            action.save_intent.unwrap_or(SaveIntent::Close),
1532            window,
1533            cx,
1534        )
1535    }
1536
1537    pub fn close_item_by_id(
1538        &mut self,
1539        item_id_to_close: EntityId,
1540        save_intent: SaveIntent,
1541        window: &mut Window,
1542        cx: &mut Context<Self>,
1543    ) -> Task<Result<()>> {
1544        self.close_items(window, cx, save_intent, move |view_id| {
1545            view_id == item_id_to_close
1546        })
1547    }
1548
1549    pub fn close_other_items(
1550        &mut self,
1551        action: &CloseOtherItems,
1552        target_item_id: Option<EntityId>,
1553        window: &mut Window,
1554        cx: &mut Context<Self>,
1555    ) -> Task<Result<()>> {
1556        if self.items.is_empty() {
1557            return Task::ready(Ok(()));
1558        }
1559
1560        let active_item_id = match target_item_id {
1561            Some(result) => result,
1562            None => self.active_item_id(),
1563        };
1564
1565        let pinned_item_ids = self.pinned_item_ids();
1566
1567        self.close_items(
1568            window,
1569            cx,
1570            action.save_intent.unwrap_or(SaveIntent::Close),
1571            move |item_id| {
1572                item_id != active_item_id
1573                    && (action.close_pinned || !pinned_item_ids.contains(&item_id))
1574            },
1575        )
1576    }
1577
1578    pub fn close_multibuffer_items(
1579        &mut self,
1580        action: &CloseMultibufferItems,
1581        window: &mut Window,
1582        cx: &mut Context<Self>,
1583    ) -> Task<Result<()>> {
1584        if self.items.is_empty() {
1585            return Task::ready(Ok(()));
1586        }
1587
1588        let pinned_item_ids = self.pinned_item_ids();
1589        let multibuffer_items = self.multibuffer_item_ids(cx);
1590
1591        self.close_items(
1592            window,
1593            cx,
1594            action.save_intent.unwrap_or(SaveIntent::Close),
1595            move |item_id| {
1596                (action.close_pinned || !pinned_item_ids.contains(&item_id))
1597                    && multibuffer_items.contains(&item_id)
1598            },
1599        )
1600    }
1601
1602    pub fn close_clean_items(
1603        &mut self,
1604        action: &CloseCleanItems,
1605        window: &mut Window,
1606        cx: &mut Context<Self>,
1607    ) -> Task<Result<()>> {
1608        if self.items.is_empty() {
1609            return Task::ready(Ok(()));
1610        }
1611
1612        let clean_item_ids = self.clean_item_ids(cx);
1613        let pinned_item_ids = self.pinned_item_ids();
1614
1615        self.close_items(window, cx, SaveIntent::Close, move |item_id| {
1616            clean_item_ids.contains(&item_id)
1617                && (action.close_pinned || !pinned_item_ids.contains(&item_id))
1618        })
1619    }
1620
1621    pub fn close_items_to_the_left_by_id(
1622        &mut self,
1623        item_id: Option<EntityId>,
1624        action: &CloseItemsToTheLeft,
1625        window: &mut Window,
1626        cx: &mut Context<Self>,
1627    ) -> Task<Result<()>> {
1628        self.close_items_to_the_side_by_id(item_id, Side::Left, action.close_pinned, window, cx)
1629    }
1630
1631    pub fn close_items_to_the_right_by_id(
1632        &mut self,
1633        item_id: Option<EntityId>,
1634        action: &CloseItemsToTheRight,
1635        window: &mut Window,
1636        cx: &mut Context<Self>,
1637    ) -> Task<Result<()>> {
1638        self.close_items_to_the_side_by_id(item_id, Side::Right, action.close_pinned, window, cx)
1639    }
1640
1641    pub fn close_items_to_the_side_by_id(
1642        &mut self,
1643        item_id: Option<EntityId>,
1644        side: Side,
1645        close_pinned: bool,
1646        window: &mut Window,
1647        cx: &mut Context<Self>,
1648    ) -> Task<Result<()>> {
1649        if self.items.is_empty() {
1650            return Task::ready(Ok(()));
1651        }
1652
1653        let item_id = item_id.unwrap_or_else(|| self.active_item_id());
1654        let to_the_side_item_ids = self.to_the_side_item_ids(item_id, side);
1655        let pinned_item_ids = self.pinned_item_ids();
1656
1657        self.close_items(window, cx, SaveIntent::Close, move |item_id| {
1658            to_the_side_item_ids.contains(&item_id)
1659                && (close_pinned || !pinned_item_ids.contains(&item_id))
1660        })
1661    }
1662
1663    pub fn close_all_items(
1664        &mut self,
1665        action: &CloseAllItems,
1666        window: &mut Window,
1667        cx: &mut Context<Self>,
1668    ) -> Task<Result<()>> {
1669        if self.items.is_empty() {
1670            return Task::ready(Ok(()));
1671        }
1672
1673        let pinned_item_ids = self.pinned_item_ids();
1674
1675        self.close_items(
1676            window,
1677            cx,
1678            action.save_intent.unwrap_or(SaveIntent::Close),
1679            |item_id| action.close_pinned || !pinned_item_ids.contains(&item_id),
1680        )
1681    }
1682
1683    fn close_items_on_item_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1684        let target = self.max_tabs.map(|m| m.get());
1685        let protect_active_item = false;
1686        self.close_items_to_target_count(target, protect_active_item, window, cx);
1687    }
1688
1689    fn close_items_on_settings_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1690        let target = self.max_tabs.map(|m| m.get() + 1);
1691        // The active item in this case is the settings.json file, which should be protected from being closed
1692        let protect_active_item = true;
1693        self.close_items_to_target_count(target, protect_active_item, window, cx);
1694    }
1695
1696    fn close_items_to_target_count(
1697        &mut self,
1698        target_count: Option<usize>,
1699        protect_active_item: bool,
1700        window: &mut Window,
1701        cx: &mut Context<Self>,
1702    ) {
1703        let Some(target_count) = target_count else {
1704            return;
1705        };
1706
1707        let mut index_list = Vec::new();
1708        let mut items_len = self.items_len();
1709        let mut indexes: HashMap<EntityId, usize> = HashMap::default();
1710        let active_ix = self.active_item_index();
1711
1712        for (index, item) in self.items.iter().enumerate() {
1713            indexes.insert(item.item_id(), index);
1714        }
1715
1716        // Close least recently used items to reach target count.
1717        // The target count is allowed to be exceeded, as we protect pinned
1718        // items, dirty items, and sometimes, the active item.
1719        for entry in self.activation_history.iter() {
1720            if items_len < target_count {
1721                break;
1722            }
1723
1724            let Some(&index) = indexes.get(&entry.entity_id) else {
1725                continue;
1726            };
1727
1728            if protect_active_item && index == active_ix {
1729                continue;
1730            }
1731
1732            if let Some(true) = self.items.get(index).map(|item| item.is_dirty(cx)) {
1733                continue;
1734            }
1735
1736            if self.is_tab_pinned(index) {
1737                continue;
1738            }
1739
1740            index_list.push(index);
1741            items_len -= 1;
1742        }
1743        // The sort and reverse is necessary since we remove items
1744        // using their index position, hence removing from the end
1745        // of the list first to avoid changing indexes.
1746        index_list.sort_unstable();
1747        index_list
1748            .iter()
1749            .rev()
1750            .for_each(|&index| self._remove_item(index, false, false, None, window, cx));
1751    }
1752
1753    // Usually when you close an item that has unsaved changes, we prompt you to
1754    // save it. That said, if you still have the buffer open in a different pane
1755    // we can close this one without fear of losing data.
1756    pub fn skip_save_on_close(item: &dyn ItemHandle, workspace: &Workspace, cx: &App) -> bool {
1757        let mut dirty_project_item_ids = Vec::new();
1758        item.for_each_project_item(cx, &mut |project_item_id, project_item| {
1759            if project_item.is_dirty() {
1760                dirty_project_item_ids.push(project_item_id);
1761            }
1762        });
1763        if dirty_project_item_ids.is_empty() {
1764            return !(item.buffer_kind(cx) == ItemBufferKind::Singleton && item.is_dirty(cx));
1765        }
1766
1767        for open_item in workspace.items(cx) {
1768            if open_item.item_id() == item.item_id() {
1769                continue;
1770            }
1771            if open_item.buffer_kind(cx) != ItemBufferKind::Singleton {
1772                continue;
1773            }
1774            let other_project_item_ids = open_item.project_item_model_ids(cx);
1775            dirty_project_item_ids.retain(|id| !other_project_item_ids.contains(id));
1776        }
1777        dirty_project_item_ids.is_empty()
1778    }
1779
1780    pub(super) fn file_names_for_prompt(
1781        items: &mut dyn Iterator<Item = &Box<dyn ItemHandle>>,
1782        cx: &App,
1783    ) -> String {
1784        let mut file_names = BTreeSet::default();
1785        for item in items {
1786            item.for_each_project_item(cx, &mut |_, project_item| {
1787                if !project_item.is_dirty() {
1788                    return;
1789                }
1790                let filename = project_item
1791                    .project_path(cx)
1792                    .and_then(|path| path.path.file_name().map(ToOwned::to_owned));
1793                file_names.insert(filename.unwrap_or("untitled".to_string()));
1794            });
1795        }
1796        if file_names.len() > 6 {
1797            format!(
1798                "{}\n.. and {} more",
1799                file_names.iter().take(5).join("\n"),
1800                file_names.len() - 5
1801            )
1802        } else {
1803            file_names.into_iter().join("\n")
1804        }
1805    }
1806
1807    pub fn close_items(
1808        &self,
1809        window: &mut Window,
1810        cx: &mut Context<Pane>,
1811        mut save_intent: SaveIntent,
1812        should_close: impl Fn(EntityId) -> bool,
1813    ) -> Task<Result<()>> {
1814        // Find the items to close.
1815        let mut items_to_close = Vec::new();
1816        for item in &self.items {
1817            if should_close(item.item_id()) {
1818                items_to_close.push(item.boxed_clone());
1819            }
1820        }
1821
1822        let active_item_id = self.active_item().map(|item| item.item_id());
1823
1824        items_to_close.sort_by_key(|item| {
1825            let path = item.project_path(cx);
1826            // Put the currently active item at the end, because if the currently active item is not closed last
1827            // closing the currently active item will cause the focus to switch to another item
1828            // This will cause Zed to expand the content of the currently active item
1829            //
1830            // Beyond that sort in order of project path, with untitled files and multibuffers coming last.
1831            (active_item_id == Some(item.item_id()), path.is_none(), path)
1832        });
1833
1834        let workspace = self.workspace.clone();
1835        let Some(project) = self.project.upgrade() else {
1836            return Task::ready(Ok(()));
1837        };
1838        cx.spawn_in(window, async move |pane, cx| {
1839            let dirty_items = workspace.update(cx, |workspace, cx| {
1840                items_to_close
1841                    .iter()
1842                    .filter(|item| {
1843                        item.is_dirty(cx) && !Self::skip_save_on_close(item.as_ref(), workspace, cx)
1844                    })
1845                    .map(|item| item.boxed_clone())
1846                    .collect::<Vec<_>>()
1847            })?;
1848
1849            if save_intent == SaveIntent::Close && dirty_items.len() > 1 {
1850                let answer = pane.update_in(cx, |_, window, cx| {
1851                    let detail = Self::file_names_for_prompt(&mut dirty_items.iter(), cx);
1852                    window.prompt(
1853                        PromptLevel::Warning,
1854                        "Do you want to save changes to the following files?",
1855                        Some(&detail),
1856                        &["Save all", "Discard all", "Cancel"],
1857                        cx,
1858                    )
1859                })?;
1860                match answer.await {
1861                    Ok(0) => save_intent = SaveIntent::SaveAll,
1862                    Ok(1) => save_intent = SaveIntent::Skip,
1863                    Ok(2) => return Ok(()),
1864                    _ => {}
1865                }
1866            }
1867
1868            for item_to_close in items_to_close {
1869                let mut should_close = true;
1870                let mut should_save = true;
1871                if save_intent == SaveIntent::Close {
1872                    workspace.update(cx, |workspace, cx| {
1873                        if Self::skip_save_on_close(item_to_close.as_ref(), workspace, cx) {
1874                            should_save = false;
1875                        }
1876                    })?;
1877                }
1878
1879                if should_save {
1880                    match Self::save_item(project.clone(), &pane, &*item_to_close, save_intent, cx)
1881                        .await
1882                    {
1883                        Ok(success) => {
1884                            if !success {
1885                                should_close = false;
1886                            }
1887                        }
1888                        Err(err) => {
1889                            let answer = pane.update_in(cx, |_, window, cx| {
1890                                let detail = Self::file_names_for_prompt(
1891                                    &mut [&item_to_close].into_iter(),
1892                                    cx,
1893                                );
1894                                window.prompt(
1895                                    PromptLevel::Warning,
1896                                    &format!("Unable to save file: {}", &err),
1897                                    Some(&detail),
1898                                    &["Close Without Saving", "Cancel"],
1899                                    cx,
1900                                )
1901                            })?;
1902                            match answer.await {
1903                                Ok(0) => {}
1904                                Ok(1..) | Err(_) => should_close = false,
1905                            }
1906                        }
1907                    }
1908                }
1909
1910                // Remove the item from the pane.
1911                if should_close {
1912                    pane.update_in(cx, |pane, window, cx| {
1913                        pane.remove_item(
1914                            item_to_close.item_id(),
1915                            false,
1916                            pane.close_pane_if_empty,
1917                            window,
1918                            cx,
1919                        );
1920                    })
1921                    .ok();
1922                }
1923            }
1924
1925            pane.update(cx, |_, cx| cx.notify()).ok();
1926            Ok(())
1927        })
1928    }
1929
1930    pub fn take_active_item(
1931        &mut self,
1932        window: &mut Window,
1933        cx: &mut Context<Self>,
1934    ) -> Option<Box<dyn ItemHandle>> {
1935        let item = self.active_item()?;
1936        self.remove_item(item.item_id(), false, false, window, cx);
1937        Some(item)
1938    }
1939
1940    pub fn remove_item(
1941        &mut self,
1942        item_id: EntityId,
1943        activate_pane: bool,
1944        close_pane_if_empty: bool,
1945        window: &mut Window,
1946        cx: &mut Context<Self>,
1947    ) {
1948        let Some(item_index) = self.index_for_item_id(item_id) else {
1949            return;
1950        };
1951        self._remove_item(
1952            item_index,
1953            activate_pane,
1954            close_pane_if_empty,
1955            None,
1956            window,
1957            cx,
1958        )
1959    }
1960
1961    pub fn remove_item_and_focus_on_pane(
1962        &mut self,
1963        item_index: usize,
1964        activate_pane: bool,
1965        focus_on_pane_if_closed: Entity<Pane>,
1966        window: &mut Window,
1967        cx: &mut Context<Self>,
1968    ) {
1969        self._remove_item(
1970            item_index,
1971            activate_pane,
1972            true,
1973            Some(focus_on_pane_if_closed),
1974            window,
1975            cx,
1976        )
1977    }
1978
1979    fn _remove_item(
1980        &mut self,
1981        item_index: usize,
1982        activate_pane: bool,
1983        close_pane_if_empty: bool,
1984        focus_on_pane_if_closed: Option<Entity<Pane>>,
1985        window: &mut Window,
1986        cx: &mut Context<Self>,
1987    ) {
1988        let activate_on_close = &ItemSettings::get_global(cx).activate_on_close;
1989        self.activation_history
1990            .retain(|entry| entry.entity_id != self.items[item_index].item_id());
1991
1992        if self.is_tab_pinned(item_index) {
1993            self.pinned_tab_count -= 1;
1994        }
1995        if item_index == self.active_item_index {
1996            let left_neighbour_index = || item_index.min(self.items.len()).saturating_sub(1);
1997            let index_to_activate = match activate_on_close {
1998                ActivateOnClose::History => self
1999                    .activation_history
2000                    .pop()
2001                    .and_then(|last_activated_item| {
2002                        self.items.iter().enumerate().find_map(|(index, item)| {
2003                            (item.item_id() == last_activated_item.entity_id).then_some(index)
2004                        })
2005                    })
2006                    // We didn't have a valid activation history entry, so fallback
2007                    // to activating the item to the left
2008                    .unwrap_or_else(left_neighbour_index),
2009                ActivateOnClose::Neighbour => {
2010                    self.activation_history.pop();
2011                    if item_index + 1 < self.items.len() {
2012                        item_index + 1
2013                    } else {
2014                        item_index.saturating_sub(1)
2015                    }
2016                }
2017                ActivateOnClose::LeftNeighbour => {
2018                    self.activation_history.pop();
2019                    left_neighbour_index()
2020                }
2021            };
2022
2023            let should_activate = activate_pane || self.has_focus(window, cx);
2024            if self.items.len() == 1 && should_activate {
2025                self.focus_handle.focus(window, cx);
2026            } else {
2027                self.activate_item(
2028                    index_to_activate,
2029                    should_activate,
2030                    should_activate,
2031                    window,
2032                    cx,
2033                );
2034            }
2035        }
2036
2037        let item = self.items.remove(item_index);
2038
2039        cx.emit(Event::RemovedItem { item: item.clone() });
2040        if self.items.is_empty() {
2041            item.deactivated(window, cx);
2042            if close_pane_if_empty {
2043                self.update_toolbar(window, cx);
2044                cx.emit(Event::Remove {
2045                    focus_on_pane: focus_on_pane_if_closed,
2046                });
2047            }
2048        }
2049
2050        if item_index < self.active_item_index {
2051            self.active_item_index -= 1;
2052        }
2053
2054        let mode = self.nav_history.mode();
2055        self.nav_history.set_mode(NavigationMode::ClosingItem);
2056        item.deactivated(window, cx);
2057        item.on_removed(cx);
2058        self.nav_history.set_mode(mode);
2059
2060        self.unpreview_item_if_preview(item.item_id());
2061
2062        if let Some(path) = item.project_path(cx) {
2063            let abs_path = self
2064                .nav_history
2065                .0
2066                .lock()
2067                .paths_by_item
2068                .get(&item.item_id())
2069                .and_then(|(_, abs_path)| abs_path.clone());
2070
2071            self.nav_history
2072                .0
2073                .lock()
2074                .paths_by_item
2075                .insert(item.item_id(), (path, abs_path));
2076        } else {
2077            self.nav_history
2078                .0
2079                .lock()
2080                .paths_by_item
2081                .remove(&item.item_id());
2082        }
2083
2084        if self.zoom_out_on_close && self.items.is_empty() && close_pane_if_empty && self.zoomed {
2085            cx.emit(Event::ZoomOut);
2086        }
2087
2088        cx.notify();
2089    }
2090
2091    pub async fn save_item(
2092        project: Entity<Project>,
2093        pane: &WeakEntity<Pane>,
2094        item: &dyn ItemHandle,
2095        save_intent: SaveIntent,
2096        cx: &mut AsyncWindowContext,
2097    ) -> Result<bool> {
2098        const CONFLICT_MESSAGE: &str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
2099
2100        const DELETED_MESSAGE: &str = "This file has been deleted on disk since you started editing it. Do you want to recreate it?";
2101
2102        let path_style = project.read_with(cx, |project, cx| project.path_style(cx))?;
2103        if save_intent == SaveIntent::Skip {
2104            return Ok(true);
2105        };
2106        let Some(item_ix) = pane
2107            .read_with(cx, |pane, _| pane.index_for_item(item))
2108            .ok()
2109            .flatten()
2110        else {
2111            return Ok(true);
2112        };
2113
2114        let (
2115            mut has_conflict,
2116            mut is_dirty,
2117            mut can_save,
2118            can_save_as,
2119            is_singleton,
2120            has_deleted_file,
2121        ) = cx.update(|_window, cx| {
2122            (
2123                item.has_conflict(cx),
2124                item.is_dirty(cx),
2125                item.can_save(cx),
2126                item.can_save_as(cx),
2127                item.buffer_kind(cx) == ItemBufferKind::Singleton,
2128                item.has_deleted_file(cx),
2129            )
2130        })?;
2131
2132        // when saving a single buffer, we ignore whether or not it's dirty.
2133        if save_intent == SaveIntent::Save || save_intent == SaveIntent::SaveWithoutFormat {
2134            is_dirty = true;
2135        }
2136
2137        if save_intent == SaveIntent::SaveAs {
2138            is_dirty = true;
2139            has_conflict = false;
2140            can_save = false;
2141        }
2142
2143        if save_intent == SaveIntent::Overwrite {
2144            has_conflict = false;
2145        }
2146
2147        let should_format = save_intent != SaveIntent::SaveWithoutFormat;
2148
2149        if has_conflict && can_save {
2150            if has_deleted_file && is_singleton {
2151                let answer = pane.update_in(cx, |pane, window, cx| {
2152                    pane.activate_item(item_ix, true, true, window, cx);
2153                    window.prompt(
2154                        PromptLevel::Warning,
2155                        DELETED_MESSAGE,
2156                        None,
2157                        &["Save", "Close", "Cancel"],
2158                        cx,
2159                    )
2160                })?;
2161                match answer.await {
2162                    Ok(0) => {
2163                        pane.update_in(cx, |_, window, cx| {
2164                            item.save(
2165                                SaveOptions {
2166                                    format: should_format,
2167                                    autosave: false,
2168                                },
2169                                project,
2170                                window,
2171                                cx,
2172                            )
2173                        })?
2174                        .await?
2175                    }
2176                    Ok(1) => {
2177                        pane.update_in(cx, |pane, window, cx| {
2178                            pane.remove_item(item.item_id(), false, true, window, cx)
2179                        })?;
2180                    }
2181                    _ => return Ok(false),
2182                }
2183                return Ok(true);
2184            } else {
2185                let answer = pane.update_in(cx, |pane, window, cx| {
2186                    pane.activate_item(item_ix, true, true, window, cx);
2187                    window.prompt(
2188                        PromptLevel::Warning,
2189                        CONFLICT_MESSAGE,
2190                        None,
2191                        &["Overwrite", "Discard", "Cancel"],
2192                        cx,
2193                    )
2194                })?;
2195                match answer.await {
2196                    Ok(0) => {
2197                        pane.update_in(cx, |_, window, cx| {
2198                            item.save(
2199                                SaveOptions {
2200                                    format: should_format,
2201                                    autosave: false,
2202                                },
2203                                project,
2204                                window,
2205                                cx,
2206                            )
2207                        })?
2208                        .await?
2209                    }
2210                    Ok(1) => {
2211                        pane.update_in(cx, |_, window, cx| item.reload(project, window, cx))?
2212                            .await?
2213                    }
2214                    _ => return Ok(false),
2215                }
2216            }
2217        } else if is_dirty && (can_save || can_save_as) {
2218            if save_intent == SaveIntent::Close {
2219                let will_autosave = cx.update(|_window, cx| {
2220                    item.can_autosave(cx)
2221                        && item.workspace_settings(cx).autosave.should_save_on_close()
2222                })?;
2223                if !will_autosave {
2224                    let item_id = item.item_id();
2225                    let answer_task = pane.update_in(cx, |pane, window, cx| {
2226                        if pane.save_modals_spawned.insert(item_id) {
2227                            pane.activate_item(item_ix, true, true, window, cx);
2228                            let prompt = dirty_message_for(item.project_path(cx), path_style);
2229                            Some(window.prompt(
2230                                PromptLevel::Warning,
2231                                &prompt,
2232                                None,
2233                                &["Save", "Don't Save", "Cancel"],
2234                                cx,
2235                            ))
2236                        } else {
2237                            None
2238                        }
2239                    })?;
2240                    if let Some(answer_task) = answer_task {
2241                        let answer = answer_task.await;
2242                        pane.update(cx, |pane, _| {
2243                            if !pane.save_modals_spawned.remove(&item_id) {
2244                                debug_panic!(
2245                                    "save modal was not present in spawned modals after awaiting for its answer"
2246                                )
2247                            }
2248                        })?;
2249                        match answer {
2250                            Ok(0) => {}
2251                            Ok(1) => {
2252                                // Don't save this file
2253                                pane.update_in(cx, |pane, _, cx| {
2254                                    if pane.is_tab_pinned(item_ix) && !item.can_save(cx) {
2255                                        pane.pinned_tab_count -= 1;
2256                                    }
2257                                })
2258                                .log_err();
2259                                return Ok(true);
2260                            }
2261                            _ => return Ok(false), // Cancel
2262                        }
2263                    } else {
2264                        return Ok(false);
2265                    }
2266                }
2267            }
2268
2269            if can_save {
2270                pane.update_in(cx, |pane, window, cx| {
2271                    pane.unpreview_item_if_preview(item.item_id());
2272                    item.save(
2273                        SaveOptions {
2274                            format: should_format,
2275                            autosave: false,
2276                        },
2277                        project,
2278                        window,
2279                        cx,
2280                    )
2281                })?
2282                .await?;
2283            } else if can_save_as && is_singleton {
2284                let suggested_name =
2285                    cx.update(|_window, cx| item.suggested_filename(cx).to_string())?;
2286                let new_path = pane.update_in(cx, |pane, window, cx| {
2287                    pane.activate_item(item_ix, true, true, window, cx);
2288                    pane.workspace.update(cx, |workspace, cx| {
2289                        let lister = if workspace.project().read(cx).is_local() {
2290                            DirectoryLister::Local(
2291                                workspace.project().clone(),
2292                                workspace.app_state().fs.clone(),
2293                            )
2294                        } else {
2295                            DirectoryLister::Project(workspace.project().clone())
2296                        };
2297                        workspace.prompt_for_new_path(lister, Some(suggested_name), window, cx)
2298                    })
2299                })??;
2300                let Some(new_path) = new_path.await.ok().flatten().into_iter().flatten().next()
2301                else {
2302                    return Ok(false);
2303                };
2304
2305                let project_path = pane
2306                    .update(cx, |pane, cx| {
2307                        pane.project
2308                            .update(cx, |project, cx| {
2309                                project.find_or_create_worktree(new_path, true, cx)
2310                            })
2311                            .ok()
2312                    })
2313                    .ok()
2314                    .flatten();
2315                let save_task = if let Some(project_path) = project_path {
2316                    let (worktree, path) = project_path.await?;
2317                    let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id())?;
2318                    let new_path = ProjectPath { worktree_id, path };
2319
2320                    pane.update_in(cx, |pane, window, cx| {
2321                        if let Some(item) = pane.item_for_path(new_path.clone(), cx) {
2322                            pane.remove_item(item.item_id(), false, false, window, cx);
2323                        }
2324
2325                        item.save_as(project, new_path, window, cx)
2326                    })?
2327                } else {
2328                    return Ok(false);
2329                };
2330
2331                save_task.await?;
2332                return Ok(true);
2333            }
2334        }
2335
2336        pane.update(cx, |_, cx| {
2337            cx.emit(Event::UserSavedItem {
2338                item: item.downgrade_item(),
2339                save_intent,
2340            });
2341            true
2342        })
2343    }
2344
2345    pub fn autosave_item(
2346        item: &dyn ItemHandle,
2347        project: Entity<Project>,
2348        window: &mut Window,
2349        cx: &mut App,
2350    ) -> Task<Result<()>> {
2351        let format = !matches!(
2352            item.workspace_settings(cx).autosave,
2353            AutosaveSetting::AfterDelay { .. }
2354        );
2355        if item.can_autosave(cx) {
2356            item.save(
2357                SaveOptions {
2358                    format,
2359                    autosave: true,
2360                },
2361                project,
2362                window,
2363                cx,
2364            )
2365        } else {
2366            Task::ready(Ok(()))
2367        }
2368    }
2369
2370    pub fn focus_active_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2371        if let Some(active_item) = self.active_item() {
2372            let focus_handle = active_item.item_focus_handle(cx);
2373            window.focus(&focus_handle, cx);
2374        }
2375    }
2376
2377    pub fn split(
2378        &mut self,
2379        direction: SplitDirection,
2380        mode: SplitMode,
2381        window: &mut Window,
2382        cx: &mut Context<Self>,
2383    ) {
2384        if self.items.len() <= 1 && mode == SplitMode::MovePane {
2385            // MovePane with only one pane present behaves like a SplitEmpty in the opposite direction
2386            let active_item = self.active_item();
2387            cx.emit(Event::Split {
2388                direction: direction.opposite(),
2389                mode: SplitMode::EmptyPane,
2390            });
2391            // ensure that we focus the moved pane
2392            // in this case we know that the window is the same as the active_item
2393            if let Some(active_item) = active_item {
2394                cx.defer_in(window, move |_, window, cx| {
2395                    let focus_handle = active_item.item_focus_handle(cx);
2396                    window.focus(&focus_handle, cx);
2397                });
2398            }
2399        } else {
2400            cx.emit(Event::Split { direction, mode });
2401        }
2402    }
2403
2404    pub fn toolbar(&self) -> &Entity<Toolbar> {
2405        &self.toolbar
2406    }
2407
2408    pub fn handle_deleted_project_item(
2409        &mut self,
2410        entry_id: ProjectEntryId,
2411        window: &mut Window,
2412        cx: &mut Context<Pane>,
2413    ) -> Option<()> {
2414        let item_id = self.items().find_map(|item| {
2415            if item.buffer_kind(cx) == ItemBufferKind::Singleton
2416                && item.project_entry_ids(cx).as_slice() == [entry_id]
2417            {
2418                Some(item.item_id())
2419            } else {
2420                None
2421            }
2422        })?;
2423
2424        self.remove_item(item_id, false, true, window, cx);
2425        self.nav_history.remove_item(item_id);
2426
2427        Some(())
2428    }
2429
2430    fn update_toolbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2431        let active_item = self
2432            .items
2433            .get(self.active_item_index)
2434            .map(|item| item.as_ref());
2435        self.toolbar.update(cx, |toolbar, cx| {
2436            toolbar.set_active_item(active_item, window, cx);
2437        });
2438    }
2439
2440    fn update_status_bar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2441        let workspace = self.workspace.clone();
2442        let pane = cx.entity();
2443
2444        window.defer(cx, move |window, cx| {
2445            let Ok(status_bar) =
2446                workspace.read_with(cx, |workspace, _| workspace.status_bar.clone())
2447            else {
2448                return;
2449            };
2450
2451            status_bar.update(cx, move |status_bar, cx| {
2452                status_bar.set_active_pane(&pane, window, cx);
2453            });
2454        });
2455    }
2456
2457    fn entry_abs_path(&self, entry: ProjectEntryId, cx: &App) -> Option<PathBuf> {
2458        let worktree = self
2459            .workspace
2460            .upgrade()?
2461            .read(cx)
2462            .project()
2463            .read(cx)
2464            .worktree_for_entry(entry, cx)?
2465            .read(cx);
2466        let entry = worktree.entry_for_id(entry)?;
2467        Some(match &entry.canonical_path {
2468            Some(canonical_path) => canonical_path.to_path_buf(),
2469            None => worktree.absolutize(&entry.path),
2470        })
2471    }
2472
2473    pub fn icon_color(selected: bool) -> Color {
2474        if selected {
2475            Color::Default
2476        } else {
2477            Color::Muted
2478        }
2479    }
2480
2481    fn toggle_pin_tab(&mut self, _: &TogglePinTab, window: &mut Window, cx: &mut Context<Self>) {
2482        if self.items.is_empty() {
2483            return;
2484        }
2485        let active_tab_ix = self.active_item_index();
2486        if self.is_tab_pinned(active_tab_ix) {
2487            self.unpin_tab_at(active_tab_ix, window, cx);
2488        } else {
2489            self.pin_tab_at(active_tab_ix, window, cx);
2490        }
2491    }
2492
2493    fn unpin_all_tabs(&mut self, _: &UnpinAllTabs, window: &mut Window, cx: &mut Context<Self>) {
2494        if self.items.is_empty() {
2495            return;
2496        }
2497
2498        let pinned_item_ids = self.pinned_item_ids().into_iter().rev();
2499
2500        for pinned_item_id in pinned_item_ids {
2501            if let Some(ix) = self.index_for_item_id(pinned_item_id) {
2502                self.unpin_tab_at(ix, window, cx);
2503            }
2504        }
2505    }
2506
2507    fn pin_tab_at(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
2508        self.change_tab_pin_state(ix, PinOperation::Pin, window, cx);
2509    }
2510
2511    fn unpin_tab_at(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
2512        self.change_tab_pin_state(ix, PinOperation::Unpin, window, cx);
2513    }
2514
2515    fn change_tab_pin_state(
2516        &mut self,
2517        ix: usize,
2518        operation: PinOperation,
2519        window: &mut Window,
2520        cx: &mut Context<Self>,
2521    ) {
2522        maybe!({
2523            let pane = cx.entity();
2524
2525            let destination_index = match operation {
2526                PinOperation::Pin => self.pinned_tab_count.min(ix),
2527                PinOperation::Unpin => self.pinned_tab_count.checked_sub(1)?,
2528            };
2529
2530            let id = self.item_for_index(ix)?.item_id();
2531            let should_activate = ix == self.active_item_index;
2532
2533            if matches!(operation, PinOperation::Pin) {
2534                self.unpreview_item_if_preview(id);
2535            }
2536
2537            match operation {
2538                PinOperation::Pin => self.pinned_tab_count += 1,
2539                PinOperation::Unpin => self.pinned_tab_count -= 1,
2540            }
2541
2542            if ix == destination_index {
2543                cx.notify();
2544            } else {
2545                self.workspace
2546                    .update(cx, |_, cx| {
2547                        cx.defer_in(window, move |_, window, cx| {
2548                            move_item(
2549                                &pane,
2550                                &pane,
2551                                id,
2552                                destination_index,
2553                                should_activate,
2554                                window,
2555                                cx,
2556                            );
2557                        });
2558                    })
2559                    .ok()?;
2560            }
2561
2562            let event = match operation {
2563                PinOperation::Pin => Event::ItemPinned,
2564                PinOperation::Unpin => Event::ItemUnpinned,
2565            };
2566
2567            cx.emit(event);
2568
2569            Some(())
2570        });
2571    }
2572
2573    fn is_tab_pinned(&self, ix: usize) -> bool {
2574        self.pinned_tab_count > ix
2575    }
2576
2577    fn has_unpinned_tabs(&self) -> bool {
2578        self.pinned_tab_count < self.items.len()
2579    }
2580
2581    fn activate_unpinned_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2582        if self.items.is_empty() {
2583            return;
2584        }
2585        let Some(index) = self
2586            .items()
2587            .enumerate()
2588            .find_map(|(index, _item)| (!self.is_tab_pinned(index)).then_some(index))
2589        else {
2590            return;
2591        };
2592        self.activate_item(index, true, true, window, cx);
2593    }
2594
2595    fn render_tab(
2596        &self,
2597        ix: usize,
2598        item: &dyn ItemHandle,
2599        detail: usize,
2600        focus_handle: &FocusHandle,
2601        window: &mut Window,
2602        cx: &mut Context<Pane>,
2603    ) -> impl IntoElement + use<> {
2604        let is_active = ix == self.active_item_index;
2605        let is_preview = self
2606            .preview_item_id
2607            .map(|id| id == item.item_id())
2608            .unwrap_or(false);
2609
2610        let label = item.tab_content(
2611            TabContentParams {
2612                detail: Some(detail),
2613                selected: is_active,
2614                preview: is_preview,
2615                deemphasized: !self.has_focus(window, cx),
2616            },
2617            window,
2618            cx,
2619        );
2620
2621        let item_diagnostic = item
2622            .project_path(cx)
2623            .map_or(None, |project_path| self.diagnostics.get(&project_path));
2624
2625        let decorated_icon = item_diagnostic.map_or(None, |diagnostic| {
2626            let icon = match item.tab_icon(window, cx) {
2627                Some(icon) => icon,
2628                None => return None,
2629            };
2630
2631            let knockout_item_color = if is_active {
2632                cx.theme().colors().tab_active_background
2633            } else {
2634                cx.theme().colors().tab_bar_background
2635            };
2636
2637            let (icon_decoration, icon_color) = if matches!(diagnostic, &DiagnosticSeverity::ERROR)
2638            {
2639                (IconDecorationKind::X, Color::Error)
2640            } else {
2641                (IconDecorationKind::Triangle, Color::Warning)
2642            };
2643
2644            Some(DecoratedIcon::new(
2645                icon.size(IconSize::Small).color(Color::Muted),
2646                Some(
2647                    IconDecoration::new(icon_decoration, knockout_item_color, cx)
2648                        .color(icon_color.color(cx))
2649                        .position(Point {
2650                            x: px(-2.),
2651                            y: px(-2.),
2652                        }),
2653                ),
2654            ))
2655        });
2656
2657        let icon = if decorated_icon.is_none() {
2658            match item_diagnostic {
2659                Some(&DiagnosticSeverity::ERROR) => None,
2660                Some(&DiagnosticSeverity::WARNING) => None,
2661                _ => item
2662                    .tab_icon(window, cx)
2663                    .map(|icon| icon.color(Color::Muted)),
2664            }
2665            .map(|icon| icon.size(IconSize::Small))
2666        } else {
2667            None
2668        };
2669
2670        let settings = ItemSettings::get_global(cx);
2671        let close_side = &settings.close_position;
2672        let show_close_button = &settings.show_close_button;
2673        let indicator = render_item_indicator(item.boxed_clone(), cx);
2674        let tab_tooltip_content = item.tab_tooltip_content(cx);
2675        let item_id = item.item_id();
2676        let is_first_item = ix == 0;
2677        let is_last_item = ix == self.items.len() - 1;
2678        let is_pinned = self.is_tab_pinned(ix);
2679        let position_relative_to_active_item = ix.cmp(&self.active_item_index);
2680
2681        let read_only_toggle = |toggleable: bool| {
2682            IconButton::new("toggle_read_only", IconName::FileLock)
2683                .size(ButtonSize::None)
2684                .shape(IconButtonShape::Square)
2685                .icon_color(Color::Muted)
2686                .icon_size(IconSize::Small)
2687                .disabled(!toggleable)
2688                .tooltip(move |_, cx| {
2689                    Tooltip::with_meta("Unlock File", None, "This will make this file editable", cx)
2690                })
2691                .on_click(cx.listener(move |pane, _, window, cx| {
2692                    if let Some(item) = pane.item_for_index(ix) {
2693                        item.toggle_read_only(window, cx);
2694                    }
2695                }))
2696        };
2697
2698        let has_file_icon = icon.is_some() | decorated_icon.is_some();
2699
2700        let capability = item.capability(cx);
2701        let tab = Tab::new(ix)
2702            .position(if is_first_item {
2703                TabPosition::First
2704            } else if is_last_item {
2705                TabPosition::Last
2706            } else {
2707                TabPosition::Middle(position_relative_to_active_item)
2708            })
2709            .close_side(match close_side {
2710                ClosePosition::Left => ui::TabCloseSide::Start,
2711                ClosePosition::Right => ui::TabCloseSide::End,
2712            })
2713            .toggle_state(is_active)
2714            .on_click(cx.listener(move |pane: &mut Self, _, window, cx| {
2715                pane.activate_item(ix, true, true, window, cx)
2716            }))
2717            // TODO: This should be a click listener with the middle mouse button instead of a mouse down listener.
2718            .on_mouse_down(
2719                MouseButton::Middle,
2720                cx.listener(move |pane, _event, window, cx| {
2721                    pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2722                        .detach_and_log_err(cx);
2723                }),
2724            )
2725            .on_mouse_down(
2726                MouseButton::Left,
2727                cx.listener(move |pane, event: &MouseDownEvent, _, _| {
2728                    if event.click_count > 1 {
2729                        pane.unpreview_item_if_preview(item_id);
2730                    }
2731                }),
2732            )
2733            .on_drag(
2734                DraggedTab {
2735                    item: item.boxed_clone(),
2736                    pane: cx.entity(),
2737                    detail,
2738                    is_active,
2739                    ix,
2740                },
2741                |tab, _, _, cx| cx.new(|_| tab.clone()),
2742            )
2743            .drag_over::<DraggedTab>(move |tab, dragged_tab: &DraggedTab, _, cx| {
2744                let mut styled_tab = tab
2745                    .bg(cx.theme().colors().drop_target_background)
2746                    .border_color(cx.theme().colors().drop_target_border)
2747                    .border_0();
2748
2749                if ix < dragged_tab.ix {
2750                    styled_tab = styled_tab.border_l_2();
2751                } else if ix > dragged_tab.ix {
2752                    styled_tab = styled_tab.border_r_2();
2753                }
2754
2755                styled_tab
2756            })
2757            .drag_over::<DraggedSelection>(|tab, _, _, cx| {
2758                tab.bg(cx.theme().colors().drop_target_background)
2759            })
2760            .when_some(self.can_drop_predicate.clone(), |this, p| {
2761                this.can_drop(move |a, window, cx| p(a, window, cx))
2762            })
2763            .on_drop(
2764                cx.listener(move |this, dragged_tab: &DraggedTab, window, cx| {
2765                    this.drag_split_direction = None;
2766                    this.handle_tab_drop(dragged_tab, ix, window, cx)
2767                }),
2768            )
2769            .on_drop(
2770                cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2771                    this.drag_split_direction = None;
2772                    this.handle_dragged_selection_drop(selection, Some(ix), window, cx)
2773                }),
2774            )
2775            .on_drop(cx.listener(move |this, paths, window, cx| {
2776                this.drag_split_direction = None;
2777                this.handle_external_paths_drop(paths, window, cx)
2778            }))
2779            .start_slot::<Indicator>(indicator)
2780            .map(|this| {
2781                let end_slot_action: &'static dyn Action;
2782                let end_slot_tooltip_text: &'static str;
2783                let end_slot = if is_pinned {
2784                    end_slot_action = &TogglePinTab;
2785                    end_slot_tooltip_text = "Unpin Tab";
2786                    IconButton::new("unpin tab", IconName::Pin)
2787                        .shape(IconButtonShape::Square)
2788                        .icon_color(Color::Muted)
2789                        .size(ButtonSize::None)
2790                        .icon_size(IconSize::Small)
2791                        .on_click(cx.listener(move |pane, _, window, cx| {
2792                            pane.unpin_tab_at(ix, window, cx);
2793                        }))
2794                } else {
2795                    end_slot_action = &CloseActiveItem {
2796                        save_intent: None,
2797                        close_pinned: false,
2798                    };
2799                    end_slot_tooltip_text = "Close Tab";
2800                    match show_close_button {
2801                        ShowCloseButton::Always => IconButton::new("close tab", IconName::Close),
2802                        ShowCloseButton::Hover => {
2803                            IconButton::new("close tab", IconName::Close).visible_on_hover("")
2804                        }
2805                        ShowCloseButton::Hidden => return this,
2806                    }
2807                    .shape(IconButtonShape::Square)
2808                    .icon_color(Color::Muted)
2809                    .size(ButtonSize::None)
2810                    .icon_size(IconSize::Small)
2811                    .on_click(cx.listener(move |pane, _, window, cx| {
2812                        pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2813                            .detach_and_log_err(cx);
2814                    }))
2815                }
2816                .map(|this| {
2817                    if is_active {
2818                        let focus_handle = focus_handle.clone();
2819                        this.tooltip(move |window, cx| {
2820                            Tooltip::for_action_in(
2821                                end_slot_tooltip_text,
2822                                end_slot_action,
2823                                &window.focused(cx).unwrap_or_else(|| focus_handle.clone()),
2824                                cx,
2825                            )
2826                        })
2827                    } else {
2828                        this.tooltip(Tooltip::text(end_slot_tooltip_text))
2829                    }
2830                });
2831                this.end_slot(end_slot)
2832            })
2833            .child(
2834                h_flex()
2835                    .id(("pane-tab-content", ix))
2836                    .gap_1()
2837                    .children(if let Some(decorated_icon) = decorated_icon {
2838                        Some(decorated_icon.into_any_element())
2839                    } else if let Some(icon) = icon {
2840                        Some(icon.into_any_element())
2841                    } else if !capability.editable() {
2842                        Some(read_only_toggle(capability == Capability::Read).into_any_element())
2843                    } else {
2844                        None
2845                    })
2846                    .child(label)
2847                    .map(|this| match tab_tooltip_content {
2848                        Some(TabTooltipContent::Text(text)) => {
2849                            if capability.editable() {
2850                                this.tooltip(Tooltip::text(text))
2851                            } else {
2852                                this.tooltip(move |_, cx| {
2853                                    let text = text.clone();
2854                                    Tooltip::with_meta(text, None, "Read-Only File", cx)
2855                                })
2856                            }
2857                        }
2858                        Some(TabTooltipContent::Custom(element_fn)) => {
2859                            this.tooltip(move |window, cx| element_fn(window, cx))
2860                        }
2861                        None => this,
2862                    })
2863                    .when(capability == Capability::Read && has_file_icon, |this| {
2864                        this.child(read_only_toggle(true))
2865                    }),
2866            );
2867
2868        let single_entry_to_resolve = (self.items[ix].buffer_kind(cx) == ItemBufferKind::Singleton)
2869            .then(|| self.items[ix].project_entry_ids(cx).get(0).copied())
2870            .flatten();
2871
2872        let total_items = self.items.len();
2873        let has_multibuffer_items = self
2874            .items
2875            .iter()
2876            .any(|item| item.buffer_kind(cx) == ItemBufferKind::Multibuffer);
2877        let has_items_to_left = ix > 0;
2878        let has_items_to_right = ix < total_items - 1;
2879        let has_clean_items = self.items.iter().any(|item| !item.is_dirty(cx));
2880        let is_pinned = self.is_tab_pinned(ix);
2881
2882        let pane = cx.entity().downgrade();
2883        let menu_context = item.item_focus_handle(cx);
2884
2885        right_click_menu(ix)
2886            .trigger(|_, _, _| tab)
2887            .menu(move |window, cx| {
2888                let pane = pane.clone();
2889                let menu_context = menu_context.clone();
2890                ContextMenu::build(window, cx, move |mut menu, window, cx| {
2891                    let close_active_item_action = CloseActiveItem {
2892                        save_intent: None,
2893                        close_pinned: true,
2894                    };
2895                    let close_inactive_items_action = CloseOtherItems {
2896                        save_intent: None,
2897                        close_pinned: false,
2898                    };
2899                    let close_multibuffers_action = CloseMultibufferItems {
2900                        save_intent: None,
2901                        close_pinned: false,
2902                    };
2903                    let close_items_to_the_left_action = CloseItemsToTheLeft {
2904                        close_pinned: false,
2905                    };
2906                    let close_items_to_the_right_action = CloseItemsToTheRight {
2907                        close_pinned: false,
2908                    };
2909                    let close_clean_items_action = CloseCleanItems {
2910                        close_pinned: false,
2911                    };
2912                    let close_all_items_action = CloseAllItems {
2913                        save_intent: None,
2914                        close_pinned: false,
2915                    };
2916                    if let Some(pane) = pane.upgrade() {
2917                        menu = menu
2918                            .entry(
2919                                "Close",
2920                                Some(Box::new(close_active_item_action)),
2921                                window.handler_for(&pane, move |pane, window, cx| {
2922                                    pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2923                                        .detach_and_log_err(cx);
2924                                }),
2925                            )
2926                            .item(ContextMenuItem::Entry(
2927                                ContextMenuEntry::new("Close Others")
2928                                    .action(Box::new(close_inactive_items_action.clone()))
2929                                    .disabled(total_items == 1)
2930                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2931                                        pane.close_other_items(
2932                                            &close_inactive_items_action,
2933                                            Some(item_id),
2934                                            window,
2935                                            cx,
2936                                        )
2937                                        .detach_and_log_err(cx);
2938                                    })),
2939                            ))
2940                            // We make this optional, instead of using disabled as to not overwhelm the context menu unnecessarily
2941                            .extend(has_multibuffer_items.then(|| {
2942                                ContextMenuItem::Entry(
2943                                    ContextMenuEntry::new("Close Multibuffers")
2944                                        .action(Box::new(close_multibuffers_action.clone()))
2945                                        .handler(window.handler_for(
2946                                            &pane,
2947                                            move |pane, window, cx| {
2948                                                pane.close_multibuffer_items(
2949                                                    &close_multibuffers_action,
2950                                                    window,
2951                                                    cx,
2952                                                )
2953                                                .detach_and_log_err(cx);
2954                                            },
2955                                        )),
2956                                )
2957                            }))
2958                            .separator()
2959                            .item(ContextMenuItem::Entry(
2960                                ContextMenuEntry::new("Close Left")
2961                                    .action(Box::new(close_items_to_the_left_action.clone()))
2962                                    .disabled(!has_items_to_left)
2963                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2964                                        pane.close_items_to_the_left_by_id(
2965                                            Some(item_id),
2966                                            &close_items_to_the_left_action,
2967                                            window,
2968                                            cx,
2969                                        )
2970                                        .detach_and_log_err(cx);
2971                                    })),
2972                            ))
2973                            .item(ContextMenuItem::Entry(
2974                                ContextMenuEntry::new("Close Right")
2975                                    .action(Box::new(close_items_to_the_right_action.clone()))
2976                                    .disabled(!has_items_to_right)
2977                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2978                                        pane.close_items_to_the_right_by_id(
2979                                            Some(item_id),
2980                                            &close_items_to_the_right_action,
2981                                            window,
2982                                            cx,
2983                                        )
2984                                        .detach_and_log_err(cx);
2985                                    })),
2986                            ))
2987                            .separator()
2988                            .item(ContextMenuItem::Entry(
2989                                ContextMenuEntry::new("Close Clean")
2990                                    .action(Box::new(close_clean_items_action.clone()))
2991                                    .disabled(!has_clean_items)
2992                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2993                                        pane.close_clean_items(
2994                                            &close_clean_items_action,
2995                                            window,
2996                                            cx,
2997                                        )
2998                                        .detach_and_log_err(cx)
2999                                    })),
3000                            ))
3001                            .entry(
3002                                "Close All",
3003                                Some(Box::new(close_all_items_action.clone())),
3004                                window.handler_for(&pane, move |pane, window, cx| {
3005                                    pane.close_all_items(&close_all_items_action, window, cx)
3006                                        .detach_and_log_err(cx)
3007                                }),
3008                            );
3009
3010                        let pin_tab_entries = |menu: ContextMenu| {
3011                            menu.separator().map(|this| {
3012                                if is_pinned {
3013                                    this.entry(
3014                                        "Unpin Tab",
3015                                        Some(TogglePinTab.boxed_clone()),
3016                                        window.handler_for(&pane, move |pane, window, cx| {
3017                                            pane.unpin_tab_at(ix, window, cx);
3018                                        }),
3019                                    )
3020                                } else {
3021                                    this.entry(
3022                                        "Pin Tab",
3023                                        Some(TogglePinTab.boxed_clone()),
3024                                        window.handler_for(&pane, move |pane, window, cx| {
3025                                            pane.pin_tab_at(ix, window, cx);
3026                                        }),
3027                                    )
3028                                }
3029                            })
3030                        };
3031
3032                        if capability != Capability::ReadOnly {
3033                            let read_only_label = if capability.editable() {
3034                                "Make File Read-Only"
3035                            } else {
3036                                "Make File Editable"
3037                            };
3038                            menu = menu.separator().entry(
3039                                read_only_label,
3040                                None,
3041                                window.handler_for(&pane, move |pane, window, cx| {
3042                                    if let Some(item) = pane.item_for_index(ix) {
3043                                        item.toggle_read_only(window, cx);
3044                                    }
3045                                }),
3046                            );
3047                        }
3048
3049                        if let Some(entry) = single_entry_to_resolve {
3050                            let project_path = pane
3051                                .read(cx)
3052                                .item_for_entry(entry, cx)
3053                                .and_then(|item| item.project_path(cx));
3054                            let worktree = project_path.as_ref().and_then(|project_path| {
3055                                pane.read(cx)
3056                                    .project
3057                                    .upgrade()?
3058                                    .read(cx)
3059                                    .worktree_for_id(project_path.worktree_id, cx)
3060                            });
3061                            let has_relative_path = worktree.as_ref().is_some_and(|worktree| {
3062                                worktree
3063                                    .read(cx)
3064                                    .root_entry()
3065                                    .is_some_and(|entry| entry.is_dir())
3066                            });
3067
3068                            let entry_abs_path = pane.read(cx).entry_abs_path(entry, cx);
3069                            let parent_abs_path = entry_abs_path
3070                                .as_deref()
3071                                .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
3072                            let relative_path = project_path
3073                                .map(|project_path| project_path.path)
3074                                .filter(|_| has_relative_path);
3075
3076                            let visible_in_project_panel = relative_path.is_some()
3077                                && worktree.is_some_and(|worktree| worktree.read(cx).is_visible());
3078
3079                            let entry_id = entry.to_proto();
3080
3081                            menu = menu
3082                                .separator()
3083                                .when_some(entry_abs_path, |menu, abs_path| {
3084                                    menu.entry(
3085                                        "Copy Path",
3086                                        Some(Box::new(zed_actions::workspace::CopyPath)),
3087                                        window.handler_for(&pane, move |_, _, cx| {
3088                                            cx.write_to_clipboard(ClipboardItem::new_string(
3089                                                abs_path.to_string_lossy().into_owned(),
3090                                            ));
3091                                        }),
3092                                    )
3093                                })
3094                                .when_some(relative_path, |menu, relative_path| {
3095                                    menu.entry(
3096                                        "Copy Relative Path",
3097                                        Some(Box::new(zed_actions::workspace::CopyRelativePath)),
3098                                        window.handler_for(&pane, move |this, _, cx| {
3099                                            let Some(project) = this.project.upgrade() else {
3100                                                return;
3101                                            };
3102                                            let path_style = project
3103                                                .update(cx, |project, cx| project.path_style(cx));
3104                                            cx.write_to_clipboard(ClipboardItem::new_string(
3105                                                relative_path.display(path_style).to_string(),
3106                                            ));
3107                                        }),
3108                                    )
3109                                })
3110                                .map(pin_tab_entries)
3111                                .separator()
3112                                .when(visible_in_project_panel, |menu| {
3113                                    menu.entry(
3114                                        "Reveal In Project Panel",
3115                                        Some(Box::new(RevealInProjectPanel::default())),
3116                                        window.handler_for(&pane, move |pane, _, cx| {
3117                                            pane.project
3118                                                .update(cx, |_, cx| {
3119                                                    cx.emit(project::Event::RevealInProjectPanel(
3120                                                        ProjectEntryId::from_proto(entry_id),
3121                                                    ))
3122                                                })
3123                                                .ok();
3124                                        }),
3125                                    )
3126                                })
3127                                .when_some(parent_abs_path, |menu, parent_abs_path| {
3128                                    menu.entry(
3129                                        "Open in Terminal",
3130                                        Some(Box::new(OpenInTerminal)),
3131                                        window.handler_for(&pane, move |_, window, cx| {
3132                                            window.dispatch_action(
3133                                                OpenTerminal {
3134                                                    working_directory: parent_abs_path.clone(),
3135                                                }
3136                                                .boxed_clone(),
3137                                                cx,
3138                                            );
3139                                        }),
3140                                    )
3141                                });
3142                        } else {
3143                            menu = menu.map(pin_tab_entries);
3144                        }
3145                    };
3146
3147                    menu.context(menu_context)
3148                })
3149            })
3150    }
3151
3152    fn render_tab_bar(&mut self, window: &mut Window, cx: &mut Context<Pane>) -> AnyElement {
3153        let Some(workspace) = self.workspace.upgrade() else {
3154            return gpui::Empty.into_any();
3155        };
3156
3157        let focus_handle = self.focus_handle.clone();
3158        let is_pane_focused = self.has_focus(window, cx);
3159
3160        let navigate_backward = IconButton::new("navigate_backward", IconName::ArrowLeft)
3161            .icon_size(IconSize::Small)
3162            .on_click({
3163                let entity = cx.entity();
3164                move |_, window, cx| {
3165                    entity.update(cx, |pane, cx| {
3166                        pane.navigate_backward(&Default::default(), window, cx)
3167                    })
3168                }
3169            })
3170            .disabled(!self.can_navigate_backward())
3171            .tooltip({
3172                let focus_handle = focus_handle.clone();
3173                move |window, cx| {
3174                    Tooltip::for_action_in(
3175                        "Go Back",
3176                        &GoBack,
3177                        &window.focused(cx).unwrap_or_else(|| focus_handle.clone()),
3178                        cx,
3179                    )
3180                }
3181            });
3182
3183        let open_aside_left = {
3184            let workspace = workspace.read(cx);
3185            workspace.utility_pane(UtilityPaneSlot::Left).map(|pane| {
3186                let toggle_icon = pane.toggle_icon(cx);
3187                let workspace_handle = self.workspace.clone();
3188
3189                h_flex()
3190                    .h_full()
3191                    .pr_1p5()
3192                    .border_r_1()
3193                    .border_color(cx.theme().colors().border)
3194                    .child(
3195                        IconButton::new("open_aside_left", toggle_icon)
3196                            .icon_size(IconSize::Small)
3197                            .tooltip(Tooltip::text("Toggle Agent Pane")) // TODO: Probably want to make this generic
3198                            .on_click(move |_, window, cx| {
3199                                workspace_handle
3200                                    .update(cx, |workspace, cx| {
3201                                        workspace.toggle_utility_pane(
3202                                            UtilityPaneSlot::Left,
3203                                            window,
3204                                            cx,
3205                                        )
3206                                    })
3207                                    .ok();
3208                            }),
3209                    )
3210                    .into_any_element()
3211            })
3212        };
3213
3214        let open_aside_right = {
3215            let workspace = workspace.read(cx);
3216            workspace.utility_pane(UtilityPaneSlot::Right).map(|pane| {
3217                let toggle_icon = pane.toggle_icon(cx);
3218                let workspace_handle = self.workspace.clone();
3219
3220                h_flex()
3221                    .h_full()
3222                    .when(is_pane_focused, |this| {
3223                        this.pl(DynamicSpacing::Base04.rems(cx))
3224                            .border_l_1()
3225                            .border_color(cx.theme().colors().border)
3226                    })
3227                    .child(
3228                        IconButton::new("open_aside_right", toggle_icon)
3229                            .icon_size(IconSize::Small)
3230                            .tooltip(Tooltip::text("Toggle Agent Pane")) // TODO: Probably want to make this generic
3231                            .on_click(move |_, window, cx| {
3232                                workspace_handle
3233                                    .update(cx, |workspace, cx| {
3234                                        workspace.toggle_utility_pane(
3235                                            UtilityPaneSlot::Right,
3236                                            window,
3237                                            cx,
3238                                        )
3239                                    })
3240                                    .ok();
3241                            }),
3242                    )
3243                    .into_any_element()
3244            })
3245        };
3246
3247        let navigate_forward = IconButton::new("navigate_forward", IconName::ArrowRight)
3248            .icon_size(IconSize::Small)
3249            .on_click({
3250                let entity = cx.entity();
3251                move |_, window, cx| {
3252                    entity.update(cx, |pane, cx| {
3253                        pane.navigate_forward(&Default::default(), window, cx)
3254                    })
3255                }
3256            })
3257            .disabled(!self.can_navigate_forward())
3258            .tooltip({
3259                let focus_handle = focus_handle.clone();
3260                move |window, cx| {
3261                    Tooltip::for_action_in(
3262                        "Go Forward",
3263                        &GoForward,
3264                        &window.focused(cx).unwrap_or_else(|| focus_handle.clone()),
3265                        cx,
3266                    )
3267                }
3268            });
3269
3270        let mut tab_items = self
3271            .items
3272            .iter()
3273            .enumerate()
3274            .zip(tab_details(&self.items, window, cx))
3275            .map(|((ix, item), detail)| {
3276                self.render_tab(ix, &**item, detail, &focus_handle, window, cx)
3277            })
3278            .collect::<Vec<_>>();
3279        let tab_count = tab_items.len();
3280        if self.is_tab_pinned(tab_count) {
3281            log::warn!(
3282                "Pinned tab count ({}) exceeds actual tab count ({}). \
3283                This should not happen. If possible, add reproduction steps, \
3284                in a comment, to https://github.com/zed-industries/zed/issues/33342",
3285                self.pinned_tab_count,
3286                tab_count
3287            );
3288            self.pinned_tab_count = tab_count;
3289        }
3290        let unpinned_tabs = tab_items.split_off(self.pinned_tab_count);
3291        let pinned_tabs = tab_items;
3292
3293        let render_aside_toggle_left = cx.has_flag::<AgentV2FeatureFlag>()
3294            && self
3295                .is_upper_left
3296                .then(|| {
3297                    self.workspace.upgrade().and_then(|entity| {
3298                        let workspace = entity.read(cx);
3299                        workspace
3300                            .utility_pane(UtilityPaneSlot::Left)
3301                            .map(|pane| !pane.expanded(cx))
3302                    })
3303                })
3304                .flatten()
3305                .unwrap_or(false);
3306
3307        let render_aside_toggle_right = cx.has_flag::<AgentV2FeatureFlag>()
3308            && self
3309                .is_upper_right
3310                .then(|| {
3311                    self.workspace.upgrade().and_then(|entity| {
3312                        let workspace = entity.read(cx);
3313                        workspace
3314                            .utility_pane(UtilityPaneSlot::Right)
3315                            .map(|pane| !pane.expanded(cx))
3316                    })
3317                })
3318                .flatten()
3319                .unwrap_or(false);
3320
3321        TabBar::new("tab_bar")
3322            .map(|tab_bar| {
3323                if let Some(open_aside_left) = open_aside_left
3324                    && render_aside_toggle_left
3325                {
3326                    tab_bar.start_child(open_aside_left)
3327                } else {
3328                    tab_bar
3329                }
3330            })
3331            .when(
3332                self.display_nav_history_buttons.unwrap_or_default(),
3333                |tab_bar| {
3334                    tab_bar
3335                        .start_child(navigate_backward)
3336                        .start_child(navigate_forward)
3337                },
3338            )
3339            .map(|tab_bar| {
3340                if self.show_tab_bar_buttons {
3341                    let render_tab_buttons = self.render_tab_bar_buttons.clone();
3342                    let (left_children, right_children) = render_tab_buttons(self, window, cx);
3343                    tab_bar
3344                        .start_children(left_children)
3345                        .end_children(right_children)
3346                } else {
3347                    tab_bar
3348                }
3349            })
3350            .children(pinned_tabs.len().ne(&0).then(|| {
3351                let max_scroll = self.tab_bar_scroll_handle.max_offset().width;
3352                // We need to check both because offset returns delta values even when the scroll handle is not scrollable
3353                let is_scrolled = self.tab_bar_scroll_handle.offset().x < px(0.);
3354                // Avoid flickering when max_offset is very small (< 2px).
3355                // The border adds 1-2px which can push max_offset back to 0, creating a loop.
3356                let is_scrollable = max_scroll > px(2.0);
3357                let has_active_unpinned_tab = self.active_item_index >= self.pinned_tab_count;
3358                h_flex()
3359                    .children(pinned_tabs)
3360                    .when(is_scrollable && is_scrolled, |this| {
3361                        this.when(has_active_unpinned_tab, |this| this.border_r_2())
3362                            .when(!has_active_unpinned_tab, |this| this.border_r_1())
3363                            .border_color(cx.theme().colors().border)
3364                    })
3365            }))
3366            .child(
3367                h_flex()
3368                    .id("unpinned tabs")
3369                    .overflow_x_scroll()
3370                    .w_full()
3371                    .track_scroll(&self.tab_bar_scroll_handle)
3372                    .on_scroll_wheel(cx.listener(|this, _, _, _| {
3373                        this.suppress_scroll = true;
3374                    }))
3375                    .children(unpinned_tabs)
3376                    .child(
3377                        div()
3378                            .id("tab_bar_drop_target")
3379                            .min_w_6()
3380                            // HACK: This empty child is currently necessary to force the drop target to appear
3381                            // despite us setting a min width above.
3382                            .child("")
3383                            // HACK: h_full doesn't occupy the complete height, using fixed height instead
3384                            .h(Tab::container_height(cx))
3385                            .flex_grow()
3386                            .drag_over::<DraggedTab>(|bar, _, _, cx| {
3387                                bar.bg(cx.theme().colors().drop_target_background)
3388                            })
3389                            .drag_over::<DraggedSelection>(|bar, _, _, cx| {
3390                                bar.bg(cx.theme().colors().drop_target_background)
3391                            })
3392                            .on_drop(cx.listener(
3393                                move |this, dragged_tab: &DraggedTab, window, cx| {
3394                                    this.drag_split_direction = None;
3395                                    this.handle_tab_drop(dragged_tab, this.items.len(), window, cx)
3396                                },
3397                            ))
3398                            .on_drop(cx.listener(
3399                                move |this, selection: &DraggedSelection, window, cx| {
3400                                    this.drag_split_direction = None;
3401                                    this.handle_project_entry_drop(
3402                                        &selection.active_selection.entry_id,
3403                                        Some(tab_count),
3404                                        window,
3405                                        cx,
3406                                    )
3407                                },
3408                            ))
3409                            .on_drop(cx.listener(move |this, paths, window, cx| {
3410                                this.drag_split_direction = None;
3411                                this.handle_external_paths_drop(paths, window, cx)
3412                            }))
3413                            .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
3414                                if event.click_count() == 2 {
3415                                    window.dispatch_action(
3416                                        this.double_click_dispatch_action.boxed_clone(),
3417                                        cx,
3418                                    );
3419                                }
3420                            })),
3421                    ),
3422            )
3423            .map(|tab_bar| {
3424                if let Some(open_aside_right) = open_aside_right
3425                    && render_aside_toggle_right
3426                {
3427                    tab_bar.end_child(open_aside_right)
3428                } else {
3429                    tab_bar
3430                }
3431            })
3432            .into_any_element()
3433    }
3434
3435    pub fn render_menu_overlay(menu: &Entity<ContextMenu>) -> Div {
3436        div().absolute().bottom_0().right_0().size_0().child(
3437            deferred(anchored().anchor(Corner::TopRight).child(menu.clone())).with_priority(1),
3438        )
3439    }
3440
3441    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut Context<Self>) {
3442        self.zoomed = zoomed;
3443        cx.notify();
3444    }
3445
3446    pub fn is_zoomed(&self) -> bool {
3447        self.zoomed
3448    }
3449
3450    fn handle_drag_move<T: 'static>(
3451        &mut self,
3452        event: &DragMoveEvent<T>,
3453        window: &mut Window,
3454        cx: &mut Context<Self>,
3455    ) {
3456        let can_split_predicate = self.can_split_predicate.take();
3457        let can_split = match &can_split_predicate {
3458            Some(can_split_predicate) => {
3459                can_split_predicate(self, event.dragged_item(), window, cx)
3460            }
3461            None => false,
3462        };
3463        self.can_split_predicate = can_split_predicate;
3464        if !can_split {
3465            return;
3466        }
3467
3468        let rect = event.bounds.size;
3469
3470        let size = event.bounds.size.width.min(event.bounds.size.height)
3471            * WorkspaceSettings::get_global(cx).drop_target_size;
3472
3473        let relative_cursor = Point::new(
3474            event.event.position.x - event.bounds.left(),
3475            event.event.position.y - event.bounds.top(),
3476        );
3477
3478        let direction = if relative_cursor.x < size
3479            || relative_cursor.x > rect.width - size
3480            || relative_cursor.y < size
3481            || relative_cursor.y > rect.height - size
3482        {
3483            [
3484                SplitDirection::Up,
3485                SplitDirection::Right,
3486                SplitDirection::Down,
3487                SplitDirection::Left,
3488            ]
3489            .iter()
3490            .min_by_key(|side| match side {
3491                SplitDirection::Up => relative_cursor.y,
3492                SplitDirection::Right => rect.width - relative_cursor.x,
3493                SplitDirection::Down => rect.height - relative_cursor.y,
3494                SplitDirection::Left => relative_cursor.x,
3495            })
3496            .cloned()
3497        } else {
3498            None
3499        };
3500
3501        if direction != self.drag_split_direction {
3502            self.drag_split_direction = direction;
3503        }
3504    }
3505
3506    pub fn handle_tab_drop(
3507        &mut self,
3508        dragged_tab: &DraggedTab,
3509        ix: usize,
3510        window: &mut Window,
3511        cx: &mut Context<Self>,
3512    ) {
3513        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3514            && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_tab, window, cx)
3515        {
3516            return;
3517        }
3518        let mut to_pane = cx.entity();
3519        let split_direction = self.drag_split_direction;
3520        let item_id = dragged_tab.item.item_id();
3521        self.unpreview_item_if_preview(item_id);
3522
3523        let is_clone = cfg!(target_os = "macos") && window.modifiers().alt
3524            || cfg!(not(target_os = "macos")) && window.modifiers().control;
3525
3526        let from_pane = dragged_tab.pane.clone();
3527
3528        self.workspace
3529            .update(cx, |_, cx| {
3530                cx.defer_in(window, move |workspace, window, cx| {
3531                    if let Some(split_direction) = split_direction {
3532                        to_pane = workspace.split_pane(to_pane, split_direction, window, cx);
3533                    }
3534                    let database_id = workspace.database_id();
3535                    let was_pinned_in_from_pane = from_pane.read_with(cx, |pane, _| {
3536                        pane.index_for_item_id(item_id)
3537                            .is_some_and(|ix| pane.is_tab_pinned(ix))
3538                    });
3539                    let to_pane_old_length = to_pane.read(cx).items.len();
3540                    if is_clone {
3541                        let Some(item) = from_pane
3542                            .read(cx)
3543                            .items()
3544                            .find(|item| item.item_id() == item_id)
3545                            .cloned()
3546                        else {
3547                            return;
3548                        };
3549                        if item.can_split(cx) {
3550                            let task = item.clone_on_split(database_id, window, cx);
3551                            let to_pane = to_pane.downgrade();
3552                            cx.spawn_in(window, async move |_, cx| {
3553                                if let Some(item) = task.await {
3554                                    to_pane
3555                                        .update_in(cx, |pane, window, cx| {
3556                                            pane.add_item(item, true, true, None, window, cx)
3557                                        })
3558                                        .ok();
3559                                }
3560                            })
3561                            .detach();
3562                        } else {
3563                            move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3564                        }
3565                    } else {
3566                        move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3567                    }
3568                    to_pane.update(cx, |this, _| {
3569                        if to_pane == from_pane {
3570                            let actual_ix = this
3571                                .items
3572                                .iter()
3573                                .position(|item| item.item_id() == item_id)
3574                                .unwrap_or(0);
3575
3576                            let is_pinned_in_to_pane = this.is_tab_pinned(actual_ix);
3577
3578                            if !was_pinned_in_from_pane && is_pinned_in_to_pane {
3579                                this.pinned_tab_count += 1;
3580                            } else if was_pinned_in_from_pane && !is_pinned_in_to_pane {
3581                                this.pinned_tab_count -= 1;
3582                            }
3583                        } else if this.items.len() >= to_pane_old_length {
3584                            let is_pinned_in_to_pane = this.is_tab_pinned(ix);
3585                            let item_created_pane = to_pane_old_length == 0;
3586                            let is_first_position = ix == 0;
3587                            let was_dropped_at_beginning = item_created_pane || is_first_position;
3588                            let should_remain_pinned = is_pinned_in_to_pane
3589                                || (was_pinned_in_from_pane && was_dropped_at_beginning);
3590
3591                            if should_remain_pinned {
3592                                this.pinned_tab_count += 1;
3593                            }
3594                        }
3595                    });
3596                });
3597            })
3598            .log_err();
3599    }
3600
3601    fn handle_dragged_selection_drop(
3602        &mut self,
3603        dragged_selection: &DraggedSelection,
3604        dragged_onto: Option<usize>,
3605        window: &mut Window,
3606        cx: &mut Context<Self>,
3607    ) {
3608        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3609            && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_selection, window, cx)
3610        {
3611            return;
3612        }
3613        self.handle_project_entry_drop(
3614            &dragged_selection.active_selection.entry_id,
3615            dragged_onto,
3616            window,
3617            cx,
3618        );
3619    }
3620
3621    fn handle_project_entry_drop(
3622        &mut self,
3623        project_entry_id: &ProjectEntryId,
3624        target: Option<usize>,
3625        window: &mut Window,
3626        cx: &mut Context<Self>,
3627    ) {
3628        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3629            && let ControlFlow::Break(()) = custom_drop_handle(self, project_entry_id, window, cx)
3630        {
3631            return;
3632        }
3633        let mut to_pane = cx.entity();
3634        let split_direction = self.drag_split_direction;
3635        let project_entry_id = *project_entry_id;
3636        self.workspace
3637            .update(cx, |_, cx| {
3638                cx.defer_in(window, move |workspace, window, cx| {
3639                    if let Some(project_path) = workspace
3640                        .project()
3641                        .read(cx)
3642                        .path_for_entry(project_entry_id, cx)
3643                    {
3644                        let load_path_task = workspace.load_path(project_path.clone(), window, cx);
3645                        cx.spawn_in(window, async move |workspace, cx| {
3646                            if let Some((project_entry_id, build_item)) =
3647                                load_path_task.await.notify_async_err(cx)
3648                            {
3649                                let (to_pane, new_item_handle) = workspace
3650                                    .update_in(cx, |workspace, window, cx| {
3651                                        if let Some(split_direction) = split_direction {
3652                                            to_pane = workspace.split_pane(
3653                                                to_pane,
3654                                                split_direction,
3655                                                window,
3656                                                cx,
3657                                            );
3658                                        }
3659                                        let new_item_handle = to_pane.update(cx, |pane, cx| {
3660                                            pane.open_item(
3661                                                project_entry_id,
3662                                                project_path,
3663                                                true,
3664                                                false,
3665                                                true,
3666                                                target,
3667                                                window,
3668                                                cx,
3669                                                build_item,
3670                                            )
3671                                        });
3672                                        (to_pane, new_item_handle)
3673                                    })
3674                                    .log_err()?;
3675                                to_pane
3676                                    .update_in(cx, |this, window, cx| {
3677                                        let Some(index) = this.index_for_item(&*new_item_handle)
3678                                        else {
3679                                            return;
3680                                        };
3681
3682                                        if target.is_some_and(|target| this.is_tab_pinned(target)) {
3683                                            this.pin_tab_at(index, window, cx);
3684                                        }
3685                                    })
3686                                    .ok()?
3687                            }
3688                            Some(())
3689                        })
3690                        .detach();
3691                    };
3692                });
3693            })
3694            .log_err();
3695    }
3696
3697    fn handle_external_paths_drop(
3698        &mut self,
3699        paths: &ExternalPaths,
3700        window: &mut Window,
3701        cx: &mut Context<Self>,
3702    ) {
3703        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3704            && let ControlFlow::Break(()) = custom_drop_handle(self, paths, window, cx)
3705        {
3706            return;
3707        }
3708        let mut to_pane = cx.entity();
3709        let mut split_direction = self.drag_split_direction;
3710        let paths = paths.paths().to_vec();
3711        let is_remote = self
3712            .workspace
3713            .update(cx, |workspace, cx| {
3714                if workspace.project().read(cx).is_via_collab() {
3715                    workspace.show_error(
3716                        &anyhow::anyhow!("Cannot drop files on a remote project"),
3717                        cx,
3718                    );
3719                    true
3720                } else {
3721                    false
3722                }
3723            })
3724            .unwrap_or(true);
3725        if is_remote {
3726            return;
3727        }
3728
3729        self.workspace
3730            .update(cx, |workspace, cx| {
3731                let fs = Arc::clone(workspace.project().read(cx).fs());
3732                cx.spawn_in(window, async move |workspace, cx| {
3733                    let mut is_file_checks = FuturesUnordered::new();
3734                    for path in &paths {
3735                        is_file_checks.push(fs.is_file(path))
3736                    }
3737                    let mut has_files_to_open = false;
3738                    while let Some(is_file) = is_file_checks.next().await {
3739                        if is_file {
3740                            has_files_to_open = true;
3741                            break;
3742                        }
3743                    }
3744                    drop(is_file_checks);
3745                    if !has_files_to_open {
3746                        split_direction = None;
3747                    }
3748
3749                    if let Ok((open_task, to_pane)) =
3750                        workspace.update_in(cx, |workspace, window, cx| {
3751                            if let Some(split_direction) = split_direction {
3752                                to_pane =
3753                                    workspace.split_pane(to_pane, split_direction, window, cx);
3754                            }
3755                            (
3756                                workspace.open_paths(
3757                                    paths,
3758                                    OpenOptions {
3759                                        visible: Some(OpenVisible::OnlyDirectories),
3760                                        ..Default::default()
3761                                    },
3762                                    Some(to_pane.downgrade()),
3763                                    window,
3764                                    cx,
3765                                ),
3766                                to_pane,
3767                            )
3768                        })
3769                    {
3770                        let opened_items: Vec<_> = open_task.await;
3771                        _ = workspace.update_in(cx, |workspace, window, cx| {
3772                            for item in opened_items.into_iter().flatten() {
3773                                if let Err(e) = item {
3774                                    workspace.show_error(&e, cx);
3775                                }
3776                            }
3777                            if to_pane.read(cx).items_len() == 0 {
3778                                workspace.remove_pane(to_pane, None, window, cx);
3779                            }
3780                        });
3781                    }
3782                })
3783                .detach();
3784            })
3785            .log_err();
3786    }
3787
3788    pub fn display_nav_history_buttons(&mut self, display: Option<bool>) {
3789        self.display_nav_history_buttons = display;
3790    }
3791
3792    fn pinned_item_ids(&self) -> Vec<EntityId> {
3793        self.items
3794            .iter()
3795            .enumerate()
3796            .filter_map(|(index, item)| {
3797                if self.is_tab_pinned(index) {
3798                    return Some(item.item_id());
3799                }
3800
3801                None
3802            })
3803            .collect()
3804    }
3805
3806    fn clean_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3807        self.items()
3808            .filter_map(|item| {
3809                if !item.is_dirty(cx) {
3810                    return Some(item.item_id());
3811                }
3812
3813                None
3814            })
3815            .collect()
3816    }
3817
3818    fn to_the_side_item_ids(&self, item_id: EntityId, side: Side) -> Vec<EntityId> {
3819        match side {
3820            Side::Left => self
3821                .items()
3822                .take_while(|item| item.item_id() != item_id)
3823                .map(|item| item.item_id())
3824                .collect(),
3825            Side::Right => self
3826                .items()
3827                .rev()
3828                .take_while(|item| item.item_id() != item_id)
3829                .map(|item| item.item_id())
3830                .collect(),
3831        }
3832    }
3833
3834    fn multibuffer_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3835        self.items()
3836            .filter(|item| item.buffer_kind(cx) == ItemBufferKind::Multibuffer)
3837            .map(|item| item.item_id())
3838            .collect()
3839    }
3840
3841    pub fn drag_split_direction(&self) -> Option<SplitDirection> {
3842        self.drag_split_direction
3843    }
3844
3845    pub fn set_zoom_out_on_close(&mut self, zoom_out_on_close: bool) {
3846        self.zoom_out_on_close = zoom_out_on_close;
3847    }
3848}
3849
3850fn default_render_tab_bar_buttons(
3851    pane: &mut Pane,
3852    window: &mut Window,
3853    cx: &mut Context<Pane>,
3854) -> (Option<AnyElement>, Option<AnyElement>) {
3855    if !pane.has_focus(window, cx) && !pane.context_menu_focused(window, cx) {
3856        return (None, None);
3857    }
3858    let (can_clone, can_split_move) = match pane.active_item() {
3859        Some(active_item) if active_item.can_split(cx) => (true, false),
3860        Some(_) => (false, pane.items_len() > 1),
3861        None => (false, false),
3862    };
3863    // Ideally we would return a vec of elements here to pass directly to the [TabBar]'s
3864    // `end_slot`, but due to needing a view here that isn't possible.
3865    let right_children = h_flex()
3866        // Instead we need to replicate the spacing from the [TabBar]'s `end_slot` here.
3867        .gap(DynamicSpacing::Base04.rems(cx))
3868        .child(
3869            PopoverMenu::new("pane-tab-bar-popover-menu")
3870                .trigger_with_tooltip(
3871                    IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
3872                    Tooltip::text("New..."),
3873                )
3874                .anchor(Corner::TopRight)
3875                .with_handle(pane.new_item_context_menu_handle.clone())
3876                .menu(move |window, cx| {
3877                    Some(ContextMenu::build(window, cx, |menu, _, _| {
3878                        menu.action("New File", NewFile.boxed_clone())
3879                            .action("Open File", ToggleFileFinder::default().boxed_clone())
3880                            .separator()
3881                            .action(
3882                                "Search Project",
3883                                DeploySearch {
3884                                    replace_enabled: false,
3885                                    included_files: None,
3886                                    excluded_files: None,
3887                                }
3888                                .boxed_clone(),
3889                            )
3890                            .action("Search Symbols", ToggleProjectSymbols.boxed_clone())
3891                            .separator()
3892                            .action("New Terminal", NewTerminal.boxed_clone())
3893                    }))
3894                }),
3895        )
3896        .child(
3897            PopoverMenu::new("pane-tab-bar-split")
3898                .trigger_with_tooltip(
3899                    IconButton::new("split", IconName::Split)
3900                        .icon_size(IconSize::Small)
3901                        .disabled(!can_clone && !can_split_move),
3902                    Tooltip::text("Split Pane"),
3903                )
3904                .anchor(Corner::TopRight)
3905                .with_handle(pane.split_item_context_menu_handle.clone())
3906                .menu(move |window, cx| {
3907                    ContextMenu::build(window, cx, |menu, _, _| {
3908                        let mode = SplitMode::MovePane;
3909                        if can_split_move {
3910                            menu.action("Split Right", SplitRight { mode }.boxed_clone())
3911                                .action("Split Left", SplitLeft { mode }.boxed_clone())
3912                                .action("Split Up", SplitUp { mode }.boxed_clone())
3913                                .action("Split Down", SplitDown { mode }.boxed_clone())
3914                        } else {
3915                            menu.action("Split Right", SplitRight::default().boxed_clone())
3916                                .action("Split Left", SplitLeft::default().boxed_clone())
3917                                .action("Split Up", SplitUp::default().boxed_clone())
3918                                .action("Split Down", SplitDown::default().boxed_clone())
3919                        }
3920                    })
3921                    .into()
3922                }),
3923        )
3924        .child({
3925            let zoomed = pane.is_zoomed();
3926            IconButton::new("toggle_zoom", IconName::Maximize)
3927                .icon_size(IconSize::Small)
3928                .toggle_state(zoomed)
3929                .selected_icon(IconName::Minimize)
3930                .on_click(cx.listener(|pane, _, window, cx| {
3931                    pane.toggle_zoom(&crate::ToggleZoom, window, cx);
3932                }))
3933                .tooltip(move |_window, cx| {
3934                    Tooltip::for_action(
3935                        if zoomed { "Zoom Out" } else { "Zoom In" },
3936                        &ToggleZoom,
3937                        cx,
3938                    )
3939                })
3940        })
3941        .into_any_element()
3942        .into();
3943    (None, right_children)
3944}
3945
3946impl Focusable for Pane {
3947    fn focus_handle(&self, _cx: &App) -> FocusHandle {
3948        self.focus_handle.clone()
3949    }
3950}
3951
3952impl Render for Pane {
3953    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3954        let mut key_context = KeyContext::new_with_defaults();
3955        key_context.add("Pane");
3956        if self.active_item().is_none() {
3957            key_context.add("EmptyPane");
3958        }
3959
3960        self.toolbar
3961            .read(cx)
3962            .contribute_context(&mut key_context, cx);
3963
3964        let should_display_tab_bar = self.should_display_tab_bar.clone();
3965        let display_tab_bar = should_display_tab_bar(window, cx);
3966        let Some(project) = self.project.upgrade() else {
3967            return div().track_focus(&self.focus_handle(cx));
3968        };
3969        let is_local = project.read(cx).is_local();
3970
3971        v_flex()
3972            .key_context(key_context)
3973            .track_focus(&self.focus_handle(cx))
3974            .size_full()
3975            .flex_none()
3976            .overflow_hidden()
3977            .on_action(cx.listener(|pane, split: &SplitLeft, window, cx| {
3978                pane.split(SplitDirection::Left, split.mode, window, cx)
3979            }))
3980            .on_action(cx.listener(|pane, split: &SplitUp, window, cx| {
3981                pane.split(SplitDirection::Up, split.mode, window, cx)
3982            }))
3983            .on_action(cx.listener(|pane, split: &SplitHorizontal, window, cx| {
3984                pane.split(SplitDirection::horizontal(cx), split.mode, window, cx)
3985            }))
3986            .on_action(cx.listener(|pane, split: &SplitVertical, window, cx| {
3987                pane.split(SplitDirection::vertical(cx), split.mode, window, cx)
3988            }))
3989            .on_action(cx.listener(|pane, split: &SplitRight, window, cx| {
3990                pane.split(SplitDirection::Right, split.mode, window, cx)
3991            }))
3992            .on_action(cx.listener(|pane, split: &SplitDown, window, cx| {
3993                pane.split(SplitDirection::Down, split.mode, window, cx)
3994            }))
3995            .on_action(cx.listener(|pane, _: &SplitAndMoveUp, window, cx| {
3996                pane.split(SplitDirection::Up, SplitMode::MovePane, window, cx)
3997            }))
3998            .on_action(cx.listener(|pane, _: &SplitAndMoveDown, window, cx| {
3999                pane.split(SplitDirection::Down, SplitMode::MovePane, window, cx)
4000            }))
4001            .on_action(cx.listener(|pane, _: &SplitAndMoveLeft, window, cx| {
4002                pane.split(SplitDirection::Left, SplitMode::MovePane, window, cx)
4003            }))
4004            .on_action(cx.listener(|pane, _: &SplitAndMoveRight, window, cx| {
4005                pane.split(SplitDirection::Right, SplitMode::MovePane, window, cx)
4006            }))
4007            .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
4008                cx.emit(Event::JoinIntoNext);
4009            }))
4010            .on_action(cx.listener(|_, _: &JoinAll, _, cx| {
4011                cx.emit(Event::JoinAll);
4012            }))
4013            .on_action(cx.listener(Pane::toggle_zoom))
4014            .on_action(cx.listener(Pane::zoom_in))
4015            .on_action(cx.listener(Pane::zoom_out))
4016            .on_action(cx.listener(Self::navigate_backward))
4017            .on_action(cx.listener(Self::navigate_forward))
4018            .on_action(
4019                cx.listener(|pane: &mut Pane, action: &ActivateItem, window, cx| {
4020                    pane.activate_item(
4021                        action.0.min(pane.items.len().saturating_sub(1)),
4022                        true,
4023                        true,
4024                        window,
4025                        cx,
4026                    );
4027                }),
4028            )
4029            .on_action(cx.listener(Self::alternate_file))
4030            .on_action(cx.listener(Self::activate_last_item))
4031            .on_action(cx.listener(Self::activate_previous_item))
4032            .on_action(cx.listener(Self::activate_next_item))
4033            .on_action(cx.listener(Self::swap_item_left))
4034            .on_action(cx.listener(Self::swap_item_right))
4035            .on_action(cx.listener(Self::toggle_pin_tab))
4036            .on_action(cx.listener(Self::unpin_all_tabs))
4037            .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
4038                this.on_action(
4039                    cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, window, cx| {
4040                        if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
4041                            if pane.is_active_preview_item(active_item_id) {
4042                                pane.unpreview_item_if_preview(active_item_id);
4043                            } else {
4044                                pane.replace_preview_item_id(active_item_id, window, cx);
4045                            }
4046                        }
4047                    }),
4048                )
4049            })
4050            .on_action(
4051                cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
4052                    pane.close_active_item(action, window, cx)
4053                        .detach_and_log_err(cx)
4054                }),
4055            )
4056            .on_action(
4057                cx.listener(|pane: &mut Self, action: &CloseOtherItems, window, cx| {
4058                    pane.close_other_items(action, None, window, cx)
4059                        .detach_and_log_err(cx);
4060                }),
4061            )
4062            .on_action(
4063                cx.listener(|pane: &mut Self, action: &CloseCleanItems, window, cx| {
4064                    pane.close_clean_items(action, window, cx)
4065                        .detach_and_log_err(cx)
4066                }),
4067            )
4068            .on_action(cx.listener(
4069                |pane: &mut Self, action: &CloseItemsToTheLeft, window, cx| {
4070                    pane.close_items_to_the_left_by_id(None, action, window, cx)
4071                        .detach_and_log_err(cx)
4072                },
4073            ))
4074            .on_action(cx.listener(
4075                |pane: &mut Self, action: &CloseItemsToTheRight, window, cx| {
4076                    pane.close_items_to_the_right_by_id(None, action, window, cx)
4077                        .detach_and_log_err(cx)
4078                },
4079            ))
4080            .on_action(
4081                cx.listener(|pane: &mut Self, action: &CloseAllItems, window, cx| {
4082                    pane.close_all_items(action, window, cx)
4083                        .detach_and_log_err(cx)
4084                }),
4085            )
4086            .on_action(cx.listener(
4087                |pane: &mut Self, action: &CloseMultibufferItems, window, cx| {
4088                    pane.close_multibuffer_items(action, window, cx)
4089                        .detach_and_log_err(cx)
4090                },
4091            ))
4092            .on_action(
4093                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, _, cx| {
4094                    let entry_id = action
4095                        .entry_id
4096                        .map(ProjectEntryId::from_proto)
4097                        .or_else(|| pane.active_item()?.project_entry_ids(cx).first().copied());
4098                    if let Some(entry_id) = entry_id {
4099                        pane.project
4100                            .update(cx, |_, cx| {
4101                                cx.emit(project::Event::RevealInProjectPanel(entry_id))
4102                            })
4103                            .ok();
4104                    }
4105                }),
4106            )
4107            .on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
4108                if cx.stop_active_drag(window) {
4109                } else {
4110                    cx.propagate();
4111                }
4112            }))
4113            .when(self.active_item().is_some() && display_tab_bar, |pane| {
4114                pane.child((self.render_tab_bar.clone())(self, window, cx))
4115            })
4116            .child({
4117                let has_worktrees = project.read(cx).visible_worktrees(cx).next().is_some();
4118                // main content
4119                div()
4120                    .flex_1()
4121                    .relative()
4122                    .group("")
4123                    .overflow_hidden()
4124                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
4125                    .on_drag_move::<DraggedSelection>(cx.listener(Self::handle_drag_move))
4126                    .when(is_local, |div| {
4127                        div.on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
4128                    })
4129                    .map(|div| {
4130                        if let Some(item) = self.active_item() {
4131                            div.id("pane_placeholder")
4132                                .v_flex()
4133                                .size_full()
4134                                .overflow_hidden()
4135                                .child(self.toolbar.clone())
4136                                .child(item.to_any_view())
4137                        } else {
4138                            let placeholder = div
4139                                .id("pane_placeholder")
4140                                .h_flex()
4141                                .size_full()
4142                                .justify_center()
4143                                .on_click(cx.listener(
4144                                    move |this, event: &ClickEvent, window, cx| {
4145                                        if event.click_count() == 2 {
4146                                            window.dispatch_action(
4147                                                this.double_click_dispatch_action.boxed_clone(),
4148                                                cx,
4149                                            );
4150                                        }
4151                                    },
4152                                ));
4153                            if has_worktrees {
4154                                placeholder
4155                            } else {
4156                                if self.welcome_page.is_none() {
4157                                    let workspace = self.workspace.clone();
4158                                    self.welcome_page = Some(cx.new(|cx| {
4159                                        crate::welcome::WelcomePage::new(
4160                                            workspace, true, window, cx,
4161                                        )
4162                                    }));
4163                                }
4164                                placeholder.child(self.welcome_page.clone().unwrap())
4165                            }
4166                        }
4167                    })
4168                    .child(
4169                        // drag target
4170                        div()
4171                            .invisible()
4172                            .absolute()
4173                            .bg(cx.theme().colors().drop_target_background)
4174                            .group_drag_over::<DraggedTab>("", |style| style.visible())
4175                            .group_drag_over::<DraggedSelection>("", |style| style.visible())
4176                            .when(is_local, |div| {
4177                                div.group_drag_over::<ExternalPaths>("", |style| style.visible())
4178                            })
4179                            .when_some(self.can_drop_predicate.clone(), |this, p| {
4180                                this.can_drop(move |a, window, cx| p(a, window, cx))
4181                            })
4182                            .on_drop(cx.listener(move |this, dragged_tab, window, cx| {
4183                                this.handle_tab_drop(
4184                                    dragged_tab,
4185                                    this.active_item_index(),
4186                                    window,
4187                                    cx,
4188                                )
4189                            }))
4190                            .on_drop(cx.listener(
4191                                move |this, selection: &DraggedSelection, window, cx| {
4192                                    this.handle_dragged_selection_drop(selection, None, window, cx)
4193                                },
4194                            ))
4195                            .on_drop(cx.listener(move |this, paths, window, cx| {
4196                                this.handle_external_paths_drop(paths, window, cx)
4197                            }))
4198                            .map(|div| {
4199                                let size = DefiniteLength::Fraction(0.5);
4200                                match self.drag_split_direction {
4201                                    None => div.top_0().right_0().bottom_0().left_0(),
4202                                    Some(SplitDirection::Up) => {
4203                                        div.top_0().left_0().right_0().h(size)
4204                                    }
4205                                    Some(SplitDirection::Down) => {
4206                                        div.left_0().bottom_0().right_0().h(size)
4207                                    }
4208                                    Some(SplitDirection::Left) => {
4209                                        div.top_0().left_0().bottom_0().w(size)
4210                                    }
4211                                    Some(SplitDirection::Right) => {
4212                                        div.top_0().bottom_0().right_0().w(size)
4213                                    }
4214                                }
4215                            }),
4216                    )
4217            })
4218            .on_mouse_down(
4219                MouseButton::Navigate(NavigationDirection::Back),
4220                cx.listener(|pane, _, window, cx| {
4221                    if let Some(workspace) = pane.workspace.upgrade() {
4222                        let pane = cx.entity().downgrade();
4223                        window.defer(cx, move |window, cx| {
4224                            workspace.update(cx, |workspace, cx| {
4225                                workspace.go_back(pane, window, cx).detach_and_log_err(cx)
4226                            })
4227                        })
4228                    }
4229                }),
4230            )
4231            .on_mouse_down(
4232                MouseButton::Navigate(NavigationDirection::Forward),
4233                cx.listener(|pane, _, window, cx| {
4234                    if let Some(workspace) = pane.workspace.upgrade() {
4235                        let pane = cx.entity().downgrade();
4236                        window.defer(cx, move |window, cx| {
4237                            workspace.update(cx, |workspace, cx| {
4238                                workspace
4239                                    .go_forward(pane, window, cx)
4240                                    .detach_and_log_err(cx)
4241                            })
4242                        })
4243                    }
4244                }),
4245            )
4246    }
4247}
4248
4249impl ItemNavHistory {
4250    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut App) {
4251        if self
4252            .item
4253            .upgrade()
4254            .is_some_and(|item| item.include_in_nav_history())
4255        {
4256            self.history
4257                .push(data, self.item.clone(), self.is_preview, cx);
4258        }
4259    }
4260
4261    pub fn pop_backward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
4262        self.history.pop(NavigationMode::GoingBack, cx)
4263    }
4264
4265    pub fn pop_forward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
4266        self.history.pop(NavigationMode::GoingForward, cx)
4267    }
4268}
4269
4270impl NavHistory {
4271    pub fn for_each_entry(
4272        &self,
4273        cx: &App,
4274        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
4275    ) {
4276        let borrowed_history = self.0.lock();
4277        borrowed_history
4278            .forward_stack
4279            .iter()
4280            .chain(borrowed_history.backward_stack.iter())
4281            .chain(borrowed_history.closed_stack.iter())
4282            .for_each(|entry| {
4283                if let Some(project_and_abs_path) =
4284                    borrowed_history.paths_by_item.get(&entry.item.id())
4285                {
4286                    f(entry, project_and_abs_path.clone());
4287                } else if let Some(item) = entry.item.upgrade()
4288                    && let Some(path) = item.project_path(cx)
4289                {
4290                    f(entry, (path, None));
4291                }
4292            })
4293    }
4294
4295    pub fn set_mode(&mut self, mode: NavigationMode) {
4296        self.0.lock().mode = mode;
4297    }
4298
4299    pub fn mode(&self) -> NavigationMode {
4300        self.0.lock().mode
4301    }
4302
4303    pub fn disable(&mut self) {
4304        self.0.lock().mode = NavigationMode::Disabled;
4305    }
4306
4307    pub fn enable(&mut self) {
4308        self.0.lock().mode = NavigationMode::Normal;
4309    }
4310
4311    pub fn clear(&mut self, cx: &mut App) {
4312        let mut state = self.0.lock();
4313
4314        if state.backward_stack.is_empty()
4315            && state.forward_stack.is_empty()
4316            && state.closed_stack.is_empty()
4317            && state.paths_by_item.is_empty()
4318        {
4319            return;
4320        }
4321
4322        state.mode = NavigationMode::Normal;
4323        state.backward_stack.clear();
4324        state.forward_stack.clear();
4325        state.closed_stack.clear();
4326        state.paths_by_item.clear();
4327        state.did_update(cx);
4328    }
4329
4330    pub fn pop(&mut self, mode: NavigationMode, cx: &mut App) -> Option<NavigationEntry> {
4331        let mut state = self.0.lock();
4332        let entry = match mode {
4333            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
4334                return None;
4335            }
4336            NavigationMode::GoingBack => &mut state.backward_stack,
4337            NavigationMode::GoingForward => &mut state.forward_stack,
4338            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
4339        }
4340        .pop_back();
4341        if entry.is_some() {
4342            state.did_update(cx);
4343        }
4344        entry
4345    }
4346
4347    pub fn push<D: 'static + Send + Any>(
4348        &mut self,
4349        data: Option<D>,
4350        item: Arc<dyn WeakItemHandle>,
4351        is_preview: bool,
4352        cx: &mut App,
4353    ) {
4354        let state = &mut *self.0.lock();
4355        match state.mode {
4356            NavigationMode::Disabled => {}
4357            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
4358                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4359                    state.backward_stack.pop_front();
4360                }
4361                state.backward_stack.push_back(NavigationEntry {
4362                    item,
4363                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4364                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4365                    is_preview,
4366                });
4367                state.forward_stack.clear();
4368            }
4369            NavigationMode::GoingBack => {
4370                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4371                    state.forward_stack.pop_front();
4372                }
4373                state.forward_stack.push_back(NavigationEntry {
4374                    item,
4375                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4376                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4377                    is_preview,
4378                });
4379            }
4380            NavigationMode::GoingForward => {
4381                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4382                    state.backward_stack.pop_front();
4383                }
4384                state.backward_stack.push_back(NavigationEntry {
4385                    item,
4386                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4387                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4388                    is_preview,
4389                });
4390            }
4391            NavigationMode::ClosingItem if is_preview => return,
4392            NavigationMode::ClosingItem => {
4393                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4394                    state.closed_stack.pop_front();
4395                }
4396                state.closed_stack.push_back(NavigationEntry {
4397                    item,
4398                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4399                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4400                    is_preview,
4401                });
4402            }
4403        }
4404        state.did_update(cx);
4405    }
4406
4407    pub fn remove_item(&mut self, item_id: EntityId) {
4408        let mut state = self.0.lock();
4409        state.paths_by_item.remove(&item_id);
4410        state
4411            .backward_stack
4412            .retain(|entry| entry.item.id() != item_id);
4413        state
4414            .forward_stack
4415            .retain(|entry| entry.item.id() != item_id);
4416        state
4417            .closed_stack
4418            .retain(|entry| entry.item.id() != item_id);
4419    }
4420
4421    pub fn rename_item(
4422        &mut self,
4423        item_id: EntityId,
4424        project_path: ProjectPath,
4425        abs_path: Option<PathBuf>,
4426    ) {
4427        let mut state = self.0.lock();
4428        let path_for_item = state.paths_by_item.get_mut(&item_id);
4429        if let Some(path_for_item) = path_for_item {
4430            path_for_item.0 = project_path;
4431            path_for_item.1 = abs_path;
4432        }
4433    }
4434
4435    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
4436        self.0.lock().paths_by_item.get(&item_id).cloned()
4437    }
4438}
4439
4440impl NavHistoryState {
4441    pub fn did_update(&self, cx: &mut App) {
4442        if let Some(pane) = self.pane.upgrade() {
4443            cx.defer(move |cx| {
4444                pane.update(cx, |pane, cx| pane.history_updated(cx));
4445            });
4446        }
4447    }
4448}
4449
4450fn dirty_message_for(buffer_path: Option<ProjectPath>, path_style: PathStyle) -> String {
4451    let path = buffer_path
4452        .as_ref()
4453        .and_then(|p| {
4454            let path = p.path.display(path_style);
4455            if path.is_empty() { None } else { Some(path) }
4456        })
4457        .unwrap_or("This buffer".into());
4458    let path = truncate_and_remove_front(&path, 80);
4459    format!("{path} contains unsaved edits. Do you want to save it?")
4460}
4461
4462pub fn tab_details(items: &[Box<dyn ItemHandle>], _window: &Window, cx: &App) -> Vec<usize> {
4463    let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
4464    let mut tab_descriptions = HashMap::default();
4465    let mut done = false;
4466    while !done {
4467        done = true;
4468
4469        // Store item indices by their tab description.
4470        for (ix, (item, detail)) in items.iter().zip(&tab_details).enumerate() {
4471            let description = item.tab_content_text(*detail, cx);
4472            if *detail == 0 || description != item.tab_content_text(detail - 1, cx) {
4473                tab_descriptions
4474                    .entry(description)
4475                    .or_insert(Vec::new())
4476                    .push(ix);
4477            }
4478        }
4479
4480        // If two or more items have the same tab description, increase their level
4481        // of detail and try again.
4482        for (_, item_ixs) in tab_descriptions.drain() {
4483            if item_ixs.len() > 1 {
4484                done = false;
4485                for ix in item_ixs {
4486                    tab_details[ix] += 1;
4487                }
4488            }
4489        }
4490    }
4491
4492    tab_details
4493}
4494
4495pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &App) -> Option<Indicator> {
4496    maybe!({
4497        let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
4498            (true, _) => Color::Warning,
4499            (_, true) => Color::Accent,
4500            (false, false) => return None,
4501        };
4502
4503        Some(Indicator::dot().color(indicator_color))
4504    })
4505}
4506
4507impl Render for DraggedTab {
4508    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4509        let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
4510        let label = self.item.tab_content(
4511            TabContentParams {
4512                detail: Some(self.detail),
4513                selected: false,
4514                preview: false,
4515                deemphasized: false,
4516            },
4517            window,
4518            cx,
4519        );
4520        Tab::new("")
4521            .toggle_state(self.is_active)
4522            .child(label)
4523            .render(window, cx)
4524            .font(ui_font)
4525    }
4526}
4527
4528#[cfg(test)]
4529mod tests {
4530    use std::{iter::zip, num::NonZero};
4531
4532    use super::*;
4533    use crate::{
4534        Member,
4535        item::test::{TestItem, TestProjectItem},
4536    };
4537    use gpui::{AppContext, Axis, TestAppContext, VisualTestContext, size};
4538    use project::FakeFs;
4539    use settings::SettingsStore;
4540    use theme::LoadThemes;
4541    use util::TryFutureExt;
4542
4543    #[gpui::test]
4544    async fn test_add_item_capped_to_max_tabs(cx: &mut TestAppContext) {
4545        init_test(cx);
4546        let fs = FakeFs::new(cx.executor());
4547
4548        let project = Project::test(fs, None, cx).await;
4549        let (workspace, cx) =
4550            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4551        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4552
4553        for i in 0..7 {
4554            add_labeled_item(&pane, format!("{}", i).as_str(), false, cx);
4555        }
4556
4557        set_max_tabs(cx, Some(5));
4558        add_labeled_item(&pane, "7", false, cx);
4559        // Remove items to respect the max tab cap.
4560        assert_item_labels(&pane, ["3", "4", "5", "6", "7*"], cx);
4561        pane.update_in(cx, |pane, window, cx| {
4562            pane.activate_item(0, false, false, window, cx);
4563        });
4564        add_labeled_item(&pane, "X", false, cx);
4565        // Respect activation order.
4566        assert_item_labels(&pane, ["3", "X*", "5", "6", "7"], cx);
4567
4568        for i in 0..7 {
4569            add_labeled_item(&pane, format!("D{}", i).as_str(), true, cx);
4570        }
4571        // Keeps dirty items, even over max tab cap.
4572        assert_item_labels(
4573            &pane,
4574            ["D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6*^"],
4575            cx,
4576        );
4577
4578        set_max_tabs(cx, None);
4579        for i in 0..7 {
4580            add_labeled_item(&pane, format!("N{}", i).as_str(), false, cx);
4581        }
4582        // No cap when max tabs is None.
4583        assert_item_labels(
4584            &pane,
4585            [
4586                "D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6^", "N0", "N1", "N2", "N3", "N4",
4587                "N5", "N6*",
4588            ],
4589            cx,
4590        );
4591    }
4592
4593    #[gpui::test]
4594    async fn test_reduce_max_tabs_closes_existing_items(cx: &mut TestAppContext) {
4595        init_test(cx);
4596        let fs = FakeFs::new(cx.executor());
4597
4598        let project = Project::test(fs, None, cx).await;
4599        let (workspace, cx) =
4600            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4601        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4602
4603        add_labeled_item(&pane, "A", false, cx);
4604        add_labeled_item(&pane, "B", false, cx);
4605        let item_c = add_labeled_item(&pane, "C", false, cx);
4606        let item_d = add_labeled_item(&pane, "D", false, cx);
4607        add_labeled_item(&pane, "E", false, cx);
4608        add_labeled_item(&pane, "Settings", false, cx);
4609        assert_item_labels(&pane, ["A", "B", "C", "D", "E", "Settings*"], cx);
4610
4611        set_max_tabs(cx, Some(5));
4612        assert_item_labels(&pane, ["B", "C", "D", "E", "Settings*"], cx);
4613
4614        set_max_tabs(cx, Some(4));
4615        assert_item_labels(&pane, ["C", "D", "E", "Settings*"], cx);
4616
4617        pane.update_in(cx, |pane, window, cx| {
4618            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4619            pane.pin_tab_at(ix, window, cx);
4620
4621            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4622            pane.pin_tab_at(ix, window, cx);
4623        });
4624        assert_item_labels(&pane, ["C!", "D!", "E", "Settings*"], cx);
4625
4626        set_max_tabs(cx, Some(2));
4627        assert_item_labels(&pane, ["C!", "D!", "Settings*"], cx);
4628    }
4629
4630    #[gpui::test]
4631    async fn test_allow_pinning_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4632        init_test(cx);
4633        let fs = FakeFs::new(cx.executor());
4634
4635        let project = Project::test(fs, None, cx).await;
4636        let (workspace, cx) =
4637            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4638        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4639
4640        set_max_tabs(cx, Some(1));
4641        let item_a = add_labeled_item(&pane, "A", true, cx);
4642
4643        pane.update_in(cx, |pane, window, cx| {
4644            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4645            pane.pin_tab_at(ix, window, cx);
4646        });
4647        assert_item_labels(&pane, ["A*^!"], cx);
4648    }
4649
4650    #[gpui::test]
4651    async fn test_allow_pinning_non_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4652        init_test(cx);
4653        let fs = FakeFs::new(cx.executor());
4654
4655        let project = Project::test(fs, None, cx).await;
4656        let (workspace, cx) =
4657            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4658        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4659
4660        set_max_tabs(cx, Some(1));
4661        let item_a = add_labeled_item(&pane, "A", false, cx);
4662
4663        pane.update_in(cx, |pane, window, cx| {
4664            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4665            pane.pin_tab_at(ix, window, cx);
4666        });
4667        assert_item_labels(&pane, ["A*!"], cx);
4668    }
4669
4670    #[gpui::test]
4671    async fn test_pin_tabs_incrementally_at_max_capacity(cx: &mut TestAppContext) {
4672        init_test(cx);
4673        let fs = FakeFs::new(cx.executor());
4674
4675        let project = Project::test(fs, None, cx).await;
4676        let (workspace, cx) =
4677            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4678        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4679
4680        set_max_tabs(cx, Some(3));
4681
4682        let item_a = add_labeled_item(&pane, "A", false, cx);
4683        assert_item_labels(&pane, ["A*"], cx);
4684
4685        pane.update_in(cx, |pane, window, cx| {
4686            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4687            pane.pin_tab_at(ix, window, cx);
4688        });
4689        assert_item_labels(&pane, ["A*!"], cx);
4690
4691        let item_b = add_labeled_item(&pane, "B", false, cx);
4692        assert_item_labels(&pane, ["A!", "B*"], cx);
4693
4694        pane.update_in(cx, |pane, window, cx| {
4695            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4696            pane.pin_tab_at(ix, window, cx);
4697        });
4698        assert_item_labels(&pane, ["A!", "B*!"], cx);
4699
4700        let item_c = add_labeled_item(&pane, "C", false, cx);
4701        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4702
4703        pane.update_in(cx, |pane, window, cx| {
4704            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4705            pane.pin_tab_at(ix, window, cx);
4706        });
4707        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4708    }
4709
4710    #[gpui::test]
4711    async fn test_pin_tabs_left_to_right_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4712        init_test(cx);
4713        let fs = FakeFs::new(cx.executor());
4714
4715        let project = Project::test(fs, None, cx).await;
4716        let (workspace, cx) =
4717            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4718        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4719
4720        set_max_tabs(cx, Some(3));
4721
4722        let item_a = add_labeled_item(&pane, "A", false, cx);
4723        assert_item_labels(&pane, ["A*"], cx);
4724
4725        let item_b = add_labeled_item(&pane, "B", false, cx);
4726        assert_item_labels(&pane, ["A", "B*"], cx);
4727
4728        let item_c = add_labeled_item(&pane, "C", false, cx);
4729        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4730
4731        pane.update_in(cx, |pane, window, cx| {
4732            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4733            pane.pin_tab_at(ix, window, cx);
4734        });
4735        assert_item_labels(&pane, ["A!", "B", "C*"], cx);
4736
4737        pane.update_in(cx, |pane, window, cx| {
4738            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4739            pane.pin_tab_at(ix, window, cx);
4740        });
4741        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4742
4743        pane.update_in(cx, |pane, window, cx| {
4744            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4745            pane.pin_tab_at(ix, window, cx);
4746        });
4747        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4748    }
4749
4750    #[gpui::test]
4751    async fn test_pin_tabs_right_to_left_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4752        init_test(cx);
4753        let fs = FakeFs::new(cx.executor());
4754
4755        let project = Project::test(fs, None, cx).await;
4756        let (workspace, cx) =
4757            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4758        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4759
4760        set_max_tabs(cx, Some(3));
4761
4762        let item_a = add_labeled_item(&pane, "A", false, cx);
4763        assert_item_labels(&pane, ["A*"], cx);
4764
4765        let item_b = add_labeled_item(&pane, "B", false, cx);
4766        assert_item_labels(&pane, ["A", "B*"], cx);
4767
4768        let item_c = add_labeled_item(&pane, "C", false, cx);
4769        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4770
4771        pane.update_in(cx, |pane, window, cx| {
4772            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4773            pane.pin_tab_at(ix, window, cx);
4774        });
4775        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4776
4777        pane.update_in(cx, |pane, window, cx| {
4778            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4779            pane.pin_tab_at(ix, window, cx);
4780        });
4781        assert_item_labels(&pane, ["C*!", "B!", "A"], cx);
4782
4783        pane.update_in(cx, |pane, window, cx| {
4784            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4785            pane.pin_tab_at(ix, window, cx);
4786        });
4787        assert_item_labels(&pane, ["C*!", "B!", "A!"], cx);
4788    }
4789
4790    #[gpui::test]
4791    async fn test_pinned_tabs_never_closed_at_max_tabs(cx: &mut TestAppContext) {
4792        init_test(cx);
4793        let fs = FakeFs::new(cx.executor());
4794
4795        let project = Project::test(fs, None, cx).await;
4796        let (workspace, cx) =
4797            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4798        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4799
4800        let item_a = add_labeled_item(&pane, "A", false, cx);
4801        pane.update_in(cx, |pane, window, cx| {
4802            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4803            pane.pin_tab_at(ix, window, cx);
4804        });
4805
4806        let item_b = add_labeled_item(&pane, "B", false, cx);
4807        pane.update_in(cx, |pane, window, cx| {
4808            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4809            pane.pin_tab_at(ix, window, cx);
4810        });
4811
4812        add_labeled_item(&pane, "C", false, cx);
4813        add_labeled_item(&pane, "D", false, cx);
4814        add_labeled_item(&pane, "E", false, cx);
4815        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
4816
4817        set_max_tabs(cx, Some(3));
4818        add_labeled_item(&pane, "F", false, cx);
4819        assert_item_labels(&pane, ["A!", "B!", "F*"], cx);
4820
4821        add_labeled_item(&pane, "G", false, cx);
4822        assert_item_labels(&pane, ["A!", "B!", "G*"], cx);
4823
4824        add_labeled_item(&pane, "H", false, cx);
4825        assert_item_labels(&pane, ["A!", "B!", "H*"], cx);
4826    }
4827
4828    #[gpui::test]
4829    async fn test_always_allows_one_unpinned_item_over_max_tabs_regardless_of_pinned_count(
4830        cx: &mut TestAppContext,
4831    ) {
4832        init_test(cx);
4833        let fs = FakeFs::new(cx.executor());
4834
4835        let project = Project::test(fs, None, cx).await;
4836        let (workspace, cx) =
4837            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4838        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4839
4840        set_max_tabs(cx, Some(3));
4841
4842        let item_a = add_labeled_item(&pane, "A", false, cx);
4843        pane.update_in(cx, |pane, window, cx| {
4844            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4845            pane.pin_tab_at(ix, window, cx);
4846        });
4847
4848        let item_b = add_labeled_item(&pane, "B", false, cx);
4849        pane.update_in(cx, |pane, window, cx| {
4850            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4851            pane.pin_tab_at(ix, window, cx);
4852        });
4853
4854        let item_c = add_labeled_item(&pane, "C", false, cx);
4855        pane.update_in(cx, |pane, window, cx| {
4856            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4857            pane.pin_tab_at(ix, window, cx);
4858        });
4859
4860        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4861
4862        let item_d = add_labeled_item(&pane, "D", false, cx);
4863        assert_item_labels(&pane, ["A!", "B!", "C!", "D*"], cx);
4864
4865        pane.update_in(cx, |pane, window, cx| {
4866            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4867            pane.pin_tab_at(ix, window, cx);
4868        });
4869        assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
4870
4871        add_labeled_item(&pane, "E", false, cx);
4872        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "E*"], cx);
4873
4874        add_labeled_item(&pane, "F", false, cx);
4875        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "F*"], cx);
4876    }
4877
4878    #[gpui::test]
4879    async fn test_can_open_one_item_when_all_tabs_are_dirty_at_max(cx: &mut TestAppContext) {
4880        init_test(cx);
4881        let fs = FakeFs::new(cx.executor());
4882
4883        let project = Project::test(fs, None, cx).await;
4884        let (workspace, cx) =
4885            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4886        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4887
4888        set_max_tabs(cx, Some(3));
4889
4890        add_labeled_item(&pane, "A", true, cx);
4891        assert_item_labels(&pane, ["A*^"], cx);
4892
4893        add_labeled_item(&pane, "B", true, cx);
4894        assert_item_labels(&pane, ["A^", "B*^"], cx);
4895
4896        add_labeled_item(&pane, "C", true, cx);
4897        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
4898
4899        add_labeled_item(&pane, "D", false, cx);
4900        assert_item_labels(&pane, ["A^", "B^", "C^", "D*"], cx);
4901
4902        add_labeled_item(&pane, "E", false, cx);
4903        assert_item_labels(&pane, ["A^", "B^", "C^", "E*"], cx);
4904
4905        add_labeled_item(&pane, "F", false, cx);
4906        assert_item_labels(&pane, ["A^", "B^", "C^", "F*"], cx);
4907
4908        add_labeled_item(&pane, "G", true, cx);
4909        assert_item_labels(&pane, ["A^", "B^", "C^", "G*^"], cx);
4910    }
4911
4912    #[gpui::test]
4913    async fn test_toggle_pin_tab(cx: &mut TestAppContext) {
4914        init_test(cx);
4915        let fs = FakeFs::new(cx.executor());
4916
4917        let project = Project::test(fs, None, cx).await;
4918        let (workspace, cx) =
4919            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4920        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4921
4922        set_labeled_items(&pane, ["A", "B*", "C"], cx);
4923        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4924
4925        pane.update_in(cx, |pane, window, cx| {
4926            pane.toggle_pin_tab(&TogglePinTab, window, cx);
4927        });
4928        assert_item_labels(&pane, ["B*!", "A", "C"], cx);
4929
4930        pane.update_in(cx, |pane, window, cx| {
4931            pane.toggle_pin_tab(&TogglePinTab, window, cx);
4932        });
4933        assert_item_labels(&pane, ["B*", "A", "C"], cx);
4934    }
4935
4936    #[gpui::test]
4937    async fn test_unpin_all_tabs(cx: &mut TestAppContext) {
4938        init_test(cx);
4939        let fs = FakeFs::new(cx.executor());
4940
4941        let project = Project::test(fs, None, cx).await;
4942        let (workspace, cx) =
4943            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4944        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4945
4946        // Unpin all, in an empty pane
4947        pane.update_in(cx, |pane, window, cx| {
4948            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4949        });
4950
4951        assert_item_labels(&pane, [], cx);
4952
4953        let item_a = add_labeled_item(&pane, "A", false, cx);
4954        let item_b = add_labeled_item(&pane, "B", false, cx);
4955        let item_c = add_labeled_item(&pane, "C", false, cx);
4956        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4957
4958        // Unpin all, when no tabs are pinned
4959        pane.update_in(cx, |pane, window, cx| {
4960            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4961        });
4962
4963        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4964
4965        // Pin inactive tabs only
4966        pane.update_in(cx, |pane, window, cx| {
4967            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4968            pane.pin_tab_at(ix, window, cx);
4969
4970            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4971            pane.pin_tab_at(ix, window, cx);
4972        });
4973        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4974
4975        pane.update_in(cx, |pane, window, cx| {
4976            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4977        });
4978
4979        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4980
4981        // Pin all tabs
4982        pane.update_in(cx, |pane, window, cx| {
4983            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4984            pane.pin_tab_at(ix, window, cx);
4985
4986            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4987            pane.pin_tab_at(ix, window, cx);
4988
4989            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4990            pane.pin_tab_at(ix, window, cx);
4991        });
4992        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4993
4994        // Activate middle tab
4995        pane.update_in(cx, |pane, window, cx| {
4996            pane.activate_item(1, false, false, window, cx);
4997        });
4998        assert_item_labels(&pane, ["A!", "B*!", "C!"], cx);
4999
5000        pane.update_in(cx, |pane, window, cx| {
5001            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
5002        });
5003
5004        // Order has not changed
5005        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5006    }
5007
5008    #[gpui::test]
5009    async fn test_pinning_active_tab_without_position_change_maintains_focus(
5010        cx: &mut TestAppContext,
5011    ) {
5012        init_test(cx);
5013        let fs = FakeFs::new(cx.executor());
5014
5015        let project = Project::test(fs, None, cx).await;
5016        let (workspace, cx) =
5017            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5018        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5019
5020        // Add A
5021        let item_a = add_labeled_item(&pane, "A", false, cx);
5022        assert_item_labels(&pane, ["A*"], cx);
5023
5024        // Add B
5025        add_labeled_item(&pane, "B", false, cx);
5026        assert_item_labels(&pane, ["A", "B*"], cx);
5027
5028        // Activate A again
5029        pane.update_in(cx, |pane, window, cx| {
5030            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5031            pane.activate_item(ix, true, true, window, cx);
5032        });
5033        assert_item_labels(&pane, ["A*", "B"], cx);
5034
5035        // Pin A - remains active
5036        pane.update_in(cx, |pane, window, cx| {
5037            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5038            pane.pin_tab_at(ix, window, cx);
5039        });
5040        assert_item_labels(&pane, ["A*!", "B"], cx);
5041
5042        // Unpin A - remain active
5043        pane.update_in(cx, |pane, window, cx| {
5044            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5045            pane.unpin_tab_at(ix, window, cx);
5046        });
5047        assert_item_labels(&pane, ["A*", "B"], cx);
5048    }
5049
5050    #[gpui::test]
5051    async fn test_pinning_active_tab_with_position_change_maintains_focus(cx: &mut TestAppContext) {
5052        init_test(cx);
5053        let fs = FakeFs::new(cx.executor());
5054
5055        let project = Project::test(fs, None, cx).await;
5056        let (workspace, cx) =
5057            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5058        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5059
5060        // Add A, B, C
5061        add_labeled_item(&pane, "A", false, cx);
5062        add_labeled_item(&pane, "B", false, cx);
5063        let item_c = add_labeled_item(&pane, "C", false, cx);
5064        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5065
5066        // Pin C - moves to pinned area, remains active
5067        pane.update_in(cx, |pane, window, cx| {
5068            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5069            pane.pin_tab_at(ix, window, cx);
5070        });
5071        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
5072
5073        // Unpin C - moves after pinned area, remains active
5074        pane.update_in(cx, |pane, window, cx| {
5075            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5076            pane.unpin_tab_at(ix, window, cx);
5077        });
5078        assert_item_labels(&pane, ["C*", "A", "B"], cx);
5079    }
5080
5081    #[gpui::test]
5082    async fn test_pinning_inactive_tab_without_position_change_preserves_existing_focus(
5083        cx: &mut TestAppContext,
5084    ) {
5085        init_test(cx);
5086        let fs = FakeFs::new(cx.executor());
5087
5088        let project = Project::test(fs, None, cx).await;
5089        let (workspace, cx) =
5090            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5091        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5092
5093        // Add A, B
5094        let item_a = add_labeled_item(&pane, "A", false, cx);
5095        add_labeled_item(&pane, "B", false, cx);
5096        assert_item_labels(&pane, ["A", "B*"], cx);
5097
5098        // Pin A - already in pinned area, B remains active
5099        pane.update_in(cx, |pane, window, cx| {
5100            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5101            pane.pin_tab_at(ix, window, cx);
5102        });
5103        assert_item_labels(&pane, ["A!", "B*"], cx);
5104
5105        // Unpin A - stays in place, B remains active
5106        pane.update_in(cx, |pane, window, cx| {
5107            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5108            pane.unpin_tab_at(ix, window, cx);
5109        });
5110        assert_item_labels(&pane, ["A", "B*"], cx);
5111    }
5112
5113    #[gpui::test]
5114    async fn test_pinning_inactive_tab_with_position_change_preserves_existing_focus(
5115        cx: &mut TestAppContext,
5116    ) {
5117        init_test(cx);
5118        let fs = FakeFs::new(cx.executor());
5119
5120        let project = Project::test(fs, None, cx).await;
5121        let (workspace, cx) =
5122            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5123        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5124
5125        // Add A, B, C
5126        add_labeled_item(&pane, "A", false, cx);
5127        let item_b = add_labeled_item(&pane, "B", false, cx);
5128        let item_c = add_labeled_item(&pane, "C", false, cx);
5129        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5130
5131        // Activate B
5132        pane.update_in(cx, |pane, window, cx| {
5133            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5134            pane.activate_item(ix, true, true, window, cx);
5135        });
5136        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5137
5138        // Pin C - moves to pinned area, B remains active
5139        pane.update_in(cx, |pane, window, cx| {
5140            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5141            pane.pin_tab_at(ix, window, cx);
5142        });
5143        assert_item_labels(&pane, ["C!", "A", "B*"], cx);
5144
5145        // Unpin C - moves after pinned area, B remains active
5146        pane.update_in(cx, |pane, window, cx| {
5147            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5148            pane.unpin_tab_at(ix, window, cx);
5149        });
5150        assert_item_labels(&pane, ["C", "A", "B*"], cx);
5151    }
5152
5153    #[gpui::test]
5154    async fn test_drag_unpinned_tab_to_split_creates_pane_with_unpinned_tab(
5155        cx: &mut TestAppContext,
5156    ) {
5157        init_test(cx);
5158        let fs = FakeFs::new(cx.executor());
5159
5160        let project = Project::test(fs, None, cx).await;
5161        let (workspace, cx) =
5162            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5163        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5164
5165        // Add A, B. Pin B. Activate A
5166        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5167        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5168
5169        pane_a.update_in(cx, |pane, window, cx| {
5170            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5171            pane.pin_tab_at(ix, window, cx);
5172
5173            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5174            pane.activate_item(ix, true, true, window, cx);
5175        });
5176
5177        // Drag A to create new split
5178        pane_a.update_in(cx, |pane, window, cx| {
5179            pane.drag_split_direction = Some(SplitDirection::Right);
5180
5181            let dragged_tab = DraggedTab {
5182                pane: pane_a.clone(),
5183                item: item_a.boxed_clone(),
5184                ix: 0,
5185                detail: 0,
5186                is_active: true,
5187            };
5188            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5189        });
5190
5191        // A should be moved to new pane. B should remain pinned, A should not be pinned
5192        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
5193            let panes = workspace.panes();
5194            (panes[0].clone(), panes[1].clone())
5195        });
5196        assert_item_labels(&pane_a, ["B*!"], cx);
5197        assert_item_labels(&pane_b, ["A*"], cx);
5198    }
5199
5200    #[gpui::test]
5201    async fn test_drag_pinned_tab_to_split_creates_pane_with_pinned_tab(cx: &mut TestAppContext) {
5202        init_test(cx);
5203        let fs = FakeFs::new(cx.executor());
5204
5205        let project = Project::test(fs, None, cx).await;
5206        let (workspace, cx) =
5207            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5208        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5209
5210        // Add A, B. Pin both. Activate A
5211        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5212        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5213
5214        pane_a.update_in(cx, |pane, window, cx| {
5215            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5216            pane.pin_tab_at(ix, window, cx);
5217
5218            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5219            pane.pin_tab_at(ix, window, cx);
5220
5221            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5222            pane.activate_item(ix, true, true, window, cx);
5223        });
5224        assert_item_labels(&pane_a, ["A*!", "B!"], cx);
5225
5226        // Drag A to create new split
5227        pane_a.update_in(cx, |pane, window, cx| {
5228            pane.drag_split_direction = Some(SplitDirection::Right);
5229
5230            let dragged_tab = DraggedTab {
5231                pane: pane_a.clone(),
5232                item: item_a.boxed_clone(),
5233                ix: 0,
5234                detail: 0,
5235                is_active: true,
5236            };
5237            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5238        });
5239
5240        // A should be moved to new pane. Both A and B should still be pinned
5241        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
5242            let panes = workspace.panes();
5243            (panes[0].clone(), panes[1].clone())
5244        });
5245        assert_item_labels(&pane_a, ["B*!"], cx);
5246        assert_item_labels(&pane_b, ["A*!"], cx);
5247    }
5248
5249    #[gpui::test]
5250    async fn test_drag_pinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5251        init_test(cx);
5252        let fs = FakeFs::new(cx.executor());
5253
5254        let project = Project::test(fs, None, cx).await;
5255        let (workspace, cx) =
5256            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5257        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5258
5259        // Add A to pane A and pin
5260        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5261        pane_a.update_in(cx, |pane, window, cx| {
5262            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5263            pane.pin_tab_at(ix, window, cx);
5264        });
5265        assert_item_labels(&pane_a, ["A*!"], cx);
5266
5267        // Add B to pane B and pin
5268        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5269            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5270        });
5271        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5272        pane_b.update_in(cx, |pane, window, cx| {
5273            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5274            pane.pin_tab_at(ix, window, cx);
5275        });
5276        assert_item_labels(&pane_b, ["B*!"], cx);
5277
5278        // Move A from pane A to pane B's pinned region
5279        pane_b.update_in(cx, |pane, window, cx| {
5280            let dragged_tab = DraggedTab {
5281                pane: pane_a.clone(),
5282                item: item_a.boxed_clone(),
5283                ix: 0,
5284                detail: 0,
5285                is_active: true,
5286            };
5287            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5288        });
5289
5290        // A should stay pinned
5291        assert_item_labels(&pane_a, [], cx);
5292        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5293    }
5294
5295    #[gpui::test]
5296    async fn test_drag_pinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5297        init_test(cx);
5298        let fs = FakeFs::new(cx.executor());
5299
5300        let project = Project::test(fs, None, cx).await;
5301        let (workspace, cx) =
5302            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5303        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5304
5305        // Add A to pane A and pin
5306        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5307        pane_a.update_in(cx, |pane, window, cx| {
5308            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5309            pane.pin_tab_at(ix, window, cx);
5310        });
5311        assert_item_labels(&pane_a, ["A*!"], cx);
5312
5313        // Create pane B with pinned item B
5314        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5315            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5316        });
5317        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5318        assert_item_labels(&pane_b, ["B*"], cx);
5319
5320        pane_b.update_in(cx, |pane, window, cx| {
5321            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5322            pane.pin_tab_at(ix, window, cx);
5323        });
5324        assert_item_labels(&pane_b, ["B*!"], cx);
5325
5326        // Move A from pane A to pane B's unpinned region
5327        pane_b.update_in(cx, |pane, window, cx| {
5328            let dragged_tab = DraggedTab {
5329                pane: pane_a.clone(),
5330                item: item_a.boxed_clone(),
5331                ix: 0,
5332                detail: 0,
5333                is_active: true,
5334            };
5335            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5336        });
5337
5338        // A should become pinned
5339        assert_item_labels(&pane_a, [], cx);
5340        assert_item_labels(&pane_b, ["B!", "A*"], cx);
5341    }
5342
5343    #[gpui::test]
5344    async fn test_drag_pinned_tab_into_existing_panes_first_position_with_no_pinned_tabs(
5345        cx: &mut TestAppContext,
5346    ) {
5347        init_test(cx);
5348        let fs = FakeFs::new(cx.executor());
5349
5350        let project = Project::test(fs, None, cx).await;
5351        let (workspace, cx) =
5352            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5353        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5354
5355        // Add A to pane A and pin
5356        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5357        pane_a.update_in(cx, |pane, window, cx| {
5358            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5359            pane.pin_tab_at(ix, window, cx);
5360        });
5361        assert_item_labels(&pane_a, ["A*!"], cx);
5362
5363        // Add B to pane B
5364        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5365            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5366        });
5367        add_labeled_item(&pane_b, "B", false, cx);
5368        assert_item_labels(&pane_b, ["B*"], cx);
5369
5370        // Move A from pane A to position 0 in pane B, indicating it should stay pinned
5371        pane_b.update_in(cx, |pane, window, cx| {
5372            let dragged_tab = DraggedTab {
5373                pane: pane_a.clone(),
5374                item: item_a.boxed_clone(),
5375                ix: 0,
5376                detail: 0,
5377                is_active: true,
5378            };
5379            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5380        });
5381
5382        // A should stay pinned
5383        assert_item_labels(&pane_a, [], cx);
5384        assert_item_labels(&pane_b, ["A*!", "B"], cx);
5385    }
5386
5387    #[gpui::test]
5388    async fn test_drag_pinned_tab_into_existing_pane_at_max_capacity_closes_unpinned_tabs(
5389        cx: &mut TestAppContext,
5390    ) {
5391        init_test(cx);
5392        let fs = FakeFs::new(cx.executor());
5393
5394        let project = Project::test(fs, None, cx).await;
5395        let (workspace, cx) =
5396            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5397        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5398        set_max_tabs(cx, Some(2));
5399
5400        // Add A, B to pane A. Pin both
5401        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5402        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5403        pane_a.update_in(cx, |pane, window, cx| {
5404            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5405            pane.pin_tab_at(ix, window, cx);
5406
5407            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5408            pane.pin_tab_at(ix, window, cx);
5409        });
5410        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5411
5412        // Add C, D to pane B. Pin both
5413        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5414            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5415        });
5416        let item_c = add_labeled_item(&pane_b, "C", false, cx);
5417        let item_d = add_labeled_item(&pane_b, "D", false, cx);
5418        pane_b.update_in(cx, |pane, window, cx| {
5419            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5420            pane.pin_tab_at(ix, window, cx);
5421
5422            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
5423            pane.pin_tab_at(ix, window, cx);
5424        });
5425        assert_item_labels(&pane_b, ["C!", "D*!"], cx);
5426
5427        // Add a third unpinned item to pane B (exceeds max tabs), but is allowed,
5428        // as we allow 1 tab over max if the others are pinned or dirty
5429        add_labeled_item(&pane_b, "E", false, cx);
5430        assert_item_labels(&pane_b, ["C!", "D!", "E*"], cx);
5431
5432        // Drag pinned A from pane A to position 0 in pane B
5433        pane_b.update_in(cx, |pane, window, cx| {
5434            let dragged_tab = DraggedTab {
5435                pane: pane_a.clone(),
5436                item: item_a.boxed_clone(),
5437                ix: 0,
5438                detail: 0,
5439                is_active: true,
5440            };
5441            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5442        });
5443
5444        // E (unpinned) should be closed, leaving 3 pinned items
5445        assert_item_labels(&pane_a, ["B*!"], cx);
5446        assert_item_labels(&pane_b, ["A*!", "C!", "D!"], cx);
5447    }
5448
5449    #[gpui::test]
5450    async fn test_drag_last_pinned_tab_to_same_position_stays_pinned(cx: &mut TestAppContext) {
5451        init_test(cx);
5452        let fs = FakeFs::new(cx.executor());
5453
5454        let project = Project::test(fs, None, cx).await;
5455        let (workspace, cx) =
5456            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5457        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5458
5459        // Add A to pane A and pin it
5460        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5461        pane_a.update_in(cx, |pane, window, cx| {
5462            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5463            pane.pin_tab_at(ix, window, cx);
5464        });
5465        assert_item_labels(&pane_a, ["A*!"], cx);
5466
5467        // Drag pinned A to position 1 (directly to the right) in the same pane
5468        pane_a.update_in(cx, |pane, window, cx| {
5469            let dragged_tab = DraggedTab {
5470                pane: pane_a.clone(),
5471                item: item_a.boxed_clone(),
5472                ix: 0,
5473                detail: 0,
5474                is_active: true,
5475            };
5476            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5477        });
5478
5479        // A should still be pinned and active
5480        assert_item_labels(&pane_a, ["A*!"], cx);
5481    }
5482
5483    #[gpui::test]
5484    async fn test_drag_pinned_tab_beyond_last_pinned_tab_in_same_pane_stays_pinned(
5485        cx: &mut TestAppContext,
5486    ) {
5487        init_test(cx);
5488        let fs = FakeFs::new(cx.executor());
5489
5490        let project = Project::test(fs, None, cx).await;
5491        let (workspace, cx) =
5492            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5493        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5494
5495        // Add A, B to pane A and pin both
5496        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5497        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5498        pane_a.update_in(cx, |pane, window, cx| {
5499            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5500            pane.pin_tab_at(ix, window, cx);
5501
5502            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5503            pane.pin_tab_at(ix, window, cx);
5504        });
5505        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5506
5507        // Drag pinned A right of B in the same pane
5508        pane_a.update_in(cx, |pane, window, cx| {
5509            let dragged_tab = DraggedTab {
5510                pane: pane_a.clone(),
5511                item: item_a.boxed_clone(),
5512                ix: 0,
5513                detail: 0,
5514                is_active: true,
5515            };
5516            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5517        });
5518
5519        // A stays pinned
5520        assert_item_labels(&pane_a, ["B!", "A*!"], cx);
5521    }
5522
5523    #[gpui::test]
5524    async fn test_dragging_pinned_tab_onto_unpinned_tab_reduces_unpinned_tab_count(
5525        cx: &mut TestAppContext,
5526    ) {
5527        init_test(cx);
5528        let fs = FakeFs::new(cx.executor());
5529
5530        let project = Project::test(fs, None, cx).await;
5531        let (workspace, cx) =
5532            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5533        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5534
5535        // Add A, B to pane A and pin A
5536        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5537        add_labeled_item(&pane_a, "B", false, cx);
5538        pane_a.update_in(cx, |pane, window, cx| {
5539            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5540            pane.pin_tab_at(ix, window, cx);
5541        });
5542        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5543
5544        // Drag pinned A on top of B in the same pane, which changes tab order to B, A
5545        pane_a.update_in(cx, |pane, window, cx| {
5546            let dragged_tab = DraggedTab {
5547                pane: pane_a.clone(),
5548                item: item_a.boxed_clone(),
5549                ix: 0,
5550                detail: 0,
5551                is_active: true,
5552            };
5553            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5554        });
5555
5556        // Neither are pinned
5557        assert_item_labels(&pane_a, ["B", "A*"], cx);
5558    }
5559
5560    #[gpui::test]
5561    async fn test_drag_pinned_tab_beyond_unpinned_tab_in_same_pane_becomes_unpinned(
5562        cx: &mut TestAppContext,
5563    ) {
5564        init_test(cx);
5565        let fs = FakeFs::new(cx.executor());
5566
5567        let project = Project::test(fs, None, cx).await;
5568        let (workspace, cx) =
5569            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5570        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5571
5572        // Add A, B to pane A and pin A
5573        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5574        add_labeled_item(&pane_a, "B", false, cx);
5575        pane_a.update_in(cx, |pane, window, cx| {
5576            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5577            pane.pin_tab_at(ix, window, cx);
5578        });
5579        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5580
5581        // Drag pinned A right of B in the same pane
5582        pane_a.update_in(cx, |pane, window, cx| {
5583            let dragged_tab = DraggedTab {
5584                pane: pane_a.clone(),
5585                item: item_a.boxed_clone(),
5586                ix: 0,
5587                detail: 0,
5588                is_active: true,
5589            };
5590            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5591        });
5592
5593        // A becomes unpinned
5594        assert_item_labels(&pane_a, ["B", "A*"], cx);
5595    }
5596
5597    #[gpui::test]
5598    async fn test_drag_unpinned_tab_in_front_of_pinned_tab_in_same_pane_becomes_pinned(
5599        cx: &mut TestAppContext,
5600    ) {
5601        init_test(cx);
5602        let fs = FakeFs::new(cx.executor());
5603
5604        let project = Project::test(fs, None, cx).await;
5605        let (workspace, cx) =
5606            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5607        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5608
5609        // Add A, B to pane A and pin A
5610        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5611        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5612        pane_a.update_in(cx, |pane, window, cx| {
5613            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5614            pane.pin_tab_at(ix, window, cx);
5615        });
5616        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5617
5618        // Drag pinned B left of A in the same pane
5619        pane_a.update_in(cx, |pane, window, cx| {
5620            let dragged_tab = DraggedTab {
5621                pane: pane_a.clone(),
5622                item: item_b.boxed_clone(),
5623                ix: 1,
5624                detail: 0,
5625                is_active: true,
5626            };
5627            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5628        });
5629
5630        // A becomes unpinned
5631        assert_item_labels(&pane_a, ["B*!", "A!"], cx);
5632    }
5633
5634    #[gpui::test]
5635    async fn test_drag_unpinned_tab_to_the_pinned_region_stays_pinned(cx: &mut TestAppContext) {
5636        init_test(cx);
5637        let fs = FakeFs::new(cx.executor());
5638
5639        let project = Project::test(fs, None, cx).await;
5640        let (workspace, cx) =
5641            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5642        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5643
5644        // Add A, B, C to pane A and pin A
5645        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5646        add_labeled_item(&pane_a, "B", false, cx);
5647        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5648        pane_a.update_in(cx, |pane, window, cx| {
5649            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5650            pane.pin_tab_at(ix, window, cx);
5651        });
5652        assert_item_labels(&pane_a, ["A!", "B", "C*"], cx);
5653
5654        // Drag pinned C left of B in the same pane
5655        pane_a.update_in(cx, |pane, window, cx| {
5656            let dragged_tab = DraggedTab {
5657                pane: pane_a.clone(),
5658                item: item_c.boxed_clone(),
5659                ix: 2,
5660                detail: 0,
5661                is_active: true,
5662            };
5663            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5664        });
5665
5666        // A stays pinned, B and C remain unpinned
5667        assert_item_labels(&pane_a, ["A!", "C*", "B"], cx);
5668    }
5669
5670    #[gpui::test]
5671    async fn test_drag_unpinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5672        init_test(cx);
5673        let fs = FakeFs::new(cx.executor());
5674
5675        let project = Project::test(fs, None, cx).await;
5676        let (workspace, cx) =
5677            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5678        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5679
5680        // Add unpinned item A to pane A
5681        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5682        assert_item_labels(&pane_a, ["A*"], cx);
5683
5684        // Create pane B with pinned item B
5685        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5686            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5687        });
5688        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5689        pane_b.update_in(cx, |pane, window, cx| {
5690            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5691            pane.pin_tab_at(ix, window, cx);
5692        });
5693        assert_item_labels(&pane_b, ["B*!"], cx);
5694
5695        // Move A from pane A to pane B's pinned region
5696        pane_b.update_in(cx, |pane, window, cx| {
5697            let dragged_tab = DraggedTab {
5698                pane: pane_a.clone(),
5699                item: item_a.boxed_clone(),
5700                ix: 0,
5701                detail: 0,
5702                is_active: true,
5703            };
5704            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5705        });
5706
5707        // A should become pinned since it was dropped in the pinned region
5708        assert_item_labels(&pane_a, [], cx);
5709        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5710    }
5711
5712    #[gpui::test]
5713    async fn test_drag_unpinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5714        init_test(cx);
5715        let fs = FakeFs::new(cx.executor());
5716
5717        let project = Project::test(fs, None, cx).await;
5718        let (workspace, cx) =
5719            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5720        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5721
5722        // Add unpinned item A to pane A
5723        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5724        assert_item_labels(&pane_a, ["A*"], cx);
5725
5726        // Create pane B with one pinned item B
5727        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5728            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5729        });
5730        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5731        pane_b.update_in(cx, |pane, window, cx| {
5732            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5733            pane.pin_tab_at(ix, window, cx);
5734        });
5735        assert_item_labels(&pane_b, ["B*!"], cx);
5736
5737        // Move A from pane A to pane B's unpinned region
5738        pane_b.update_in(cx, |pane, window, cx| {
5739            let dragged_tab = DraggedTab {
5740                pane: pane_a.clone(),
5741                item: item_a.boxed_clone(),
5742                ix: 0,
5743                detail: 0,
5744                is_active: true,
5745            };
5746            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5747        });
5748
5749        // A should remain unpinned since it was dropped outside the pinned region
5750        assert_item_labels(&pane_a, [], cx);
5751        assert_item_labels(&pane_b, ["B!", "A*"], cx);
5752    }
5753
5754    #[gpui::test]
5755    async fn test_drag_pinned_tab_throughout_entire_range_of_pinned_tabs_both_directions(
5756        cx: &mut TestAppContext,
5757    ) {
5758        init_test(cx);
5759        let fs = FakeFs::new(cx.executor());
5760
5761        let project = Project::test(fs, None, cx).await;
5762        let (workspace, cx) =
5763            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5764        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5765
5766        // Add A, B, C and pin all
5767        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5768        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5769        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5770        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5771
5772        pane_a.update_in(cx, |pane, window, cx| {
5773            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5774            pane.pin_tab_at(ix, window, cx);
5775
5776            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5777            pane.pin_tab_at(ix, window, cx);
5778
5779            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5780            pane.pin_tab_at(ix, window, cx);
5781        });
5782        assert_item_labels(&pane_a, ["A!", "B!", "C*!"], cx);
5783
5784        // Move A to right of B
5785        pane_a.update_in(cx, |pane, window, cx| {
5786            let dragged_tab = DraggedTab {
5787                pane: pane_a.clone(),
5788                item: item_a.boxed_clone(),
5789                ix: 0,
5790                detail: 0,
5791                is_active: true,
5792            };
5793            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5794        });
5795
5796        // A should be after B and all are pinned
5797        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5798
5799        // Move A to right of C
5800        pane_a.update_in(cx, |pane, window, cx| {
5801            let dragged_tab = DraggedTab {
5802                pane: pane_a.clone(),
5803                item: item_a.boxed_clone(),
5804                ix: 1,
5805                detail: 0,
5806                is_active: true,
5807            };
5808            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5809        });
5810
5811        // A should be after C and all are pinned
5812        assert_item_labels(&pane_a, ["B!", "C!", "A*!"], cx);
5813
5814        // Move A to left of C
5815        pane_a.update_in(cx, |pane, window, cx| {
5816            let dragged_tab = DraggedTab {
5817                pane: pane_a.clone(),
5818                item: item_a.boxed_clone(),
5819                ix: 2,
5820                detail: 0,
5821                is_active: true,
5822            };
5823            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5824        });
5825
5826        // A should be before C and all are pinned
5827        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5828
5829        // Move A to left of B
5830        pane_a.update_in(cx, |pane, window, cx| {
5831            let dragged_tab = DraggedTab {
5832                pane: pane_a.clone(),
5833                item: item_a.boxed_clone(),
5834                ix: 1,
5835                detail: 0,
5836                is_active: true,
5837            };
5838            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5839        });
5840
5841        // A should be before B and all are pinned
5842        assert_item_labels(&pane_a, ["A*!", "B!", "C!"], cx);
5843    }
5844
5845    #[gpui::test]
5846    async fn test_drag_first_tab_to_last_position(cx: &mut TestAppContext) {
5847        init_test(cx);
5848        let fs = FakeFs::new(cx.executor());
5849
5850        let project = Project::test(fs, None, cx).await;
5851        let (workspace, cx) =
5852            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5853        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5854
5855        // Add A, B, C
5856        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5857        add_labeled_item(&pane_a, "B", false, cx);
5858        add_labeled_item(&pane_a, "C", false, cx);
5859        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5860
5861        // Move A to the end
5862        pane_a.update_in(cx, |pane, window, cx| {
5863            let dragged_tab = DraggedTab {
5864                pane: pane_a.clone(),
5865                item: item_a.boxed_clone(),
5866                ix: 0,
5867                detail: 0,
5868                is_active: true,
5869            };
5870            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5871        });
5872
5873        // A should be at the end
5874        assert_item_labels(&pane_a, ["B", "C", "A*"], cx);
5875    }
5876
5877    #[gpui::test]
5878    async fn test_drag_last_tab_to_first_position(cx: &mut TestAppContext) {
5879        init_test(cx);
5880        let fs = FakeFs::new(cx.executor());
5881
5882        let project = Project::test(fs, None, cx).await;
5883        let (workspace, cx) =
5884            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5885        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5886
5887        // Add A, B, C
5888        add_labeled_item(&pane_a, "A", false, cx);
5889        add_labeled_item(&pane_a, "B", false, cx);
5890        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5891        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5892
5893        // Move C to the beginning
5894        pane_a.update_in(cx, |pane, window, cx| {
5895            let dragged_tab = DraggedTab {
5896                pane: pane_a.clone(),
5897                item: item_c.boxed_clone(),
5898                ix: 2,
5899                detail: 0,
5900                is_active: true,
5901            };
5902            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5903        });
5904
5905        // C should be at the beginning
5906        assert_item_labels(&pane_a, ["C*", "A", "B"], cx);
5907    }
5908
5909    #[gpui::test]
5910    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
5911        init_test(cx);
5912        let fs = FakeFs::new(cx.executor());
5913
5914        let project = Project::test(fs, None, cx).await;
5915        let (workspace, cx) =
5916            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5917        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5918
5919        // 1. Add with a destination index
5920        //   a. Add before the active item
5921        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5922        pane.update_in(cx, |pane, window, cx| {
5923            pane.add_item(
5924                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5925                false,
5926                false,
5927                Some(0),
5928                window,
5929                cx,
5930            );
5931        });
5932        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5933
5934        //   b. Add after the active item
5935        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5936        pane.update_in(cx, |pane, window, cx| {
5937            pane.add_item(
5938                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5939                false,
5940                false,
5941                Some(2),
5942                window,
5943                cx,
5944            );
5945        });
5946        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5947
5948        //   c. Add at the end of the item list (including off the length)
5949        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5950        pane.update_in(cx, |pane, window, cx| {
5951            pane.add_item(
5952                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5953                false,
5954                false,
5955                Some(5),
5956                window,
5957                cx,
5958            );
5959        });
5960        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5961
5962        // 2. Add without a destination index
5963        //   a. Add with active item at the start of the item list
5964        set_labeled_items(&pane, ["A*", "B", "C"], cx);
5965        pane.update_in(cx, |pane, window, cx| {
5966            pane.add_item(
5967                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5968                false,
5969                false,
5970                None,
5971                window,
5972                cx,
5973            );
5974        });
5975        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
5976
5977        //   b. Add with active item at the end of the item list
5978        set_labeled_items(&pane, ["A", "B", "C*"], cx);
5979        pane.update_in(cx, |pane, window, cx| {
5980            pane.add_item(
5981                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5982                false,
5983                false,
5984                None,
5985                window,
5986                cx,
5987            );
5988        });
5989        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5990    }
5991
5992    #[gpui::test]
5993    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
5994        init_test(cx);
5995        let fs = FakeFs::new(cx.executor());
5996
5997        let project = Project::test(fs, None, cx).await;
5998        let (workspace, cx) =
5999            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6000        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6001
6002        // 1. Add with a destination index
6003        //   1a. Add before the active item
6004        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
6005        pane.update_in(cx, |pane, window, cx| {
6006            pane.add_item(d, false, false, Some(0), window, cx);
6007        });
6008        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
6009
6010        //   1b. Add after the active item
6011        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
6012        pane.update_in(cx, |pane, window, cx| {
6013            pane.add_item(d, false, false, Some(2), window, cx);
6014        });
6015        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
6016
6017        //   1c. Add at the end of the item list (including off the length)
6018        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
6019        pane.update_in(cx, |pane, window, cx| {
6020            pane.add_item(a, false, false, Some(5), window, cx);
6021        });
6022        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
6023
6024        //   1d. Add same item to active index
6025        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
6026        pane.update_in(cx, |pane, window, cx| {
6027            pane.add_item(b, false, false, Some(1), window, cx);
6028        });
6029        assert_item_labels(&pane, ["A", "B*", "C"], cx);
6030
6031        //   1e. Add item to index after same item in last position
6032        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
6033        pane.update_in(cx, |pane, window, cx| {
6034            pane.add_item(c, false, false, Some(2), window, cx);
6035        });
6036        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6037
6038        // 2. Add without a destination index
6039        //   2a. Add with active item at the start of the item list
6040        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
6041        pane.update_in(cx, |pane, window, cx| {
6042            pane.add_item(d, false, false, None, window, cx);
6043        });
6044        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
6045
6046        //   2b. Add with active item at the end of the item list
6047        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
6048        pane.update_in(cx, |pane, window, cx| {
6049            pane.add_item(a, false, false, None, window, cx);
6050        });
6051        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
6052
6053        //   2c. Add active item to active item at end of list
6054        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
6055        pane.update_in(cx, |pane, window, cx| {
6056            pane.add_item(c, false, false, None, window, cx);
6057        });
6058        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6059
6060        //   2d. Add active item to active item at start of list
6061        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
6062        pane.update_in(cx, |pane, window, cx| {
6063            pane.add_item(a, false, false, None, window, cx);
6064        });
6065        assert_item_labels(&pane, ["A*", "B", "C"], cx);
6066    }
6067
6068    #[gpui::test]
6069    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
6070        init_test(cx);
6071        let fs = FakeFs::new(cx.executor());
6072
6073        let project = Project::test(fs, None, cx).await;
6074        let (workspace, cx) =
6075            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6076        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6077
6078        // singleton view
6079        pane.update_in(cx, |pane, window, cx| {
6080            pane.add_item(
6081                Box::new(cx.new(|cx| {
6082                    TestItem::new(cx)
6083                        .with_buffer_kind(ItemBufferKind::Singleton)
6084                        .with_label("buffer 1")
6085                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
6086                })),
6087                false,
6088                false,
6089                None,
6090                window,
6091                cx,
6092            );
6093        });
6094        assert_item_labels(&pane, ["buffer 1*"], cx);
6095
6096        // new singleton view with the same project entry
6097        pane.update_in(cx, |pane, window, cx| {
6098            pane.add_item(
6099                Box::new(cx.new(|cx| {
6100                    TestItem::new(cx)
6101                        .with_buffer_kind(ItemBufferKind::Singleton)
6102                        .with_label("buffer 1")
6103                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
6104                })),
6105                false,
6106                false,
6107                None,
6108                window,
6109                cx,
6110            );
6111        });
6112        assert_item_labels(&pane, ["buffer 1*"], cx);
6113
6114        // new singleton view with different project entry
6115        pane.update_in(cx, |pane, window, cx| {
6116            pane.add_item(
6117                Box::new(cx.new(|cx| {
6118                    TestItem::new(cx)
6119                        .with_buffer_kind(ItemBufferKind::Singleton)
6120                        .with_label("buffer 2")
6121                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
6122                })),
6123                false,
6124                false,
6125                None,
6126                window,
6127                cx,
6128            );
6129        });
6130        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
6131
6132        // new multibuffer view with the same project entry
6133        pane.update_in(cx, |pane, window, cx| {
6134            pane.add_item(
6135                Box::new(cx.new(|cx| {
6136                    TestItem::new(cx)
6137                        .with_buffer_kind(ItemBufferKind::Multibuffer)
6138                        .with_label("multibuffer 1")
6139                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
6140                })),
6141                false,
6142                false,
6143                None,
6144                window,
6145                cx,
6146            );
6147        });
6148        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
6149
6150        // another multibuffer view with the same project entry
6151        pane.update_in(cx, |pane, window, cx| {
6152            pane.add_item(
6153                Box::new(cx.new(|cx| {
6154                    TestItem::new(cx)
6155                        .with_buffer_kind(ItemBufferKind::Multibuffer)
6156                        .with_label("multibuffer 1b")
6157                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
6158                })),
6159                false,
6160                false,
6161                None,
6162                window,
6163                cx,
6164            );
6165        });
6166        assert_item_labels(
6167            &pane,
6168            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
6169            cx,
6170        );
6171    }
6172
6173    #[gpui::test]
6174    async fn test_remove_item_ordering_history(cx: &mut TestAppContext) {
6175        init_test(cx);
6176        let fs = FakeFs::new(cx.executor());
6177
6178        let project = Project::test(fs, None, cx).await;
6179        let (workspace, cx) =
6180            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6181        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6182
6183        add_labeled_item(&pane, "A", false, cx);
6184        add_labeled_item(&pane, "B", false, cx);
6185        add_labeled_item(&pane, "C", false, cx);
6186        add_labeled_item(&pane, "D", false, cx);
6187        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6188
6189        pane.update_in(cx, |pane, window, cx| {
6190            pane.activate_item(1, false, false, window, cx)
6191        });
6192        add_labeled_item(&pane, "1", false, cx);
6193        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6194
6195        pane.update_in(cx, |pane, window, cx| {
6196            pane.close_active_item(
6197                &CloseActiveItem {
6198                    save_intent: None,
6199                    close_pinned: false,
6200                },
6201                window,
6202                cx,
6203            )
6204        })
6205        .await
6206        .unwrap();
6207        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
6208
6209        pane.update_in(cx, |pane, window, cx| {
6210            pane.activate_item(3, false, false, window, cx)
6211        });
6212        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6213
6214        pane.update_in(cx, |pane, window, cx| {
6215            pane.close_active_item(
6216                &CloseActiveItem {
6217                    save_intent: None,
6218                    close_pinned: false,
6219                },
6220                window,
6221                cx,
6222            )
6223        })
6224        .await
6225        .unwrap();
6226        assert_item_labels(&pane, ["A", "B*", "C"], cx);
6227
6228        pane.update_in(cx, |pane, window, cx| {
6229            pane.close_active_item(
6230                &CloseActiveItem {
6231                    save_intent: None,
6232                    close_pinned: false,
6233                },
6234                window,
6235                cx,
6236            )
6237        })
6238        .await
6239        .unwrap();
6240        assert_item_labels(&pane, ["A", "C*"], cx);
6241
6242        pane.update_in(cx, |pane, window, cx| {
6243            pane.close_active_item(
6244                &CloseActiveItem {
6245                    save_intent: None,
6246                    close_pinned: false,
6247                },
6248                window,
6249                cx,
6250            )
6251        })
6252        .await
6253        .unwrap();
6254        assert_item_labels(&pane, ["A*"], cx);
6255    }
6256
6257    #[gpui::test]
6258    async fn test_remove_item_ordering_neighbour(cx: &mut TestAppContext) {
6259        init_test(cx);
6260        cx.update_global::<SettingsStore, ()>(|s, cx| {
6261            s.update_user_settings(cx, |s| {
6262                s.tabs.get_or_insert_default().activate_on_close = Some(ActivateOnClose::Neighbour);
6263            });
6264        });
6265        let fs = FakeFs::new(cx.executor());
6266
6267        let project = Project::test(fs, None, cx).await;
6268        let (workspace, cx) =
6269            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6270        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6271
6272        add_labeled_item(&pane, "A", false, cx);
6273        add_labeled_item(&pane, "B", false, cx);
6274        add_labeled_item(&pane, "C", false, cx);
6275        add_labeled_item(&pane, "D", false, cx);
6276        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6277
6278        pane.update_in(cx, |pane, window, cx| {
6279            pane.activate_item(1, false, false, window, cx)
6280        });
6281        add_labeled_item(&pane, "1", false, cx);
6282        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6283
6284        pane.update_in(cx, |pane, window, cx| {
6285            pane.close_active_item(
6286                &CloseActiveItem {
6287                    save_intent: None,
6288                    close_pinned: false,
6289                },
6290                window,
6291                cx,
6292            )
6293        })
6294        .await
6295        .unwrap();
6296        assert_item_labels(&pane, ["A", "B", "C*", "D"], cx);
6297
6298        pane.update_in(cx, |pane, window, cx| {
6299            pane.activate_item(3, false, false, window, cx)
6300        });
6301        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6302
6303        pane.update_in(cx, |pane, window, cx| {
6304            pane.close_active_item(
6305                &CloseActiveItem {
6306                    save_intent: None,
6307                    close_pinned: false,
6308                },
6309                window,
6310                cx,
6311            )
6312        })
6313        .await
6314        .unwrap();
6315        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6316
6317        pane.update_in(cx, |pane, window, cx| {
6318            pane.close_active_item(
6319                &CloseActiveItem {
6320                    save_intent: None,
6321                    close_pinned: false,
6322                },
6323                window,
6324                cx,
6325            )
6326        })
6327        .await
6328        .unwrap();
6329        assert_item_labels(&pane, ["A", "B*"], cx);
6330
6331        pane.update_in(cx, |pane, window, cx| {
6332            pane.close_active_item(
6333                &CloseActiveItem {
6334                    save_intent: None,
6335                    close_pinned: false,
6336                },
6337                window,
6338                cx,
6339            )
6340        })
6341        .await
6342        .unwrap();
6343        assert_item_labels(&pane, ["A*"], cx);
6344    }
6345
6346    #[gpui::test]
6347    async fn test_remove_item_ordering_left_neighbour(cx: &mut TestAppContext) {
6348        init_test(cx);
6349        cx.update_global::<SettingsStore, ()>(|s, cx| {
6350            s.update_user_settings(cx, |s| {
6351                s.tabs.get_or_insert_default().activate_on_close =
6352                    Some(ActivateOnClose::LeftNeighbour);
6353            });
6354        });
6355        let fs = FakeFs::new(cx.executor());
6356
6357        let project = Project::test(fs, None, cx).await;
6358        let (workspace, cx) =
6359            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6360        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6361
6362        add_labeled_item(&pane, "A", false, cx);
6363        add_labeled_item(&pane, "B", false, cx);
6364        add_labeled_item(&pane, "C", false, cx);
6365        add_labeled_item(&pane, "D", false, cx);
6366        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6367
6368        pane.update_in(cx, |pane, window, cx| {
6369            pane.activate_item(1, false, false, window, cx)
6370        });
6371        add_labeled_item(&pane, "1", false, cx);
6372        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6373
6374        pane.update_in(cx, |pane, window, cx| {
6375            pane.close_active_item(
6376                &CloseActiveItem {
6377                    save_intent: None,
6378                    close_pinned: false,
6379                },
6380                window,
6381                cx,
6382            )
6383        })
6384        .await
6385        .unwrap();
6386        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
6387
6388        pane.update_in(cx, |pane, window, cx| {
6389            pane.activate_item(3, false, false, window, cx)
6390        });
6391        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6392
6393        pane.update_in(cx, |pane, window, cx| {
6394            pane.close_active_item(
6395                &CloseActiveItem {
6396                    save_intent: None,
6397                    close_pinned: false,
6398                },
6399                window,
6400                cx,
6401            )
6402        })
6403        .await
6404        .unwrap();
6405        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6406
6407        pane.update_in(cx, |pane, window, cx| {
6408            pane.activate_item(0, false, false, window, cx)
6409        });
6410        assert_item_labels(&pane, ["A*", "B", "C"], cx);
6411
6412        pane.update_in(cx, |pane, window, cx| {
6413            pane.close_active_item(
6414                &CloseActiveItem {
6415                    save_intent: None,
6416                    close_pinned: false,
6417                },
6418                window,
6419                cx,
6420            )
6421        })
6422        .await
6423        .unwrap();
6424        assert_item_labels(&pane, ["B*", "C"], cx);
6425
6426        pane.update_in(cx, |pane, window, cx| {
6427            pane.close_active_item(
6428                &CloseActiveItem {
6429                    save_intent: None,
6430                    close_pinned: false,
6431                },
6432                window,
6433                cx,
6434            )
6435        })
6436        .await
6437        .unwrap();
6438        assert_item_labels(&pane, ["C*"], cx);
6439    }
6440
6441    #[gpui::test]
6442    async fn test_close_inactive_items(cx: &mut TestAppContext) {
6443        init_test(cx);
6444        let fs = FakeFs::new(cx.executor());
6445
6446        let project = Project::test(fs, None, cx).await;
6447        let (workspace, cx) =
6448            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6449        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6450
6451        let item_a = add_labeled_item(&pane, "A", false, cx);
6452        pane.update_in(cx, |pane, window, cx| {
6453            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6454            pane.pin_tab_at(ix, window, cx);
6455        });
6456        assert_item_labels(&pane, ["A*!"], cx);
6457
6458        let item_b = add_labeled_item(&pane, "B", false, cx);
6459        pane.update_in(cx, |pane, window, cx| {
6460            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6461            pane.pin_tab_at(ix, window, cx);
6462        });
6463        assert_item_labels(&pane, ["A!", "B*!"], cx);
6464
6465        add_labeled_item(&pane, "C", false, cx);
6466        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
6467
6468        add_labeled_item(&pane, "D", false, cx);
6469        add_labeled_item(&pane, "E", false, cx);
6470        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
6471
6472        pane.update_in(cx, |pane, window, cx| {
6473            pane.close_other_items(
6474                &CloseOtherItems {
6475                    save_intent: None,
6476                    close_pinned: false,
6477                },
6478                None,
6479                window,
6480                cx,
6481            )
6482        })
6483        .await
6484        .unwrap();
6485        assert_item_labels(&pane, ["A!", "B!", "E*"], cx);
6486    }
6487
6488    #[gpui::test]
6489    async fn test_running_close_inactive_items_via_an_inactive_item(cx: &mut TestAppContext) {
6490        init_test(cx);
6491        let fs = FakeFs::new(cx.executor());
6492
6493        let project = Project::test(fs, None, cx).await;
6494        let (workspace, cx) =
6495            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6496        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6497
6498        add_labeled_item(&pane, "A", false, cx);
6499        assert_item_labels(&pane, ["A*"], cx);
6500
6501        let item_b = add_labeled_item(&pane, "B", false, cx);
6502        assert_item_labels(&pane, ["A", "B*"], cx);
6503
6504        add_labeled_item(&pane, "C", false, cx);
6505        add_labeled_item(&pane, "D", false, cx);
6506        add_labeled_item(&pane, "E", false, cx);
6507        assert_item_labels(&pane, ["A", "B", "C", "D", "E*"], cx);
6508
6509        pane.update_in(cx, |pane, window, cx| {
6510            pane.close_other_items(
6511                &CloseOtherItems {
6512                    save_intent: None,
6513                    close_pinned: false,
6514                },
6515                Some(item_b.item_id()),
6516                window,
6517                cx,
6518            )
6519        })
6520        .await
6521        .unwrap();
6522        assert_item_labels(&pane, ["B*"], cx);
6523    }
6524
6525    #[gpui::test]
6526    async fn test_close_clean_items(cx: &mut TestAppContext) {
6527        init_test(cx);
6528        let fs = FakeFs::new(cx.executor());
6529
6530        let project = Project::test(fs, None, cx).await;
6531        let (workspace, cx) =
6532            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6533        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6534
6535        add_labeled_item(&pane, "A", true, cx);
6536        add_labeled_item(&pane, "B", false, cx);
6537        add_labeled_item(&pane, "C", true, cx);
6538        add_labeled_item(&pane, "D", false, cx);
6539        add_labeled_item(&pane, "E", false, cx);
6540        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
6541
6542        pane.update_in(cx, |pane, window, cx| {
6543            pane.close_clean_items(
6544                &CloseCleanItems {
6545                    close_pinned: false,
6546                },
6547                window,
6548                cx,
6549            )
6550        })
6551        .await
6552        .unwrap();
6553        assert_item_labels(&pane, ["A^", "C*^"], cx);
6554    }
6555
6556    #[gpui::test]
6557    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
6558        init_test(cx);
6559        let fs = FakeFs::new(cx.executor());
6560
6561        let project = Project::test(fs, None, cx).await;
6562        let (workspace, cx) =
6563            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6564        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6565
6566        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6567
6568        pane.update_in(cx, |pane, window, cx| {
6569            pane.close_items_to_the_left_by_id(
6570                None,
6571                &CloseItemsToTheLeft {
6572                    close_pinned: false,
6573                },
6574                window,
6575                cx,
6576            )
6577        })
6578        .await
6579        .unwrap();
6580        assert_item_labels(&pane, ["C*", "D", "E"], cx);
6581    }
6582
6583    #[gpui::test]
6584    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
6585        init_test(cx);
6586        let fs = FakeFs::new(cx.executor());
6587
6588        let project = Project::test(fs, None, cx).await;
6589        let (workspace, cx) =
6590            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6591        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6592
6593        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6594
6595        pane.update_in(cx, |pane, window, cx| {
6596            pane.close_items_to_the_right_by_id(
6597                None,
6598                &CloseItemsToTheRight {
6599                    close_pinned: false,
6600                },
6601                window,
6602                cx,
6603            )
6604        })
6605        .await
6606        .unwrap();
6607        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6608    }
6609
6610    #[gpui::test]
6611    async fn test_close_all_items(cx: &mut TestAppContext) {
6612        init_test(cx);
6613        let fs = FakeFs::new(cx.executor());
6614
6615        let project = Project::test(fs, None, cx).await;
6616        let (workspace, cx) =
6617            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6618        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6619
6620        let item_a = add_labeled_item(&pane, "A", false, cx);
6621        add_labeled_item(&pane, "B", false, cx);
6622        add_labeled_item(&pane, "C", false, cx);
6623        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6624
6625        pane.update_in(cx, |pane, window, cx| {
6626            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6627            pane.pin_tab_at(ix, window, cx);
6628            pane.close_all_items(
6629                &CloseAllItems {
6630                    save_intent: None,
6631                    close_pinned: false,
6632                },
6633                window,
6634                cx,
6635            )
6636        })
6637        .await
6638        .unwrap();
6639        assert_item_labels(&pane, ["A*!"], cx);
6640
6641        pane.update_in(cx, |pane, window, cx| {
6642            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6643            pane.unpin_tab_at(ix, window, cx);
6644            pane.close_all_items(
6645                &CloseAllItems {
6646                    save_intent: None,
6647                    close_pinned: false,
6648                },
6649                window,
6650                cx,
6651            )
6652        })
6653        .await
6654        .unwrap();
6655
6656        assert_item_labels(&pane, [], cx);
6657
6658        add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6659            item.project_items
6660                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6661        });
6662        add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6663            item.project_items
6664                .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6665        });
6666        add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6667            item.project_items
6668                .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6669        });
6670        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6671
6672        let save = pane.update_in(cx, |pane, window, cx| {
6673            pane.close_all_items(
6674                &CloseAllItems {
6675                    save_intent: None,
6676                    close_pinned: false,
6677                },
6678                window,
6679                cx,
6680            )
6681        });
6682
6683        cx.executor().run_until_parked();
6684        cx.simulate_prompt_answer("Save all");
6685        save.await.unwrap();
6686        assert_item_labels(&pane, [], cx);
6687
6688        add_labeled_item(&pane, "A", true, cx);
6689        add_labeled_item(&pane, "B", true, cx);
6690        add_labeled_item(&pane, "C", true, cx);
6691        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6692        let save = pane.update_in(cx, |pane, window, cx| {
6693            pane.close_all_items(
6694                &CloseAllItems {
6695                    save_intent: None,
6696                    close_pinned: false,
6697                },
6698                window,
6699                cx,
6700            )
6701        });
6702
6703        cx.executor().run_until_parked();
6704        cx.simulate_prompt_answer("Discard all");
6705        save.await.unwrap();
6706        assert_item_labels(&pane, [], cx);
6707
6708        add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6709            item.project_items
6710                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6711        });
6712        add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6713            item.project_items
6714                .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6715        });
6716        add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6717            item.project_items
6718                .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6719        });
6720        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6721
6722        let close_task = pane.update_in(cx, |pane, window, cx| {
6723            pane.close_all_items(
6724                &CloseAllItems {
6725                    save_intent: None,
6726                    close_pinned: false,
6727                },
6728                window,
6729                cx,
6730            )
6731        });
6732
6733        cx.executor().run_until_parked();
6734        cx.simulate_prompt_answer("Discard all");
6735        close_task.await.unwrap();
6736        assert_item_labels(&pane, [], cx);
6737
6738        add_labeled_item(&pane, "Clean1", false, cx);
6739        add_labeled_item(&pane, "Dirty", true, cx).update(cx, |item, cx| {
6740            item.project_items
6741                .push(TestProjectItem::new_dirty(1, "Dirty.txt", cx))
6742        });
6743        add_labeled_item(&pane, "Clean2", false, cx);
6744        assert_item_labels(&pane, ["Clean1", "Dirty^", "Clean2*"], cx);
6745
6746        let close_task = pane.update_in(cx, |pane, window, cx| {
6747            pane.close_all_items(
6748                &CloseAllItems {
6749                    save_intent: None,
6750                    close_pinned: false,
6751                },
6752                window,
6753                cx,
6754            )
6755        });
6756
6757        cx.executor().run_until_parked();
6758        cx.simulate_prompt_answer("Cancel");
6759        close_task.await.unwrap();
6760        assert_item_labels(&pane, ["Dirty*^"], cx);
6761    }
6762
6763    #[gpui::test]
6764    async fn test_close_multibuffer_items(cx: &mut TestAppContext) {
6765        init_test(cx);
6766        let fs = FakeFs::new(cx.executor());
6767
6768        let project = Project::test(fs, None, cx).await;
6769        let (workspace, cx) =
6770            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6771        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6772
6773        let add_labeled_item = |pane: &Entity<Pane>,
6774                                label,
6775                                is_dirty,
6776                                kind: ItemBufferKind,
6777                                cx: &mut VisualTestContext| {
6778            pane.update_in(cx, |pane, window, cx| {
6779                let labeled_item = Box::new(cx.new(|cx| {
6780                    TestItem::new(cx)
6781                        .with_label(label)
6782                        .with_dirty(is_dirty)
6783                        .with_buffer_kind(kind)
6784                }));
6785                pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6786                labeled_item
6787            })
6788        };
6789
6790        let item_a = add_labeled_item(&pane, "A", false, ItemBufferKind::Multibuffer, cx);
6791        add_labeled_item(&pane, "B", false, ItemBufferKind::Multibuffer, cx);
6792        add_labeled_item(&pane, "C", false, ItemBufferKind::Singleton, cx);
6793        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6794
6795        pane.update_in(cx, |pane, window, cx| {
6796            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6797            pane.pin_tab_at(ix, window, cx);
6798            pane.close_multibuffer_items(
6799                &CloseMultibufferItems {
6800                    save_intent: None,
6801                    close_pinned: false,
6802                },
6803                window,
6804                cx,
6805            )
6806        })
6807        .await
6808        .unwrap();
6809        assert_item_labels(&pane, ["A!", "C*"], cx);
6810
6811        pane.update_in(cx, |pane, window, cx| {
6812            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6813            pane.unpin_tab_at(ix, window, cx);
6814            pane.close_multibuffer_items(
6815                &CloseMultibufferItems {
6816                    save_intent: None,
6817                    close_pinned: false,
6818                },
6819                window,
6820                cx,
6821            )
6822        })
6823        .await
6824        .unwrap();
6825
6826        assert_item_labels(&pane, ["C*"], cx);
6827
6828        add_labeled_item(&pane, "A", true, ItemBufferKind::Singleton, cx).update(cx, |item, cx| {
6829            item.project_items
6830                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6831        });
6832        add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
6833            cx,
6834            |item, cx| {
6835                item.project_items
6836                    .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6837            },
6838        );
6839        add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
6840            cx,
6841            |item, cx| {
6842                item.project_items
6843                    .push(TestProjectItem::new_dirty(3, "D.txt", cx))
6844            },
6845        );
6846        assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
6847
6848        let save = pane.update_in(cx, |pane, window, cx| {
6849            pane.close_multibuffer_items(
6850                &CloseMultibufferItems {
6851                    save_intent: None,
6852                    close_pinned: false,
6853                },
6854                window,
6855                cx,
6856            )
6857        });
6858
6859        cx.executor().run_until_parked();
6860        cx.simulate_prompt_answer("Save all");
6861        save.await.unwrap();
6862        assert_item_labels(&pane, ["C", "A*^"], cx);
6863
6864        add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
6865            cx,
6866            |item, cx| {
6867                item.project_items
6868                    .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6869            },
6870        );
6871        add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
6872            cx,
6873            |item, cx| {
6874                item.project_items
6875                    .push(TestProjectItem::new_dirty(3, "D.txt", cx))
6876            },
6877        );
6878        assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
6879        let save = pane.update_in(cx, |pane, window, cx| {
6880            pane.close_multibuffer_items(
6881                &CloseMultibufferItems {
6882                    save_intent: None,
6883                    close_pinned: false,
6884                },
6885                window,
6886                cx,
6887            )
6888        });
6889
6890        cx.executor().run_until_parked();
6891        cx.simulate_prompt_answer("Discard all");
6892        save.await.unwrap();
6893        assert_item_labels(&pane, ["C", "A*^"], cx);
6894    }
6895
6896    #[gpui::test]
6897    async fn test_close_with_save_intent(cx: &mut TestAppContext) {
6898        init_test(cx);
6899        let fs = FakeFs::new(cx.executor());
6900
6901        let project = Project::test(fs, None, cx).await;
6902        let (workspace, cx) =
6903            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6904        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6905
6906        let a = cx.update(|_, cx| TestProjectItem::new_dirty(1, "A.txt", cx));
6907        let b = cx.update(|_, cx| TestProjectItem::new_dirty(1, "B.txt", cx));
6908        let c = cx.update(|_, cx| TestProjectItem::new_dirty(1, "C.txt", cx));
6909
6910        add_labeled_item(&pane, "AB", true, cx).update(cx, |item, _| {
6911            item.project_items.push(a.clone());
6912            item.project_items.push(b.clone());
6913        });
6914        add_labeled_item(&pane, "C", true, cx)
6915            .update(cx, |item, _| item.project_items.push(c.clone()));
6916        assert_item_labels(&pane, ["AB^", "C*^"], cx);
6917
6918        pane.update_in(cx, |pane, window, cx| {
6919            pane.close_all_items(
6920                &CloseAllItems {
6921                    save_intent: Some(SaveIntent::Save),
6922                    close_pinned: false,
6923                },
6924                window,
6925                cx,
6926            )
6927        })
6928        .await
6929        .unwrap();
6930
6931        assert_item_labels(&pane, [], cx);
6932        cx.update(|_, cx| {
6933            assert!(!a.read(cx).is_dirty);
6934            assert!(!b.read(cx).is_dirty);
6935            assert!(!c.read(cx).is_dirty);
6936        });
6937    }
6938
6939    #[gpui::test]
6940    async fn test_new_tab_scrolls_into_view_completely(cx: &mut TestAppContext) {
6941        // Arrange
6942        init_test(cx);
6943        let fs = FakeFs::new(cx.executor());
6944
6945        let project = Project::test(fs, None, cx).await;
6946        let (workspace, cx) =
6947            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6948        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6949
6950        cx.simulate_resize(size(px(300.), px(300.)));
6951
6952        add_labeled_item(&pane, "untitled", false, cx);
6953        add_labeled_item(&pane, "untitled", false, cx);
6954        add_labeled_item(&pane, "untitled", false, cx);
6955        add_labeled_item(&pane, "untitled", false, cx);
6956        // Act: this should trigger a scroll
6957        add_labeled_item(&pane, "untitled", false, cx);
6958        // Assert
6959        let tab_bar_scroll_handle =
6960            pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
6961        assert_eq!(tab_bar_scroll_handle.children_count(), 6);
6962        let tab_bounds = cx.debug_bounds("TAB-4").unwrap();
6963        let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
6964        let scroll_bounds = tab_bar_scroll_handle.bounds();
6965        let scroll_offset = tab_bar_scroll_handle.offset();
6966        assert!(tab_bounds.right() <= scroll_bounds.right());
6967        // -43.0 is the magic number for this setup
6968        assert_eq!(scroll_offset.x, px(-43.0));
6969        assert!(
6970            !tab_bounds.intersects(&new_tab_button_bounds),
6971            "Tab should not overlap with the new tab button, if this is failing check if there's been a redesign!"
6972        );
6973    }
6974
6975    #[gpui::test]
6976    async fn test_close_all_items_including_pinned(cx: &mut TestAppContext) {
6977        init_test(cx);
6978        let fs = FakeFs::new(cx.executor());
6979
6980        let project = Project::test(fs, None, cx).await;
6981        let (workspace, cx) =
6982            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6983        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6984
6985        let item_a = add_labeled_item(&pane, "A", false, cx);
6986        add_labeled_item(&pane, "B", false, cx);
6987        add_labeled_item(&pane, "C", false, cx);
6988        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6989
6990        pane.update_in(cx, |pane, window, cx| {
6991            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6992            pane.pin_tab_at(ix, window, cx);
6993            pane.close_all_items(
6994                &CloseAllItems {
6995                    save_intent: None,
6996                    close_pinned: true,
6997                },
6998                window,
6999                cx,
7000            )
7001        })
7002        .await
7003        .unwrap();
7004        assert_item_labels(&pane, [], cx);
7005    }
7006
7007    #[gpui::test]
7008    async fn test_close_pinned_tab_with_non_pinned_in_same_pane(cx: &mut TestAppContext) {
7009        init_test(cx);
7010        let fs = FakeFs::new(cx.executor());
7011        let project = Project::test(fs, None, cx).await;
7012        let (workspace, cx) =
7013            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7014
7015        // Non-pinned tabs in same pane
7016        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7017        add_labeled_item(&pane, "A", false, cx);
7018        add_labeled_item(&pane, "B", false, cx);
7019        add_labeled_item(&pane, "C", false, cx);
7020        pane.update_in(cx, |pane, window, cx| {
7021            pane.pin_tab_at(0, window, cx);
7022        });
7023        set_labeled_items(&pane, ["A*", "B", "C"], cx);
7024        pane.update_in(cx, |pane, window, cx| {
7025            pane.close_active_item(
7026                &CloseActiveItem {
7027                    save_intent: None,
7028                    close_pinned: false,
7029                },
7030                window,
7031                cx,
7032            )
7033            .unwrap();
7034        });
7035        // Non-pinned tab should be active
7036        assert_item_labels(&pane, ["A!", "B*", "C"], cx);
7037    }
7038
7039    #[gpui::test]
7040    async fn test_close_pinned_tab_with_non_pinned_in_different_pane(cx: &mut TestAppContext) {
7041        init_test(cx);
7042        let fs = FakeFs::new(cx.executor());
7043        let project = Project::test(fs, None, cx).await;
7044        let (workspace, cx) =
7045            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7046
7047        // No non-pinned tabs in same pane, non-pinned tabs in another pane
7048        let pane1 = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7049        let pane2 = workspace.update_in(cx, |workspace, window, cx| {
7050            workspace.split_pane(pane1.clone(), SplitDirection::Right, window, cx)
7051        });
7052        add_labeled_item(&pane1, "A", false, cx);
7053        pane1.update_in(cx, |pane, window, cx| {
7054            pane.pin_tab_at(0, window, cx);
7055        });
7056        set_labeled_items(&pane1, ["A*"], cx);
7057        add_labeled_item(&pane2, "B", false, cx);
7058        set_labeled_items(&pane2, ["B"], cx);
7059        pane1.update_in(cx, |pane, window, cx| {
7060            pane.close_active_item(
7061                &CloseActiveItem {
7062                    save_intent: None,
7063                    close_pinned: false,
7064                },
7065                window,
7066                cx,
7067            )
7068            .unwrap();
7069        });
7070        //  Non-pinned tab of other pane should be active
7071        assert_item_labels(&pane2, ["B*"], cx);
7072    }
7073
7074    #[gpui::test]
7075    async fn ensure_item_closing_actions_do_not_panic_when_no_items_exist(cx: &mut TestAppContext) {
7076        init_test(cx);
7077        let fs = FakeFs::new(cx.executor());
7078        let project = Project::test(fs, None, cx).await;
7079        let (workspace, cx) =
7080            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7081
7082        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7083        assert_item_labels(&pane, [], cx);
7084
7085        pane.update_in(cx, |pane, window, cx| {
7086            pane.close_active_item(
7087                &CloseActiveItem {
7088                    save_intent: None,
7089                    close_pinned: false,
7090                },
7091                window,
7092                cx,
7093            )
7094        })
7095        .await
7096        .unwrap();
7097
7098        pane.update_in(cx, |pane, window, cx| {
7099            pane.close_other_items(
7100                &CloseOtherItems {
7101                    save_intent: None,
7102                    close_pinned: false,
7103                },
7104                None,
7105                window,
7106                cx,
7107            )
7108        })
7109        .await
7110        .unwrap();
7111
7112        pane.update_in(cx, |pane, window, cx| {
7113            pane.close_all_items(
7114                &CloseAllItems {
7115                    save_intent: None,
7116                    close_pinned: false,
7117                },
7118                window,
7119                cx,
7120            )
7121        })
7122        .await
7123        .unwrap();
7124
7125        pane.update_in(cx, |pane, window, cx| {
7126            pane.close_clean_items(
7127                &CloseCleanItems {
7128                    close_pinned: false,
7129                },
7130                window,
7131                cx,
7132            )
7133        })
7134        .await
7135        .unwrap();
7136
7137        pane.update_in(cx, |pane, window, cx| {
7138            pane.close_items_to_the_right_by_id(
7139                None,
7140                &CloseItemsToTheRight {
7141                    close_pinned: false,
7142                },
7143                window,
7144                cx,
7145            )
7146        })
7147        .await
7148        .unwrap();
7149
7150        pane.update_in(cx, |pane, window, cx| {
7151            pane.close_items_to_the_left_by_id(
7152                None,
7153                &CloseItemsToTheLeft {
7154                    close_pinned: false,
7155                },
7156                window,
7157                cx,
7158            )
7159        })
7160        .await
7161        .unwrap();
7162    }
7163
7164    #[gpui::test]
7165    async fn test_item_swapping_actions(cx: &mut TestAppContext) {
7166        init_test(cx);
7167        let fs = FakeFs::new(cx.executor());
7168        let project = Project::test(fs, None, cx).await;
7169        let (workspace, cx) =
7170            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7171
7172        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7173        assert_item_labels(&pane, [], cx);
7174
7175        // Test that these actions do not panic
7176        pane.update_in(cx, |pane, window, cx| {
7177            pane.swap_item_right(&Default::default(), window, cx);
7178        });
7179
7180        pane.update_in(cx, |pane, window, cx| {
7181            pane.swap_item_left(&Default::default(), window, cx);
7182        });
7183
7184        add_labeled_item(&pane, "A", false, cx);
7185        add_labeled_item(&pane, "B", false, cx);
7186        add_labeled_item(&pane, "C", false, cx);
7187        assert_item_labels(&pane, ["A", "B", "C*"], cx);
7188
7189        pane.update_in(cx, |pane, window, cx| {
7190            pane.swap_item_right(&Default::default(), window, cx);
7191        });
7192        assert_item_labels(&pane, ["A", "B", "C*"], cx);
7193
7194        pane.update_in(cx, |pane, window, cx| {
7195            pane.swap_item_left(&Default::default(), window, cx);
7196        });
7197        assert_item_labels(&pane, ["A", "C*", "B"], cx);
7198
7199        pane.update_in(cx, |pane, window, cx| {
7200            pane.swap_item_left(&Default::default(), window, cx);
7201        });
7202        assert_item_labels(&pane, ["C*", "A", "B"], cx);
7203
7204        pane.update_in(cx, |pane, window, cx| {
7205            pane.swap_item_left(&Default::default(), window, cx);
7206        });
7207        assert_item_labels(&pane, ["C*", "A", "B"], cx);
7208
7209        pane.update_in(cx, |pane, window, cx| {
7210            pane.swap_item_right(&Default::default(), window, cx);
7211        });
7212        assert_item_labels(&pane, ["A", "C*", "B"], cx);
7213    }
7214
7215    #[gpui::test]
7216    async fn test_split_empty(cx: &mut TestAppContext) {
7217        for split_direction in SplitDirection::all() {
7218            test_single_pane_split(["A"], split_direction, SplitMode::EmptyPane, cx).await;
7219        }
7220    }
7221
7222    #[gpui::test]
7223    async fn test_split_clone(cx: &mut TestAppContext) {
7224        for split_direction in SplitDirection::all() {
7225            test_single_pane_split(["A"], split_direction, SplitMode::ClonePane, cx).await;
7226        }
7227    }
7228
7229    #[gpui::test]
7230    async fn test_split_move_right_on_single_pane(cx: &mut TestAppContext) {
7231        test_single_pane_split(["A"], SplitDirection::Right, SplitMode::MovePane, cx).await;
7232    }
7233
7234    #[gpui::test]
7235    async fn test_split_move(cx: &mut TestAppContext) {
7236        for split_direction in SplitDirection::all() {
7237            test_single_pane_split(["A", "B"], split_direction, SplitMode::MovePane, cx).await;
7238        }
7239    }
7240
7241    fn init_test(cx: &mut TestAppContext) {
7242        cx.update(|cx| {
7243            let settings_store = SettingsStore::test(cx);
7244            cx.set_global(settings_store);
7245            theme::init(LoadThemes::JustBase, cx);
7246        });
7247    }
7248
7249    fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
7250        cx.update_global(|store: &mut SettingsStore, cx| {
7251            store.update_user_settings(cx, |settings| {
7252                settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
7253            });
7254        });
7255    }
7256
7257    fn add_labeled_item(
7258        pane: &Entity<Pane>,
7259        label: &str,
7260        is_dirty: bool,
7261        cx: &mut VisualTestContext,
7262    ) -> Box<Entity<TestItem>> {
7263        pane.update_in(cx, |pane, window, cx| {
7264            let labeled_item =
7265                Box::new(cx.new(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)));
7266            pane.add_item(labeled_item.clone(), false, false, None, window, cx);
7267            labeled_item
7268        })
7269    }
7270
7271    fn set_labeled_items<const COUNT: usize>(
7272        pane: &Entity<Pane>,
7273        labels: [&str; COUNT],
7274        cx: &mut VisualTestContext,
7275    ) -> [Box<Entity<TestItem>>; COUNT] {
7276        pane.update_in(cx, |pane, window, cx| {
7277            pane.items.clear();
7278            let mut active_item_index = 0;
7279
7280            let mut index = 0;
7281            let items = labels.map(|mut label| {
7282                if label.ends_with('*') {
7283                    label = label.trim_end_matches('*');
7284                    active_item_index = index;
7285                }
7286
7287                let labeled_item = Box::new(cx.new(|cx| TestItem::new(cx).with_label(label)));
7288                pane.add_item(labeled_item.clone(), false, false, None, window, cx);
7289                index += 1;
7290                labeled_item
7291            });
7292
7293            pane.activate_item(active_item_index, false, false, window, cx);
7294
7295            items
7296        })
7297    }
7298
7299    // Assert the item label, with the active item label suffixed with a '*'
7300    #[track_caller]
7301    fn assert_item_labels<const COUNT: usize>(
7302        pane: &Entity<Pane>,
7303        expected_states: [&str; COUNT],
7304        cx: &mut VisualTestContext,
7305    ) {
7306        let actual_states = pane.update(cx, |pane, cx| {
7307            pane.items
7308                .iter()
7309                .enumerate()
7310                .map(|(ix, item)| {
7311                    let mut state = item
7312                        .to_any_view()
7313                        .downcast::<TestItem>()
7314                        .unwrap()
7315                        .read(cx)
7316                        .label
7317                        .clone();
7318                    if ix == pane.active_item_index {
7319                        state.push('*');
7320                    }
7321                    if item.is_dirty(cx) {
7322                        state.push('^');
7323                    }
7324                    if pane.is_tab_pinned(ix) {
7325                        state.push('!');
7326                    }
7327                    state
7328                })
7329                .collect::<Vec<_>>()
7330        });
7331        assert_eq!(
7332            actual_states, expected_states,
7333            "pane items do not match expectation"
7334        );
7335    }
7336
7337    // Assert the item label, with the active item label expected active index
7338    #[track_caller]
7339    fn assert_item_labels_active_index(
7340        pane: &Entity<Pane>,
7341        expected_states: &[&str],
7342        expected_active_idx: usize,
7343        cx: &mut VisualTestContext,
7344    ) {
7345        let actual_states = pane.update(cx, |pane, cx| {
7346            pane.items
7347                .iter()
7348                .enumerate()
7349                .map(|(ix, item)| {
7350                    let mut state = item
7351                        .to_any_view()
7352                        .downcast::<TestItem>()
7353                        .unwrap()
7354                        .read(cx)
7355                        .label
7356                        .clone();
7357                    if ix == pane.active_item_index {
7358                        assert_eq!(ix, expected_active_idx);
7359                    }
7360                    if item.is_dirty(cx) {
7361                        state.push('^');
7362                    }
7363                    if pane.is_tab_pinned(ix) {
7364                        state.push('!');
7365                    }
7366                    state
7367                })
7368                .collect::<Vec<_>>()
7369        });
7370        assert_eq!(
7371            actual_states, expected_states,
7372            "pane items do not match expectation"
7373        );
7374    }
7375
7376    #[track_caller]
7377    fn assert_pane_ids_on_axis<const COUNT: usize>(
7378        workspace: &Entity<Workspace>,
7379        expected_ids: [&EntityId; COUNT],
7380        expected_axis: Axis,
7381        cx: &mut VisualTestContext,
7382    ) {
7383        workspace.read_with(cx, |workspace, _| match &workspace.center.root {
7384            Member::Axis(axis) => {
7385                assert_eq!(axis.axis, expected_axis);
7386                assert_eq!(axis.members.len(), expected_ids.len());
7387                assert!(
7388                    zip(expected_ids, &axis.members).all(|(e, a)| {
7389                        if let Member::Pane(p) = a {
7390                            p.entity_id() == *e
7391                        } else {
7392                            false
7393                        }
7394                    }),
7395                    "pane ids do not match expectation: {expected_ids:?} != {actual_ids:?}",
7396                    actual_ids = axis.members
7397                );
7398            }
7399            Member::Pane(_) => panic!("expected axis"),
7400        });
7401    }
7402
7403    async fn test_single_pane_split<const COUNT: usize>(
7404        pane_labels: [&str; COUNT],
7405        direction: SplitDirection,
7406        operation: SplitMode,
7407        cx: &mut TestAppContext,
7408    ) {
7409        init_test(cx);
7410        let fs = FakeFs::new(cx.executor());
7411        let project = Project::test(fs, None, cx).await;
7412        let (workspace, cx) =
7413            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7414
7415        let mut pane_before =
7416            workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7417        for label in pane_labels {
7418            add_labeled_item(&pane_before, label, false, cx);
7419        }
7420        pane_before.update_in(cx, |pane, window, cx| {
7421            pane.split(direction, operation, window, cx)
7422        });
7423        cx.executor().run_until_parked();
7424        let pane_after = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7425
7426        let num_labels = pane_labels.len();
7427        let last_as_active = format!("{}*", String::from(pane_labels[num_labels - 1]));
7428
7429        // check labels for all split operations
7430        match operation {
7431            SplitMode::EmptyPane => {
7432                assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
7433                assert_item_labels(&pane_after, [], cx);
7434            }
7435            SplitMode::ClonePane => {
7436                assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
7437                assert_item_labels(&pane_after, [&last_as_active], cx);
7438            }
7439            SplitMode::MovePane => {
7440                let head = &pane_labels[..(num_labels - 1)];
7441                if num_labels == 1 {
7442                    // We special-case this behavior and actually execute an empty pane command
7443                    // followed by a refocus of the old pane for this case.
7444                    pane_before = workspace.read_with(cx, |workspace, _cx| {
7445                        workspace
7446                            .panes()
7447                            .into_iter()
7448                            .find(|pane| *pane != &pane_after)
7449                            .unwrap()
7450                            .clone()
7451                    });
7452                };
7453
7454                assert_item_labels_active_index(
7455                    &pane_before,
7456                    &head,
7457                    head.len().saturating_sub(1),
7458                    cx,
7459                );
7460                assert_item_labels(&pane_after, [&last_as_active], cx);
7461                pane_after.update_in(cx, |pane, window, cx| {
7462                    window.focused(cx).is_some_and(|focus_handle| {
7463                        focus_handle == pane.active_item().unwrap().item_focus_handle(cx)
7464                    })
7465                });
7466            }
7467        }
7468
7469        // expected axis depends on split direction
7470        let expected_axis = match direction {
7471            SplitDirection::Right | SplitDirection::Left => Axis::Horizontal,
7472            SplitDirection::Up | SplitDirection::Down => Axis::Vertical,
7473        };
7474
7475        // expected ids depends on split direction
7476        let expected_ids = match direction {
7477            SplitDirection::Right | SplitDirection::Down => {
7478                [&pane_before.entity_id(), &pane_after.entity_id()]
7479            }
7480            SplitDirection::Left | SplitDirection::Up => {
7481                [&pane_after.entity_id(), &pane_before.entity_id()]
7482            }
7483        };
7484
7485        // check pane axes for all operations
7486        match operation {
7487            SplitMode::EmptyPane | SplitMode::ClonePane => {
7488                assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
7489            }
7490            SplitMode::MovePane => {
7491                assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
7492            }
7493        }
7494    }
7495}