pane.rs

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