pane.rs

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