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