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    #[serde(default)]
 202    pub query: Option<String>,
 203    #[serde(default)]
 204    pub regex: Option<bool>,
 205    #[serde(default)]
 206    pub case_sensitive: Option<bool>,
 207    #[serde(default)]
 208    pub whole_word: Option<bool>,
 209    #[serde(default)]
 210    pub include_ignored: Option<bool>,
 211}
 212
 213#[derive(Clone, Copy, PartialEq, Debug, Deserialize, JsonSchema, Default)]
 214#[serde(deny_unknown_fields)]
 215pub enum SplitMode {
 216    /// Clone the current pane.
 217    #[default]
 218    ClonePane,
 219    /// Create an empty new pane.
 220    EmptyPane,
 221    /// Move the item into a new pane. This will map to nop if only one pane exists.
 222    MovePane,
 223}
 224
 225macro_rules! split_structs {
 226    ($($name:ident => $doc:literal),* $(,)?) => {
 227        $(
 228            #[doc = $doc]
 229            #[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
 230            #[action(namespace = pane)]
 231            #[serde(deny_unknown_fields, default)]
 232            pub struct $name {
 233                pub mode: SplitMode,
 234            }
 235        )*
 236    };
 237}
 238
 239split_structs!(
 240    SplitLeft => "Splits the pane to the left.",
 241    SplitRight => "Splits the pane to the right.",
 242    SplitUp => "Splits the pane upward.",
 243    SplitDown => "Splits the pane downward.",
 244    SplitHorizontal => "Splits the pane horizontally.",
 245    SplitVertical => "Splits the pane vertically."
 246);
 247
 248/// Activates the previous item in the pane.
 249#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
 250#[action(namespace = pane)]
 251#[serde(deny_unknown_fields, default)]
 252pub struct ActivatePreviousItem {
 253    /// Whether to wrap from the first item to the last item.
 254    #[serde(default = "default_true")]
 255    pub wrap_around: bool,
 256}
 257
 258impl Default for ActivatePreviousItem {
 259    fn default() -> Self {
 260        Self { wrap_around: true }
 261    }
 262}
 263
 264/// Activates the next item in the pane.
 265#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
 266#[action(namespace = pane)]
 267#[serde(deny_unknown_fields, default)]
 268pub struct ActivateNextItem {
 269    /// Whether to wrap from the last item to the first item.
 270    #[serde(default = "default_true")]
 271    pub wrap_around: bool,
 272}
 273
 274impl Default for ActivateNextItem {
 275    fn default() -> Self {
 276        Self { wrap_around: true }
 277    }
 278}
 279
 280actions!(
 281    pane,
 282    [
 283        /// Activates the last item in the pane.
 284        ActivateLastItem,
 285        /// Switches to the alternate file.
 286        AlternateFile,
 287        /// Navigates back in history.
 288        GoBack,
 289        /// Navigates forward in history.
 290        GoForward,
 291        /// Navigates back in the tag stack.
 292        GoToOlderTag,
 293        /// Navigates forward in the tag stack.
 294        GoToNewerTag,
 295        /// Joins this pane into the next pane.
 296        JoinIntoNext,
 297        /// Joins all panes into one.
 298        JoinAll,
 299        /// Reopens the most recently closed item.
 300        ReopenClosedItem,
 301        /// Splits the pane to the left, moving the current item.
 302        SplitAndMoveLeft,
 303        /// Splits the pane upward, moving the current item.
 304        SplitAndMoveUp,
 305        /// Splits the pane to the right, moving the current item.
 306        SplitAndMoveRight,
 307        /// Splits the pane downward, moving the current item.
 308        SplitAndMoveDown,
 309        /// Swaps the current item with the one to the left.
 310        SwapItemLeft,
 311        /// Swaps the current item with the one to the right.
 312        SwapItemRight,
 313        /// Toggles preview mode for the current tab.
 314        TogglePreviewTab,
 315        /// Toggles pin status for the current tab.
 316        TogglePinTab,
 317        /// Unpins all tabs in the pane.
 318        UnpinAllTabs,
 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("Search Project", DeploySearch::default().boxed_clone())
4192                            .action("Search Symbols", ToggleProjectSymbols.boxed_clone())
4193                            .separator()
4194                            .action("New Terminal", NewTerminal::default().boxed_clone())
4195                    }))
4196                }),
4197        )
4198        .child(
4199            PopoverMenu::new("pane-tab-bar-split")
4200                .trigger_with_tooltip(
4201                    IconButton::new("split", IconName::Split)
4202                        .icon_size(IconSize::Small)
4203                        .disabled(!can_clone && !can_split_move),
4204                    Tooltip::text("Split Pane"),
4205                )
4206                .anchor(Corner::TopRight)
4207                .with_handle(pane.split_item_context_menu_handle.clone())
4208                .menu(move |window, cx| {
4209                    ContextMenu::build(window, cx, |menu, _, _| {
4210                        let mode = SplitMode::MovePane;
4211                        if can_split_move {
4212                            menu.action("Split Right", SplitRight { mode }.boxed_clone())
4213                                .action("Split Left", SplitLeft { mode }.boxed_clone())
4214                                .action("Split Up", SplitUp { mode }.boxed_clone())
4215                                .action("Split Down", SplitDown { mode }.boxed_clone())
4216                        } else {
4217                            menu.action("Split Right", SplitRight::default().boxed_clone())
4218                                .action("Split Left", SplitLeft::default().boxed_clone())
4219                                .action("Split Up", SplitUp::default().boxed_clone())
4220                                .action("Split Down", SplitDown::default().boxed_clone())
4221                        }
4222                    })
4223                    .into()
4224                }),
4225        )
4226        .child({
4227            let zoomed = pane.is_zoomed();
4228            IconButton::new("toggle_zoom", IconName::Maximize)
4229                .icon_size(IconSize::Small)
4230                .toggle_state(zoomed)
4231                .selected_icon(IconName::Minimize)
4232                .on_click(cx.listener(|pane, _, window, cx| {
4233                    pane.toggle_zoom(&crate::ToggleZoom, window, cx);
4234                }))
4235                .tooltip(move |_window, cx| {
4236                    Tooltip::for_action(
4237                        if zoomed { "Zoom Out" } else { "Zoom In" },
4238                        &ToggleZoom,
4239                        cx,
4240                    )
4241                })
4242        })
4243        .into_any_element()
4244        .into();
4245    (None, right_children)
4246}
4247
4248impl Focusable for Pane {
4249    fn focus_handle(&self, _cx: &App) -> FocusHandle {
4250        self.focus_handle.clone()
4251    }
4252}
4253
4254impl Render for Pane {
4255    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4256        let mut key_context = KeyContext::new_with_defaults();
4257        key_context.add("Pane");
4258        if self.active_item().is_none() {
4259            key_context.add("EmptyPane");
4260        }
4261
4262        self.toolbar
4263            .read(cx)
4264            .contribute_context(&mut key_context, cx);
4265
4266        let should_display_tab_bar = self.should_display_tab_bar.clone();
4267        let display_tab_bar = should_display_tab_bar(window, cx);
4268        let Some(project) = self.project.upgrade() else {
4269            return div().track_focus(&self.focus_handle(cx));
4270        };
4271        let is_local = project.read(cx).is_local();
4272
4273        v_flex()
4274            .key_context(key_context)
4275            .track_focus(&self.focus_handle(cx))
4276            .size_full()
4277            .flex_none()
4278            .overflow_hidden()
4279            .on_action(cx.listener(|pane, split: &SplitLeft, window, cx| {
4280                pane.split(SplitDirection::Left, split.mode, window, cx)
4281            }))
4282            .on_action(cx.listener(|pane, split: &SplitUp, window, cx| {
4283                pane.split(SplitDirection::Up, split.mode, window, cx)
4284            }))
4285            .on_action(cx.listener(|pane, split: &SplitHorizontal, window, cx| {
4286                pane.split(SplitDirection::horizontal(cx), split.mode, window, cx)
4287            }))
4288            .on_action(cx.listener(|pane, split: &SplitVertical, window, cx| {
4289                pane.split(SplitDirection::vertical(cx), split.mode, window, cx)
4290            }))
4291            .on_action(cx.listener(|pane, split: &SplitRight, window, cx| {
4292                pane.split(SplitDirection::Right, split.mode, window, cx)
4293            }))
4294            .on_action(cx.listener(|pane, split: &SplitDown, window, cx| {
4295                pane.split(SplitDirection::Down, split.mode, window, cx)
4296            }))
4297            .on_action(cx.listener(|pane, _: &SplitAndMoveUp, window, cx| {
4298                pane.split(SplitDirection::Up, SplitMode::MovePane, window, cx)
4299            }))
4300            .on_action(cx.listener(|pane, _: &SplitAndMoveDown, window, cx| {
4301                pane.split(SplitDirection::Down, SplitMode::MovePane, window, cx)
4302            }))
4303            .on_action(cx.listener(|pane, _: &SplitAndMoveLeft, window, cx| {
4304                pane.split(SplitDirection::Left, SplitMode::MovePane, window, cx)
4305            }))
4306            .on_action(cx.listener(|pane, _: &SplitAndMoveRight, window, cx| {
4307                pane.split(SplitDirection::Right, SplitMode::MovePane, window, cx)
4308            }))
4309            .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
4310                cx.emit(Event::JoinIntoNext);
4311            }))
4312            .on_action(cx.listener(|_, _: &JoinAll, _, cx| {
4313                cx.emit(Event::JoinAll);
4314            }))
4315            .on_action(cx.listener(Pane::toggle_zoom))
4316            .on_action(cx.listener(Pane::zoom_in))
4317            .on_action(cx.listener(Pane::zoom_out))
4318            .on_action(cx.listener(Self::navigate_backward))
4319            .on_action(cx.listener(Self::navigate_forward))
4320            .on_action(cx.listener(Self::go_to_older_tag))
4321            .on_action(cx.listener(Self::go_to_newer_tag))
4322            .on_action(
4323                cx.listener(|pane: &mut Pane, action: &ActivateItem, window, cx| {
4324                    pane.activate_item(
4325                        action.0.min(pane.items.len().saturating_sub(1)),
4326                        true,
4327                        true,
4328                        window,
4329                        cx,
4330                    );
4331                }),
4332            )
4333            .on_action(cx.listener(Self::alternate_file))
4334            .on_action(cx.listener(Self::activate_last_item))
4335            .on_action(cx.listener(Self::activate_previous_item))
4336            .on_action(cx.listener(Self::activate_next_item))
4337            .on_action(cx.listener(Self::swap_item_left))
4338            .on_action(cx.listener(Self::swap_item_right))
4339            .on_action(cx.listener(Self::toggle_pin_tab))
4340            .on_action(cx.listener(Self::unpin_all_tabs))
4341            .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
4342                this.on_action(
4343                    cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, window, cx| {
4344                        if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
4345                            if pane.is_active_preview_item(active_item_id) {
4346                                pane.unpreview_item_if_preview(active_item_id);
4347                            } else {
4348                                pane.replace_preview_item_id(active_item_id, window, cx);
4349                            }
4350                        }
4351                    }),
4352                )
4353            })
4354            .on_action(
4355                cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
4356                    pane.close_active_item(action, window, cx)
4357                        .detach_and_log_err(cx)
4358                }),
4359            )
4360            .on_action(
4361                cx.listener(|pane: &mut Self, action: &CloseOtherItems, window, cx| {
4362                    pane.close_other_items(action, None, window, cx)
4363                        .detach_and_log_err(cx);
4364                }),
4365            )
4366            .on_action(
4367                cx.listener(|pane: &mut Self, action: &CloseCleanItems, window, cx| {
4368                    pane.close_clean_items(action, window, cx)
4369                        .detach_and_log_err(cx)
4370                }),
4371            )
4372            .on_action(cx.listener(
4373                |pane: &mut Self, action: &CloseItemsToTheLeft, window, cx| {
4374                    pane.close_items_to_the_left_by_id(None, action, window, cx)
4375                        .detach_and_log_err(cx)
4376                },
4377            ))
4378            .on_action(cx.listener(
4379                |pane: &mut Self, action: &CloseItemsToTheRight, window, cx| {
4380                    pane.close_items_to_the_right_by_id(None, action, window, cx)
4381                        .detach_and_log_err(cx)
4382                },
4383            ))
4384            .on_action(
4385                cx.listener(|pane: &mut Self, action: &CloseAllItems, window, cx| {
4386                    pane.close_all_items(action, window, cx)
4387                        .detach_and_log_err(cx)
4388                }),
4389            )
4390            .on_action(cx.listener(
4391                |pane: &mut Self, action: &CloseMultibufferItems, window, cx| {
4392                    pane.close_multibuffer_items(action, window, cx)
4393                        .detach_and_log_err(cx)
4394                },
4395            ))
4396            .on_action(
4397                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, _, cx| {
4398                    let Some(active_item) = pane.active_item() else {
4399                        return;
4400                    };
4401
4402                    let entry_id = action
4403                        .entry_id
4404                        .map(ProjectEntryId::from_proto)
4405                        .or_else(|| active_item.project_entry_ids(cx).first().copied());
4406
4407                    let show_reveal_error_toast = |display_name: &str, cx: &mut App| {
4408                        let notification_id = NotificationId::unique::<RevealInProjectPanel>();
4409                        let message = SharedString::from(format!(
4410                            "\"{display_name}\" is not part of any open projects."
4411                        ));
4412
4413                        show_app_notification(notification_id, cx, move |cx| {
4414                            let message = message.clone();
4415                            cx.new(|cx| MessageNotification::new(message, cx))
4416                        });
4417                    };
4418
4419                    let Some(entry_id) = entry_id else {
4420                        // When working with an unsaved buffer, display a toast
4421                        // informing the user that the buffer is not present in
4422                        // any of the open projects and stop execution, as we
4423                        // don't want to open the project panel.
4424                        let display_name = active_item
4425                            .tab_tooltip_text(cx)
4426                            .unwrap_or_else(|| active_item.tab_content_text(0, cx));
4427
4428                        return show_reveal_error_toast(&display_name, cx);
4429                    };
4430
4431                    // We'll now check whether the entry belongs to a visible
4432                    // worktree and, if that's not the case, it means the user
4433                    // is interacting with a file that does not belong to any of
4434                    // the open projects, so we'll show a toast informing them
4435                    // of this and stop execution.
4436                    let display_name = pane
4437                        .project
4438                        .read_with(cx, |project, cx| {
4439                            project
4440                                .worktree_for_entry(entry_id, cx)
4441                                .filter(|worktree| !worktree.read(cx).is_visible())
4442                                .map(|worktree| worktree.read(cx).root_name_str().to_string())
4443                        })
4444                        .ok()
4445                        .flatten();
4446
4447                    if let Some(display_name) = display_name {
4448                        return show_reveal_error_toast(&display_name, cx);
4449                    }
4450
4451                    pane.project
4452                        .update(cx, |_, cx| {
4453                            cx.emit(project::Event::RevealInProjectPanel(entry_id))
4454                        })
4455                        .log_err();
4456                }),
4457            )
4458            .on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
4459                if cx.stop_active_drag(window) {
4460                } else {
4461                    cx.propagate();
4462                }
4463            }))
4464            .when(self.active_item().is_some() && display_tab_bar, |pane| {
4465                pane.child((self.render_tab_bar.clone())(self, window, cx))
4466            })
4467            .child({
4468                let has_worktrees = project.read(cx).visible_worktrees(cx).next().is_some();
4469                // main content
4470                div()
4471                    .flex_1()
4472                    .relative()
4473                    .group("")
4474                    .overflow_hidden()
4475                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
4476                    .on_drag_move::<DraggedSelection>(cx.listener(Self::handle_drag_move))
4477                    .when(is_local, |div| {
4478                        div.on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
4479                    })
4480                    .map(|div| {
4481                        if let Some(item) = self.active_item() {
4482                            div.id("pane_placeholder")
4483                                .v_flex()
4484                                .size_full()
4485                                .overflow_hidden()
4486                                .child(self.toolbar.clone())
4487                                .child(item.to_any_view())
4488                        } else {
4489                            let placeholder = div
4490                                .id("pane_placeholder")
4491                                .h_flex()
4492                                .size_full()
4493                                .justify_center()
4494                                .on_click(cx.listener(
4495                                    move |this, event: &ClickEvent, window, cx| {
4496                                        if event.click_count() == 2 {
4497                                            window.dispatch_action(
4498                                                this.double_click_dispatch_action.boxed_clone(),
4499                                                cx,
4500                                            );
4501                                        }
4502                                    },
4503                                ));
4504                            if has_worktrees || !self.should_display_welcome_page {
4505                                placeholder
4506                            } else {
4507                                if self.welcome_page.is_none() {
4508                                    let workspace = self.workspace.clone();
4509                                    self.welcome_page = Some(cx.new(|cx| {
4510                                        crate::welcome::WelcomePage::new(
4511                                            workspace, true, window, cx,
4512                                        )
4513                                    }));
4514                                }
4515                                placeholder.child(self.welcome_page.clone().unwrap())
4516                            }
4517                        }
4518                        .focus_follows_mouse(self.focus_follows_mouse, cx)
4519                    })
4520                    .child(
4521                        // drag target
4522                        div()
4523                            .invisible()
4524                            .absolute()
4525                            .bg(cx.theme().colors().drop_target_background)
4526                            .group_drag_over::<DraggedTab>("", |style| style.visible())
4527                            .group_drag_over::<DraggedSelection>("", |style| style.visible())
4528                            .when(is_local, |div| {
4529                                div.group_drag_over::<ExternalPaths>("", |style| style.visible())
4530                            })
4531                            .when_some(self.can_drop_predicate.clone(), |this, p| {
4532                                this.can_drop(move |a, window, cx| p(a, window, cx))
4533                            })
4534                            .on_drop(cx.listener(move |this, dragged_tab, window, cx| {
4535                                this.handle_tab_drop(
4536                                    dragged_tab,
4537                                    this.active_item_index(),
4538                                    true,
4539                                    window,
4540                                    cx,
4541                                )
4542                            }))
4543                            .on_drop(cx.listener(
4544                                move |this, selection: &DraggedSelection, window, cx| {
4545                                    this.handle_dragged_selection_drop(selection, None, window, cx)
4546                                },
4547                            ))
4548                            .on_drop(cx.listener(move |this, paths, window, cx| {
4549                                this.handle_external_paths_drop(paths, window, cx)
4550                            }))
4551                            .map(|div| {
4552                                let size = DefiniteLength::Fraction(0.5);
4553                                match self.drag_split_direction {
4554                                    None => div.top_0().right_0().bottom_0().left_0(),
4555                                    Some(SplitDirection::Up) => {
4556                                        div.top_0().left_0().right_0().h(size)
4557                                    }
4558                                    Some(SplitDirection::Down) => {
4559                                        div.left_0().bottom_0().right_0().h(size)
4560                                    }
4561                                    Some(SplitDirection::Left) => {
4562                                        div.top_0().left_0().bottom_0().w(size)
4563                                    }
4564                                    Some(SplitDirection::Right) => {
4565                                        div.top_0().bottom_0().right_0().w(size)
4566                                    }
4567                                }
4568                            }),
4569                    )
4570            })
4571            .on_mouse_down(
4572                MouseButton::Navigate(NavigationDirection::Back),
4573                cx.listener(|pane, _, window, cx| {
4574                    if let Some(workspace) = pane.workspace.upgrade() {
4575                        let pane = cx.entity().downgrade();
4576                        window.defer(cx, move |window, cx| {
4577                            workspace.update(cx, |workspace, cx| {
4578                                workspace.go_back(pane, window, cx).detach_and_log_err(cx)
4579                            })
4580                        })
4581                    }
4582                }),
4583            )
4584            .on_mouse_down(
4585                MouseButton::Navigate(NavigationDirection::Forward),
4586                cx.listener(|pane, _, window, cx| {
4587                    if let Some(workspace) = pane.workspace.upgrade() {
4588                        let pane = cx.entity().downgrade();
4589                        window.defer(cx, move |window, cx| {
4590                            workspace.update(cx, |workspace, cx| {
4591                                workspace
4592                                    .go_forward(pane, window, cx)
4593                                    .detach_and_log_err(cx)
4594                            })
4595                        })
4596                    }
4597                }),
4598            )
4599    }
4600}
4601
4602impl ItemNavHistory {
4603    pub fn push<D: 'static + Any + Send + Sync>(
4604        &mut self,
4605        data: Option<D>,
4606        row: Option<u32>,
4607        cx: &mut App,
4608    ) {
4609        if self
4610            .item
4611            .upgrade()
4612            .is_some_and(|item| item.include_in_nav_history())
4613        {
4614            let is_preview_item = self.history.0.lock().preview_item_id == Some(self.item.id());
4615            self.history
4616                .push(data, self.item.clone(), is_preview_item, row, cx);
4617        }
4618    }
4619
4620    pub fn navigation_entry(&self, data: Option<Arc<dyn Any + Send + Sync>>) -> NavigationEntry {
4621        let is_preview_item = self.history.0.lock().preview_item_id == Some(self.item.id());
4622        NavigationEntry {
4623            item: self.item.clone(),
4624            data,
4625            timestamp: 0,
4626            is_preview: is_preview_item,
4627            row: None,
4628        }
4629    }
4630
4631    pub fn push_tag(&mut self, origin: Option<NavigationEntry>, target: Option<NavigationEntry>) {
4632        if let (Some(origin_entry), Some(target_entry)) = (origin, target) {
4633            self.history.push_tag(origin_entry, target_entry);
4634        }
4635    }
4636
4637    pub fn pop_backward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
4638        self.history.pop(NavigationMode::GoingBack, cx)
4639    }
4640
4641    pub fn pop_forward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
4642        self.history.pop(NavigationMode::GoingForward, cx)
4643    }
4644}
4645
4646impl NavHistory {
4647    pub fn for_each_entry(
4648        &self,
4649        cx: &App,
4650        f: &mut dyn FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
4651    ) {
4652        let borrowed_history = self.0.lock();
4653        borrowed_history
4654            .forward_stack
4655            .iter()
4656            .chain(borrowed_history.backward_stack.iter())
4657            .chain(borrowed_history.closed_stack.iter())
4658            .for_each(|entry| {
4659                if let Some(project_and_abs_path) =
4660                    borrowed_history.paths_by_item.get(&entry.item.id())
4661                {
4662                    f(entry, project_and_abs_path.clone());
4663                } else if let Some(item) = entry.item.upgrade()
4664                    && let Some(path) = item.project_path(cx)
4665                {
4666                    f(entry, (path, None));
4667                }
4668            })
4669    }
4670
4671    pub fn set_mode(&mut self, mode: NavigationMode) {
4672        self.0.lock().mode = mode;
4673    }
4674
4675    pub fn mode(&self) -> NavigationMode {
4676        self.0.lock().mode
4677    }
4678
4679    pub fn disable(&mut self) {
4680        self.0.lock().mode = NavigationMode::Disabled;
4681    }
4682
4683    pub fn enable(&mut self) {
4684        self.0.lock().mode = NavigationMode::Normal;
4685    }
4686
4687    pub fn clear(&mut self, cx: &mut App) {
4688        let mut state = self.0.lock();
4689
4690        if state.backward_stack.is_empty()
4691            && state.forward_stack.is_empty()
4692            && state.closed_stack.is_empty()
4693            && state.paths_by_item.is_empty()
4694            && state.tag_stack.is_empty()
4695        {
4696            return;
4697        }
4698
4699        state.mode = NavigationMode::Normal;
4700        state.backward_stack.clear();
4701        state.forward_stack.clear();
4702        state.closed_stack.clear();
4703        state.paths_by_item.clear();
4704        state.tag_stack.clear();
4705        state.tag_stack_pos = 0;
4706        state.did_update(cx);
4707    }
4708
4709    pub fn pop(&mut self, mode: NavigationMode, cx: &mut App) -> Option<NavigationEntry> {
4710        let mut state = self.0.lock();
4711        let entry = match mode {
4712            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
4713                return None;
4714            }
4715            NavigationMode::GoingBack => &mut state.backward_stack,
4716            NavigationMode::GoingForward => &mut state.forward_stack,
4717            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
4718        }
4719        .pop_back();
4720        if entry.is_some() {
4721            state.did_update(cx);
4722        }
4723        entry
4724    }
4725
4726    pub fn push<D: 'static + Any + Send + Sync>(
4727        &mut self,
4728        data: Option<D>,
4729        item: Arc<dyn WeakItemHandle + Send + Sync>,
4730        is_preview: bool,
4731        row: Option<u32>,
4732        cx: &mut App,
4733    ) {
4734        let state = &mut *self.0.lock();
4735        let new_item_id = item.id();
4736
4737        let is_same_location =
4738            |entry: &NavigationEntry| entry.item.id() == new_item_id && entry.row == row;
4739
4740        match state.mode {
4741            NavigationMode::Disabled => {}
4742            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
4743                state
4744                    .backward_stack
4745                    .retain(|entry| !is_same_location(entry));
4746
4747                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4748                    state.backward_stack.pop_front();
4749                }
4750                state.backward_stack.push_back(NavigationEntry {
4751                    item,
4752                    data: data.map(|data| Arc::new(data) as Arc<dyn Any + Send + Sync>),
4753                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4754                    is_preview,
4755                    row,
4756                });
4757                state.forward_stack.clear();
4758            }
4759            NavigationMode::GoingBack => {
4760                state.forward_stack.retain(|entry| !is_same_location(entry));
4761
4762                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4763                    state.forward_stack.pop_front();
4764                }
4765                state.forward_stack.push_back(NavigationEntry {
4766                    item,
4767                    data: data.map(|data| Arc::new(data) as Arc<dyn Any + Send + Sync>),
4768                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4769                    is_preview,
4770                    row,
4771                });
4772            }
4773            NavigationMode::GoingForward => {
4774                state
4775                    .backward_stack
4776                    .retain(|entry| !is_same_location(entry));
4777
4778                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4779                    state.backward_stack.pop_front();
4780                }
4781                state.backward_stack.push_back(NavigationEntry {
4782                    item,
4783                    data: data.map(|data| Arc::new(data) as Arc<dyn Any + Send + Sync>),
4784                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4785                    is_preview,
4786                    row,
4787                });
4788            }
4789            NavigationMode::ClosingItem if is_preview => return,
4790            NavigationMode::ClosingItem => {
4791                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4792                    state.closed_stack.pop_front();
4793                }
4794                state.closed_stack.push_back(NavigationEntry {
4795                    item,
4796                    data: data.map(|data| Arc::new(data) as Arc<dyn Any + Send + Sync>),
4797                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4798                    is_preview,
4799                    row,
4800                });
4801            }
4802        }
4803        state.did_update(cx);
4804    }
4805
4806    pub fn remove_item(&mut self, item_id: EntityId) {
4807        let mut state = self.0.lock();
4808        state.paths_by_item.remove(&item_id);
4809        state
4810            .backward_stack
4811            .retain(|entry| entry.item.id() != item_id);
4812        state
4813            .forward_stack
4814            .retain(|entry| entry.item.id() != item_id);
4815        state
4816            .closed_stack
4817            .retain(|entry| entry.item.id() != item_id);
4818        state
4819            .tag_stack
4820            .retain(|entry| entry.origin.item.id() != item_id && entry.target.item.id() != item_id);
4821    }
4822
4823    pub fn rename_item(
4824        &mut self,
4825        item_id: EntityId,
4826        project_path: ProjectPath,
4827        abs_path: Option<PathBuf>,
4828    ) {
4829        let mut state = self.0.lock();
4830        let path_for_item = state.paths_by_item.get_mut(&item_id);
4831        if let Some(path_for_item) = path_for_item {
4832            path_for_item.0 = project_path;
4833            path_for_item.1 = abs_path;
4834        }
4835    }
4836
4837    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
4838        self.0.lock().paths_by_item.get(&item_id).cloned()
4839    }
4840
4841    pub fn push_tag(&mut self, origin: NavigationEntry, target: NavigationEntry) {
4842        let mut state = self.0.lock();
4843        let truncate_to = state.tag_stack_pos;
4844        state.tag_stack.truncate(truncate_to);
4845        state.tag_stack.push_back(TagStackEntry { origin, target });
4846        state.tag_stack_pos = state.tag_stack.len();
4847    }
4848
4849    pub fn pop_tag(&mut self, mode: TagNavigationMode) -> Option<NavigationEntry> {
4850        let mut state = self.0.lock();
4851        match mode {
4852            TagNavigationMode::Older => {
4853                if state.tag_stack_pos > 0 {
4854                    state.tag_stack_pos -= 1;
4855                    state
4856                        .tag_stack
4857                        .get(state.tag_stack_pos)
4858                        .map(|e| e.origin.clone())
4859                } else {
4860                    None
4861                }
4862            }
4863            TagNavigationMode::Newer => {
4864                let entry = state
4865                    .tag_stack
4866                    .get(state.tag_stack_pos)
4867                    .map(|e| e.target.clone());
4868                if state.tag_stack_pos < state.tag_stack.len() {
4869                    state.tag_stack_pos += 1;
4870                }
4871                entry
4872            }
4873        }
4874    }
4875}
4876
4877impl NavHistoryState {
4878    pub fn did_update(&self, cx: &mut App) {
4879        if let Some(pane) = self.pane.upgrade() {
4880            cx.defer(move |cx| {
4881                pane.update(cx, |pane, cx| pane.history_updated(cx));
4882            });
4883        }
4884    }
4885}
4886
4887fn dirty_message_for(buffer_path: Option<ProjectPath>, path_style: PathStyle) -> String {
4888    let path = buffer_path
4889        .as_ref()
4890        .and_then(|p| {
4891            let path = p.path.display(path_style);
4892            if path.is_empty() { None } else { Some(path) }
4893        })
4894        .unwrap_or("This buffer".into());
4895    let path = truncate_and_remove_front(&path, 80);
4896    format!("{path} contains unsaved edits. Do you want to save it?")
4897}
4898
4899pub fn tab_details(items: &[Box<dyn ItemHandle>], _window: &Window, cx: &App) -> Vec<usize> {
4900    let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
4901    let mut tab_descriptions = HashMap::default();
4902    let mut done = false;
4903    while !done {
4904        done = true;
4905
4906        // Store item indices by their tab description.
4907        for (ix, (item, detail)) in items.iter().zip(&tab_details).enumerate() {
4908            let description = item.tab_content_text(*detail, cx);
4909            if *detail == 0 || description != item.tab_content_text(detail - 1, cx) {
4910                tab_descriptions
4911                    .entry(description)
4912                    .or_insert(Vec::new())
4913                    .push(ix);
4914            }
4915        }
4916
4917        // If two or more items have the same tab description, increase their level
4918        // of detail and try again.
4919        for (_, item_ixs) in tab_descriptions.drain() {
4920            if item_ixs.len() > 1 {
4921                done = false;
4922                for ix in item_ixs {
4923                    tab_details[ix] += 1;
4924                }
4925            }
4926        }
4927    }
4928
4929    tab_details
4930}
4931
4932pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &App) -> Option<Indicator> {
4933    maybe!({
4934        let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
4935            (true, _) => Color::Warning,
4936            (_, true) => Color::Accent,
4937            (false, false) => return None,
4938        };
4939
4940        Some(Indicator::dot().color(indicator_color))
4941    })
4942}
4943
4944impl Render for DraggedTab {
4945    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4946        let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
4947        let label = self.item.tab_content(
4948            TabContentParams {
4949                detail: Some(self.detail),
4950                selected: false,
4951                preview: false,
4952                deemphasized: false,
4953            },
4954            window,
4955            cx,
4956        );
4957        Tab::new("")
4958            .toggle_state(self.is_active)
4959            .child(label)
4960            .render(window, cx)
4961            .font(ui_font)
4962    }
4963}
4964
4965#[cfg(test)]
4966mod tests {
4967    use std::{cell::Cell, iter::zip, num::NonZero, rc::Rc};
4968
4969    use super::*;
4970    use crate::{
4971        Member,
4972        item::test::{TestItem, TestProjectItem},
4973    };
4974    use gpui::{
4975        AppContext, Axis, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
4976        TestAppContext, VisualTestContext, size,
4977    };
4978    use project::FakeFs;
4979    use settings::SettingsStore;
4980    use theme::LoadThemes;
4981    use util::TryFutureExt;
4982
4983    // drop_call_count is a Cell here because `handle_drop` takes &self, not &mut self.
4984    struct CustomDropHandlingItem {
4985        focus_handle: gpui::FocusHandle,
4986        drop_call_count: Cell<usize>,
4987    }
4988
4989    impl CustomDropHandlingItem {
4990        fn new(cx: &mut Context<Self>) -> Self {
4991            Self {
4992                focus_handle: cx.focus_handle(),
4993                drop_call_count: Cell::new(0),
4994            }
4995        }
4996
4997        fn drop_call_count(&self) -> usize {
4998            self.drop_call_count.get()
4999        }
5000    }
5001
5002    impl EventEmitter<()> for CustomDropHandlingItem {}
5003
5004    impl Focusable for CustomDropHandlingItem {
5005        fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
5006            self.focus_handle.clone()
5007        }
5008    }
5009
5010    impl Render for CustomDropHandlingItem {
5011        fn render(
5012            &mut self,
5013            _window: &mut Window,
5014            _cx: &mut Context<Self>,
5015        ) -> impl gpui::IntoElement {
5016            gpui::Empty
5017        }
5018    }
5019
5020    impl Item for CustomDropHandlingItem {
5021        type Event = ();
5022
5023        fn tab_content_text(&self, _detail: usize, _cx: &App) -> gpui::SharedString {
5024            "custom_drop_handling_item".into()
5025        }
5026
5027        fn handle_drop(
5028            &self,
5029            _active_pane: &Pane,
5030            dropped: &dyn std::any::Any,
5031            _window: &mut Window,
5032            _cx: &mut App,
5033        ) -> bool {
5034            let is_dragged_tab = dropped.downcast_ref::<DraggedTab>().is_some();
5035            if is_dragged_tab {
5036                self.drop_call_count.set(self.drop_call_count.get() + 1);
5037            }
5038            is_dragged_tab
5039        }
5040    }
5041
5042    #[gpui::test]
5043    async fn test_add_item_capped_to_max_tabs(cx: &mut TestAppContext) {
5044        init_test(cx);
5045        let fs = FakeFs::new(cx.executor());
5046
5047        let project = Project::test(fs, None, cx).await;
5048        let (workspace, cx) =
5049            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5050        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5051
5052        for i in 0..7 {
5053            add_labeled_item(&pane, format!("{}", i).as_str(), false, cx);
5054        }
5055
5056        set_max_tabs(cx, Some(5));
5057        add_labeled_item(&pane, "7", false, cx);
5058        // Remove items to respect the max tab cap.
5059        assert_item_labels(&pane, ["3", "4", "5", "6", "7*"], cx);
5060        pane.update_in(cx, |pane, window, cx| {
5061            pane.activate_item(0, false, false, window, cx);
5062        });
5063        add_labeled_item(&pane, "X", false, cx);
5064        // Respect activation order.
5065        assert_item_labels(&pane, ["3", "X*", "5", "6", "7"], cx);
5066
5067        for i in 0..7 {
5068            add_labeled_item(&pane, format!("D{}", i).as_str(), true, cx);
5069        }
5070        // Keeps dirty items, even over max tab cap.
5071        assert_item_labels(
5072            &pane,
5073            ["D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6*^"],
5074            cx,
5075        );
5076
5077        set_max_tabs(cx, None);
5078        for i in 0..7 {
5079            add_labeled_item(&pane, format!("N{}", i).as_str(), false, cx);
5080        }
5081        // No cap when max tabs is None.
5082        assert_item_labels(
5083            &pane,
5084            [
5085                "D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6^", "N0", "N1", "N2", "N3", "N4",
5086                "N5", "N6*",
5087            ],
5088            cx,
5089        );
5090    }
5091
5092    #[gpui::test]
5093    async fn test_reduce_max_tabs_closes_existing_items(cx: &mut TestAppContext) {
5094        init_test(cx);
5095        let fs = FakeFs::new(cx.executor());
5096
5097        let project = Project::test(fs, None, cx).await;
5098        let (workspace, cx) =
5099            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5100        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5101
5102        add_labeled_item(&pane, "A", false, cx);
5103        add_labeled_item(&pane, "B", false, cx);
5104        let item_c = add_labeled_item(&pane, "C", false, cx);
5105        let item_d = add_labeled_item(&pane, "D", false, cx);
5106        add_labeled_item(&pane, "E", false, cx);
5107        add_labeled_item(&pane, "Settings", false, cx);
5108        assert_item_labels(&pane, ["A", "B", "C", "D", "E", "Settings*"], cx);
5109
5110        set_max_tabs(cx, Some(5));
5111        assert_item_labels(&pane, ["B", "C", "D", "E", "Settings*"], cx);
5112
5113        set_max_tabs(cx, Some(4));
5114        assert_item_labels(&pane, ["C", "D", "E", "Settings*"], cx);
5115
5116        pane.update_in(cx, |pane, window, cx| {
5117            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5118            pane.pin_tab_at(ix, window, cx);
5119
5120            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
5121            pane.pin_tab_at(ix, window, cx);
5122        });
5123        assert_item_labels(&pane, ["C!", "D!", "E", "Settings*"], cx);
5124
5125        set_max_tabs(cx, Some(2));
5126        assert_item_labels(&pane, ["C!", "D!", "Settings*"], cx);
5127    }
5128
5129    #[gpui::test]
5130    async fn test_allow_pinning_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
5131        init_test(cx);
5132        let fs = FakeFs::new(cx.executor());
5133
5134        let project = Project::test(fs, None, cx).await;
5135        let (workspace, cx) =
5136            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5137        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5138
5139        set_max_tabs(cx, Some(1));
5140        let item_a = add_labeled_item(&pane, "A", true, cx);
5141
5142        pane.update_in(cx, |pane, window, cx| {
5143            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5144            pane.pin_tab_at(ix, window, cx);
5145        });
5146        assert_item_labels(&pane, ["A*^!"], cx);
5147    }
5148
5149    #[gpui::test]
5150    async fn test_allow_pinning_non_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
5151        init_test(cx);
5152        let fs = FakeFs::new(cx.executor());
5153
5154        let project = Project::test(fs, None, cx).await;
5155        let (workspace, cx) =
5156            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5157        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5158
5159        set_max_tabs(cx, Some(1));
5160        let item_a = add_labeled_item(&pane, "A", false, cx);
5161
5162        pane.update_in(cx, |pane, window, cx| {
5163            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5164            pane.pin_tab_at(ix, window, cx);
5165        });
5166        assert_item_labels(&pane, ["A*!"], cx);
5167    }
5168
5169    #[gpui::test]
5170    async fn test_pin_tabs_incrementally_at_max_capacity(cx: &mut TestAppContext) {
5171        init_test(cx);
5172        let fs = FakeFs::new(cx.executor());
5173
5174        let project = Project::test(fs, None, cx).await;
5175        let (workspace, cx) =
5176            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5177        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5178
5179        set_max_tabs(cx, Some(3));
5180
5181        let item_a = add_labeled_item(&pane, "A", false, cx);
5182        assert_item_labels(&pane, ["A*"], cx);
5183
5184        pane.update_in(cx, |pane, window, cx| {
5185            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5186            pane.pin_tab_at(ix, window, cx);
5187        });
5188        assert_item_labels(&pane, ["A*!"], cx);
5189
5190        let item_b = add_labeled_item(&pane, "B", false, cx);
5191        assert_item_labels(&pane, ["A!", "B*"], cx);
5192
5193        pane.update_in(cx, |pane, window, cx| {
5194            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5195            pane.pin_tab_at(ix, window, cx);
5196        });
5197        assert_item_labels(&pane, ["A!", "B*!"], cx);
5198
5199        let item_c = add_labeled_item(&pane, "C", false, cx);
5200        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
5201
5202        pane.update_in(cx, |pane, window, cx| {
5203            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5204            pane.pin_tab_at(ix, window, cx);
5205        });
5206        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
5207    }
5208
5209    #[gpui::test]
5210    async fn test_pin_tabs_left_to_right_after_opening_at_max_capacity(cx: &mut TestAppContext) {
5211        init_test(cx);
5212        let fs = FakeFs::new(cx.executor());
5213
5214        let project = Project::test(fs, None, cx).await;
5215        let (workspace, cx) =
5216            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5217        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5218
5219        set_max_tabs(cx, Some(3));
5220
5221        let item_a = add_labeled_item(&pane, "A", false, cx);
5222        assert_item_labels(&pane, ["A*"], cx);
5223
5224        let item_b = add_labeled_item(&pane, "B", false, cx);
5225        assert_item_labels(&pane, ["A", "B*"], cx);
5226
5227        let item_c = add_labeled_item(&pane, "C", false, cx);
5228        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5229
5230        pane.update_in(cx, |pane, window, cx| {
5231            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5232            pane.pin_tab_at(ix, window, cx);
5233        });
5234        assert_item_labels(&pane, ["A!", "B", "C*"], cx);
5235
5236        pane.update_in(cx, |pane, window, cx| {
5237            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5238            pane.pin_tab_at(ix, window, cx);
5239        });
5240        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
5241
5242        pane.update_in(cx, |pane, window, cx| {
5243            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5244            pane.pin_tab_at(ix, window, cx);
5245        });
5246        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
5247    }
5248
5249    #[gpui::test]
5250    async fn test_pin_tabs_right_to_left_after_opening_at_max_capacity(cx: &mut TestAppContext) {
5251        init_test(cx);
5252        let fs = FakeFs::new(cx.executor());
5253
5254        let project = Project::test(fs, None, cx).await;
5255        let (workspace, cx) =
5256            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5257        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5258
5259        set_max_tabs(cx, Some(3));
5260
5261        let item_a = add_labeled_item(&pane, "A", false, cx);
5262        assert_item_labels(&pane, ["A*"], cx);
5263
5264        let item_b = add_labeled_item(&pane, "B", false, cx);
5265        assert_item_labels(&pane, ["A", "B*"], cx);
5266
5267        let item_c = add_labeled_item(&pane, "C", false, cx);
5268        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5269
5270        pane.update_in(cx, |pane, window, cx| {
5271            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5272            pane.pin_tab_at(ix, window, cx);
5273        });
5274        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
5275
5276        pane.update_in(cx, |pane, window, cx| {
5277            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5278            pane.pin_tab_at(ix, window, cx);
5279        });
5280        assert_item_labels(&pane, ["C*!", "B!", "A"], cx);
5281
5282        pane.update_in(cx, |pane, window, cx| {
5283            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5284            pane.pin_tab_at(ix, window, cx);
5285        });
5286        assert_item_labels(&pane, ["C*!", "B!", "A!"], cx);
5287    }
5288
5289    #[gpui::test]
5290    async fn test_pinned_tabs_never_closed_at_max_tabs(cx: &mut TestAppContext) {
5291        init_test(cx);
5292        let fs = FakeFs::new(cx.executor());
5293
5294        let project = Project::test(fs, None, cx).await;
5295        let (workspace, cx) =
5296            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5297        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5298
5299        let item_a = add_labeled_item(&pane, "A", false, cx);
5300        pane.update_in(cx, |pane, window, cx| {
5301            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5302            pane.pin_tab_at(ix, window, cx);
5303        });
5304
5305        let item_b = add_labeled_item(&pane, "B", false, cx);
5306        pane.update_in(cx, |pane, window, cx| {
5307            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5308            pane.pin_tab_at(ix, window, cx);
5309        });
5310
5311        add_labeled_item(&pane, "C", false, cx);
5312        add_labeled_item(&pane, "D", false, cx);
5313        add_labeled_item(&pane, "E", false, cx);
5314        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
5315
5316        set_max_tabs(cx, Some(3));
5317        add_labeled_item(&pane, "F", false, cx);
5318        assert_item_labels(&pane, ["A!", "B!", "F*"], cx);
5319
5320        add_labeled_item(&pane, "G", false, cx);
5321        assert_item_labels(&pane, ["A!", "B!", "G*"], cx);
5322
5323        add_labeled_item(&pane, "H", false, cx);
5324        assert_item_labels(&pane, ["A!", "B!", "H*"], cx);
5325    }
5326
5327    #[gpui::test]
5328    async fn test_always_allows_one_unpinned_item_over_max_tabs_regardless_of_pinned_count(
5329        cx: &mut TestAppContext,
5330    ) {
5331        init_test(cx);
5332        let fs = FakeFs::new(cx.executor());
5333
5334        let project = Project::test(fs, None, cx).await;
5335        let (workspace, cx) =
5336            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5337        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5338
5339        set_max_tabs(cx, Some(3));
5340
5341        let item_a = add_labeled_item(&pane, "A", false, cx);
5342        pane.update_in(cx, |pane, window, cx| {
5343            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5344            pane.pin_tab_at(ix, window, cx);
5345        });
5346
5347        let item_b = add_labeled_item(&pane, "B", false, cx);
5348        pane.update_in(cx, |pane, window, cx| {
5349            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5350            pane.pin_tab_at(ix, window, cx);
5351        });
5352
5353        let item_c = add_labeled_item(&pane, "C", false, cx);
5354        pane.update_in(cx, |pane, window, cx| {
5355            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5356            pane.pin_tab_at(ix, window, cx);
5357        });
5358
5359        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
5360
5361        let item_d = add_labeled_item(&pane, "D", false, cx);
5362        assert_item_labels(&pane, ["A!", "B!", "C!", "D*"], cx);
5363
5364        pane.update_in(cx, |pane, window, cx| {
5365            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
5366            pane.pin_tab_at(ix, window, cx);
5367        });
5368        assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
5369
5370        add_labeled_item(&pane, "E", false, cx);
5371        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "E*"], cx);
5372
5373        add_labeled_item(&pane, "F", false, cx);
5374        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "F*"], cx);
5375    }
5376
5377    #[gpui::test]
5378    async fn test_can_open_one_item_when_all_tabs_are_dirty_at_max(cx: &mut TestAppContext) {
5379        init_test(cx);
5380        let fs = FakeFs::new(cx.executor());
5381
5382        let project = Project::test(fs, None, cx).await;
5383        let (workspace, cx) =
5384            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5385        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5386
5387        set_max_tabs(cx, Some(3));
5388
5389        add_labeled_item(&pane, "A", true, cx);
5390        assert_item_labels(&pane, ["A*^"], cx);
5391
5392        add_labeled_item(&pane, "B", true, cx);
5393        assert_item_labels(&pane, ["A^", "B*^"], cx);
5394
5395        add_labeled_item(&pane, "C", true, cx);
5396        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
5397
5398        add_labeled_item(&pane, "D", false, cx);
5399        assert_item_labels(&pane, ["A^", "B^", "C^", "D*"], cx);
5400
5401        add_labeled_item(&pane, "E", false, cx);
5402        assert_item_labels(&pane, ["A^", "B^", "C^", "E*"], cx);
5403
5404        add_labeled_item(&pane, "F", false, cx);
5405        assert_item_labels(&pane, ["A^", "B^", "C^", "F*"], cx);
5406
5407        add_labeled_item(&pane, "G", true, cx);
5408        assert_item_labels(&pane, ["A^", "B^", "C^", "G*^"], cx);
5409    }
5410
5411    #[gpui::test]
5412    async fn test_toggle_pin_tab(cx: &mut TestAppContext) {
5413        init_test(cx);
5414        let fs = FakeFs::new(cx.executor());
5415
5416        let project = Project::test(fs, None, cx).await;
5417        let (workspace, cx) =
5418            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5419        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5420
5421        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5422        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5423
5424        pane.update_in(cx, |pane, window, cx| {
5425            pane.toggle_pin_tab(&TogglePinTab, window, cx);
5426        });
5427        assert_item_labels(&pane, ["B*!", "A", "C"], cx);
5428
5429        pane.update_in(cx, |pane, window, cx| {
5430            pane.toggle_pin_tab(&TogglePinTab, window, cx);
5431        });
5432        assert_item_labels(&pane, ["B*", "A", "C"], cx);
5433    }
5434
5435    #[gpui::test]
5436    async fn test_unpin_all_tabs(cx: &mut TestAppContext) {
5437        init_test(cx);
5438        let fs = FakeFs::new(cx.executor());
5439
5440        let project = Project::test(fs, None, cx).await;
5441        let (workspace, cx) =
5442            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5443        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5444
5445        // Unpin all, in an empty pane
5446        pane.update_in(cx, |pane, window, cx| {
5447            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
5448        });
5449
5450        assert_item_labels(&pane, [], cx);
5451
5452        let item_a = add_labeled_item(&pane, "A", false, cx);
5453        let item_b = add_labeled_item(&pane, "B", false, cx);
5454        let item_c = add_labeled_item(&pane, "C", false, cx);
5455        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5456
5457        // Unpin all, when no tabs are pinned
5458        pane.update_in(cx, |pane, window, cx| {
5459            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
5460        });
5461
5462        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5463
5464        // Pin inactive tabs only
5465        pane.update_in(cx, |pane, window, cx| {
5466            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5467            pane.pin_tab_at(ix, window, cx);
5468
5469            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5470            pane.pin_tab_at(ix, window, cx);
5471        });
5472        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
5473
5474        pane.update_in(cx, |pane, window, cx| {
5475            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
5476        });
5477
5478        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5479
5480        // Pin all tabs
5481        pane.update_in(cx, |pane, window, cx| {
5482            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5483            pane.pin_tab_at(ix, window, cx);
5484
5485            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5486            pane.pin_tab_at(ix, window, cx);
5487
5488            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5489            pane.pin_tab_at(ix, window, cx);
5490        });
5491        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
5492
5493        // Activate middle tab
5494        pane.update_in(cx, |pane, window, cx| {
5495            pane.activate_item(1, false, false, window, cx);
5496        });
5497        assert_item_labels(&pane, ["A!", "B*!", "C!"], cx);
5498
5499        pane.update_in(cx, |pane, window, cx| {
5500            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
5501        });
5502
5503        // Order has not changed
5504        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5505    }
5506
5507    #[gpui::test]
5508    async fn test_separate_pinned_row_disabled_by_default(cx: &mut TestAppContext) {
5509        init_test(cx);
5510        let fs = FakeFs::new(cx.executor());
5511
5512        let project = Project::test(fs, None, cx).await;
5513        let (workspace, cx) =
5514            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5515        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5516
5517        let item_a = add_labeled_item(&pane, "A", false, cx);
5518        add_labeled_item(&pane, "B", false, cx);
5519        add_labeled_item(&pane, "C", false, cx);
5520
5521        // Pin one tab
5522        pane.update_in(cx, |pane, window, cx| {
5523            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5524            pane.pin_tab_at(ix, window, cx);
5525        });
5526        assert_item_labels(&pane, ["A!", "B", "C*"], cx);
5527
5528        // Verify setting is disabled by default
5529        let is_separate_row_enabled = pane.read_with(cx, |_, cx| {
5530            TabBarSettings::get_global(cx).show_pinned_tabs_in_separate_row
5531        });
5532        assert!(
5533            !is_separate_row_enabled,
5534            "Separate pinned row should be disabled by default"
5535        );
5536
5537        // Verify pinned_tabs_row element does NOT exist (single row layout)
5538        let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5539        assert!(
5540            pinned_row_bounds.is_none(),
5541            "pinned_tabs_row should not exist when setting is disabled"
5542        );
5543    }
5544
5545    #[gpui::test]
5546    async fn test_separate_pinned_row_two_rows_when_both_tab_types_exist(cx: &mut TestAppContext) {
5547        init_test(cx);
5548        let fs = FakeFs::new(cx.executor());
5549
5550        let project = Project::test(fs, None, cx).await;
5551        let (workspace, cx) =
5552            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5553        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5554
5555        // Enable separate row setting
5556        set_pinned_tabs_separate_row(cx, true);
5557
5558        let item_a = add_labeled_item(&pane, "A", false, cx);
5559        add_labeled_item(&pane, "B", false, cx);
5560        add_labeled_item(&pane, "C", false, cx);
5561
5562        // Pin one tab - now we have both pinned and unpinned tabs
5563        pane.update_in(cx, |pane, window, cx| {
5564            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5565            pane.pin_tab_at(ix, window, cx);
5566        });
5567        assert_item_labels(&pane, ["A!", "B", "C*"], cx);
5568
5569        // Verify pinned_tabs_row element exists (two row layout)
5570        let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5571        assert!(
5572            pinned_row_bounds.is_some(),
5573            "pinned_tabs_row should exist when setting is enabled and both tab types exist"
5574        );
5575    }
5576
5577    #[gpui::test]
5578    async fn test_separate_pinned_row_single_row_when_only_pinned_tabs(cx: &mut TestAppContext) {
5579        init_test(cx);
5580        let fs = FakeFs::new(cx.executor());
5581
5582        let project = Project::test(fs, None, cx).await;
5583        let (workspace, cx) =
5584            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5585        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5586
5587        // Enable separate row setting
5588        set_pinned_tabs_separate_row(cx, true);
5589
5590        let item_a = add_labeled_item(&pane, "A", false, cx);
5591        let item_b = add_labeled_item(&pane, "B", false, cx);
5592
5593        // Pin all tabs - only pinned tabs exist
5594        pane.update_in(cx, |pane, window, cx| {
5595            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5596            pane.pin_tab_at(ix, window, cx);
5597            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5598            pane.pin_tab_at(ix, window, cx);
5599        });
5600        assert_item_labels(&pane, ["A!", "B*!"], cx);
5601
5602        // Verify pinned_tabs_row does NOT exist (single row layout for pinned-only)
5603        let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5604        assert!(
5605            pinned_row_bounds.is_none(),
5606            "pinned_tabs_row should not exist when only pinned tabs exist (uses single row)"
5607        );
5608    }
5609
5610    #[gpui::test]
5611    async fn test_separate_pinned_row_single_row_when_only_unpinned_tabs(cx: &mut TestAppContext) {
5612        init_test(cx);
5613        let fs = FakeFs::new(cx.executor());
5614
5615        let project = Project::test(fs, None, cx).await;
5616        let (workspace, cx) =
5617            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5618        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5619
5620        // Enable separate row setting
5621        set_pinned_tabs_separate_row(cx, true);
5622
5623        // Add only unpinned tabs
5624        add_labeled_item(&pane, "A", false, cx);
5625        add_labeled_item(&pane, "B", false, cx);
5626        add_labeled_item(&pane, "C", false, cx);
5627        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5628
5629        // Verify pinned_tabs_row does NOT exist (single row layout for unpinned-only)
5630        let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5631        assert!(
5632            pinned_row_bounds.is_none(),
5633            "pinned_tabs_row should not exist when only unpinned tabs exist (uses single row)"
5634        );
5635    }
5636
5637    #[gpui::test]
5638    async fn test_separate_pinned_row_toggles_between_layouts(cx: &mut TestAppContext) {
5639        init_test(cx);
5640        let fs = FakeFs::new(cx.executor());
5641
5642        let project = Project::test(fs, None, cx).await;
5643        let (workspace, cx) =
5644            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5645        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5646
5647        let item_a = add_labeled_item(&pane, "A", false, cx);
5648        add_labeled_item(&pane, "B", false, cx);
5649
5650        // Pin one tab
5651        pane.update_in(cx, |pane, window, cx| {
5652            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5653            pane.pin_tab_at(ix, window, cx);
5654        });
5655
5656        // Initially disabled - single row
5657        let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5658        assert!(
5659            pinned_row_bounds.is_none(),
5660            "Should be single row when disabled"
5661        );
5662
5663        // Enable - two rows
5664        set_pinned_tabs_separate_row(cx, true);
5665        cx.run_until_parked();
5666        let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5667        assert!(
5668            pinned_row_bounds.is_some(),
5669            "Should be two rows when enabled"
5670        );
5671
5672        // Disable again - back to single row
5673        set_pinned_tabs_separate_row(cx, false);
5674        cx.run_until_parked();
5675        let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5676        assert!(
5677            pinned_row_bounds.is_none(),
5678            "Should be single row when disabled again"
5679        );
5680    }
5681
5682    #[gpui::test]
5683    async fn test_separate_pinned_row_has_right_border(cx: &mut TestAppContext) {
5684        init_test(cx);
5685        let fs = FakeFs::new(cx.executor());
5686
5687        let project = Project::test(fs, None, cx).await;
5688        let (workspace, cx) =
5689            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5690        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5691
5692        // Enable separate row setting
5693        set_pinned_tabs_separate_row(cx, true);
5694
5695        let item_a = add_labeled_item(&pane, "A", false, cx);
5696        add_labeled_item(&pane, "B", false, cx);
5697        add_labeled_item(&pane, "C", false, cx);
5698
5699        // Pin one tab - now we have both pinned and unpinned tabs (two-row layout)
5700        pane.update_in(cx, |pane, window, cx| {
5701            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5702            pane.pin_tab_at(ix, window, cx);
5703        });
5704        assert_item_labels(&pane, ["A!", "B", "C*"], cx);
5705        cx.run_until_parked();
5706
5707        // Verify two-row layout is active
5708        let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5709        assert!(
5710            pinned_row_bounds.is_some(),
5711            "Two-row layout should be active when both pinned and unpinned tabs exist"
5712        );
5713
5714        // Verify pinned_tabs_border element exists (the right border after pinned tabs)
5715        let border_bounds = cx.debug_bounds("pinned_tabs_border");
5716        assert!(
5717            border_bounds.is_some(),
5718            "pinned_tabs_border should exist in two-row layout to show right border"
5719        );
5720    }
5721
5722    #[gpui::test]
5723    async fn test_pinning_active_tab_without_position_change_maintains_focus(
5724        cx: &mut TestAppContext,
5725    ) {
5726        init_test(cx);
5727        let fs = FakeFs::new(cx.executor());
5728
5729        let project = Project::test(fs, None, cx).await;
5730        let (workspace, cx) =
5731            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5732        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5733
5734        // Add A
5735        let item_a = add_labeled_item(&pane, "A", false, cx);
5736        assert_item_labels(&pane, ["A*"], cx);
5737
5738        // Add B
5739        add_labeled_item(&pane, "B", false, cx);
5740        assert_item_labels(&pane, ["A", "B*"], cx);
5741
5742        // Activate A again
5743        pane.update_in(cx, |pane, window, cx| {
5744            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5745            pane.activate_item(ix, true, true, window, cx);
5746        });
5747        assert_item_labels(&pane, ["A*", "B"], cx);
5748
5749        // Pin A - remains active
5750        pane.update_in(cx, |pane, window, cx| {
5751            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5752            pane.pin_tab_at(ix, window, cx);
5753        });
5754        assert_item_labels(&pane, ["A*!", "B"], cx);
5755
5756        // Unpin A - remain active
5757        pane.update_in(cx, |pane, window, cx| {
5758            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5759            pane.unpin_tab_at(ix, window, cx);
5760        });
5761        assert_item_labels(&pane, ["A*", "B"], cx);
5762    }
5763
5764    #[gpui::test]
5765    async fn test_pinning_active_tab_with_position_change_maintains_focus(cx: &mut TestAppContext) {
5766        init_test(cx);
5767        let fs = FakeFs::new(cx.executor());
5768
5769        let project = Project::test(fs, None, cx).await;
5770        let (workspace, cx) =
5771            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5772        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5773
5774        // Add A, B, C
5775        add_labeled_item(&pane, "A", false, cx);
5776        add_labeled_item(&pane, "B", false, cx);
5777        let item_c = add_labeled_item(&pane, "C", false, cx);
5778        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5779
5780        // Pin C - moves to pinned area, remains active
5781        pane.update_in(cx, |pane, window, cx| {
5782            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5783            pane.pin_tab_at(ix, window, cx);
5784        });
5785        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
5786
5787        // Unpin C - moves after pinned area, remains active
5788        pane.update_in(cx, |pane, window, cx| {
5789            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5790            pane.unpin_tab_at(ix, window, cx);
5791        });
5792        assert_item_labels(&pane, ["C*", "A", "B"], cx);
5793    }
5794
5795    #[gpui::test]
5796    async fn test_pinning_inactive_tab_without_position_change_preserves_existing_focus(
5797        cx: &mut TestAppContext,
5798    ) {
5799        init_test(cx);
5800        let fs = FakeFs::new(cx.executor());
5801
5802        let project = Project::test(fs, None, cx).await;
5803        let (workspace, cx) =
5804            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5805        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5806
5807        // Add A, B
5808        let item_a = add_labeled_item(&pane, "A", false, cx);
5809        add_labeled_item(&pane, "B", false, cx);
5810        assert_item_labels(&pane, ["A", "B*"], cx);
5811
5812        // Pin A - already in pinned area, B remains active
5813        pane.update_in(cx, |pane, window, cx| {
5814            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5815            pane.pin_tab_at(ix, window, cx);
5816        });
5817        assert_item_labels(&pane, ["A!", "B*"], cx);
5818
5819        // Unpin A - stays in place, B remains active
5820        pane.update_in(cx, |pane, window, cx| {
5821            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5822            pane.unpin_tab_at(ix, window, cx);
5823        });
5824        assert_item_labels(&pane, ["A", "B*"], cx);
5825    }
5826
5827    #[gpui::test]
5828    async fn test_pinning_inactive_tab_with_position_change_preserves_existing_focus(
5829        cx: &mut TestAppContext,
5830    ) {
5831        init_test(cx);
5832        let fs = FakeFs::new(cx.executor());
5833
5834        let project = Project::test(fs, None, cx).await;
5835        let (workspace, cx) =
5836            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5837        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5838
5839        // Add A, B, C
5840        add_labeled_item(&pane, "A", false, cx);
5841        let item_b = add_labeled_item(&pane, "B", false, cx);
5842        let item_c = add_labeled_item(&pane, "C", false, cx);
5843        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5844
5845        // Activate B
5846        pane.update_in(cx, |pane, window, cx| {
5847            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5848            pane.activate_item(ix, true, true, window, cx);
5849        });
5850        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5851
5852        // Pin C - moves to pinned area, B remains active
5853        pane.update_in(cx, |pane, window, cx| {
5854            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5855            pane.pin_tab_at(ix, window, cx);
5856        });
5857        assert_item_labels(&pane, ["C!", "A", "B*"], cx);
5858
5859        // Unpin C - moves after pinned area, B remains active
5860        pane.update_in(cx, |pane, window, cx| {
5861            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5862            pane.unpin_tab_at(ix, window, cx);
5863        });
5864        assert_item_labels(&pane, ["C", "A", "B*"], cx);
5865    }
5866
5867    #[gpui::test]
5868    async fn test_handle_tab_drop_respects_is_pane_target(cx: &mut TestAppContext) {
5869        init_test(cx);
5870        let fs = FakeFs::new(cx.executor());
5871        let project = Project::test(fs, None, cx).await;
5872        let (workspace, cx) =
5873            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5874        let source_pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5875
5876        let item_a = add_labeled_item(&source_pane, "A", false, cx);
5877        let item_b = add_labeled_item(&source_pane, "B", false, cx);
5878
5879        let target_pane = workspace.update_in(cx, |workspace, window, cx| {
5880            workspace.split_pane(source_pane.clone(), SplitDirection::Right, window, cx)
5881        });
5882
5883        let custom_item = target_pane.update_in(cx, |pane, window, cx| {
5884            let custom_item = Box::new(cx.new(CustomDropHandlingItem::new));
5885            pane.add_item(custom_item.clone(), true, true, None, window, cx);
5886            custom_item
5887        });
5888
5889        let moved_item_id = item_a.item_id();
5890        let other_item_id = item_b.item_id();
5891        let custom_item_id = custom_item.item_id();
5892
5893        let pane_item_ids = |pane: &Entity<Pane>, cx: &mut VisualTestContext| {
5894            pane.read_with(cx, |pane, _| {
5895                pane.items().map(|item| item.item_id()).collect::<Vec<_>>()
5896            })
5897        };
5898
5899        let source_before_item_ids = pane_item_ids(&source_pane, cx);
5900        assert_eq!(source_before_item_ids, vec![moved_item_id, other_item_id]);
5901
5902        let target_before_item_ids = pane_item_ids(&target_pane, cx);
5903        assert_eq!(target_before_item_ids, vec![custom_item_id]);
5904
5905        let dragged_tab = DraggedTab {
5906            pane: source_pane.clone(),
5907            item: item_a.boxed_clone(),
5908            ix: 0,
5909            detail: 0,
5910            is_active: true,
5911        };
5912
5913        // Dropping item_a onto the target pane itself means the
5914        // custom item handles the drop and no tab move should occur
5915        target_pane.update_in(cx, |pane, window, cx| {
5916            pane.handle_tab_drop(&dragged_tab, pane.active_item_index(), true, window, cx);
5917        });
5918        cx.run_until_parked();
5919
5920        assert_eq!(
5921            custom_item.read_with(cx, |item, _| item.drop_call_count()),
5922            1
5923        );
5924        assert_eq!(pane_item_ids(&source_pane, cx), source_before_item_ids);
5925        assert_eq!(pane_item_ids(&target_pane, cx), target_before_item_ids);
5926
5927        // Dropping item_a onto the tab target means the custom handler
5928        // should be skipped and the pane's default tab drop behavior should run.
5929        target_pane.update_in(cx, |pane, window, cx| {
5930            pane.handle_tab_drop(&dragged_tab, pane.active_item_index(), false, window, cx);
5931        });
5932        cx.run_until_parked();
5933
5934        assert_eq!(
5935            custom_item.read_with(cx, |item, _| item.drop_call_count()),
5936            1
5937        );
5938        assert_eq!(pane_item_ids(&source_pane, cx), vec![other_item_id]);
5939
5940        let target_item_ids = pane_item_ids(&target_pane, cx);
5941        assert_eq!(target_item_ids, vec![moved_item_id, custom_item_id]);
5942    }
5943
5944    #[gpui::test]
5945    async fn test_drag_unpinned_tab_to_split_creates_pane_with_unpinned_tab(
5946        cx: &mut TestAppContext,
5947    ) {
5948        init_test(cx);
5949        let fs = FakeFs::new(cx.executor());
5950
5951        let project = Project::test(fs, None, cx).await;
5952        let (workspace, cx) =
5953            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5954        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5955
5956        // Add A, B. Pin B. Activate A
5957        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5958        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5959
5960        pane_a.update_in(cx, |pane, window, cx| {
5961            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5962            pane.pin_tab_at(ix, window, cx);
5963
5964            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5965            pane.activate_item(ix, true, true, window, cx);
5966        });
5967
5968        // Drag A to create new split
5969        pane_a.update_in(cx, |pane, window, cx| {
5970            pane.drag_split_direction = Some(SplitDirection::Right);
5971
5972            let dragged_tab = DraggedTab {
5973                pane: pane_a.clone(),
5974                item: item_a.boxed_clone(),
5975                ix: 0,
5976                detail: 0,
5977                is_active: true,
5978            };
5979            pane.handle_tab_drop(&dragged_tab, 0, true, window, cx);
5980        });
5981
5982        // A should be moved to new pane. B should remain pinned, A should not be pinned
5983        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
5984            let panes = workspace.panes();
5985            (panes[0].clone(), panes[1].clone())
5986        });
5987        assert_item_labels(&pane_a, ["B*!"], cx);
5988        assert_item_labels(&pane_b, ["A*"], cx);
5989    }
5990
5991    #[gpui::test]
5992    async fn test_drag_pinned_tab_to_split_creates_pane_with_pinned_tab(cx: &mut TestAppContext) {
5993        init_test(cx);
5994        let fs = FakeFs::new(cx.executor());
5995
5996        let project = Project::test(fs, None, cx).await;
5997        let (workspace, cx) =
5998            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5999        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6000
6001        // Add A, B. Pin both. Activate A
6002        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6003        let item_b = add_labeled_item(&pane_a, "B", false, cx);
6004
6005        pane_a.update_in(cx, |pane, window, cx| {
6006            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6007            pane.pin_tab_at(ix, window, cx);
6008
6009            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6010            pane.pin_tab_at(ix, window, cx);
6011
6012            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6013            pane.activate_item(ix, true, true, window, cx);
6014        });
6015        assert_item_labels(&pane_a, ["A*!", "B!"], cx);
6016
6017        // Drag A to create new split
6018        pane_a.update_in(cx, |pane, window, cx| {
6019            pane.drag_split_direction = Some(SplitDirection::Right);
6020
6021            let dragged_tab = DraggedTab {
6022                pane: pane_a.clone(),
6023                item: item_a.boxed_clone(),
6024                ix: 0,
6025                detail: 0,
6026                is_active: true,
6027            };
6028            pane.handle_tab_drop(&dragged_tab, 0, true, window, cx);
6029        });
6030
6031        // A should be moved to new pane. Both A and B should still be pinned
6032        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
6033            let panes = workspace.panes();
6034            (panes[0].clone(), panes[1].clone())
6035        });
6036        assert_item_labels(&pane_a, ["B*!"], cx);
6037        assert_item_labels(&pane_b, ["A*!"], cx);
6038    }
6039
6040    #[gpui::test]
6041    async fn test_drag_pinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
6042        init_test(cx);
6043        let fs = FakeFs::new(cx.executor());
6044
6045        let project = Project::test(fs, None, cx).await;
6046        let (workspace, cx) =
6047            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6048        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6049
6050        // Add A to pane A and pin
6051        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6052        pane_a.update_in(cx, |pane, window, cx| {
6053            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6054            pane.pin_tab_at(ix, window, cx);
6055        });
6056        assert_item_labels(&pane_a, ["A*!"], cx);
6057
6058        // Add B to pane B and pin
6059        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6060            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6061        });
6062        let item_b = add_labeled_item(&pane_b, "B", false, cx);
6063        pane_b.update_in(cx, |pane, window, cx| {
6064            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6065            pane.pin_tab_at(ix, window, cx);
6066        });
6067        assert_item_labels(&pane_b, ["B*!"], cx);
6068
6069        // Move A from pane A to pane B's pinned region
6070        pane_b.update_in(cx, |pane, window, cx| {
6071            let dragged_tab = DraggedTab {
6072                pane: pane_a.clone(),
6073                item: item_a.boxed_clone(),
6074                ix: 0,
6075                detail: 0,
6076                is_active: true,
6077            };
6078            pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6079        });
6080
6081        // A should stay pinned
6082        assert_item_labels(&pane_a, [], cx);
6083        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
6084    }
6085
6086    #[gpui::test]
6087    async fn test_drag_pinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
6088        init_test(cx);
6089        let fs = FakeFs::new(cx.executor());
6090
6091        let project = Project::test(fs, None, cx).await;
6092        let (workspace, cx) =
6093            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6094        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6095
6096        // Add A to pane A and pin
6097        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6098        pane_a.update_in(cx, |pane, window, cx| {
6099            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6100            pane.pin_tab_at(ix, window, cx);
6101        });
6102        assert_item_labels(&pane_a, ["A*!"], cx);
6103
6104        // Create pane B with pinned item B
6105        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6106            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6107        });
6108        let item_b = add_labeled_item(&pane_b, "B", false, cx);
6109        assert_item_labels(&pane_b, ["B*"], cx);
6110
6111        pane_b.update_in(cx, |pane, window, cx| {
6112            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6113            pane.pin_tab_at(ix, window, cx);
6114        });
6115        assert_item_labels(&pane_b, ["B*!"], cx);
6116
6117        // Move A from pane A to pane B's unpinned region
6118        pane_b.update_in(cx, |pane, window, cx| {
6119            let dragged_tab = DraggedTab {
6120                pane: pane_a.clone(),
6121                item: item_a.boxed_clone(),
6122                ix: 0,
6123                detail: 0,
6124                is_active: true,
6125            };
6126            pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6127        });
6128
6129        // A should become pinned
6130        assert_item_labels(&pane_a, [], cx);
6131        assert_item_labels(&pane_b, ["B!", "A*"], cx);
6132    }
6133
6134    #[gpui::test]
6135    async fn test_drag_pinned_tab_into_existing_panes_first_position_with_no_pinned_tabs(
6136        cx: &mut TestAppContext,
6137    ) {
6138        init_test(cx);
6139        let fs = FakeFs::new(cx.executor());
6140
6141        let project = Project::test(fs, None, cx).await;
6142        let (workspace, cx) =
6143            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6144        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6145
6146        // Add A to pane A and pin
6147        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6148        pane_a.update_in(cx, |pane, window, cx| {
6149            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6150            pane.pin_tab_at(ix, window, cx);
6151        });
6152        assert_item_labels(&pane_a, ["A*!"], cx);
6153
6154        // Add B to pane B
6155        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6156            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6157        });
6158        add_labeled_item(&pane_b, "B", false, cx);
6159        assert_item_labels(&pane_b, ["B*"], cx);
6160
6161        // Move A from pane A to position 0 in pane B, indicating it should stay pinned
6162        pane_b.update_in(cx, |pane, window, cx| {
6163            let dragged_tab = DraggedTab {
6164                pane: pane_a.clone(),
6165                item: item_a.boxed_clone(),
6166                ix: 0,
6167                detail: 0,
6168                is_active: true,
6169            };
6170            pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6171        });
6172
6173        // A should stay pinned
6174        assert_item_labels(&pane_a, [], cx);
6175        assert_item_labels(&pane_b, ["A*!", "B"], cx);
6176    }
6177
6178    #[gpui::test]
6179    async fn test_drag_pinned_tab_into_existing_pane_at_max_capacity_closes_unpinned_tabs(
6180        cx: &mut TestAppContext,
6181    ) {
6182        init_test(cx);
6183        let fs = FakeFs::new(cx.executor());
6184
6185        let project = Project::test(fs, None, cx).await;
6186        let (workspace, cx) =
6187            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6188        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6189        set_max_tabs(cx, Some(2));
6190
6191        // Add A, B to pane A. Pin both
6192        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6193        let item_b = add_labeled_item(&pane_a, "B", false, cx);
6194        pane_a.update_in(cx, |pane, window, cx| {
6195            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6196            pane.pin_tab_at(ix, window, cx);
6197
6198            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6199            pane.pin_tab_at(ix, window, cx);
6200        });
6201        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
6202
6203        // Add C, D to pane B. Pin both
6204        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6205            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6206        });
6207        let item_c = add_labeled_item(&pane_b, "C", false, cx);
6208        let item_d = add_labeled_item(&pane_b, "D", false, cx);
6209        pane_b.update_in(cx, |pane, window, cx| {
6210            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
6211            pane.pin_tab_at(ix, window, cx);
6212
6213            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
6214            pane.pin_tab_at(ix, window, cx);
6215        });
6216        assert_item_labels(&pane_b, ["C!", "D*!"], cx);
6217
6218        // Add a third unpinned item to pane B (exceeds max tabs), but is allowed,
6219        // as we allow 1 tab over max if the others are pinned or dirty
6220        add_labeled_item(&pane_b, "E", false, cx);
6221        assert_item_labels(&pane_b, ["C!", "D!", "E*"], cx);
6222
6223        // Drag pinned A from pane A to position 0 in pane B
6224        pane_b.update_in(cx, |pane, window, cx| {
6225            let dragged_tab = DraggedTab {
6226                pane: pane_a.clone(),
6227                item: item_a.boxed_clone(),
6228                ix: 0,
6229                detail: 0,
6230                is_active: true,
6231            };
6232            pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6233        });
6234
6235        // E (unpinned) should be closed, leaving 3 pinned items
6236        assert_item_labels(&pane_a, ["B*!"], cx);
6237        assert_item_labels(&pane_b, ["A*!", "C!", "D!"], cx);
6238    }
6239
6240    #[gpui::test]
6241    async fn test_drag_last_pinned_tab_to_same_position_stays_pinned(cx: &mut TestAppContext) {
6242        init_test(cx);
6243        let fs = FakeFs::new(cx.executor());
6244
6245        let project = Project::test(fs, None, cx).await;
6246        let (workspace, cx) =
6247            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6248        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6249
6250        // Add A to pane A and pin it
6251        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6252        pane_a.update_in(cx, |pane, window, cx| {
6253            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6254            pane.pin_tab_at(ix, window, cx);
6255        });
6256        assert_item_labels(&pane_a, ["A*!"], cx);
6257
6258        // Drag pinned A to position 1 (directly to the right) in the same pane
6259        pane_a.update_in(cx, |pane, window, cx| {
6260            let dragged_tab = DraggedTab {
6261                pane: pane_a.clone(),
6262                item: item_a.boxed_clone(),
6263                ix: 0,
6264                detail: 0,
6265                is_active: true,
6266            };
6267            pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6268        });
6269
6270        // A should still be pinned and active
6271        assert_item_labels(&pane_a, ["A*!"], cx);
6272    }
6273
6274    #[gpui::test]
6275    async fn test_drag_pinned_tab_beyond_last_pinned_tab_in_same_pane_stays_pinned(
6276        cx: &mut TestAppContext,
6277    ) {
6278        init_test(cx);
6279        let fs = FakeFs::new(cx.executor());
6280
6281        let project = Project::test(fs, None, cx).await;
6282        let (workspace, cx) =
6283            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6284        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6285
6286        // Add A, B to pane A and pin both
6287        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6288        let item_b = add_labeled_item(&pane_a, "B", false, cx);
6289        pane_a.update_in(cx, |pane, window, cx| {
6290            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6291            pane.pin_tab_at(ix, window, cx);
6292
6293            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6294            pane.pin_tab_at(ix, window, cx);
6295        });
6296        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
6297
6298        // Drag pinned A right of B in the same pane
6299        pane_a.update_in(cx, |pane, window, cx| {
6300            let dragged_tab = DraggedTab {
6301                pane: pane_a.clone(),
6302                item: item_a.boxed_clone(),
6303                ix: 0,
6304                detail: 0,
6305                is_active: true,
6306            };
6307            pane.handle_tab_drop(&dragged_tab, 2, false, window, cx);
6308        });
6309
6310        // A stays pinned
6311        assert_item_labels(&pane_a, ["B!", "A*!"], cx);
6312    }
6313
6314    #[gpui::test]
6315    async fn test_dragging_pinned_tab_onto_unpinned_tab_reduces_unpinned_tab_count(
6316        cx: &mut TestAppContext,
6317    ) {
6318        init_test(cx);
6319        let fs = FakeFs::new(cx.executor());
6320
6321        let project = Project::test(fs, None, cx).await;
6322        let (workspace, cx) =
6323            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6324        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6325
6326        // Add A, B to pane A and pin A
6327        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6328        add_labeled_item(&pane_a, "B", false, cx);
6329        pane_a.update_in(cx, |pane, window, cx| {
6330            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6331            pane.pin_tab_at(ix, window, cx);
6332        });
6333        assert_item_labels(&pane_a, ["A!", "B*"], cx);
6334
6335        // Drag pinned A on top of B in the same pane, which changes tab order to B, A
6336        pane_a.update_in(cx, |pane, window, cx| {
6337            let dragged_tab = DraggedTab {
6338                pane: pane_a.clone(),
6339                item: item_a.boxed_clone(),
6340                ix: 0,
6341                detail: 0,
6342                is_active: true,
6343            };
6344            pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6345        });
6346
6347        // Neither are pinned
6348        assert_item_labels(&pane_a, ["B", "A*"], cx);
6349    }
6350
6351    #[gpui::test]
6352    async fn test_drag_pinned_tab_beyond_unpinned_tab_in_same_pane_becomes_unpinned(
6353        cx: &mut TestAppContext,
6354    ) {
6355        init_test(cx);
6356        let fs = FakeFs::new(cx.executor());
6357
6358        let project = Project::test(fs, None, cx).await;
6359        let (workspace, cx) =
6360            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6361        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6362
6363        // Add A, B to pane A and pin A
6364        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6365        add_labeled_item(&pane_a, "B", false, cx);
6366        pane_a.update_in(cx, |pane, window, cx| {
6367            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6368            pane.pin_tab_at(ix, window, cx);
6369        });
6370        assert_item_labels(&pane_a, ["A!", "B*"], cx);
6371
6372        // Drag pinned A right of B in the same pane
6373        pane_a.update_in(cx, |pane, window, cx| {
6374            let dragged_tab = DraggedTab {
6375                pane: pane_a.clone(),
6376                item: item_a.boxed_clone(),
6377                ix: 0,
6378                detail: 0,
6379                is_active: true,
6380            };
6381            pane.handle_tab_drop(&dragged_tab, 2, false, window, cx);
6382        });
6383
6384        // A becomes unpinned
6385        assert_item_labels(&pane_a, ["B", "A*"], cx);
6386    }
6387
6388    #[gpui::test]
6389    async fn test_drag_unpinned_tab_in_front_of_pinned_tab_in_same_pane_becomes_pinned(
6390        cx: &mut TestAppContext,
6391    ) {
6392        init_test(cx);
6393        let fs = FakeFs::new(cx.executor());
6394
6395        let project = Project::test(fs, None, cx).await;
6396        let (workspace, cx) =
6397            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6398        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6399
6400        // Add A, B to pane A and pin A
6401        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6402        let item_b = add_labeled_item(&pane_a, "B", false, cx);
6403        pane_a.update_in(cx, |pane, window, cx| {
6404            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6405            pane.pin_tab_at(ix, window, cx);
6406        });
6407        assert_item_labels(&pane_a, ["A!", "B*"], cx);
6408
6409        // Drag pinned B left of A in the same pane
6410        pane_a.update_in(cx, |pane, window, cx| {
6411            let dragged_tab = DraggedTab {
6412                pane: pane_a.clone(),
6413                item: item_b.boxed_clone(),
6414                ix: 1,
6415                detail: 0,
6416                is_active: true,
6417            };
6418            pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6419        });
6420
6421        // A becomes unpinned
6422        assert_item_labels(&pane_a, ["B*!", "A!"], cx);
6423    }
6424
6425    #[gpui::test]
6426    async fn test_drag_unpinned_tab_to_the_pinned_region_stays_pinned(cx: &mut TestAppContext) {
6427        init_test(cx);
6428        let fs = FakeFs::new(cx.executor());
6429
6430        let project = Project::test(fs, None, cx).await;
6431        let (workspace, cx) =
6432            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6433        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6434
6435        // Add A, B, C to pane A and pin A
6436        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6437        add_labeled_item(&pane_a, "B", false, cx);
6438        let item_c = add_labeled_item(&pane_a, "C", false, cx);
6439        pane_a.update_in(cx, |pane, window, cx| {
6440            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6441            pane.pin_tab_at(ix, window, cx);
6442        });
6443        assert_item_labels(&pane_a, ["A!", "B", "C*"], cx);
6444
6445        // Drag pinned C left of B in the same pane
6446        pane_a.update_in(cx, |pane, window, cx| {
6447            let dragged_tab = DraggedTab {
6448                pane: pane_a.clone(),
6449                item: item_c.boxed_clone(),
6450                ix: 2,
6451                detail: 0,
6452                is_active: true,
6453            };
6454            pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6455        });
6456
6457        // A stays pinned, B and C remain unpinned
6458        assert_item_labels(&pane_a, ["A!", "C*", "B"], cx);
6459    }
6460
6461    #[gpui::test]
6462    async fn test_drag_unpinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
6463        init_test(cx);
6464        let fs = FakeFs::new(cx.executor());
6465
6466        let project = Project::test(fs, None, cx).await;
6467        let (workspace, cx) =
6468            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6469        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6470
6471        // Add unpinned item A to pane A
6472        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6473        assert_item_labels(&pane_a, ["A*"], cx);
6474
6475        // Create pane B with pinned item B
6476        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6477            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6478        });
6479        let item_b = add_labeled_item(&pane_b, "B", false, cx);
6480        pane_b.update_in(cx, |pane, window, cx| {
6481            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6482            pane.pin_tab_at(ix, window, cx);
6483        });
6484        assert_item_labels(&pane_b, ["B*!"], cx);
6485
6486        // Move A from pane A to pane B's pinned region
6487        pane_b.update_in(cx, |pane, window, cx| {
6488            let dragged_tab = DraggedTab {
6489                pane: pane_a.clone(),
6490                item: item_a.boxed_clone(),
6491                ix: 0,
6492                detail: 0,
6493                is_active: true,
6494            };
6495            pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6496        });
6497
6498        // A should become pinned since it was dropped in the pinned region
6499        assert_item_labels(&pane_a, [], cx);
6500        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
6501    }
6502
6503    #[gpui::test]
6504    async fn test_drag_unpinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
6505        init_test(cx);
6506        let fs = FakeFs::new(cx.executor());
6507
6508        let project = Project::test(fs, None, cx).await;
6509        let (workspace, cx) =
6510            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6511        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6512
6513        // Add unpinned item A to pane A
6514        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6515        assert_item_labels(&pane_a, ["A*"], cx);
6516
6517        // Create pane B with one pinned item B
6518        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6519            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6520        });
6521        let item_b = add_labeled_item(&pane_b, "B", false, cx);
6522        pane_b.update_in(cx, |pane, window, cx| {
6523            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6524            pane.pin_tab_at(ix, window, cx);
6525        });
6526        assert_item_labels(&pane_b, ["B*!"], cx);
6527
6528        // Move A from pane A to pane B's unpinned region
6529        pane_b.update_in(cx, |pane, window, cx| {
6530            let dragged_tab = DraggedTab {
6531                pane: pane_a.clone(),
6532                item: item_a.boxed_clone(),
6533                ix: 0,
6534                detail: 0,
6535                is_active: true,
6536            };
6537            pane.handle_tab_drop(&dragged_tab, 1, true, window, cx);
6538        });
6539
6540        // A should remain unpinned since it was dropped outside the pinned region
6541        assert_item_labels(&pane_a, [], cx);
6542        assert_item_labels(&pane_b, ["B!", "A*"], cx);
6543    }
6544
6545    #[gpui::test]
6546    async fn test_drag_pinned_tab_throughout_entire_range_of_pinned_tabs_both_directions(
6547        cx: &mut TestAppContext,
6548    ) {
6549        init_test(cx);
6550        let fs = FakeFs::new(cx.executor());
6551
6552        let project = Project::test(fs, None, cx).await;
6553        let (workspace, cx) =
6554            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6555        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6556
6557        // Add A, B, C and pin all
6558        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6559        let item_b = add_labeled_item(&pane_a, "B", false, cx);
6560        let item_c = add_labeled_item(&pane_a, "C", false, cx);
6561        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
6562
6563        pane_a.update_in(cx, |pane, window, cx| {
6564            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6565            pane.pin_tab_at(ix, window, cx);
6566
6567            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6568            pane.pin_tab_at(ix, window, cx);
6569
6570            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
6571            pane.pin_tab_at(ix, window, cx);
6572        });
6573        assert_item_labels(&pane_a, ["A!", "B!", "C*!"], cx);
6574
6575        // Move A to right of B
6576        pane_a.update_in(cx, |pane, window, cx| {
6577            let dragged_tab = DraggedTab {
6578                pane: pane_a.clone(),
6579                item: item_a.boxed_clone(),
6580                ix: 0,
6581                detail: 0,
6582                is_active: true,
6583            };
6584            pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6585        });
6586
6587        // A should be after B and all are pinned
6588        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
6589
6590        // Move A to right of C
6591        pane_a.update_in(cx, |pane, window, cx| {
6592            let dragged_tab = DraggedTab {
6593                pane: pane_a.clone(),
6594                item: item_a.boxed_clone(),
6595                ix: 1,
6596                detail: 0,
6597                is_active: true,
6598            };
6599            pane.handle_tab_drop(&dragged_tab, 2, false, window, cx);
6600        });
6601
6602        // A should be after C and all are pinned
6603        assert_item_labels(&pane_a, ["B!", "C!", "A*!"], cx);
6604
6605        // Move A to left of C
6606        pane_a.update_in(cx, |pane, window, cx| {
6607            let dragged_tab = DraggedTab {
6608                pane: pane_a.clone(),
6609                item: item_a.boxed_clone(),
6610                ix: 2,
6611                detail: 0,
6612                is_active: true,
6613            };
6614            pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6615        });
6616
6617        // A should be before C and all are pinned
6618        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
6619
6620        // Move A to left of B
6621        pane_a.update_in(cx, |pane, window, cx| {
6622            let dragged_tab = DraggedTab {
6623                pane: pane_a.clone(),
6624                item: item_a.boxed_clone(),
6625                ix: 1,
6626                detail: 0,
6627                is_active: true,
6628            };
6629            pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6630        });
6631
6632        // A should be before B and all are pinned
6633        assert_item_labels(&pane_a, ["A*!", "B!", "C!"], cx);
6634    }
6635
6636    #[gpui::test]
6637    async fn test_drag_first_tab_to_last_position(cx: &mut TestAppContext) {
6638        init_test(cx);
6639        let fs = FakeFs::new(cx.executor());
6640
6641        let project = Project::test(fs, None, cx).await;
6642        let (workspace, cx) =
6643            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6644        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6645
6646        // Add A, B, C
6647        let item_a = add_labeled_item(&pane_a, "A", false, cx);
6648        add_labeled_item(&pane_a, "B", false, cx);
6649        add_labeled_item(&pane_a, "C", false, cx);
6650        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
6651
6652        // Move A to the end
6653        pane_a.update_in(cx, |pane, window, cx| {
6654            let dragged_tab = DraggedTab {
6655                pane: pane_a.clone(),
6656                item: item_a.boxed_clone(),
6657                ix: 0,
6658                detail: 0,
6659                is_active: true,
6660            };
6661            pane.handle_tab_drop(&dragged_tab, 2, false, window, cx);
6662        });
6663
6664        // A should be at the end
6665        assert_item_labels(&pane_a, ["B", "C", "A*"], cx);
6666    }
6667
6668    #[gpui::test]
6669    async fn test_drag_last_tab_to_first_position(cx: &mut TestAppContext) {
6670        init_test(cx);
6671        let fs = FakeFs::new(cx.executor());
6672
6673        let project = Project::test(fs, None, cx).await;
6674        let (workspace, cx) =
6675            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6676        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6677
6678        // Add A, B, C
6679        add_labeled_item(&pane_a, "A", false, cx);
6680        add_labeled_item(&pane_a, "B", false, cx);
6681        let item_c = add_labeled_item(&pane_a, "C", false, cx);
6682        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
6683
6684        // Move C to the beginning
6685        pane_a.update_in(cx, |pane, window, cx| {
6686            let dragged_tab = DraggedTab {
6687                pane: pane_a.clone(),
6688                item: item_c.boxed_clone(),
6689                ix: 2,
6690                detail: 0,
6691                is_active: true,
6692            };
6693            pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6694        });
6695
6696        // C should be at the beginning
6697        assert_item_labels(&pane_a, ["C*", "A", "B"], cx);
6698    }
6699
6700    #[gpui::test]
6701    async fn test_drag_tab_to_middle_tab_with_mouse_events(cx: &mut TestAppContext) {
6702        init_test(cx);
6703        let fs = FakeFs::new(cx.executor());
6704
6705        let project = Project::test(fs, None, cx).await;
6706        let (workspace, cx) =
6707            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6708        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6709
6710        add_labeled_item(&pane, "A", false, cx);
6711        add_labeled_item(&pane, "B", false, cx);
6712        add_labeled_item(&pane, "C", false, cx);
6713        add_labeled_item(&pane, "D", false, cx);
6714        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6715        cx.run_until_parked();
6716
6717        let tab_a_bounds = cx
6718            .debug_bounds("TAB-0")
6719            .expect("Tab A (index 0) should have debug bounds");
6720        let tab_c_bounds = cx
6721            .debug_bounds("TAB-2")
6722            .expect("Tab C (index 2) should have debug bounds");
6723
6724        cx.simulate_event(MouseDownEvent {
6725            position: tab_a_bounds.center(),
6726            button: MouseButton::Left,
6727            modifiers: Modifiers::default(),
6728            click_count: 1,
6729            first_mouse: false,
6730        });
6731        cx.run_until_parked();
6732        cx.simulate_event(MouseMoveEvent {
6733            position: tab_c_bounds.center(),
6734            pressed_button: Some(MouseButton::Left),
6735            modifiers: Modifiers::default(),
6736        });
6737        cx.run_until_parked();
6738        cx.simulate_event(MouseUpEvent {
6739            position: tab_c_bounds.center(),
6740            button: MouseButton::Left,
6741            modifiers: Modifiers::default(),
6742            click_count: 1,
6743        });
6744        cx.run_until_parked();
6745
6746        assert_item_labels(&pane, ["B", "C", "A*", "D"], cx);
6747    }
6748
6749    #[gpui::test]
6750    async fn test_drag_pinned_tab_when_show_pinned_tabs_in_separate_row_enabled(
6751        cx: &mut TestAppContext,
6752    ) {
6753        init_test(cx);
6754        set_pinned_tabs_separate_row(cx, true);
6755        let fs = FakeFs::new(cx.executor());
6756
6757        let project = Project::test(fs, None, cx).await;
6758        let (workspace, cx) =
6759            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6760        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6761
6762        let item_a = add_labeled_item(&pane, "A", false, cx);
6763        let item_b = add_labeled_item(&pane, "B", false, cx);
6764        let item_c = add_labeled_item(&pane, "C", false, cx);
6765        let item_d = add_labeled_item(&pane, "D", false, cx);
6766
6767        pane.update_in(cx, |pane, window, cx| {
6768            pane.pin_tab_at(
6769                pane.index_for_item_id(item_a.item_id()).unwrap(),
6770                window,
6771                cx,
6772            );
6773            pane.pin_tab_at(
6774                pane.index_for_item_id(item_b.item_id()).unwrap(),
6775                window,
6776                cx,
6777            );
6778            pane.pin_tab_at(
6779                pane.index_for_item_id(item_c.item_id()).unwrap(),
6780                window,
6781                cx,
6782            );
6783            pane.pin_tab_at(
6784                pane.index_for_item_id(item_d.item_id()).unwrap(),
6785                window,
6786                cx,
6787            );
6788        });
6789        assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
6790        cx.run_until_parked();
6791
6792        let tab_a_bounds = cx
6793            .debug_bounds("TAB-0")
6794            .expect("Tab A (index 0) should have debug bounds");
6795        let tab_c_bounds = cx
6796            .debug_bounds("TAB-2")
6797            .expect("Tab C (index 2) should have debug bounds");
6798
6799        cx.simulate_event(MouseDownEvent {
6800            position: tab_a_bounds.center(),
6801            button: MouseButton::Left,
6802            modifiers: Modifiers::default(),
6803            click_count: 1,
6804            first_mouse: false,
6805        });
6806        cx.run_until_parked();
6807        cx.simulate_event(MouseMoveEvent {
6808            position: tab_c_bounds.center(),
6809            pressed_button: Some(MouseButton::Left),
6810            modifiers: Modifiers::default(),
6811        });
6812        cx.run_until_parked();
6813        cx.simulate_event(MouseUpEvent {
6814            position: tab_c_bounds.center(),
6815            button: MouseButton::Left,
6816            modifiers: Modifiers::default(),
6817            click_count: 1,
6818        });
6819        cx.run_until_parked();
6820
6821        assert_item_labels(&pane, ["B!", "C!", "A*!", "D!"], cx);
6822    }
6823
6824    #[gpui::test]
6825    async fn test_drag_unpinned_tab_when_show_pinned_tabs_in_separate_row_enabled(
6826        cx: &mut TestAppContext,
6827    ) {
6828        init_test(cx);
6829        set_pinned_tabs_separate_row(cx, true);
6830        let fs = FakeFs::new(cx.executor());
6831
6832        let project = Project::test(fs, None, cx).await;
6833        let (workspace, cx) =
6834            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6835        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6836
6837        add_labeled_item(&pane, "A", false, cx);
6838        add_labeled_item(&pane, "B", false, cx);
6839        add_labeled_item(&pane, "C", false, cx);
6840        add_labeled_item(&pane, "D", false, cx);
6841        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6842        cx.run_until_parked();
6843
6844        let tab_a_bounds = cx
6845            .debug_bounds("TAB-0")
6846            .expect("Tab A (index 0) should have debug bounds");
6847        let tab_c_bounds = cx
6848            .debug_bounds("TAB-2")
6849            .expect("Tab C (index 2) should have debug bounds");
6850
6851        cx.simulate_event(MouseDownEvent {
6852            position: tab_a_bounds.center(),
6853            button: MouseButton::Left,
6854            modifiers: Modifiers::default(),
6855            click_count: 1,
6856            first_mouse: false,
6857        });
6858        cx.run_until_parked();
6859        cx.simulate_event(MouseMoveEvent {
6860            position: tab_c_bounds.center(),
6861            pressed_button: Some(MouseButton::Left),
6862            modifiers: Modifiers::default(),
6863        });
6864        cx.run_until_parked();
6865        cx.simulate_event(MouseUpEvent {
6866            position: tab_c_bounds.center(),
6867            button: MouseButton::Left,
6868            modifiers: Modifiers::default(),
6869            click_count: 1,
6870        });
6871        cx.run_until_parked();
6872
6873        assert_item_labels(&pane, ["B", "C", "A*", "D"], cx);
6874    }
6875
6876    #[gpui::test]
6877    async fn test_drag_mixed_tabs_when_show_pinned_tabs_in_separate_row_enabled(
6878        cx: &mut TestAppContext,
6879    ) {
6880        init_test(cx);
6881        set_pinned_tabs_separate_row(cx, true);
6882        let fs = FakeFs::new(cx.executor());
6883
6884        let project = Project::test(fs, None, cx).await;
6885        let (workspace, cx) =
6886            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6887        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6888
6889        let item_a = add_labeled_item(&pane, "A", false, cx);
6890        let item_b = add_labeled_item(&pane, "B", false, cx);
6891        add_labeled_item(&pane, "C", false, cx);
6892        add_labeled_item(&pane, "D", false, cx);
6893        add_labeled_item(&pane, "E", false, cx);
6894        add_labeled_item(&pane, "F", false, cx);
6895
6896        pane.update_in(cx, |pane, window, cx| {
6897            pane.pin_tab_at(
6898                pane.index_for_item_id(item_a.item_id()).unwrap(),
6899                window,
6900                cx,
6901            );
6902            pane.pin_tab_at(
6903                pane.index_for_item_id(item_b.item_id()).unwrap(),
6904                window,
6905                cx,
6906            );
6907        });
6908        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E", "F*"], cx);
6909        cx.run_until_parked();
6910
6911        let tab_c_bounds = cx
6912            .debug_bounds("TAB-2")
6913            .expect("Tab C (index 2) should have debug bounds");
6914        let tab_e_bounds = cx
6915            .debug_bounds("TAB-4")
6916            .expect("Tab E (index 4) should have debug bounds");
6917
6918        cx.simulate_event(MouseDownEvent {
6919            position: tab_c_bounds.center(),
6920            button: MouseButton::Left,
6921            modifiers: Modifiers::default(),
6922            click_count: 1,
6923            first_mouse: false,
6924        });
6925        cx.run_until_parked();
6926        cx.simulate_event(MouseMoveEvent {
6927            position: tab_e_bounds.center(),
6928            pressed_button: Some(MouseButton::Left),
6929            modifiers: Modifiers::default(),
6930        });
6931        cx.run_until_parked();
6932        cx.simulate_event(MouseUpEvent {
6933            position: tab_e_bounds.center(),
6934            button: MouseButton::Left,
6935            modifiers: Modifiers::default(),
6936            click_count: 1,
6937        });
6938        cx.run_until_parked();
6939
6940        assert_item_labels(&pane, ["A!", "B!", "D", "E", "C*", "F"], cx);
6941    }
6942
6943    #[gpui::test]
6944    async fn test_middle_click_pinned_tab_does_not_close(cx: &mut TestAppContext) {
6945        init_test(cx);
6946        let fs = FakeFs::new(cx.executor());
6947
6948        let project = Project::test(fs, None, cx).await;
6949        let (workspace, cx) =
6950            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6951        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6952
6953        let item_a = add_labeled_item(&pane, "A", false, cx);
6954        add_labeled_item(&pane, "B", false, cx);
6955
6956        pane.update_in(cx, |pane, window, cx| {
6957            pane.pin_tab_at(
6958                pane.index_for_item_id(item_a.item_id()).unwrap(),
6959                window,
6960                cx,
6961            );
6962        });
6963        assert_item_labels(&pane, ["A!", "B*"], cx);
6964        cx.run_until_parked();
6965
6966        let tab_a_bounds = cx
6967            .debug_bounds("TAB-0")
6968            .expect("Tab A (index 1) should have debug bounds");
6969        let tab_b_bounds = cx
6970            .debug_bounds("TAB-1")
6971            .expect("Tab B (index 2) should have debug bounds");
6972
6973        cx.simulate_event(MouseDownEvent {
6974            position: tab_a_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_a_bounds.center(),
6985            button: MouseButton::Middle,
6986            modifiers: Modifiers::default(),
6987            click_count: 1,
6988        });
6989
6990        cx.run_until_parked();
6991
6992        cx.simulate_event(MouseDownEvent {
6993            position: tab_b_bounds.center(),
6994            button: MouseButton::Middle,
6995            modifiers: Modifiers::default(),
6996            click_count: 1,
6997            first_mouse: false,
6998        });
6999
7000        cx.run_until_parked();
7001
7002        cx.simulate_event(MouseUpEvent {
7003            position: tab_b_bounds.center(),
7004            button: MouseButton::Middle,
7005            modifiers: Modifiers::default(),
7006            click_count: 1,
7007        });
7008
7009        cx.run_until_parked();
7010
7011        assert_item_labels(&pane, ["A*!"], cx);
7012    }
7013
7014    #[gpui::test]
7015    async fn test_double_click_pinned_tab_bar_empty_space_creates_new_tab(cx: &mut TestAppContext) {
7016        init_test(cx);
7017        let fs = FakeFs::new(cx.executor());
7018
7019        let project = Project::test(fs, None, cx).await;
7020        let (workspace, cx) =
7021            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7022        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7023
7024        // The real NewFile handler lives in editor::init, which isn't initialized
7025        // in workspace tests. Register a global action handler that sets a flag so
7026        // we can verify the action is dispatched without depending on the editor crate.
7027        // TODO: If editor::init is ever available in workspace tests, remove this
7028        // flag and assert the resulting tab bar state directly instead.
7029        let new_file_dispatched = Rc::new(Cell::new(false));
7030        cx.update(|_, cx| {
7031            let new_file_dispatched = new_file_dispatched.clone();
7032            cx.on_action(move |_: &NewFile, _cx| {
7033                new_file_dispatched.set(true);
7034            });
7035        });
7036
7037        set_pinned_tabs_separate_row(cx, true);
7038
7039        let item_a = add_labeled_item(&pane, "A", false, cx);
7040        add_labeled_item(&pane, "B", false, cx);
7041
7042        pane.update_in(cx, |pane, window, cx| {
7043            let ix = pane
7044                .index_for_item_id(item_a.item_id())
7045                .expect("item A should exist");
7046            pane.pin_tab_at(ix, window, cx);
7047        });
7048        assert_item_labels(&pane, ["A!", "B*"], cx);
7049        cx.run_until_parked();
7050
7051        let pinned_drop_target_bounds = cx
7052            .debug_bounds("pinned_tabs_border")
7053            .expect("pinned_tabs_border should have debug bounds");
7054
7055        cx.simulate_event(MouseDownEvent {
7056            position: pinned_drop_target_bounds.center(),
7057            button: MouseButton::Left,
7058            modifiers: Modifiers::default(),
7059            click_count: 2,
7060            first_mouse: false,
7061        });
7062
7063        cx.run_until_parked();
7064
7065        cx.simulate_event(MouseUpEvent {
7066            position: pinned_drop_target_bounds.center(),
7067            button: MouseButton::Left,
7068            modifiers: Modifiers::default(),
7069            click_count: 2,
7070        });
7071
7072        cx.run_until_parked();
7073
7074        // TODO: If editor::init is ever available in workspace tests, replace this
7075        // with an assert_item_labels check that verifies a new tab is actually created.
7076        assert!(
7077            new_file_dispatched.get(),
7078            "Double-clicking pinned tab bar empty space should dispatch the new file action"
7079        );
7080    }
7081
7082    #[gpui::test]
7083    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
7084        init_test(cx);
7085        let fs = FakeFs::new(cx.executor());
7086
7087        let project = Project::test(fs, None, cx).await;
7088        let (workspace, cx) =
7089            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7090        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7091
7092        // 1. Add with a destination index
7093        //   a. Add before the active item
7094        set_labeled_items(&pane, ["A", "B*", "C"], cx);
7095        pane.update_in(cx, |pane, window, cx| {
7096            pane.add_item(
7097                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
7098                false,
7099                false,
7100                Some(0),
7101                window,
7102                cx,
7103            );
7104        });
7105        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
7106
7107        //   b. Add after the active item
7108        set_labeled_items(&pane, ["A", "B*", "C"], cx);
7109        pane.update_in(cx, |pane, window, cx| {
7110            pane.add_item(
7111                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
7112                false,
7113                false,
7114                Some(2),
7115                window,
7116                cx,
7117            );
7118        });
7119        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
7120
7121        //   c. Add at the end of the item list (including off the length)
7122        set_labeled_items(&pane, ["A", "B*", "C"], cx);
7123        pane.update_in(cx, |pane, window, cx| {
7124            pane.add_item(
7125                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
7126                false,
7127                false,
7128                Some(5),
7129                window,
7130                cx,
7131            );
7132        });
7133        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7134
7135        // 2. Add without a destination index
7136        //   a. Add with active item at the start of the item list
7137        set_labeled_items(&pane, ["A*", "B", "C"], cx);
7138        pane.update_in(cx, |pane, window, cx| {
7139            pane.add_item(
7140                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
7141                false,
7142                false,
7143                None,
7144                window,
7145                cx,
7146            );
7147        });
7148        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
7149
7150        //   b. Add with active item at the end of the item list
7151        set_labeled_items(&pane, ["A", "B", "C*"], cx);
7152        pane.update_in(cx, |pane, window, cx| {
7153            pane.add_item(
7154                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
7155                false,
7156                false,
7157                None,
7158                window,
7159                cx,
7160            );
7161        });
7162        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7163    }
7164
7165    #[gpui::test]
7166    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
7167        init_test(cx);
7168        let fs = FakeFs::new(cx.executor());
7169
7170        let project = Project::test(fs, None, cx).await;
7171        let (workspace, cx) =
7172            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7173        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7174
7175        // 1. Add with a destination index
7176        //   1a. Add before the active item
7177        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
7178        pane.update_in(cx, |pane, window, cx| {
7179            pane.add_item(d, false, false, Some(0), window, cx);
7180        });
7181        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
7182
7183        //   1b. Add after the active item
7184        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
7185        pane.update_in(cx, |pane, window, cx| {
7186            pane.add_item(d, false, false, Some(2), window, cx);
7187        });
7188        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
7189
7190        //   1c. Add at the end of the item list (including off the length)
7191        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
7192        pane.update_in(cx, |pane, window, cx| {
7193            pane.add_item(a, false, false, Some(5), window, cx);
7194        });
7195        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
7196
7197        //   1d. Add same item to active index
7198        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
7199        pane.update_in(cx, |pane, window, cx| {
7200            pane.add_item(b, false, false, Some(1), window, cx);
7201        });
7202        assert_item_labels(&pane, ["A", "B*", "C"], cx);
7203
7204        //   1e. Add item to index after same item in last position
7205        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
7206        pane.update_in(cx, |pane, window, cx| {
7207            pane.add_item(c, false, false, Some(2), window, cx);
7208        });
7209        assert_item_labels(&pane, ["A", "B", "C*"], cx);
7210
7211        // 2. Add without a destination index
7212        //   2a. Add with active item at the start of the item list
7213        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
7214        pane.update_in(cx, |pane, window, cx| {
7215            pane.add_item(d, false, false, None, window, cx);
7216        });
7217        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
7218
7219        //   2b. Add with active item at the end of the item list
7220        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
7221        pane.update_in(cx, |pane, window, cx| {
7222            pane.add_item(a, false, false, None, window, cx);
7223        });
7224        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
7225
7226        //   2c. Add active item to active item at end of list
7227        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
7228        pane.update_in(cx, |pane, window, cx| {
7229            pane.add_item(c, false, false, None, window, cx);
7230        });
7231        assert_item_labels(&pane, ["A", "B", "C*"], cx);
7232
7233        //   2d. Add active item to active item at start of list
7234        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
7235        pane.update_in(cx, |pane, window, cx| {
7236            pane.add_item(a, false, false, None, window, cx);
7237        });
7238        assert_item_labels(&pane, ["A*", "B", "C"], cx);
7239    }
7240
7241    #[gpui::test]
7242    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
7243        init_test(cx);
7244        let fs = FakeFs::new(cx.executor());
7245
7246        let project = Project::test(fs, None, cx).await;
7247        let (workspace, cx) =
7248            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7249        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7250
7251        // singleton view
7252        pane.update_in(cx, |pane, window, cx| {
7253            pane.add_item(
7254                Box::new(cx.new(|cx| {
7255                    TestItem::new(cx)
7256                        .with_buffer_kind(ItemBufferKind::Singleton)
7257                        .with_label("buffer 1")
7258                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
7259                })),
7260                false,
7261                false,
7262                None,
7263                window,
7264                cx,
7265            );
7266        });
7267        assert_item_labels(&pane, ["buffer 1*"], cx);
7268
7269        // new singleton view with the same project entry
7270        pane.update_in(cx, |pane, window, cx| {
7271            pane.add_item(
7272                Box::new(cx.new(|cx| {
7273                    TestItem::new(cx)
7274                        .with_buffer_kind(ItemBufferKind::Singleton)
7275                        .with_label("buffer 1")
7276                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
7277                })),
7278                false,
7279                false,
7280                None,
7281                window,
7282                cx,
7283            );
7284        });
7285        assert_item_labels(&pane, ["buffer 1*"], cx);
7286
7287        // new singleton view with different project entry
7288        pane.update_in(cx, |pane, window, cx| {
7289            pane.add_item(
7290                Box::new(cx.new(|cx| {
7291                    TestItem::new(cx)
7292                        .with_buffer_kind(ItemBufferKind::Singleton)
7293                        .with_label("buffer 2")
7294                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
7295                })),
7296                false,
7297                false,
7298                None,
7299                window,
7300                cx,
7301            );
7302        });
7303        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
7304
7305        // new multibuffer view with the same project entry
7306        pane.update_in(cx, |pane, window, cx| {
7307            pane.add_item(
7308                Box::new(cx.new(|cx| {
7309                    TestItem::new(cx)
7310                        .with_buffer_kind(ItemBufferKind::Multibuffer)
7311                        .with_label("multibuffer 1")
7312                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
7313                })),
7314                false,
7315                false,
7316                None,
7317                window,
7318                cx,
7319            );
7320        });
7321        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
7322
7323        // another multibuffer view with the same project entry
7324        pane.update_in(cx, |pane, window, cx| {
7325            pane.add_item(
7326                Box::new(cx.new(|cx| {
7327                    TestItem::new(cx)
7328                        .with_buffer_kind(ItemBufferKind::Multibuffer)
7329                        .with_label("multibuffer 1b")
7330                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
7331                })),
7332                false,
7333                false,
7334                None,
7335                window,
7336                cx,
7337            );
7338        });
7339        assert_item_labels(
7340            &pane,
7341            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
7342            cx,
7343        );
7344    }
7345
7346    #[gpui::test]
7347    async fn test_remove_item_ordering_history(cx: &mut TestAppContext) {
7348        init_test(cx);
7349        let fs = FakeFs::new(cx.executor());
7350
7351        let project = Project::test(fs, None, cx).await;
7352        let (workspace, cx) =
7353            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7354        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7355
7356        add_labeled_item(&pane, "A", false, cx);
7357        add_labeled_item(&pane, "B", false, cx);
7358        add_labeled_item(&pane, "C", false, cx);
7359        add_labeled_item(&pane, "D", false, cx);
7360        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7361
7362        pane.update_in(cx, |pane, window, cx| {
7363            pane.activate_item(1, false, false, window, cx)
7364        });
7365        add_labeled_item(&pane, "1", false, cx);
7366        assert_item_labels(&pane, ["A", "B", "1*", "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", "D"], cx);
7381
7382        pane.update_in(cx, |pane, window, cx| {
7383            pane.activate_item(3, false, false, window, cx)
7384        });
7385        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7386
7387        pane.update_in(cx, |pane, window, cx| {
7388            pane.close_active_item(
7389                &CloseActiveItem {
7390                    save_intent: None,
7391                    close_pinned: false,
7392                },
7393                window,
7394                cx,
7395            )
7396        })
7397        .await
7398        .unwrap();
7399        assert_item_labels(&pane, ["A", "B*", "C"], cx);
7400
7401        pane.update_in(cx, |pane, window, cx| {
7402            pane.close_active_item(
7403                &CloseActiveItem {
7404                    save_intent: None,
7405                    close_pinned: false,
7406                },
7407                window,
7408                cx,
7409            )
7410        })
7411        .await
7412        .unwrap();
7413        assert_item_labels(&pane, ["A", "C*"], cx);
7414
7415        pane.update_in(cx, |pane, window, cx| {
7416            pane.close_active_item(
7417                &CloseActiveItem {
7418                    save_intent: None,
7419                    close_pinned: false,
7420                },
7421                window,
7422                cx,
7423            )
7424        })
7425        .await
7426        .unwrap();
7427        assert_item_labels(&pane, ["A*"], cx);
7428    }
7429
7430    #[gpui::test]
7431    async fn test_remove_item_ordering_neighbour(cx: &mut TestAppContext) {
7432        init_test(cx);
7433        cx.update_global::<SettingsStore, ()>(|s, cx| {
7434            s.update_user_settings(cx, |s| {
7435                s.tabs.get_or_insert_default().activate_on_close = Some(ActivateOnClose::Neighbour);
7436            });
7437        });
7438        let fs = FakeFs::new(cx.executor());
7439
7440        let project = Project::test(fs, None, cx).await;
7441        let (workspace, cx) =
7442            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7443        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7444
7445        add_labeled_item(&pane, "A", false, cx);
7446        add_labeled_item(&pane, "B", false, cx);
7447        add_labeled_item(&pane, "C", false, cx);
7448        add_labeled_item(&pane, "D", false, cx);
7449        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7450
7451        pane.update_in(cx, |pane, window, cx| {
7452            pane.activate_item(1, false, false, window, cx)
7453        });
7454        add_labeled_item(&pane, "1", false, cx);
7455        assert_item_labels(&pane, ["A", "B", "1*", "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*", "D"], cx);
7470
7471        pane.update_in(cx, |pane, window, cx| {
7472            pane.activate_item(3, false, false, window, cx)
7473        });
7474        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7475
7476        pane.update_in(cx, |pane, window, cx| {
7477            pane.close_active_item(
7478                &CloseActiveItem {
7479                    save_intent: None,
7480                    close_pinned: false,
7481                },
7482                window,
7483                cx,
7484            )
7485        })
7486        .await
7487        .unwrap();
7488        assert_item_labels(&pane, ["A", "B", "C*"], cx);
7489
7490        pane.update_in(cx, |pane, window, cx| {
7491            pane.close_active_item(
7492                &CloseActiveItem {
7493                    save_intent: None,
7494                    close_pinned: false,
7495                },
7496                window,
7497                cx,
7498            )
7499        })
7500        .await
7501        .unwrap();
7502        assert_item_labels(&pane, ["A", "B*"], cx);
7503
7504        pane.update_in(cx, |pane, window, cx| {
7505            pane.close_active_item(
7506                &CloseActiveItem {
7507                    save_intent: None,
7508                    close_pinned: false,
7509                },
7510                window,
7511                cx,
7512            )
7513        })
7514        .await
7515        .unwrap();
7516        assert_item_labels(&pane, ["A*"], cx);
7517    }
7518
7519    #[gpui::test]
7520    async fn test_remove_item_ordering_left_neighbour(cx: &mut TestAppContext) {
7521        init_test(cx);
7522        cx.update_global::<SettingsStore, ()>(|s, cx| {
7523            s.update_user_settings(cx, |s| {
7524                s.tabs.get_or_insert_default().activate_on_close =
7525                    Some(ActivateOnClose::LeftNeighbour);
7526            });
7527        });
7528        let fs = FakeFs::new(cx.executor());
7529
7530        let project = Project::test(fs, None, cx).await;
7531        let (workspace, cx) =
7532            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7533        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7534
7535        add_labeled_item(&pane, "A", false, cx);
7536        add_labeled_item(&pane, "B", false, cx);
7537        add_labeled_item(&pane, "C", false, cx);
7538        add_labeled_item(&pane, "D", false, cx);
7539        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7540
7541        pane.update_in(cx, |pane, window, cx| {
7542            pane.activate_item(1, false, false, window, cx)
7543        });
7544        add_labeled_item(&pane, "1", false, cx);
7545        assert_item_labels(&pane, ["A", "B", "1*", "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", "D"], cx);
7560
7561        pane.update_in(cx, |pane, window, cx| {
7562            pane.activate_item(3, false, false, window, cx)
7563        });
7564        assert_item_labels(&pane, ["A", "B", "C", "D*"], 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, ["A", "B", "C*"], cx);
7579
7580        pane.update_in(cx, |pane, window, cx| {
7581            pane.activate_item(0, false, false, window, cx)
7582        });
7583        assert_item_labels(&pane, ["A*", "B", "C"], cx);
7584
7585        pane.update_in(cx, |pane, window, cx| {
7586            pane.close_active_item(
7587                &CloseActiveItem {
7588                    save_intent: None,
7589                    close_pinned: false,
7590                },
7591                window,
7592                cx,
7593            )
7594        })
7595        .await
7596        .unwrap();
7597        assert_item_labels(&pane, ["B*", "C"], cx);
7598
7599        pane.update_in(cx, |pane, window, cx| {
7600            pane.close_active_item(
7601                &CloseActiveItem {
7602                    save_intent: None,
7603                    close_pinned: false,
7604                },
7605                window,
7606                cx,
7607            )
7608        })
7609        .await
7610        .unwrap();
7611        assert_item_labels(&pane, ["C*"], cx);
7612    }
7613
7614    #[gpui::test]
7615    async fn test_close_inactive_items(cx: &mut TestAppContext) {
7616        init_test(cx);
7617        let fs = FakeFs::new(cx.executor());
7618
7619        let project = Project::test(fs, None, cx).await;
7620        let (workspace, cx) =
7621            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7622        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7623
7624        let item_a = add_labeled_item(&pane, "A", false, cx);
7625        pane.update_in(cx, |pane, window, cx| {
7626            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
7627            pane.pin_tab_at(ix, window, cx);
7628        });
7629        assert_item_labels(&pane, ["A*!"], cx);
7630
7631        let item_b = add_labeled_item(&pane, "B", false, cx);
7632        pane.update_in(cx, |pane, window, cx| {
7633            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
7634            pane.pin_tab_at(ix, window, cx);
7635        });
7636        assert_item_labels(&pane, ["A!", "B*!"], cx);
7637
7638        add_labeled_item(&pane, "C", false, cx);
7639        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
7640
7641        add_labeled_item(&pane, "D", false, cx);
7642        add_labeled_item(&pane, "E", false, cx);
7643        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
7644
7645        pane.update_in(cx, |pane, window, cx| {
7646            pane.close_other_items(
7647                &CloseOtherItems {
7648                    save_intent: None,
7649                    close_pinned: false,
7650                },
7651                None,
7652                window,
7653                cx,
7654            )
7655        })
7656        .await
7657        .unwrap();
7658        assert_item_labels(&pane, ["A!", "B!", "E*"], cx);
7659    }
7660
7661    #[gpui::test]
7662    async fn test_running_close_inactive_items_via_an_inactive_item(cx: &mut TestAppContext) {
7663        init_test(cx);
7664        let fs = FakeFs::new(cx.executor());
7665
7666        let project = Project::test(fs, None, cx).await;
7667        let (workspace, cx) =
7668            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7669        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7670
7671        add_labeled_item(&pane, "A", false, cx);
7672        assert_item_labels(&pane, ["A*"], cx);
7673
7674        let item_b = add_labeled_item(&pane, "B", false, cx);
7675        assert_item_labels(&pane, ["A", "B*"], cx);
7676
7677        add_labeled_item(&pane, "C", false, cx);
7678        add_labeled_item(&pane, "D", false, cx);
7679        add_labeled_item(&pane, "E", false, cx);
7680        assert_item_labels(&pane, ["A", "B", "C", "D", "E*"], cx);
7681
7682        pane.update_in(cx, |pane, window, cx| {
7683            pane.close_other_items(
7684                &CloseOtherItems {
7685                    save_intent: None,
7686                    close_pinned: false,
7687                },
7688                Some(item_b.item_id()),
7689                window,
7690                cx,
7691            )
7692        })
7693        .await
7694        .unwrap();
7695        assert_item_labels(&pane, ["B*"], cx);
7696    }
7697
7698    #[gpui::test]
7699    async fn test_close_other_items_unpreviews_active_item(cx: &mut TestAppContext) {
7700        init_test(cx);
7701        let fs = FakeFs::new(cx.executor());
7702
7703        let project = Project::test(fs, None, cx).await;
7704        let (workspace, cx) =
7705            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7706        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7707
7708        add_labeled_item(&pane, "A", false, cx);
7709        add_labeled_item(&pane, "B", false, cx);
7710        let item_c = add_labeled_item(&pane, "C", false, cx);
7711        assert_item_labels(&pane, ["A", "B", "C*"], cx);
7712
7713        pane.update(cx, |pane, cx| {
7714            pane.set_preview_item_id(Some(item_c.item_id()), cx);
7715        });
7716        assert!(pane.read_with(cx, |pane, _| pane.preview_item_id()
7717            == Some(item_c.item_id())));
7718
7719        pane.update_in(cx, |pane, window, cx| {
7720            pane.close_other_items(
7721                &CloseOtherItems {
7722                    save_intent: None,
7723                    close_pinned: false,
7724                },
7725                Some(item_c.item_id()),
7726                window,
7727                cx,
7728            )
7729        })
7730        .await
7731        .unwrap();
7732
7733        assert!(pane.read_with(cx, |pane, _| pane.preview_item_id().is_none()));
7734        assert_item_labels(&pane, ["C*"], cx);
7735    }
7736
7737    #[gpui::test]
7738    async fn test_close_clean_items(cx: &mut TestAppContext) {
7739        init_test(cx);
7740        let fs = FakeFs::new(cx.executor());
7741
7742        let project = Project::test(fs, None, cx).await;
7743        let (workspace, cx) =
7744            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7745        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7746
7747        add_labeled_item(&pane, "A", true, cx);
7748        add_labeled_item(&pane, "B", false, cx);
7749        add_labeled_item(&pane, "C", true, cx);
7750        add_labeled_item(&pane, "D", false, cx);
7751        add_labeled_item(&pane, "E", false, cx);
7752        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
7753
7754        pane.update_in(cx, |pane, window, cx| {
7755            pane.close_clean_items(
7756                &CloseCleanItems {
7757                    close_pinned: false,
7758                },
7759                window,
7760                cx,
7761            )
7762        })
7763        .await
7764        .unwrap();
7765        assert_item_labels(&pane, ["A^", "C*^"], cx);
7766    }
7767
7768    #[gpui::test]
7769    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
7770        init_test(cx);
7771        let fs = FakeFs::new(cx.executor());
7772
7773        let project = Project::test(fs, None, cx).await;
7774        let (workspace, cx) =
7775            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7776        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7777
7778        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
7779
7780        pane.update_in(cx, |pane, window, cx| {
7781            pane.close_items_to_the_left_by_id(
7782                None,
7783                &CloseItemsToTheLeft {
7784                    close_pinned: false,
7785                },
7786                window,
7787                cx,
7788            )
7789        })
7790        .await
7791        .unwrap();
7792        assert_item_labels(&pane, ["C*", "D", "E"], cx);
7793    }
7794
7795    #[gpui::test]
7796    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
7797        init_test(cx);
7798        let fs = FakeFs::new(cx.executor());
7799
7800        let project = Project::test(fs, None, cx).await;
7801        let (workspace, cx) =
7802            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7803        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7804
7805        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
7806
7807        pane.update_in(cx, |pane, window, cx| {
7808            pane.close_items_to_the_right_by_id(
7809                None,
7810                &CloseItemsToTheRight {
7811                    close_pinned: false,
7812                },
7813                window,
7814                cx,
7815            )
7816        })
7817        .await
7818        .unwrap();
7819        assert_item_labels(&pane, ["A", "B", "C*"], cx);
7820    }
7821
7822    #[gpui::test]
7823    async fn test_close_all_items(cx: &mut TestAppContext) {
7824        init_test(cx);
7825        let fs = FakeFs::new(cx.executor());
7826
7827        let project = Project::test(fs, None, cx).await;
7828        let (workspace, cx) =
7829            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7830        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7831
7832        let item_a = add_labeled_item(&pane, "A", false, cx);
7833        add_labeled_item(&pane, "B", false, cx);
7834        add_labeled_item(&pane, "C", false, cx);
7835        assert_item_labels(&pane, ["A", "B", "C*"], cx);
7836
7837        pane.update_in(cx, |pane, window, cx| {
7838            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
7839            pane.pin_tab_at(ix, window, cx);
7840            pane.close_all_items(
7841                &CloseAllItems {
7842                    save_intent: None,
7843                    close_pinned: false,
7844                },
7845                window,
7846                cx,
7847            )
7848        })
7849        .await
7850        .unwrap();
7851        assert_item_labels(&pane, ["A*!"], cx);
7852
7853        pane.update_in(cx, |pane, window, cx| {
7854            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
7855            pane.unpin_tab_at(ix, window, cx);
7856            pane.close_all_items(
7857                &CloseAllItems {
7858                    save_intent: None,
7859                    close_pinned: false,
7860                },
7861                window,
7862                cx,
7863            )
7864        })
7865        .await
7866        .unwrap();
7867
7868        assert_item_labels(&pane, [], cx);
7869
7870        add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
7871            item.project_items
7872                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
7873        });
7874        add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
7875            item.project_items
7876                .push(TestProjectItem::new_dirty(2, "B.txt", cx))
7877        });
7878        add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
7879            item.project_items
7880                .push(TestProjectItem::new_dirty(3, "C.txt", cx))
7881        });
7882        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
7883
7884        let save = pane.update_in(cx, |pane, window, cx| {
7885            pane.close_all_items(
7886                &CloseAllItems {
7887                    save_intent: None,
7888                    close_pinned: false,
7889                },
7890                window,
7891                cx,
7892            )
7893        });
7894
7895        cx.executor().run_until_parked();
7896        cx.simulate_prompt_answer("Save all");
7897        save.await.unwrap();
7898        assert_item_labels(&pane, [], cx);
7899
7900        add_labeled_item(&pane, "A", true, cx);
7901        add_labeled_item(&pane, "B", true, cx);
7902        add_labeled_item(&pane, "C", true, cx);
7903        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
7904        let save = pane.update_in(cx, |pane, window, cx| {
7905            pane.close_all_items(
7906                &CloseAllItems {
7907                    save_intent: None,
7908                    close_pinned: false,
7909                },
7910                window,
7911                cx,
7912            )
7913        });
7914
7915        cx.executor().run_until_parked();
7916        cx.simulate_prompt_answer("Discard all");
7917        save.await.unwrap();
7918        assert_item_labels(&pane, [], cx);
7919
7920        add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
7921            item.project_items
7922                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
7923        });
7924        add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
7925            item.project_items
7926                .push(TestProjectItem::new_dirty(2, "B.txt", cx))
7927        });
7928        add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
7929            item.project_items
7930                .push(TestProjectItem::new_dirty(3, "C.txt", cx))
7931        });
7932        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
7933
7934        let close_task = pane.update_in(cx, |pane, window, cx| {
7935            pane.close_all_items(
7936                &CloseAllItems {
7937                    save_intent: None,
7938                    close_pinned: false,
7939                },
7940                window,
7941                cx,
7942            )
7943        });
7944
7945        cx.executor().run_until_parked();
7946        cx.simulate_prompt_answer("Discard all");
7947        close_task.await.unwrap();
7948        assert_item_labels(&pane, [], cx);
7949
7950        add_labeled_item(&pane, "Clean1", false, cx);
7951        add_labeled_item(&pane, "Dirty", true, cx).update(cx, |item, cx| {
7952            item.project_items
7953                .push(TestProjectItem::new_dirty(1, "Dirty.txt", cx))
7954        });
7955        add_labeled_item(&pane, "Clean2", false, cx);
7956        assert_item_labels(&pane, ["Clean1", "Dirty^", "Clean2*"], cx);
7957
7958        let close_task = pane.update_in(cx, |pane, window, cx| {
7959            pane.close_all_items(
7960                &CloseAllItems {
7961                    save_intent: None,
7962                    close_pinned: false,
7963                },
7964                window,
7965                cx,
7966            )
7967        });
7968
7969        cx.executor().run_until_parked();
7970        cx.simulate_prompt_answer("Cancel");
7971        close_task.await.unwrap();
7972        assert_item_labels(&pane, ["Dirty*^"], cx);
7973    }
7974
7975    #[gpui::test]
7976    async fn test_discard_all_reloads_from_disk(cx: &mut TestAppContext) {
7977        init_test(cx);
7978        let fs = FakeFs::new(cx.executor());
7979
7980        let project = Project::test(fs, None, cx).await;
7981        let (workspace, cx) =
7982            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7983        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7984
7985        let item_a = add_labeled_item(&pane, "A", true, cx);
7986        item_a.update(cx, |item, cx| {
7987            item.project_items
7988                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
7989        });
7990        let item_b = add_labeled_item(&pane, "B", true, cx);
7991        item_b.update(cx, |item, cx| {
7992            item.project_items
7993                .push(TestProjectItem::new_dirty(2, "B.txt", cx))
7994        });
7995        assert_item_labels(&pane, ["A^", "B*^"], cx);
7996
7997        let close_task = pane.update_in(cx, |pane, window, cx| {
7998            pane.close_all_items(
7999                &CloseAllItems {
8000                    save_intent: None,
8001                    close_pinned: false,
8002                },
8003                window,
8004                cx,
8005            )
8006        });
8007
8008        cx.executor().run_until_parked();
8009        cx.simulate_prompt_answer("Discard all");
8010        close_task.await.unwrap();
8011        assert_item_labels(&pane, [], cx);
8012
8013        item_a.read_with(cx, |item, _| {
8014            assert_eq!(item.reload_count, 1, "item A should have been reloaded");
8015            assert!(
8016                !item.is_dirty,
8017                "item A should no longer be dirty after reload"
8018            );
8019        });
8020        item_b.read_with(cx, |item, _| {
8021            assert_eq!(item.reload_count, 1, "item B should have been reloaded");
8022            assert!(
8023                !item.is_dirty,
8024                "item B should no longer be dirty after reload"
8025            );
8026        });
8027    }
8028
8029    #[gpui::test]
8030    async fn test_dont_save_single_file_reloads_from_disk(cx: &mut TestAppContext) {
8031        init_test(cx);
8032        let fs = FakeFs::new(cx.executor());
8033
8034        let project = Project::test(fs, None, cx).await;
8035        let (workspace, cx) =
8036            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8037        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8038
8039        let item = add_labeled_item(&pane, "Dirty", true, cx);
8040        item.update(cx, |item, cx| {
8041            item.project_items
8042                .push(TestProjectItem::new_dirty(1, "Dirty.txt", cx))
8043        });
8044        assert_item_labels(&pane, ["Dirty*^"], cx);
8045
8046        let close_task = pane.update_in(cx, |pane, window, cx| {
8047            pane.close_item_by_id(item.item_id(), SaveIntent::Close, window, cx)
8048        });
8049
8050        cx.executor().run_until_parked();
8051        cx.simulate_prompt_answer("Don't Save");
8052        close_task.await.unwrap();
8053        assert_item_labels(&pane, [], cx);
8054
8055        item.read_with(cx, |item, _| {
8056            assert_eq!(item.reload_count, 1, "item should have been reloaded");
8057            assert!(
8058                !item.is_dirty,
8059                "item should no longer be dirty after reload"
8060            );
8061        });
8062    }
8063
8064    #[gpui::test]
8065    async fn test_discard_does_not_reload_multibuffer(cx: &mut TestAppContext) {
8066        init_test(cx);
8067        let fs = FakeFs::new(cx.executor());
8068
8069        let project = Project::test(fs, None, cx).await;
8070        let (workspace, cx) =
8071            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8072        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8073
8074        let singleton_item = pane.update_in(cx, |pane, window, cx| {
8075            let item = Box::new(cx.new(|cx| {
8076                TestItem::new(cx)
8077                    .with_label("Singleton")
8078                    .with_dirty(true)
8079                    .with_buffer_kind(ItemBufferKind::Singleton)
8080            }));
8081            pane.add_item(item.clone(), false, false, None, window, cx);
8082            item
8083        });
8084        singleton_item.update(cx, |item, cx| {
8085            item.project_items
8086                .push(TestProjectItem::new_dirty(1, "Singleton.txt", cx))
8087        });
8088
8089        let multi_item = pane.update_in(cx, |pane, window, cx| {
8090            let item = Box::new(cx.new(|cx| {
8091                TestItem::new(cx)
8092                    .with_label("Multi")
8093                    .with_dirty(true)
8094                    .with_buffer_kind(ItemBufferKind::Multibuffer)
8095            }));
8096            pane.add_item(item.clone(), false, false, None, window, cx);
8097            item
8098        });
8099        multi_item.update(cx, |item, cx| {
8100            item.project_items
8101                .push(TestProjectItem::new_dirty(2, "Multi.txt", cx))
8102        });
8103
8104        let close_task = pane.update_in(cx, |pane, window, cx| {
8105            pane.close_all_items(
8106                &CloseAllItems {
8107                    save_intent: None,
8108                    close_pinned: false,
8109                },
8110                window,
8111                cx,
8112            )
8113        });
8114
8115        cx.executor().run_until_parked();
8116        cx.simulate_prompt_answer("Discard all");
8117        close_task.await.unwrap();
8118        assert_item_labels(&pane, [], cx);
8119
8120        singleton_item.read_with(cx, |item, _| {
8121            assert_eq!(item.reload_count, 1, "singleton should have been reloaded");
8122            assert!(
8123                !item.is_dirty,
8124                "singleton should no longer be dirty after reload"
8125            );
8126        });
8127        multi_item.read_with(cx, |item, _| {
8128            assert_eq!(
8129                item.reload_count, 0,
8130                "multibuffer should not have been reloaded"
8131            );
8132        });
8133    }
8134
8135    #[gpui::test]
8136    async fn test_close_multibuffer_items(cx: &mut TestAppContext) {
8137        init_test(cx);
8138        let fs = FakeFs::new(cx.executor());
8139
8140        let project = Project::test(fs, None, cx).await;
8141        let (workspace, cx) =
8142            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8143        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8144
8145        let add_labeled_item = |pane: &Entity<Pane>,
8146                                label,
8147                                is_dirty,
8148                                kind: ItemBufferKind,
8149                                cx: &mut VisualTestContext| {
8150            pane.update_in(cx, |pane, window, cx| {
8151                let labeled_item = Box::new(cx.new(|cx| {
8152                    TestItem::new(cx)
8153                        .with_label(label)
8154                        .with_dirty(is_dirty)
8155                        .with_buffer_kind(kind)
8156                }));
8157                pane.add_item(labeled_item.clone(), false, false, None, window, cx);
8158                labeled_item
8159            })
8160        };
8161
8162        let item_a = add_labeled_item(&pane, "A", false, ItemBufferKind::Multibuffer, cx);
8163        add_labeled_item(&pane, "B", false, ItemBufferKind::Multibuffer, cx);
8164        add_labeled_item(&pane, "C", false, ItemBufferKind::Singleton, cx);
8165        assert_item_labels(&pane, ["A", "B", "C*"], cx);
8166
8167        pane.update_in(cx, |pane, window, cx| {
8168            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
8169            pane.pin_tab_at(ix, window, cx);
8170            pane.close_multibuffer_items(
8171                &CloseMultibufferItems {
8172                    save_intent: None,
8173                    close_pinned: false,
8174                },
8175                window,
8176                cx,
8177            )
8178        })
8179        .await
8180        .unwrap();
8181        assert_item_labels(&pane, ["A!", "C*"], cx);
8182
8183        pane.update_in(cx, |pane, window, cx| {
8184            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
8185            pane.unpin_tab_at(ix, window, cx);
8186            pane.close_multibuffer_items(
8187                &CloseMultibufferItems {
8188                    save_intent: None,
8189                    close_pinned: false,
8190                },
8191                window,
8192                cx,
8193            )
8194        })
8195        .await
8196        .unwrap();
8197
8198        assert_item_labels(&pane, ["C*"], cx);
8199
8200        add_labeled_item(&pane, "A", true, ItemBufferKind::Singleton, cx).update(cx, |item, cx| {
8201            item.project_items
8202                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
8203        });
8204        add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
8205            cx,
8206            |item, cx| {
8207                item.project_items
8208                    .push(TestProjectItem::new_dirty(2, "B.txt", cx))
8209            },
8210        );
8211        add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
8212            cx,
8213            |item, cx| {
8214                item.project_items
8215                    .push(TestProjectItem::new_dirty(3, "D.txt", cx))
8216            },
8217        );
8218        assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
8219
8220        let save = pane.update_in(cx, |pane, window, cx| {
8221            pane.close_multibuffer_items(
8222                &CloseMultibufferItems {
8223                    save_intent: None,
8224                    close_pinned: false,
8225                },
8226                window,
8227                cx,
8228            )
8229        });
8230
8231        cx.executor().run_until_parked();
8232        cx.simulate_prompt_answer("Save all");
8233        save.await.unwrap();
8234        assert_item_labels(&pane, ["C", "A*^"], cx);
8235
8236        add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
8237            cx,
8238            |item, cx| {
8239                item.project_items
8240                    .push(TestProjectItem::new_dirty(2, "B.txt", cx))
8241            },
8242        );
8243        add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
8244            cx,
8245            |item, cx| {
8246                item.project_items
8247                    .push(TestProjectItem::new_dirty(3, "D.txt", cx))
8248            },
8249        );
8250        assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
8251        let save = pane.update_in(cx, |pane, window, cx| {
8252            pane.close_multibuffer_items(
8253                &CloseMultibufferItems {
8254                    save_intent: None,
8255                    close_pinned: false,
8256                },
8257                window,
8258                cx,
8259            )
8260        });
8261
8262        cx.executor().run_until_parked();
8263        cx.simulate_prompt_answer("Discard all");
8264        save.await.unwrap();
8265        assert_item_labels(&pane, ["C", "A*^"], cx);
8266    }
8267
8268    #[gpui::test]
8269    async fn test_close_with_save_intent(cx: &mut TestAppContext) {
8270        init_test(cx);
8271        let fs = FakeFs::new(cx.executor());
8272
8273        let project = Project::test(fs, None, cx).await;
8274        let (workspace, cx) =
8275            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8276        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8277
8278        let a = cx.update(|_, cx| TestProjectItem::new_dirty(1, "A.txt", cx));
8279        let b = cx.update(|_, cx| TestProjectItem::new_dirty(1, "B.txt", cx));
8280        let c = cx.update(|_, cx| TestProjectItem::new_dirty(1, "C.txt", cx));
8281
8282        add_labeled_item(&pane, "AB", true, cx).update(cx, |item, _| {
8283            item.project_items.push(a.clone());
8284            item.project_items.push(b.clone());
8285        });
8286        add_labeled_item(&pane, "C", true, cx)
8287            .update(cx, |item, _| item.project_items.push(c.clone()));
8288        assert_item_labels(&pane, ["AB^", "C*^"], cx);
8289
8290        pane.update_in(cx, |pane, window, cx| {
8291            pane.close_all_items(
8292                &CloseAllItems {
8293                    save_intent: Some(SaveIntent::Save),
8294                    close_pinned: false,
8295                },
8296                window,
8297                cx,
8298            )
8299        })
8300        .await
8301        .unwrap();
8302
8303        assert_item_labels(&pane, [], cx);
8304        cx.update(|_, cx| {
8305            assert!(!a.read(cx).is_dirty);
8306            assert!(!b.read(cx).is_dirty);
8307            assert!(!c.read(cx).is_dirty);
8308        });
8309    }
8310
8311    #[gpui::test]
8312    async fn test_new_tab_scrolls_into_view_completely(cx: &mut TestAppContext) {
8313        // Arrange
8314        init_test(cx);
8315        let fs = FakeFs::new(cx.executor());
8316
8317        let project = Project::test(fs, None, cx).await;
8318        let (workspace, cx) =
8319            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8320        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8321
8322        cx.simulate_resize(size(px(300.), px(300.)));
8323
8324        add_labeled_item(&pane, "untitled", false, cx);
8325        add_labeled_item(&pane, "untitled", false, cx);
8326        add_labeled_item(&pane, "untitled", false, cx);
8327        add_labeled_item(&pane, "untitled", false, cx);
8328        // Act: this should trigger a scroll
8329        add_labeled_item(&pane, "untitled", false, cx);
8330        // Assert
8331        let tab_bar_scroll_handle =
8332            pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
8333        assert_eq!(tab_bar_scroll_handle.children_count(), 6);
8334        let tab_bounds = cx.debug_bounds("TAB-4").unwrap();
8335        let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
8336        let scroll_bounds = tab_bar_scroll_handle.bounds();
8337        let scroll_offset = tab_bar_scroll_handle.offset();
8338        assert!(tab_bounds.right() <= scroll_bounds.right());
8339        // -39.5 is the magic number for this setup
8340        assert_eq!(scroll_offset.x, px(-39.5));
8341        assert!(
8342            !tab_bounds.intersects(&new_tab_button_bounds),
8343            "Tab should not overlap with the new tab button, if this is failing check if there's been a redesign!"
8344        );
8345    }
8346
8347    #[gpui::test]
8348    async fn test_pinned_tabs_scroll_to_item_uses_correct_index(cx: &mut TestAppContext) {
8349        init_test(cx);
8350        let fs = FakeFs::new(cx.executor());
8351
8352        let project = Project::test(fs, None, cx).await;
8353        let (workspace, cx) =
8354            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8355        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8356
8357        cx.simulate_resize(size(px(400.), px(300.)));
8358
8359        for label in ["A", "B", "C"] {
8360            add_labeled_item(&pane, label, false, cx);
8361        }
8362
8363        pane.update_in(cx, |pane, window, cx| {
8364            pane.pin_tab_at(0, window, cx);
8365            pane.pin_tab_at(1, window, cx);
8366            pane.pin_tab_at(2, window, cx);
8367        });
8368
8369        for label in ["D", "E", "F", "G", "H", "I", "J", "K"] {
8370            add_labeled_item(&pane, label, false, cx);
8371        }
8372
8373        assert_item_labels(
8374            &pane,
8375            ["A!", "B!", "C!", "D", "E", "F", "G", "H", "I", "J", "K*"],
8376            cx,
8377        );
8378
8379        cx.run_until_parked();
8380
8381        // Verify overflow exists (precondition for scroll test)
8382        let scroll_handle =
8383            pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
8384        assert!(
8385            scroll_handle.max_offset().x > px(0.),
8386            "Test requires tab overflow to verify scrolling. Increase tab count or reduce window width."
8387        );
8388
8389        // Activate a different tab first, then activate K
8390        // This ensures we're not just re-activating an already-active tab
8391        pane.update_in(cx, |pane, window, cx| {
8392            pane.activate_item(3, true, true, window, cx);
8393        });
8394        cx.run_until_parked();
8395
8396        pane.update_in(cx, |pane, window, cx| {
8397            pane.activate_item(10, true, true, window, cx);
8398        });
8399        cx.run_until_parked();
8400
8401        let scroll_handle =
8402            pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
8403        let k_tab_bounds = cx.debug_bounds("TAB-10").unwrap();
8404        let scroll_bounds = scroll_handle.bounds();
8405
8406        assert!(
8407            k_tab_bounds.left() >= scroll_bounds.left(),
8408            "Active tab K should be scrolled into view"
8409        );
8410    }
8411
8412    #[gpui::test]
8413    async fn test_close_all_items_including_pinned(cx: &mut TestAppContext) {
8414        init_test(cx);
8415        let fs = FakeFs::new(cx.executor());
8416
8417        let project = Project::test(fs, None, cx).await;
8418        let (workspace, cx) =
8419            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8420        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8421
8422        let item_a = add_labeled_item(&pane, "A", false, cx);
8423        add_labeled_item(&pane, "B", false, cx);
8424        add_labeled_item(&pane, "C", false, cx);
8425        assert_item_labels(&pane, ["A", "B", "C*"], cx);
8426
8427        pane.update_in(cx, |pane, window, cx| {
8428            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
8429            pane.pin_tab_at(ix, window, cx);
8430            pane.close_all_items(
8431                &CloseAllItems {
8432                    save_intent: None,
8433                    close_pinned: true,
8434                },
8435                window,
8436                cx,
8437            )
8438        })
8439        .await
8440        .unwrap();
8441        assert_item_labels(&pane, [], cx);
8442    }
8443
8444    #[gpui::test]
8445    async fn test_close_pinned_tab_with_non_pinned_in_same_pane(cx: &mut TestAppContext) {
8446        init_test(cx);
8447        let fs = FakeFs::new(cx.executor());
8448        let project = Project::test(fs, None, cx).await;
8449        let (workspace, cx) =
8450            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8451
8452        // Non-pinned tabs in same pane
8453        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8454        add_labeled_item(&pane, "A", false, cx);
8455        add_labeled_item(&pane, "B", false, cx);
8456        add_labeled_item(&pane, "C", false, cx);
8457        pane.update_in(cx, |pane, window, cx| {
8458            pane.pin_tab_at(0, window, cx);
8459        });
8460        set_labeled_items(&pane, ["A*", "B", "C"], cx);
8461        pane.update_in(cx, |pane, window, cx| {
8462            pane.close_active_item(
8463                &CloseActiveItem {
8464                    save_intent: None,
8465                    close_pinned: false,
8466                },
8467                window,
8468                cx,
8469            )
8470            .unwrap();
8471        });
8472        // Non-pinned tab should be active
8473        assert_item_labels(&pane, ["A!", "B*", "C"], cx);
8474    }
8475
8476    #[gpui::test]
8477    async fn test_close_pinned_tab_with_non_pinned_in_different_pane(cx: &mut TestAppContext) {
8478        init_test(cx);
8479        let fs = FakeFs::new(cx.executor());
8480        let project = Project::test(fs, None, cx).await;
8481        let (workspace, cx) =
8482            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8483
8484        // No non-pinned tabs in same pane, non-pinned tabs in another pane
8485        let pane1 = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8486        let pane2 = workspace.update_in(cx, |workspace, window, cx| {
8487            workspace.split_pane(pane1.clone(), SplitDirection::Right, window, cx)
8488        });
8489        add_labeled_item(&pane1, "A", false, cx);
8490        pane1.update_in(cx, |pane, window, cx| {
8491            pane.pin_tab_at(0, window, cx);
8492        });
8493        set_labeled_items(&pane1, ["A*"], cx);
8494        add_labeled_item(&pane2, "B", false, cx);
8495        set_labeled_items(&pane2, ["B"], cx);
8496        pane1.update_in(cx, |pane, window, cx| {
8497            pane.close_active_item(
8498                &CloseActiveItem {
8499                    save_intent: None,
8500                    close_pinned: false,
8501                },
8502                window,
8503                cx,
8504            )
8505            .unwrap();
8506        });
8507        //  Non-pinned tab of other pane should be active
8508        assert_item_labels(&pane2, ["B*"], cx);
8509    }
8510
8511    #[gpui::test]
8512    async fn ensure_item_closing_actions_do_not_panic_when_no_items_exist(cx: &mut TestAppContext) {
8513        init_test(cx);
8514        let fs = FakeFs::new(cx.executor());
8515        let project = Project::test(fs, None, cx).await;
8516        let (workspace, cx) =
8517            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8518
8519        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8520        assert_item_labels(&pane, [], cx);
8521
8522        pane.update_in(cx, |pane, window, cx| {
8523            pane.close_active_item(
8524                &CloseActiveItem {
8525                    save_intent: None,
8526                    close_pinned: false,
8527                },
8528                window,
8529                cx,
8530            )
8531        })
8532        .await
8533        .unwrap();
8534
8535        pane.update_in(cx, |pane, window, cx| {
8536            pane.close_other_items(
8537                &CloseOtherItems {
8538                    save_intent: None,
8539                    close_pinned: false,
8540                },
8541                None,
8542                window,
8543                cx,
8544            )
8545        })
8546        .await
8547        .unwrap();
8548
8549        pane.update_in(cx, |pane, window, cx| {
8550            pane.close_all_items(
8551                &CloseAllItems {
8552                    save_intent: None,
8553                    close_pinned: false,
8554                },
8555                window,
8556                cx,
8557            )
8558        })
8559        .await
8560        .unwrap();
8561
8562        pane.update_in(cx, |pane, window, cx| {
8563            pane.close_clean_items(
8564                &CloseCleanItems {
8565                    close_pinned: false,
8566                },
8567                window,
8568                cx,
8569            )
8570        })
8571        .await
8572        .unwrap();
8573
8574        pane.update_in(cx, |pane, window, cx| {
8575            pane.close_items_to_the_right_by_id(
8576                None,
8577                &CloseItemsToTheRight {
8578                    close_pinned: false,
8579                },
8580                window,
8581                cx,
8582            )
8583        })
8584        .await
8585        .unwrap();
8586
8587        pane.update_in(cx, |pane, window, cx| {
8588            pane.close_items_to_the_left_by_id(
8589                None,
8590                &CloseItemsToTheLeft {
8591                    close_pinned: false,
8592                },
8593                window,
8594                cx,
8595            )
8596        })
8597        .await
8598        .unwrap();
8599    }
8600
8601    #[gpui::test]
8602    async fn test_item_swapping_actions(cx: &mut TestAppContext) {
8603        init_test(cx);
8604        let fs = FakeFs::new(cx.executor());
8605        let project = Project::test(fs, None, cx).await;
8606        let (workspace, cx) =
8607            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8608
8609        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8610        assert_item_labels(&pane, [], cx);
8611
8612        // Test that these actions do not panic
8613        pane.update_in(cx, |pane, window, cx| {
8614            pane.swap_item_right(&Default::default(), window, cx);
8615        });
8616
8617        pane.update_in(cx, |pane, window, cx| {
8618            pane.swap_item_left(&Default::default(), window, cx);
8619        });
8620
8621        add_labeled_item(&pane, "A", false, cx);
8622        add_labeled_item(&pane, "B", false, cx);
8623        add_labeled_item(&pane, "C", false, cx);
8624        assert_item_labels(&pane, ["A", "B", "C*"], cx);
8625
8626        pane.update_in(cx, |pane, window, cx| {
8627            pane.swap_item_right(&Default::default(), window, cx);
8628        });
8629        assert_item_labels(&pane, ["A", "B", "C*"], cx);
8630
8631        pane.update_in(cx, |pane, window, cx| {
8632            pane.swap_item_left(&Default::default(), window, cx);
8633        });
8634        assert_item_labels(&pane, ["A", "C*", "B"], cx);
8635
8636        pane.update_in(cx, |pane, window, cx| {
8637            pane.swap_item_left(&Default::default(), window, cx);
8638        });
8639        assert_item_labels(&pane, ["C*", "A", "B"], cx);
8640
8641        pane.update_in(cx, |pane, window, cx| {
8642            pane.swap_item_left(&Default::default(), window, cx);
8643        });
8644        assert_item_labels(&pane, ["C*", "A", "B"], cx);
8645
8646        pane.update_in(cx, |pane, window, cx| {
8647            pane.swap_item_right(&Default::default(), window, cx);
8648        });
8649        assert_item_labels(&pane, ["A", "C*", "B"], cx);
8650    }
8651
8652    #[gpui::test]
8653    async fn test_split_empty(cx: &mut TestAppContext) {
8654        for split_direction in SplitDirection::all() {
8655            test_single_pane_split(["A"], split_direction, SplitMode::EmptyPane, cx).await;
8656        }
8657    }
8658
8659    #[gpui::test]
8660    async fn test_split_clone(cx: &mut TestAppContext) {
8661        for split_direction in SplitDirection::all() {
8662            test_single_pane_split(["A"], split_direction, SplitMode::ClonePane, cx).await;
8663        }
8664    }
8665
8666    #[gpui::test]
8667    async fn test_split_move_right_on_single_pane(cx: &mut TestAppContext) {
8668        test_single_pane_split(["A"], SplitDirection::Right, SplitMode::MovePane, cx).await;
8669    }
8670
8671    #[gpui::test]
8672    async fn test_split_move(cx: &mut TestAppContext) {
8673        for split_direction in SplitDirection::all() {
8674            test_single_pane_split(["A", "B"], split_direction, SplitMode::MovePane, cx).await;
8675        }
8676    }
8677
8678    #[gpui::test]
8679    async fn test_reopening_closed_item_after_unpreview(cx: &mut TestAppContext) {
8680        init_test(cx);
8681
8682        cx.update_global::<SettingsStore, ()>(|store, cx| {
8683            store.update_user_settings(cx, |settings| {
8684                settings.preview_tabs.get_or_insert_default().enabled = Some(true);
8685            });
8686        });
8687
8688        let fs = FakeFs::new(cx.executor());
8689        let project = Project::test(fs, None, cx).await;
8690        let (workspace, cx) =
8691            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8692        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8693
8694        // Add an item as preview
8695        let item = pane.update_in(cx, |pane, window, cx| {
8696            let item = Box::new(cx.new(|cx| TestItem::new(cx).with_label("A")));
8697            pane.add_item(item.clone(), true, true, None, window, cx);
8698            pane.set_preview_item_id(Some(item.item_id()), cx);
8699            item
8700        });
8701
8702        // Verify item is preview
8703        pane.read_with(cx, |pane, _| {
8704            assert_eq!(pane.preview_item_id(), Some(item.item_id()));
8705        });
8706
8707        // Unpreview the item
8708        pane.update_in(cx, |pane, _window, _cx| {
8709            pane.unpreview_item_if_preview(item.item_id());
8710        });
8711
8712        // Verify item is no longer preview
8713        pane.read_with(cx, |pane, _| {
8714            assert_eq!(pane.preview_item_id(), None);
8715        });
8716
8717        // Close the item
8718        pane.update_in(cx, |pane, window, cx| {
8719            pane.close_item_by_id(item.item_id(), SaveIntent::Skip, window, cx)
8720                .detach_and_log_err(cx);
8721        });
8722
8723        cx.run_until_parked();
8724
8725        // The item should be in the closed_stack and reopenable
8726        let has_closed_items = pane.read_with(cx, |pane, _| {
8727            !pane.nav_history.0.lock().closed_stack.is_empty()
8728        });
8729        assert!(
8730            has_closed_items,
8731            "closed item should be in closed_stack and reopenable"
8732        );
8733    }
8734
8735    #[gpui::test]
8736    async fn test_activate_item_with_wrap_around(cx: &mut TestAppContext) {
8737        init_test(cx);
8738        let fs = FakeFs::new(cx.executor());
8739        let project = Project::test(fs, None, cx).await;
8740        let (workspace, cx) =
8741            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8742        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8743
8744        add_labeled_item(&pane, "A", false, cx);
8745        add_labeled_item(&pane, "B", false, cx);
8746        add_labeled_item(&pane, "C", false, cx);
8747        assert_item_labels(&pane, ["A", "B", "C*"], cx);
8748
8749        pane.update_in(cx, |pane, window, cx| {
8750            pane.activate_next_item(&ActivateNextItem { wrap_around: false }, window, cx);
8751        });
8752        assert_item_labels(&pane, ["A", "B", "C*"], cx);
8753
8754        pane.update_in(cx, |pane, window, cx| {
8755            pane.activate_next_item(&ActivateNextItem::default(), window, cx);
8756        });
8757        assert_item_labels(&pane, ["A*", "B", "C"], cx);
8758
8759        pane.update_in(cx, |pane, window, cx| {
8760            pane.activate_previous_item(&ActivatePreviousItem { wrap_around: false }, window, cx);
8761        });
8762        assert_item_labels(&pane, ["A*", "B", "C"], cx);
8763
8764        pane.update_in(cx, |pane, window, cx| {
8765            pane.activate_previous_item(&ActivatePreviousItem::default(), window, cx);
8766        });
8767        assert_item_labels(&pane, ["A", "B", "C*"], cx);
8768
8769        pane.update_in(cx, |pane, window, cx| {
8770            pane.activate_previous_item(&ActivatePreviousItem { wrap_around: false }, window, cx);
8771        });
8772        assert_item_labels(&pane, ["A", "B*", "C"], cx);
8773
8774        pane.update_in(cx, |pane, window, cx| {
8775            pane.activate_next_item(&ActivateNextItem { wrap_around: false }, window, cx);
8776        });
8777        assert_item_labels(&pane, ["A", "B", "C*"], cx);
8778    }
8779
8780    fn init_test(cx: &mut TestAppContext) {
8781        cx.update(|cx| {
8782            let settings_store = SettingsStore::test(cx);
8783            cx.set_global(settings_store);
8784            theme_settings::init(LoadThemes::JustBase, cx);
8785        });
8786    }
8787
8788    fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
8789        cx.update_global(|store: &mut SettingsStore, cx| {
8790            store.update_user_settings(cx, |settings| {
8791                settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
8792            });
8793        });
8794    }
8795
8796    fn set_pinned_tabs_separate_row(cx: &mut TestAppContext, enabled: bool) {
8797        cx.update_global(|store: &mut SettingsStore, cx| {
8798            store.update_user_settings(cx, |settings| {
8799                settings
8800                    .tab_bar
8801                    .get_or_insert_default()
8802                    .show_pinned_tabs_in_separate_row = Some(enabled);
8803            });
8804        });
8805    }
8806
8807    fn add_labeled_item(
8808        pane: &Entity<Pane>,
8809        label: &str,
8810        is_dirty: bool,
8811        cx: &mut VisualTestContext,
8812    ) -> Box<Entity<TestItem>> {
8813        pane.update_in(cx, |pane, window, cx| {
8814            let labeled_item =
8815                Box::new(cx.new(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)));
8816            pane.add_item(labeled_item.clone(), false, false, None, window, cx);
8817            labeled_item
8818        })
8819    }
8820
8821    fn set_labeled_items<const COUNT: usize>(
8822        pane: &Entity<Pane>,
8823        labels: [&str; COUNT],
8824        cx: &mut VisualTestContext,
8825    ) -> [Box<Entity<TestItem>>; COUNT] {
8826        pane.update_in(cx, |pane, window, cx| {
8827            pane.items.clear();
8828            let mut active_item_index = 0;
8829
8830            let mut index = 0;
8831            let items = labels.map(|mut label| {
8832                if label.ends_with('*') {
8833                    label = label.trim_end_matches('*');
8834                    active_item_index = index;
8835                }
8836
8837                let labeled_item = Box::new(cx.new(|cx| TestItem::new(cx).with_label(label)));
8838                pane.add_item(labeled_item.clone(), false, false, None, window, cx);
8839                index += 1;
8840                labeled_item
8841            });
8842
8843            pane.activate_item(active_item_index, false, false, window, cx);
8844
8845            items
8846        })
8847    }
8848
8849    // Assert the item label, with the active item label suffixed with a '*'
8850    #[track_caller]
8851    fn assert_item_labels<const COUNT: usize>(
8852        pane: &Entity<Pane>,
8853        expected_states: [&str; COUNT],
8854        cx: &mut VisualTestContext,
8855    ) {
8856        let actual_states = pane.update(cx, |pane, cx| {
8857            pane.items
8858                .iter()
8859                .enumerate()
8860                .map(|(ix, item)| {
8861                    let mut state = item
8862                        .to_any_view()
8863                        .downcast::<TestItem>()
8864                        .unwrap()
8865                        .read(cx)
8866                        .label
8867                        .clone();
8868                    if ix == pane.active_item_index {
8869                        state.push('*');
8870                    }
8871                    if item.is_dirty(cx) {
8872                        state.push('^');
8873                    }
8874                    if pane.is_tab_pinned(ix) {
8875                        state.push('!');
8876                    }
8877                    state
8878                })
8879                .collect::<Vec<_>>()
8880        });
8881        assert_eq!(
8882            actual_states, expected_states,
8883            "pane items do not match expectation"
8884        );
8885    }
8886
8887    // Assert the item label, with the active item label expected active index
8888    #[track_caller]
8889    fn assert_item_labels_active_index(
8890        pane: &Entity<Pane>,
8891        expected_states: &[&str],
8892        expected_active_idx: usize,
8893        cx: &mut VisualTestContext,
8894    ) {
8895        let actual_states = pane.update(cx, |pane, cx| {
8896            pane.items
8897                .iter()
8898                .enumerate()
8899                .map(|(ix, item)| {
8900                    let mut state = item
8901                        .to_any_view()
8902                        .downcast::<TestItem>()
8903                        .unwrap()
8904                        .read(cx)
8905                        .label
8906                        .clone();
8907                    if ix == pane.active_item_index {
8908                        assert_eq!(ix, expected_active_idx);
8909                    }
8910                    if item.is_dirty(cx) {
8911                        state.push('^');
8912                    }
8913                    if pane.is_tab_pinned(ix) {
8914                        state.push('!');
8915                    }
8916                    state
8917                })
8918                .collect::<Vec<_>>()
8919        });
8920        assert_eq!(
8921            actual_states, expected_states,
8922            "pane items do not match expectation"
8923        );
8924    }
8925
8926    #[track_caller]
8927    fn assert_pane_ids_on_axis<const COUNT: usize>(
8928        workspace: &Entity<Workspace>,
8929        expected_ids: [&EntityId; COUNT],
8930        expected_axis: Axis,
8931        cx: &mut VisualTestContext,
8932    ) {
8933        workspace.read_with(cx, |workspace, _| match &workspace.center.root {
8934            Member::Axis(axis) => {
8935                assert_eq!(axis.axis, expected_axis);
8936                assert_eq!(axis.members.len(), expected_ids.len());
8937                assert!(
8938                    zip(expected_ids, &axis.members).all(|(e, a)| {
8939                        if let Member::Pane(p) = a {
8940                            p.entity_id() == *e
8941                        } else {
8942                            false
8943                        }
8944                    }),
8945                    "pane ids do not match expectation: {expected_ids:?} != {actual_ids:?}",
8946                    actual_ids = axis.members
8947                );
8948            }
8949            Member::Pane(_) => panic!("expected axis"),
8950        });
8951    }
8952
8953    async fn test_single_pane_split<const COUNT: usize>(
8954        pane_labels: [&str; COUNT],
8955        direction: SplitDirection,
8956        operation: SplitMode,
8957        cx: &mut TestAppContext,
8958    ) {
8959        init_test(cx);
8960        let fs = FakeFs::new(cx.executor());
8961        let project = Project::test(fs, None, cx).await;
8962        let (workspace, cx) =
8963            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8964
8965        let mut pane_before =
8966            workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8967        for label in pane_labels {
8968            add_labeled_item(&pane_before, label, false, cx);
8969        }
8970        pane_before.update_in(cx, |pane, window, cx| {
8971            pane.split(direction, operation, window, cx)
8972        });
8973        cx.executor().run_until_parked();
8974        let pane_after = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8975
8976        let num_labels = pane_labels.len();
8977        let last_as_active = format!("{}*", String::from(pane_labels[num_labels - 1]));
8978
8979        // check labels for all split operations
8980        match operation {
8981            SplitMode::EmptyPane => {
8982                assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
8983                assert_item_labels(&pane_after, [], cx);
8984            }
8985            SplitMode::ClonePane => {
8986                assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
8987                assert_item_labels(&pane_after, [&last_as_active], cx);
8988            }
8989            SplitMode::MovePane => {
8990                let head = &pane_labels[..(num_labels - 1)];
8991                if num_labels == 1 {
8992                    // We special-case this behavior and actually execute an empty pane command
8993                    // followed by a refocus of the old pane for this case.
8994                    pane_before = workspace.read_with(cx, |workspace, _cx| {
8995                        workspace
8996                            .panes()
8997                            .into_iter()
8998                            .find(|pane| *pane != &pane_after)
8999                            .unwrap()
9000                            .clone()
9001                    });
9002                };
9003
9004                assert_item_labels_active_index(
9005                    &pane_before,
9006                    &head,
9007                    head.len().saturating_sub(1),
9008                    cx,
9009                );
9010                assert_item_labels(&pane_after, [&last_as_active], cx);
9011                pane_after.update_in(cx, |pane, window, cx| {
9012                    window.focused(cx).is_some_and(|focus_handle| {
9013                        focus_handle == pane.active_item().unwrap().item_focus_handle(cx)
9014                    })
9015                });
9016            }
9017        }
9018
9019        // expected axis depends on split direction
9020        let expected_axis = match direction {
9021            SplitDirection::Right | SplitDirection::Left => Axis::Horizontal,
9022            SplitDirection::Up | SplitDirection::Down => Axis::Vertical,
9023        };
9024
9025        // expected ids depends on split direction
9026        let expected_ids = match direction {
9027            SplitDirection::Right | SplitDirection::Down => {
9028                [&pane_before.entity_id(), &pane_after.entity_id()]
9029            }
9030            SplitDirection::Left | SplitDirection::Up => {
9031                [&pane_after.entity_id(), &pane_before.entity_id()]
9032            }
9033        };
9034
9035        // check pane axes for all operations
9036        match operation {
9037            SplitMode::EmptyPane | SplitMode::ClonePane => {
9038                assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
9039            }
9040            SplitMode::MovePane => {
9041                assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
9042            }
9043        }
9044    }
9045}