pane.rs

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