pane.rs

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