pane.rs

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