pane.rs

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