pane.rs

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