pane.rs

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