pane.rs

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