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