pane.rs

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