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