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