pane.rs

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