pane.rs

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