pane.rs

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