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