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