pane.rs

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