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, 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.project_path(cx).and_then(|path| {
1656                    path.path
1657                        .file_name()
1658                        .and_then(|name| name.to_str().map(ToOwned::to_owned))
1659                });
1660                file_names.insert(filename.unwrap_or("untitled".to_string()));
1661            });
1662        }
1663        if file_names.len() > 6 {
1664            format!(
1665                "{}\n.. and {} more",
1666                file_names.iter().take(5).join("\n"),
1667                file_names.len() - 5
1668            )
1669        } else {
1670            file_names.into_iter().join("\n")
1671        }
1672    }
1673
1674    pub fn close_items(
1675        &self,
1676        window: &mut Window,
1677        cx: &mut Context<Pane>,
1678        mut save_intent: SaveIntent,
1679        should_close: impl Fn(EntityId) -> bool,
1680    ) -> Task<Result<()>> {
1681        // Find the items to close.
1682        let mut items_to_close = Vec::new();
1683        for item in &self.items {
1684            if should_close(item.item_id()) {
1685                items_to_close.push(item.boxed_clone());
1686            }
1687        }
1688
1689        let active_item_id = self.active_item().map(|item| item.item_id());
1690
1691        items_to_close.sort_by_key(|item| {
1692            let path = item.project_path(cx);
1693            // Put the currently active item at the end, because if the currently active item is not closed last
1694            // closing the currently active item will cause the focus to switch to another item
1695            // This will cause Zed to expand the content of the currently active item
1696            //
1697            // Beyond that sort in order of project path, with untitled files and multibuffers coming last.
1698            (active_item_id == Some(item.item_id()), path.is_none(), path)
1699        });
1700
1701        let workspace = self.workspace.clone();
1702        let Some(project) = self.project.upgrade() else {
1703            return Task::ready(Ok(()));
1704        };
1705        cx.spawn_in(window, async move |pane, cx| {
1706            let dirty_items = workspace.update(cx, |workspace, cx| {
1707                items_to_close
1708                    .iter()
1709                    .filter(|item| {
1710                        item.is_dirty(cx) && !Self::skip_save_on_close(item.as_ref(), workspace, cx)
1711                    })
1712                    .map(|item| item.boxed_clone())
1713                    .collect::<Vec<_>>()
1714            })?;
1715
1716            if save_intent == SaveIntent::Close && dirty_items.len() > 1 {
1717                let answer = pane.update_in(cx, |_, window, cx| {
1718                    let detail = Self::file_names_for_prompt(&mut dirty_items.iter(), cx);
1719                    window.prompt(
1720                        PromptLevel::Warning,
1721                        "Do you want to save changes to the following files?",
1722                        Some(&detail),
1723                        &["Save all", "Discard all", "Cancel"],
1724                        cx,
1725                    )
1726                })?;
1727                match answer.await {
1728                    Ok(0) => save_intent = SaveIntent::SaveAll,
1729                    Ok(1) => save_intent = SaveIntent::Skip,
1730                    Ok(2) => return Ok(()),
1731                    _ => {}
1732                }
1733            }
1734
1735            for item_to_close in items_to_close {
1736                let mut should_save = true;
1737                if save_intent == SaveIntent::Close {
1738                    workspace.update(cx, |workspace, cx| {
1739                        if Self::skip_save_on_close(item_to_close.as_ref(), workspace, cx) {
1740                            should_save = false;
1741                        }
1742                    })?;
1743                }
1744
1745                if should_save {
1746                    match Self::save_item(project.clone(), &pane, &*item_to_close, save_intent, cx)
1747                        .await
1748                    {
1749                        Ok(success) => {
1750                            if !success {
1751                                break;
1752                            }
1753                        }
1754                        Err(err) => {
1755                            let answer = pane.update_in(cx, |_, window, cx| {
1756                                let detail = Self::file_names_for_prompt(
1757                                    &mut [&item_to_close].into_iter(),
1758                                    cx,
1759                                );
1760                                window.prompt(
1761                                    PromptLevel::Warning,
1762                                    &format!("Unable to save file: {}", &err),
1763                                    Some(&detail),
1764                                    &["Close Without Saving", "Cancel"],
1765                                    cx,
1766                                )
1767                            })?;
1768                            match answer.await {
1769                                Ok(0) => {}
1770                                Ok(1..) | Err(_) => break,
1771                            }
1772                        }
1773                    }
1774                }
1775
1776                // Remove the item from the pane.
1777                pane.update_in(cx, |pane, window, cx| {
1778                    pane.remove_item(
1779                        item_to_close.item_id(),
1780                        false,
1781                        pane.close_pane_if_empty,
1782                        window,
1783                        cx,
1784                    );
1785                })
1786                .ok();
1787            }
1788
1789            pane.update(cx, |_, cx| cx.notify()).ok();
1790            Ok(())
1791        })
1792    }
1793
1794    pub fn take_active_item(
1795        &mut self,
1796        window: &mut Window,
1797        cx: &mut Context<Self>,
1798    ) -> Option<Box<dyn ItemHandle>> {
1799        let item = self.active_item()?;
1800        self.remove_item(item.item_id(), false, false, window, cx);
1801        Some(item)
1802    }
1803
1804    pub fn remove_item(
1805        &mut self,
1806        item_id: EntityId,
1807        activate_pane: bool,
1808        close_pane_if_empty: bool,
1809        window: &mut Window,
1810        cx: &mut Context<Self>,
1811    ) {
1812        let Some(item_index) = self.index_for_item_id(item_id) else {
1813            return;
1814        };
1815        self._remove_item(
1816            item_index,
1817            activate_pane,
1818            close_pane_if_empty,
1819            None,
1820            window,
1821            cx,
1822        )
1823    }
1824
1825    pub fn remove_item_and_focus_on_pane(
1826        &mut self,
1827        item_index: usize,
1828        activate_pane: bool,
1829        focus_on_pane_if_closed: Entity<Pane>,
1830        window: &mut Window,
1831        cx: &mut Context<Self>,
1832    ) {
1833        self._remove_item(
1834            item_index,
1835            activate_pane,
1836            true,
1837            Some(focus_on_pane_if_closed),
1838            window,
1839            cx,
1840        )
1841    }
1842
1843    fn _remove_item(
1844        &mut self,
1845        item_index: usize,
1846        activate_pane: bool,
1847        close_pane_if_empty: bool,
1848        focus_on_pane_if_closed: Option<Entity<Pane>>,
1849        window: &mut Window,
1850        cx: &mut Context<Self>,
1851    ) {
1852        let activate_on_close = &ItemSettings::get_global(cx).activate_on_close;
1853        self.activation_history
1854            .retain(|entry| entry.entity_id != self.items[item_index].item_id());
1855
1856        if self.is_tab_pinned(item_index) {
1857            self.pinned_tab_count -= 1;
1858        }
1859        if item_index == self.active_item_index {
1860            let left_neighbour_index = || item_index.min(self.items.len()).saturating_sub(1);
1861            let index_to_activate = match activate_on_close {
1862                ActivateOnClose::History => self
1863                    .activation_history
1864                    .pop()
1865                    .and_then(|last_activated_item| {
1866                        self.items.iter().enumerate().find_map(|(index, item)| {
1867                            (item.item_id() == last_activated_item.entity_id).then_some(index)
1868                        })
1869                    })
1870                    // We didn't have a valid activation history entry, so fallback
1871                    // to activating the item to the left
1872                    .unwrap_or_else(left_neighbour_index),
1873                ActivateOnClose::Neighbour => {
1874                    self.activation_history.pop();
1875                    if item_index + 1 < self.items.len() {
1876                        item_index + 1
1877                    } else {
1878                        item_index.saturating_sub(1)
1879                    }
1880                }
1881                ActivateOnClose::LeftNeighbour => {
1882                    self.activation_history.pop();
1883                    left_neighbour_index()
1884                }
1885            };
1886
1887            let should_activate = activate_pane || self.has_focus(window, cx);
1888            if self.items.len() == 1 && should_activate {
1889                self.focus_handle.focus(window);
1890            } else {
1891                self.activate_item(
1892                    index_to_activate,
1893                    should_activate,
1894                    should_activate,
1895                    window,
1896                    cx,
1897                );
1898            }
1899        }
1900
1901        let item = self.items.remove(item_index);
1902
1903        cx.emit(Event::RemovedItem { item: item.clone() });
1904        if self.items.is_empty() {
1905            item.deactivated(window, cx);
1906            if close_pane_if_empty {
1907                self.update_toolbar(window, cx);
1908                cx.emit(Event::Remove {
1909                    focus_on_pane: focus_on_pane_if_closed,
1910                });
1911            }
1912        }
1913
1914        if item_index < self.active_item_index {
1915            self.active_item_index -= 1;
1916        }
1917
1918        let mode = self.nav_history.mode();
1919        self.nav_history.set_mode(NavigationMode::ClosingItem);
1920        item.deactivated(window, cx);
1921        item.on_removed(cx);
1922        self.nav_history.set_mode(mode);
1923
1924        if self.is_active_preview_item(item.item_id()) {
1925            self.set_preview_item_id(None, cx);
1926        }
1927
1928        if let Some(path) = item.project_path(cx) {
1929            let abs_path = self
1930                .nav_history
1931                .0
1932                .lock()
1933                .paths_by_item
1934                .get(&item.item_id())
1935                .and_then(|(_, abs_path)| abs_path.clone());
1936
1937            self.nav_history
1938                .0
1939                .lock()
1940                .paths_by_item
1941                .insert(item.item_id(), (path, abs_path));
1942        } else {
1943            self.nav_history
1944                .0
1945                .lock()
1946                .paths_by_item
1947                .remove(&item.item_id());
1948        }
1949
1950        if self.zoom_out_on_close && self.items.is_empty() && close_pane_if_empty && self.zoomed {
1951            cx.emit(Event::ZoomOut);
1952        }
1953
1954        cx.notify();
1955    }
1956
1957    pub async fn save_item(
1958        project: Entity<Project>,
1959        pane: &WeakEntity<Pane>,
1960        item: &dyn ItemHandle,
1961        save_intent: SaveIntent,
1962        cx: &mut AsyncWindowContext,
1963    ) -> Result<bool> {
1964        const CONFLICT_MESSAGE: &str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1965
1966        const DELETED_MESSAGE: &str = "This file has been deleted on disk since you started editing it. Do you want to recreate it?";
1967
1968        if save_intent == SaveIntent::Skip {
1969            return Ok(true);
1970        }
1971        let Some(item_ix) = pane
1972            .read_with(cx, |pane, _| pane.index_for_item(item))
1973            .ok()
1974            .flatten()
1975        else {
1976            return Ok(true);
1977        };
1978
1979        let (
1980            mut has_conflict,
1981            mut is_dirty,
1982            mut can_save,
1983            can_save_as,
1984            is_singleton,
1985            has_deleted_file,
1986        ) = cx.update(|_window, cx| {
1987            (
1988                item.has_conflict(cx),
1989                item.is_dirty(cx),
1990                item.can_save(cx),
1991                item.can_save_as(cx),
1992                item.is_singleton(cx),
1993                item.has_deleted_file(cx),
1994            )
1995        })?;
1996
1997        // when saving a single buffer, we ignore whether or not it's dirty.
1998        if save_intent == SaveIntent::Save || save_intent == SaveIntent::SaveWithoutFormat {
1999            is_dirty = true;
2000        }
2001
2002        if save_intent == SaveIntent::SaveAs {
2003            is_dirty = true;
2004            has_conflict = false;
2005            can_save = false;
2006        }
2007
2008        if save_intent == SaveIntent::Overwrite {
2009            has_conflict = false;
2010        }
2011
2012        let should_format = save_intent != SaveIntent::SaveWithoutFormat;
2013
2014        if has_conflict && can_save {
2015            if has_deleted_file && is_singleton {
2016                let answer = pane.update_in(cx, |pane, window, cx| {
2017                    pane.activate_item(item_ix, true, true, window, cx);
2018                    window.prompt(
2019                        PromptLevel::Warning,
2020                        DELETED_MESSAGE,
2021                        None,
2022                        &["Save", "Close", "Cancel"],
2023                        cx,
2024                    )
2025                })?;
2026                match answer.await {
2027                    Ok(0) => {
2028                        pane.update_in(cx, |_, window, cx| {
2029                            item.save(
2030                                SaveOptions {
2031                                    format: should_format,
2032                                    autosave: false,
2033                                },
2034                                project,
2035                                window,
2036                                cx,
2037                            )
2038                        })?
2039                        .await?
2040                    }
2041                    Ok(1) => {
2042                        pane.update_in(cx, |pane, window, cx| {
2043                            pane.remove_item(item.item_id(), false, true, window, cx)
2044                        })?;
2045                    }
2046                    _ => return Ok(false),
2047                }
2048                return Ok(true);
2049            } else {
2050                let answer = pane.update_in(cx, |pane, window, cx| {
2051                    pane.activate_item(item_ix, true, true, window, cx);
2052                    window.prompt(
2053                        PromptLevel::Warning,
2054                        CONFLICT_MESSAGE,
2055                        None,
2056                        &["Overwrite", "Discard", "Cancel"],
2057                        cx,
2058                    )
2059                })?;
2060                match answer.await {
2061                    Ok(0) => {
2062                        pane.update_in(cx, |_, window, cx| {
2063                            item.save(
2064                                SaveOptions {
2065                                    format: should_format,
2066                                    autosave: false,
2067                                },
2068                                project,
2069                                window,
2070                                cx,
2071                            )
2072                        })?
2073                        .await?
2074                    }
2075                    Ok(1) => {
2076                        pane.update_in(cx, |_, window, cx| item.reload(project, window, cx))?
2077                            .await?
2078                    }
2079                    _ => return Ok(false),
2080                }
2081            }
2082        } else if is_dirty && (can_save || can_save_as) {
2083            if save_intent == SaveIntent::Close {
2084                let will_autosave = cx.update(|_window, cx| {
2085                    item.can_autosave(cx)
2086                        && item.workspace_settings(cx).autosave.should_save_on_close()
2087                })?;
2088                if !will_autosave {
2089                    let item_id = item.item_id();
2090                    let answer_task = pane.update_in(cx, |pane, window, cx| {
2091                        if pane.save_modals_spawned.insert(item_id) {
2092                            pane.activate_item(item_ix, true, true, window, cx);
2093                            let prompt = dirty_message_for(item.project_path(cx));
2094                            Some(window.prompt(
2095                                PromptLevel::Warning,
2096                                &prompt,
2097                                None,
2098                                &["Save", "Don't Save", "Cancel"],
2099                                cx,
2100                            ))
2101                        } else {
2102                            None
2103                        }
2104                    })?;
2105                    if let Some(answer_task) = answer_task {
2106                        let answer = answer_task.await;
2107                        pane.update(cx, |pane, _| {
2108                            if !pane.save_modals_spawned.remove(&item_id) {
2109                                debug_panic!(
2110                                    "save modal was not present in spawned modals after awaiting for its answer"
2111                                )
2112                            }
2113                        })?;
2114                        match answer {
2115                            Ok(0) => {}
2116                            Ok(1) => {
2117                                // Don't save this file
2118                                pane.update_in(cx, |pane, _, cx| {
2119                                    if pane.is_tab_pinned(item_ix) && !item.can_save(cx) {
2120                                        pane.pinned_tab_count -= 1;
2121                                    }
2122                                })
2123                                .log_err();
2124                                return Ok(true);
2125                            }
2126                            _ => return Ok(false), // Cancel
2127                        }
2128                    } else {
2129                        return Ok(false);
2130                    }
2131                }
2132            }
2133
2134            if can_save {
2135                pane.update_in(cx, |pane, window, cx| {
2136                    if pane.is_active_preview_item(item.item_id()) {
2137                        pane.set_preview_item_id(None, cx);
2138                    }
2139                    item.save(
2140                        SaveOptions {
2141                            format: should_format,
2142                            autosave: false,
2143                        },
2144                        project,
2145                        window,
2146                        cx,
2147                    )
2148                })?
2149                .await?;
2150            } else if can_save_as && is_singleton {
2151                let suggested_name =
2152                    cx.update(|_window, cx| item.suggested_filename(cx).to_string())?;
2153                let new_path = pane.update_in(cx, |pane, window, cx| {
2154                    pane.activate_item(item_ix, true, true, window, cx);
2155                    pane.workspace.update(cx, |workspace, cx| {
2156                        let lister = if workspace.project().read(cx).is_local() {
2157                            DirectoryLister::Local(
2158                                workspace.project().clone(),
2159                                workspace.app_state().fs.clone(),
2160                            )
2161                        } else {
2162                            DirectoryLister::Project(workspace.project().clone())
2163                        };
2164                        workspace.prompt_for_new_path(lister, Some(suggested_name), window, cx)
2165                    })
2166                })??;
2167                let Some(new_path) = new_path.await.ok().flatten().into_iter().flatten().next()
2168                else {
2169                    return Ok(false);
2170                };
2171
2172                let project_path = pane
2173                    .update(cx, |pane, cx| {
2174                        pane.project
2175                            .update(cx, |project, cx| {
2176                                project.find_or_create_worktree(new_path, true, cx)
2177                            })
2178                            .ok()
2179                    })
2180                    .ok()
2181                    .flatten();
2182                let save_task = if let Some(project_path) = project_path {
2183                    let (worktree, path) = project_path.await?;
2184                    let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id())?;
2185                    let new_path = ProjectPath {
2186                        worktree_id,
2187                        path: path.into(),
2188                    };
2189
2190                    pane.update_in(cx, |pane, window, cx| {
2191                        if let Some(item) = pane.item_for_path(new_path.clone(), cx) {
2192                            pane.remove_item(item.item_id(), false, false, window, cx);
2193                        }
2194
2195                        item.save_as(project, new_path, window, cx)
2196                    })?
2197                } else {
2198                    return Ok(false);
2199                };
2200
2201                save_task.await?;
2202                return Ok(true);
2203            }
2204        }
2205
2206        pane.update(cx, |_, cx| {
2207            cx.emit(Event::UserSavedItem {
2208                item: item.downgrade_item(),
2209                save_intent,
2210            });
2211            true
2212        })
2213    }
2214
2215    pub fn autosave_item(
2216        item: &dyn ItemHandle,
2217        project: Entity<Project>,
2218        window: &mut Window,
2219        cx: &mut App,
2220    ) -> Task<Result<()>> {
2221        let format = !matches!(
2222            item.workspace_settings(cx).autosave,
2223            AutosaveSetting::AfterDelay { .. }
2224        );
2225        if item.can_autosave(cx) {
2226            item.save(
2227                SaveOptions {
2228                    format,
2229                    autosave: true,
2230                },
2231                project,
2232                window,
2233                cx,
2234            )
2235        } else {
2236            Task::ready(Ok(()))
2237        }
2238    }
2239
2240    pub fn focus_active_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2241        if let Some(active_item) = self.active_item() {
2242            let focus_handle = active_item.item_focus_handle(cx);
2243            window.focus(&focus_handle);
2244        }
2245    }
2246
2247    pub fn split(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
2248        cx.emit(Event::Split {
2249            direction,
2250            clone_active_item: true,
2251        });
2252    }
2253
2254    pub fn split_and_move(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
2255        if self.items.len() > 1 {
2256            cx.emit(Event::Split {
2257                direction,
2258                clone_active_item: false,
2259            });
2260        }
2261    }
2262
2263    pub fn toolbar(&self) -> &Entity<Toolbar> {
2264        &self.toolbar
2265    }
2266
2267    pub fn handle_deleted_project_item(
2268        &mut self,
2269        entry_id: ProjectEntryId,
2270        window: &mut Window,
2271        cx: &mut Context<Pane>,
2272    ) -> Option<()> {
2273        let item_id = self.items().find_map(|item| {
2274            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
2275                Some(item.item_id())
2276            } else {
2277                None
2278            }
2279        })?;
2280
2281        self.remove_item(item_id, false, true, window, cx);
2282        self.nav_history.remove_item(item_id);
2283
2284        Some(())
2285    }
2286
2287    fn update_toolbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2288        let active_item = self
2289            .items
2290            .get(self.active_item_index)
2291            .map(|item| item.as_ref());
2292        self.toolbar.update(cx, |toolbar, cx| {
2293            toolbar.set_active_item(active_item, window, cx);
2294        });
2295    }
2296
2297    fn update_status_bar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2298        let workspace = self.workspace.clone();
2299        let pane = cx.entity();
2300
2301        window.defer(cx, move |window, cx| {
2302            let Ok(status_bar) =
2303                workspace.read_with(cx, |workspace, _| workspace.status_bar.clone())
2304            else {
2305                return;
2306            };
2307
2308            status_bar.update(cx, move |status_bar, cx| {
2309                status_bar.set_active_pane(&pane, window, cx);
2310            });
2311        });
2312    }
2313
2314    fn entry_abs_path(&self, entry: ProjectEntryId, cx: &App) -> Option<PathBuf> {
2315        let worktree = self
2316            .workspace
2317            .upgrade()?
2318            .read(cx)
2319            .project()
2320            .read(cx)
2321            .worktree_for_entry(entry, cx)?
2322            .read(cx);
2323        let entry = worktree.entry_for_id(entry)?;
2324        match &entry.canonical_path {
2325            Some(canonical_path) => Some(canonical_path.to_path_buf()),
2326            None => worktree.absolutize(&entry.path).ok(),
2327        }
2328    }
2329
2330    pub fn icon_color(selected: bool) -> Color {
2331        if selected {
2332            Color::Default
2333        } else {
2334            Color::Muted
2335        }
2336    }
2337
2338    fn toggle_pin_tab(&mut self, _: &TogglePinTab, window: &mut Window, cx: &mut Context<Self>) {
2339        if self.items.is_empty() {
2340            return;
2341        }
2342        let active_tab_ix = self.active_item_index();
2343        if self.is_tab_pinned(active_tab_ix) {
2344            self.unpin_tab_at(active_tab_ix, window, cx);
2345        } else {
2346            self.pin_tab_at(active_tab_ix, window, cx);
2347        }
2348    }
2349
2350    fn unpin_all_tabs(&mut self, _: &UnpinAllTabs, window: &mut Window, cx: &mut Context<Self>) {
2351        if self.items.is_empty() {
2352            return;
2353        }
2354
2355        let pinned_item_ids = self.pinned_item_ids().into_iter().rev();
2356
2357        for pinned_item_id in pinned_item_ids {
2358            if let Some(ix) = self.index_for_item_id(pinned_item_id) {
2359                self.unpin_tab_at(ix, window, cx);
2360            }
2361        }
2362    }
2363
2364    fn pin_tab_at(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
2365        self.change_tab_pin_state(ix, PinOperation::Pin, window, cx);
2366    }
2367
2368    fn unpin_tab_at(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
2369        self.change_tab_pin_state(ix, PinOperation::Unpin, window, cx);
2370    }
2371
2372    fn change_tab_pin_state(
2373        &mut self,
2374        ix: usize,
2375        operation: PinOperation,
2376        window: &mut Window,
2377        cx: &mut Context<Self>,
2378    ) {
2379        maybe!({
2380            let pane = cx.entity();
2381
2382            let destination_index = match operation {
2383                PinOperation::Pin => self.pinned_tab_count.min(ix),
2384                PinOperation::Unpin => self.pinned_tab_count.checked_sub(1)?,
2385            };
2386
2387            let id = self.item_for_index(ix)?.item_id();
2388            let should_activate = ix == self.active_item_index;
2389
2390            if matches!(operation, PinOperation::Pin) && self.is_active_preview_item(id) {
2391                self.set_preview_item_id(None, cx);
2392            }
2393
2394            match operation {
2395                PinOperation::Pin => self.pinned_tab_count += 1,
2396                PinOperation::Unpin => self.pinned_tab_count -= 1,
2397            }
2398
2399            if ix == destination_index {
2400                cx.notify();
2401            } else {
2402                self.workspace
2403                    .update(cx, |_, cx| {
2404                        cx.defer_in(window, move |_, window, cx| {
2405                            move_item(
2406                                &pane,
2407                                &pane,
2408                                id,
2409                                destination_index,
2410                                should_activate,
2411                                window,
2412                                cx,
2413                            );
2414                        });
2415                    })
2416                    .ok()?;
2417            }
2418
2419            let event = match operation {
2420                PinOperation::Pin => Event::ItemPinned,
2421                PinOperation::Unpin => Event::ItemUnpinned,
2422            };
2423
2424            cx.emit(event);
2425
2426            Some(())
2427        });
2428    }
2429
2430    fn is_tab_pinned(&self, ix: usize) -> bool {
2431        self.pinned_tab_count > ix
2432    }
2433
2434    fn has_unpinned_tabs(&self) -> bool {
2435        self.pinned_tab_count < self.items.len()
2436    }
2437
2438    fn activate_unpinned_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2439        if self.items.is_empty() {
2440            return;
2441        }
2442        let Some(index) = self
2443            .items()
2444            .enumerate()
2445            .find_map(|(index, _item)| (!self.is_tab_pinned(index)).then_some(index))
2446        else {
2447            return;
2448        };
2449        self.activate_item(index, true, true, window, cx);
2450    }
2451
2452    fn render_tab(
2453        &self,
2454        ix: usize,
2455        item: &dyn ItemHandle,
2456        detail: usize,
2457        focus_handle: &FocusHandle,
2458        window: &mut Window,
2459        cx: &mut Context<Pane>,
2460    ) -> impl IntoElement + use<> {
2461        let is_active = ix == self.active_item_index;
2462        let is_preview = self
2463            .preview_item_id
2464            .map(|id| id == item.item_id())
2465            .unwrap_or(false);
2466
2467        let label = item.tab_content(
2468            TabContentParams {
2469                detail: Some(detail),
2470                selected: is_active,
2471                preview: is_preview,
2472                deemphasized: !self.has_focus(window, cx),
2473            },
2474            window,
2475            cx,
2476        );
2477
2478        let item_diagnostic = item
2479            .project_path(cx)
2480            .map_or(None, |project_path| self.diagnostics.get(&project_path));
2481
2482        let decorated_icon = item_diagnostic.map_or(None, |diagnostic| {
2483            let icon = match item.tab_icon(window, cx) {
2484                Some(icon) => icon,
2485                None => return None,
2486            };
2487
2488            let knockout_item_color = if is_active {
2489                cx.theme().colors().tab_active_background
2490            } else {
2491                cx.theme().colors().tab_bar_background
2492            };
2493
2494            let (icon_decoration, icon_color) = if matches!(diagnostic, &DiagnosticSeverity::ERROR)
2495            {
2496                (IconDecorationKind::X, Color::Error)
2497            } else {
2498                (IconDecorationKind::Triangle, Color::Warning)
2499            };
2500
2501            Some(DecoratedIcon::new(
2502                icon.size(IconSize::Small).color(Color::Muted),
2503                Some(
2504                    IconDecoration::new(icon_decoration, knockout_item_color, cx)
2505                        .color(icon_color.color(cx))
2506                        .position(Point {
2507                            x: px(-2.),
2508                            y: px(-2.),
2509                        }),
2510                ),
2511            ))
2512        });
2513
2514        let icon = if decorated_icon.is_none() {
2515            match item_diagnostic {
2516                Some(&DiagnosticSeverity::ERROR) => None,
2517                Some(&DiagnosticSeverity::WARNING) => None,
2518                _ => item
2519                    .tab_icon(window, cx)
2520                    .map(|icon| icon.color(Color::Muted)),
2521            }
2522            .map(|icon| icon.size(IconSize::Small))
2523        } else {
2524            None
2525        };
2526
2527        let settings = ItemSettings::get_global(cx);
2528        let close_side = &settings.close_position;
2529        let show_close_button = &settings.show_close_button;
2530        let indicator = render_item_indicator(item.boxed_clone(), cx);
2531        let item_id = item.item_id();
2532        let is_first_item = ix == 0;
2533        let is_last_item = ix == self.items.len() - 1;
2534        let is_pinned = self.is_tab_pinned(ix);
2535        let position_relative_to_active_item = ix.cmp(&self.active_item_index);
2536
2537        let tab = Tab::new(ix)
2538            .position(if is_first_item {
2539                TabPosition::First
2540            } else if is_last_item {
2541                TabPosition::Last
2542            } else {
2543                TabPosition::Middle(position_relative_to_active_item)
2544            })
2545            .close_side(match close_side {
2546                ClosePosition::Left => ui::TabCloseSide::Start,
2547                ClosePosition::Right => ui::TabCloseSide::End,
2548            })
2549            .toggle_state(is_active)
2550            .on_click(cx.listener(move |pane: &mut Self, _, window, cx| {
2551                pane.activate_item(ix, true, true, window, cx)
2552            }))
2553            // TODO: This should be a click listener with the middle mouse button instead of a mouse down listener.
2554            .on_mouse_down(
2555                MouseButton::Middle,
2556                cx.listener(move |pane, _event, window, cx| {
2557                    pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2558                        .detach_and_log_err(cx);
2559                }),
2560            )
2561            .on_mouse_down(
2562                MouseButton::Left,
2563                cx.listener(move |pane, event: &MouseDownEvent, _, cx| {
2564                    if let Some(id) = pane.preview_item_id
2565                        && id == item_id
2566                        && event.click_count > 1
2567                    {
2568                        pane.set_preview_item_id(None, cx);
2569                    }
2570                }),
2571            )
2572            .on_drag(
2573                DraggedTab {
2574                    item: item.boxed_clone(),
2575                    pane: cx.entity(),
2576                    detail,
2577                    is_active,
2578                    ix,
2579                },
2580                |tab, _, _, cx| cx.new(|_| tab.clone()),
2581            )
2582            .drag_over::<DraggedTab>(move |tab, dragged_tab: &DraggedTab, _, cx| {
2583                let mut styled_tab = tab
2584                    .bg(cx.theme().colors().drop_target_background)
2585                    .border_color(cx.theme().colors().drop_target_border)
2586                    .border_0();
2587
2588                if ix < dragged_tab.ix {
2589                    styled_tab = styled_tab.border_l_2();
2590                } else if ix > dragged_tab.ix {
2591                    styled_tab = styled_tab.border_r_2();
2592                }
2593
2594                styled_tab
2595            })
2596            .drag_over::<DraggedSelection>(|tab, _, _, cx| {
2597                tab.bg(cx.theme().colors().drop_target_background)
2598            })
2599            .when_some(self.can_drop_predicate.clone(), |this, p| {
2600                this.can_drop(move |a, window, cx| p(a, window, cx))
2601            })
2602            .on_drop(
2603                cx.listener(move |this, dragged_tab: &DraggedTab, window, cx| {
2604                    this.drag_split_direction = None;
2605                    this.handle_tab_drop(dragged_tab, ix, window, cx)
2606                }),
2607            )
2608            .on_drop(
2609                cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2610                    this.drag_split_direction = None;
2611                    this.handle_dragged_selection_drop(selection, Some(ix), window, cx)
2612                }),
2613            )
2614            .on_drop(cx.listener(move |this, paths, window, cx| {
2615                this.drag_split_direction = None;
2616                this.handle_external_paths_drop(paths, window, cx)
2617            }))
2618            .when_some(item.tab_tooltip_content(cx), |tab, content| match content {
2619                TabTooltipContent::Text(text) => tab.tooltip(Tooltip::text(text)),
2620                TabTooltipContent::Custom(element_fn) => {
2621                    tab.tooltip(move |window, cx| element_fn(window, cx))
2622                }
2623            })
2624            .start_slot::<Indicator>(indicator)
2625            .map(|this| {
2626                let end_slot_action: &'static dyn Action;
2627                let end_slot_tooltip_text: &'static str;
2628                let end_slot = if is_pinned {
2629                    end_slot_action = &TogglePinTab;
2630                    end_slot_tooltip_text = "Unpin Tab";
2631                    IconButton::new("unpin tab", IconName::Pin)
2632                        .shape(IconButtonShape::Square)
2633                        .icon_color(Color::Muted)
2634                        .size(ButtonSize::None)
2635                        .icon_size(IconSize::Small)
2636                        .on_click(cx.listener(move |pane, _, window, cx| {
2637                            pane.unpin_tab_at(ix, window, cx);
2638                        }))
2639                } else {
2640                    end_slot_action = &CloseActiveItem {
2641                        save_intent: None,
2642                        close_pinned: false,
2643                    };
2644                    end_slot_tooltip_text = "Close Tab";
2645                    match show_close_button {
2646                        ShowCloseButton::Always => IconButton::new("close tab", IconName::Close),
2647                        ShowCloseButton::Hover => {
2648                            IconButton::new("close tab", IconName::Close).visible_on_hover("")
2649                        }
2650                        ShowCloseButton::Hidden => return this,
2651                    }
2652                    .shape(IconButtonShape::Square)
2653                    .icon_color(Color::Muted)
2654                    .size(ButtonSize::None)
2655                    .icon_size(IconSize::Small)
2656                    .on_click(cx.listener(move |pane, _, window, cx| {
2657                        pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2658                            .detach_and_log_err(cx);
2659                    }))
2660                }
2661                .map(|this| {
2662                    if is_active {
2663                        let focus_handle = focus_handle.clone();
2664                        this.tooltip(move |window, cx| {
2665                            Tooltip::for_action_in(
2666                                end_slot_tooltip_text,
2667                                end_slot_action,
2668                                &focus_handle,
2669                                window,
2670                                cx,
2671                            )
2672                        })
2673                    } else {
2674                        this.tooltip(Tooltip::text(end_slot_tooltip_text))
2675                    }
2676                });
2677                this.end_slot(end_slot)
2678            })
2679            .child(
2680                h_flex()
2681                    .gap_1()
2682                    .items_center()
2683                    .children(
2684                        std::iter::once(if let Some(decorated_icon) = decorated_icon {
2685                            Some(div().child(decorated_icon.into_any_element()))
2686                        } else {
2687                            icon.map(|icon| div().child(icon.into_any_element()))
2688                        })
2689                        .flatten(),
2690                    )
2691                    .child(label),
2692            );
2693
2694        let single_entry_to_resolve = self.items[ix]
2695            .is_singleton(cx)
2696            .then(|| self.items[ix].project_entry_ids(cx).get(0).copied())
2697            .flatten();
2698
2699        let total_items = self.items.len();
2700        let has_items_to_left = ix > 0;
2701        let has_items_to_right = ix < total_items - 1;
2702        let has_clean_items = self.items.iter().any(|item| !item.is_dirty(cx));
2703        let is_pinned = self.is_tab_pinned(ix);
2704        let pane = cx.entity().downgrade();
2705        let menu_context = item.item_focus_handle(cx);
2706        right_click_menu(ix)
2707            .trigger(|_, _, _| tab)
2708            .menu(move |window, cx| {
2709                let pane = pane.clone();
2710                let menu_context = menu_context.clone();
2711                ContextMenu::build(window, cx, move |mut menu, window, cx| {
2712                    let close_active_item_action = CloseActiveItem {
2713                        save_intent: None,
2714                        close_pinned: true,
2715                    };
2716                    let close_inactive_items_action = CloseOtherItems {
2717                        save_intent: None,
2718                        close_pinned: false,
2719                    };
2720                    let close_items_to_the_left_action = CloseItemsToTheLeft {
2721                        close_pinned: false,
2722                    };
2723                    let close_items_to_the_right_action = CloseItemsToTheRight {
2724                        close_pinned: false,
2725                    };
2726                    let close_clean_items_action = CloseCleanItems {
2727                        close_pinned: false,
2728                    };
2729                    let close_all_items_action = CloseAllItems {
2730                        save_intent: None,
2731                        close_pinned: false,
2732                    };
2733                    if let Some(pane) = pane.upgrade() {
2734                        menu = menu
2735                            .entry(
2736                                "Close",
2737                                Some(Box::new(close_active_item_action)),
2738                                window.handler_for(&pane, move |pane, window, cx| {
2739                                    pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2740                                        .detach_and_log_err(cx);
2741                                }),
2742                            )
2743                            .item(ContextMenuItem::Entry(
2744                                ContextMenuEntry::new("Close Others")
2745                                    .action(Box::new(close_inactive_items_action.clone()))
2746                                    .disabled(total_items == 1)
2747                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2748                                        pane.close_other_items(
2749                                            &close_inactive_items_action,
2750                                            Some(item_id),
2751                                            window,
2752                                            cx,
2753                                        )
2754                                        .detach_and_log_err(cx);
2755                                    })),
2756                            ))
2757                            .separator()
2758                            .item(ContextMenuItem::Entry(
2759                                ContextMenuEntry::new("Close Left")
2760                                    .action(Box::new(close_items_to_the_left_action.clone()))
2761                                    .disabled(!has_items_to_left)
2762                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2763                                        pane.close_items_to_the_left_by_id(
2764                                            Some(item_id),
2765                                            &close_items_to_the_left_action,
2766                                            window,
2767                                            cx,
2768                                        )
2769                                        .detach_and_log_err(cx);
2770                                    })),
2771                            ))
2772                            .item(ContextMenuItem::Entry(
2773                                ContextMenuEntry::new("Close Right")
2774                                    .action(Box::new(close_items_to_the_right_action.clone()))
2775                                    .disabled(!has_items_to_right)
2776                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2777                                        pane.close_items_to_the_right_by_id(
2778                                            Some(item_id),
2779                                            &close_items_to_the_right_action,
2780                                            window,
2781                                            cx,
2782                                        )
2783                                        .detach_and_log_err(cx);
2784                                    })),
2785                            ))
2786                            .separator()
2787                            .item(ContextMenuItem::Entry(
2788                                ContextMenuEntry::new("Close Clean")
2789                                    .action(Box::new(close_clean_items_action.clone()))
2790                                    .disabled(!has_clean_items)
2791                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2792                                        pane.close_clean_items(
2793                                            &close_clean_items_action,
2794                                            window,
2795                                            cx,
2796                                        )
2797                                        .detach_and_log_err(cx)
2798                                    })),
2799                            ))
2800                            .entry(
2801                                "Close All",
2802                                Some(Box::new(close_all_items_action.clone())),
2803                                window.handler_for(&pane, move |pane, window, cx| {
2804                                    pane.close_all_items(&close_all_items_action, window, cx)
2805                                        .detach_and_log_err(cx)
2806                                }),
2807                            );
2808
2809                        let pin_tab_entries = |menu: ContextMenu| {
2810                            menu.separator().map(|this| {
2811                                if is_pinned {
2812                                    this.entry(
2813                                        "Unpin Tab",
2814                                        Some(TogglePinTab.boxed_clone()),
2815                                        window.handler_for(&pane, move |pane, window, cx| {
2816                                            pane.unpin_tab_at(ix, window, cx);
2817                                        }),
2818                                    )
2819                                } else {
2820                                    this.entry(
2821                                        "Pin Tab",
2822                                        Some(TogglePinTab.boxed_clone()),
2823                                        window.handler_for(&pane, move |pane, window, cx| {
2824                                            pane.pin_tab_at(ix, window, cx);
2825                                        }),
2826                                    )
2827                                }
2828                            })
2829                        };
2830                        if let Some(entry) = single_entry_to_resolve {
2831                            let project_path = pane
2832                                .read(cx)
2833                                .item_for_entry(entry, cx)
2834                                .and_then(|item| item.project_path(cx));
2835                            let worktree = project_path.as_ref().and_then(|project_path| {
2836                                pane.read(cx)
2837                                    .project
2838                                    .upgrade()?
2839                                    .read(cx)
2840                                    .worktree_for_id(project_path.worktree_id, cx)
2841                            });
2842                            let has_relative_path = worktree.as_ref().is_some_and(|worktree| {
2843                                worktree
2844                                    .read(cx)
2845                                    .root_entry()
2846                                    .is_some_and(|entry| entry.is_dir())
2847                            });
2848
2849                            let entry_abs_path = pane.read(cx).entry_abs_path(entry, cx);
2850                            let parent_abs_path = entry_abs_path
2851                                .as_deref()
2852                                .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
2853                            let relative_path = project_path
2854                                .map(|project_path| project_path.path)
2855                                .filter(|_| has_relative_path);
2856
2857                            let visible_in_project_panel = relative_path.is_some()
2858                                && worktree.is_some_and(|worktree| worktree.read(cx).is_visible());
2859
2860                            let entry_id = entry.to_proto();
2861                            menu = menu
2862                                .separator()
2863                                .when_some(entry_abs_path, |menu, abs_path| {
2864                                    menu.entry(
2865                                        "Copy Path",
2866                                        Some(Box::new(zed_actions::workspace::CopyPath)),
2867                                        window.handler_for(&pane, move |_, _, cx| {
2868                                            cx.write_to_clipboard(ClipboardItem::new_string(
2869                                                abs_path.to_string_lossy().to_string(),
2870                                            ));
2871                                        }),
2872                                    )
2873                                })
2874                                .when_some(relative_path, |menu, relative_path| {
2875                                    menu.entry(
2876                                        "Copy Relative Path",
2877                                        Some(Box::new(zed_actions::workspace::CopyRelativePath)),
2878                                        window.handler_for(&pane, move |_, _, cx| {
2879                                            cx.write_to_clipboard(ClipboardItem::new_string(
2880                                                relative_path.to_string_lossy().to_string(),
2881                                            ));
2882                                        }),
2883                                    )
2884                                })
2885                                .map(pin_tab_entries)
2886                                .separator()
2887                                .when(visible_in_project_panel, |menu| {
2888                                    menu.entry(
2889                                        "Reveal In Project Panel",
2890                                        Some(Box::new(RevealInProjectPanel::default())),
2891                                        window.handler_for(&pane, move |pane, _, cx| {
2892                                            pane.project
2893                                                .update(cx, |_, cx| {
2894                                                    cx.emit(project::Event::RevealInProjectPanel(
2895                                                        ProjectEntryId::from_proto(entry_id),
2896                                                    ))
2897                                                })
2898                                                .ok();
2899                                        }),
2900                                    )
2901                                })
2902                                .when_some(parent_abs_path, |menu, parent_abs_path| {
2903                                    menu.entry(
2904                                        "Open in Terminal",
2905                                        Some(Box::new(OpenInTerminal)),
2906                                        window.handler_for(&pane, move |_, window, cx| {
2907                                            window.dispatch_action(
2908                                                OpenTerminal {
2909                                                    working_directory: parent_abs_path.clone(),
2910                                                }
2911                                                .boxed_clone(),
2912                                                cx,
2913                                            );
2914                                        }),
2915                                    )
2916                                });
2917                        } else {
2918                            menu = menu.map(pin_tab_entries);
2919                        }
2920                    }
2921
2922                    menu.context(menu_context)
2923                })
2924            })
2925    }
2926
2927    fn render_tab_bar(&mut self, window: &mut Window, cx: &mut Context<Pane>) -> AnyElement {
2928        let focus_handle = self.focus_handle.clone();
2929        let navigate_backward = IconButton::new("navigate_backward", IconName::ArrowLeft)
2930            .icon_size(IconSize::Small)
2931            .on_click({
2932                let entity = cx.entity();
2933                move |_, window, cx| {
2934                    entity.update(cx, |pane, cx| {
2935                        pane.navigate_backward(&Default::default(), window, cx)
2936                    })
2937                }
2938            })
2939            .disabled(!self.can_navigate_backward())
2940            .tooltip({
2941                let focus_handle = focus_handle.clone();
2942                move |window, cx| {
2943                    Tooltip::for_action_in("Go Back", &GoBack, &focus_handle, window, cx)
2944                }
2945            });
2946
2947        let navigate_forward = IconButton::new("navigate_forward", IconName::ArrowRight)
2948            .icon_size(IconSize::Small)
2949            .on_click({
2950                let entity = cx.entity();
2951                move |_, window, cx| {
2952                    entity.update(cx, |pane, cx| {
2953                        pane.navigate_forward(&Default::default(), window, cx)
2954                    })
2955                }
2956            })
2957            .disabled(!self.can_navigate_forward())
2958            .tooltip({
2959                let focus_handle = focus_handle.clone();
2960                move |window, cx| {
2961                    Tooltip::for_action_in("Go Forward", &GoForward, &focus_handle, window, cx)
2962                }
2963            });
2964
2965        let mut tab_items = self
2966            .items
2967            .iter()
2968            .enumerate()
2969            .zip(tab_details(&self.items, window, cx))
2970            .map(|((ix, item), detail)| {
2971                self.render_tab(ix, &**item, detail, &focus_handle, window, cx)
2972            })
2973            .collect::<Vec<_>>();
2974        let tab_count = tab_items.len();
2975        if self.is_tab_pinned(tab_count) {
2976            log::warn!(
2977                "Pinned tab count ({}) exceeds actual tab count ({}). \
2978                This should not happen. If possible, add reproduction steps, \
2979                in a comment, to https://github.com/zed-industries/zed/issues/33342",
2980                self.pinned_tab_count,
2981                tab_count
2982            );
2983            self.pinned_tab_count = tab_count;
2984        }
2985        let unpinned_tabs = tab_items.split_off(self.pinned_tab_count);
2986        let pinned_tabs = tab_items;
2987        TabBar::new("tab_bar")
2988            .when(
2989                self.display_nav_history_buttons.unwrap_or_default(),
2990                |tab_bar| {
2991                    tab_bar
2992                        .start_child(navigate_backward)
2993                        .start_child(navigate_forward)
2994                },
2995            )
2996            .map(|tab_bar| {
2997                if self.show_tab_bar_buttons {
2998                    let render_tab_buttons = self.render_tab_bar_buttons.clone();
2999                    let (left_children, right_children) = render_tab_buttons(self, window, cx);
3000                    tab_bar
3001                        .start_children(left_children)
3002                        .end_children(right_children)
3003                } else {
3004                    tab_bar
3005                }
3006            })
3007            .children(pinned_tabs.len().ne(&0).then(|| {
3008                let max_scroll = self.tab_bar_scroll_handle.max_offset().width;
3009                // We need to check both because offset returns delta values even when the scroll handle is not scrollable
3010                let is_scrollable = !max_scroll.is_zero();
3011                let is_scrolled = self.tab_bar_scroll_handle.offset().x < px(0.);
3012                let has_active_unpinned_tab = self.active_item_index >= self.pinned_tab_count;
3013                h_flex()
3014                    .children(pinned_tabs)
3015                    .when(is_scrollable && is_scrolled, |this| {
3016                        this.when(has_active_unpinned_tab, |this| this.border_r_2())
3017                            .when(!has_active_unpinned_tab, |this| this.border_r_1())
3018                            .border_color(cx.theme().colors().border)
3019                    })
3020            }))
3021            .child(
3022                h_flex()
3023                    .id("unpinned tabs")
3024                    .overflow_x_scroll()
3025                    .w_full()
3026                    .track_scroll(&self.tab_bar_scroll_handle)
3027                    .children(unpinned_tabs)
3028                    .child(
3029                        div()
3030                            .id("tab_bar_drop_target")
3031                            .min_w_6()
3032                            // HACK: This empty child is currently necessary to force the drop target to appear
3033                            // despite us setting a min width above.
3034                            .child("")
3035                            // HACK: h_full doesn't occupy the complete height, using fixed height instead
3036                            .h(Tab::container_height(cx))
3037                            .flex_grow()
3038                            .drag_over::<DraggedTab>(|bar, _, _, cx| {
3039                                bar.bg(cx.theme().colors().drop_target_background)
3040                            })
3041                            .drag_over::<DraggedSelection>(|bar, _, _, cx| {
3042                                bar.bg(cx.theme().colors().drop_target_background)
3043                            })
3044                            .on_drop(cx.listener(
3045                                move |this, dragged_tab: &DraggedTab, window, cx| {
3046                                    this.drag_split_direction = None;
3047                                    this.handle_tab_drop(dragged_tab, this.items.len(), window, cx)
3048                                },
3049                            ))
3050                            .on_drop(cx.listener(
3051                                move |this, selection: &DraggedSelection, window, cx| {
3052                                    this.drag_split_direction = None;
3053                                    this.handle_project_entry_drop(
3054                                        &selection.active_selection.entry_id,
3055                                        Some(tab_count),
3056                                        window,
3057                                        cx,
3058                                    )
3059                                },
3060                            ))
3061                            .on_drop(cx.listener(move |this, paths, window, cx| {
3062                                this.drag_split_direction = None;
3063                                this.handle_external_paths_drop(paths, window, cx)
3064                            }))
3065                            .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
3066                                if event.click_count() == 2 {
3067                                    window.dispatch_action(
3068                                        this.double_click_dispatch_action.boxed_clone(),
3069                                        cx,
3070                                    );
3071                                }
3072                            })),
3073                    ),
3074            )
3075            .into_any_element()
3076    }
3077
3078    pub fn render_menu_overlay(menu: &Entity<ContextMenu>) -> Div {
3079        div().absolute().bottom_0().right_0().size_0().child(
3080            deferred(anchored().anchor(Corner::TopRight).child(menu.clone())).with_priority(1),
3081        )
3082    }
3083
3084    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut Context<Self>) {
3085        self.zoomed = zoomed;
3086        cx.notify();
3087    }
3088
3089    pub fn is_zoomed(&self) -> bool {
3090        self.zoomed
3091    }
3092
3093    fn handle_drag_move<T: 'static>(
3094        &mut self,
3095        event: &DragMoveEvent<T>,
3096        window: &mut Window,
3097        cx: &mut Context<Self>,
3098    ) {
3099        let can_split_predicate = self.can_split_predicate.take();
3100        let can_split = match &can_split_predicate {
3101            Some(can_split_predicate) => {
3102                can_split_predicate(self, event.dragged_item(), window, cx)
3103            }
3104            None => false,
3105        };
3106        self.can_split_predicate = can_split_predicate;
3107        if !can_split {
3108            return;
3109        }
3110
3111        let rect = event.bounds.size;
3112
3113        let size = event.bounds.size.width.min(event.bounds.size.height)
3114            * WorkspaceSettings::get_global(cx).drop_target_size;
3115
3116        let relative_cursor = Point::new(
3117            event.event.position.x - event.bounds.left(),
3118            event.event.position.y - event.bounds.top(),
3119        );
3120
3121        let direction = if relative_cursor.x < size
3122            || relative_cursor.x > rect.width - size
3123            || relative_cursor.y < size
3124            || relative_cursor.y > rect.height - size
3125        {
3126            [
3127                SplitDirection::Up,
3128                SplitDirection::Right,
3129                SplitDirection::Down,
3130                SplitDirection::Left,
3131            ]
3132            .iter()
3133            .min_by_key(|side| match side {
3134                SplitDirection::Up => relative_cursor.y,
3135                SplitDirection::Right => rect.width - relative_cursor.x,
3136                SplitDirection::Down => rect.height - relative_cursor.y,
3137                SplitDirection::Left => relative_cursor.x,
3138            })
3139            .cloned()
3140        } else {
3141            None
3142        };
3143
3144        if direction != self.drag_split_direction {
3145            self.drag_split_direction = direction;
3146        }
3147    }
3148
3149    pub fn handle_tab_drop(
3150        &mut self,
3151        dragged_tab: &DraggedTab,
3152        ix: usize,
3153        window: &mut Window,
3154        cx: &mut Context<Self>,
3155    ) {
3156        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3157            && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_tab, window, cx)
3158        {
3159            return;
3160        }
3161        let mut to_pane = cx.entity();
3162        let split_direction = self.drag_split_direction;
3163        let item_id = dragged_tab.item.item_id();
3164        if let Some(preview_item_id) = self.preview_item_id
3165            && item_id == preview_item_id
3166        {
3167            self.set_preview_item_id(None, cx);
3168        }
3169
3170        let is_clone = cfg!(target_os = "macos") && window.modifiers().alt
3171            || cfg!(not(target_os = "macos")) && window.modifiers().control;
3172
3173        let from_pane = dragged_tab.pane.clone();
3174
3175        self.workspace
3176            .update(cx, |_, cx| {
3177                cx.defer_in(window, move |workspace, window, cx| {
3178                    if let Some(split_direction) = split_direction {
3179                        to_pane = workspace.split_pane(to_pane, split_direction, window, cx);
3180                    }
3181                    let database_id = workspace.database_id();
3182                    let was_pinned_in_from_pane = from_pane.read_with(cx, |pane, _| {
3183                        pane.index_for_item_id(item_id)
3184                            .is_some_and(|ix| pane.is_tab_pinned(ix))
3185                    });
3186                    let to_pane_old_length = to_pane.read(cx).items.len();
3187                    if is_clone {
3188                        let Some(item) = from_pane
3189                            .read(cx)
3190                            .items()
3191                            .find(|item| item.item_id() == item_id)
3192                            .cloned()
3193                        else {
3194                            return;
3195                        };
3196                        if let Some(item) = item.clone_on_split(database_id, window, cx) {
3197                            to_pane.update(cx, |pane, cx| {
3198                                pane.add_item(item, true, true, None, window, cx);
3199                            })
3200                        }
3201                    } else {
3202                        move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3203                    }
3204                    to_pane.update(cx, |this, _| {
3205                        if to_pane == from_pane {
3206                            let actual_ix = this
3207                                .items
3208                                .iter()
3209                                .position(|item| item.item_id() == item_id)
3210                                .unwrap_or(0);
3211
3212                            let is_pinned_in_to_pane = this.is_tab_pinned(actual_ix);
3213
3214                            if !was_pinned_in_from_pane && is_pinned_in_to_pane {
3215                                this.pinned_tab_count += 1;
3216                            } else if was_pinned_in_from_pane && !is_pinned_in_to_pane {
3217                                this.pinned_tab_count -= 1;
3218                            }
3219                        } else if this.items.len() >= to_pane_old_length {
3220                            let is_pinned_in_to_pane = this.is_tab_pinned(ix);
3221                            let item_created_pane = to_pane_old_length == 0;
3222                            let is_first_position = ix == 0;
3223                            let was_dropped_at_beginning = item_created_pane || is_first_position;
3224                            let should_remain_pinned = is_pinned_in_to_pane
3225                                || (was_pinned_in_from_pane && was_dropped_at_beginning);
3226
3227                            if should_remain_pinned {
3228                                this.pinned_tab_count += 1;
3229                            }
3230                        }
3231                    });
3232                });
3233            })
3234            .log_err();
3235    }
3236
3237    fn handle_dragged_selection_drop(
3238        &mut self,
3239        dragged_selection: &DraggedSelection,
3240        dragged_onto: Option<usize>,
3241        window: &mut Window,
3242        cx: &mut Context<Self>,
3243    ) {
3244        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3245            && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_selection, window, cx)
3246        {
3247            return;
3248        }
3249        self.handle_project_entry_drop(
3250            &dragged_selection.active_selection.entry_id,
3251            dragged_onto,
3252            window,
3253            cx,
3254        );
3255    }
3256
3257    fn handle_project_entry_drop(
3258        &mut self,
3259        project_entry_id: &ProjectEntryId,
3260        target: Option<usize>,
3261        window: &mut Window,
3262        cx: &mut Context<Self>,
3263    ) {
3264        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3265            && let ControlFlow::Break(()) = custom_drop_handle(self, project_entry_id, window, cx)
3266        {
3267            return;
3268        }
3269        let mut to_pane = cx.entity();
3270        let split_direction = self.drag_split_direction;
3271        let project_entry_id = *project_entry_id;
3272        self.workspace
3273            .update(cx, |_, cx| {
3274                cx.defer_in(window, move |workspace, window, cx| {
3275                    if let Some(project_path) = workspace
3276                        .project()
3277                        .read(cx)
3278                        .path_for_entry(project_entry_id, cx)
3279                    {
3280                        let load_path_task = workspace.load_path(project_path.clone(), window, cx);
3281                        cx.spawn_in(window, async move |workspace, cx| {
3282                            if let Some((project_entry_id, build_item)) =
3283                                load_path_task.await.notify_async_err(cx)
3284                            {
3285                                let (to_pane, new_item_handle) = workspace
3286                                    .update_in(cx, |workspace, window, cx| {
3287                                        if let Some(split_direction) = split_direction {
3288                                            to_pane = workspace.split_pane(
3289                                                to_pane,
3290                                                split_direction,
3291                                                window,
3292                                                cx,
3293                                            );
3294                                        }
3295                                        let new_item_handle = to_pane.update(cx, |pane, cx| {
3296                                            pane.open_item(
3297                                                project_entry_id,
3298                                                project_path,
3299                                                true,
3300                                                false,
3301                                                true,
3302                                                target,
3303                                                window,
3304                                                cx,
3305                                                build_item,
3306                                            )
3307                                        });
3308                                        (to_pane, new_item_handle)
3309                                    })
3310                                    .log_err()?;
3311                                to_pane
3312                                    .update_in(cx, |this, window, cx| {
3313                                        let Some(index) = this.index_for_item(&*new_item_handle)
3314                                        else {
3315                                            return;
3316                                        };
3317
3318                                        if target.is_some_and(|target| this.is_tab_pinned(target)) {
3319                                            this.pin_tab_at(index, window, cx);
3320                                        }
3321                                    })
3322                                    .ok()?
3323                            }
3324                            Some(())
3325                        })
3326                        .detach();
3327                    };
3328                });
3329            })
3330            .log_err();
3331    }
3332
3333    fn handle_external_paths_drop(
3334        &mut self,
3335        paths: &ExternalPaths,
3336        window: &mut Window,
3337        cx: &mut Context<Self>,
3338    ) {
3339        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3340            && let ControlFlow::Break(()) = custom_drop_handle(self, paths, window, cx)
3341        {
3342            return;
3343        }
3344        let mut to_pane = cx.entity();
3345        let mut split_direction = self.drag_split_direction;
3346        let paths = paths.paths().to_vec();
3347        let is_remote = self
3348            .workspace
3349            .update(cx, |workspace, cx| {
3350                if workspace.project().read(cx).is_via_collab() {
3351                    workspace.show_error(
3352                        &anyhow::anyhow!("Cannot drop files on a remote project"),
3353                        cx,
3354                    );
3355                    true
3356                } else {
3357                    false
3358                }
3359            })
3360            .unwrap_or(true);
3361        if is_remote {
3362            return;
3363        }
3364
3365        self.workspace
3366            .update(cx, |workspace, cx| {
3367                let fs = Arc::clone(workspace.project().read(cx).fs());
3368                cx.spawn_in(window, async move |workspace, cx| {
3369                    let mut is_file_checks = FuturesUnordered::new();
3370                    for path in &paths {
3371                        is_file_checks.push(fs.is_file(path))
3372                    }
3373                    let mut has_files_to_open = false;
3374                    while let Some(is_file) = is_file_checks.next().await {
3375                        if is_file {
3376                            has_files_to_open = true;
3377                            break;
3378                        }
3379                    }
3380                    drop(is_file_checks);
3381                    if !has_files_to_open {
3382                        split_direction = None;
3383                    }
3384
3385                    if let Ok((open_task, to_pane)) =
3386                        workspace.update_in(cx, |workspace, window, cx| {
3387                            if let Some(split_direction) = split_direction {
3388                                to_pane =
3389                                    workspace.split_pane(to_pane, split_direction, window, cx);
3390                            }
3391                            (
3392                                workspace.open_paths(
3393                                    paths,
3394                                    OpenOptions {
3395                                        visible: Some(OpenVisible::OnlyDirectories),
3396                                        ..Default::default()
3397                                    },
3398                                    Some(to_pane.downgrade()),
3399                                    window,
3400                                    cx,
3401                                ),
3402                                to_pane,
3403                            )
3404                        })
3405                    {
3406                        let opened_items: Vec<_> = open_task.await;
3407                        _ = workspace.update_in(cx, |workspace, window, cx| {
3408                            for item in opened_items.into_iter().flatten() {
3409                                if let Err(e) = item {
3410                                    workspace.show_error(&e, cx);
3411                                }
3412                            }
3413                            if to_pane.read(cx).items_len() == 0 {
3414                                workspace.remove_pane(to_pane, None, window, cx);
3415                            }
3416                        });
3417                    }
3418                })
3419                .detach();
3420            })
3421            .log_err();
3422    }
3423
3424    pub fn display_nav_history_buttons(&mut self, display: Option<bool>) {
3425        self.display_nav_history_buttons = display;
3426    }
3427
3428    fn pinned_item_ids(&self) -> Vec<EntityId> {
3429        self.items
3430            .iter()
3431            .enumerate()
3432            .filter_map(|(index, item)| {
3433                if self.is_tab_pinned(index) {
3434                    return Some(item.item_id());
3435                }
3436
3437                None
3438            })
3439            .collect()
3440    }
3441
3442    fn clean_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3443        self.items()
3444            .filter_map(|item| {
3445                if !item.is_dirty(cx) {
3446                    return Some(item.item_id());
3447                }
3448
3449                None
3450            })
3451            .collect()
3452    }
3453
3454    fn to_the_side_item_ids(&self, item_id: EntityId, side: Side) -> Vec<EntityId> {
3455        match side {
3456            Side::Left => self
3457                .items()
3458                .take_while(|item| item.item_id() != item_id)
3459                .map(|item| item.item_id())
3460                .collect(),
3461            Side::Right => self
3462                .items()
3463                .rev()
3464                .take_while(|item| item.item_id() != item_id)
3465                .map(|item| item.item_id())
3466                .collect(),
3467        }
3468    }
3469
3470    pub fn drag_split_direction(&self) -> Option<SplitDirection> {
3471        self.drag_split_direction
3472    }
3473
3474    pub fn set_zoom_out_on_close(&mut self, zoom_out_on_close: bool) {
3475        self.zoom_out_on_close = zoom_out_on_close;
3476    }
3477}
3478
3479fn default_render_tab_bar_buttons(
3480    pane: &mut Pane,
3481    window: &mut Window,
3482    cx: &mut Context<Pane>,
3483) -> (Option<AnyElement>, Option<AnyElement>) {
3484    if !pane.has_focus(window, cx) && !pane.context_menu_focused(window, cx) {
3485        return (None, None);
3486    }
3487    // Ideally we would return a vec of elements here to pass directly to the [TabBar]'s
3488    // `end_slot`, but due to needing a view here that isn't possible.
3489    let right_children = h_flex()
3490        // Instead we need to replicate the spacing from the [TabBar]'s `end_slot` here.
3491        .gap(DynamicSpacing::Base04.rems(cx))
3492        .child(
3493            PopoverMenu::new("pane-tab-bar-popover-menu")
3494                .trigger_with_tooltip(
3495                    IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
3496                    Tooltip::text("New..."),
3497                )
3498                .anchor(Corner::TopRight)
3499                .with_handle(pane.new_item_context_menu_handle.clone())
3500                .menu(move |window, cx| {
3501                    Some(ContextMenu::build(window, cx, |menu, _, _| {
3502                        menu.action("New File", NewFile.boxed_clone())
3503                            .action("Open File", ToggleFileFinder::default().boxed_clone())
3504                            .separator()
3505                            .action(
3506                                "Search Project",
3507                                DeploySearch {
3508                                    replace_enabled: false,
3509                                    included_files: None,
3510                                    excluded_files: None,
3511                                }
3512                                .boxed_clone(),
3513                            )
3514                            .action("Search Symbols", ToggleProjectSymbols.boxed_clone())
3515                            .separator()
3516                            .action("New Terminal", NewTerminal.boxed_clone())
3517                    }))
3518                }),
3519        )
3520        .child(
3521            PopoverMenu::new("pane-tab-bar-split")
3522                .trigger_with_tooltip(
3523                    IconButton::new("split", IconName::Split).icon_size(IconSize::Small),
3524                    Tooltip::text("Split Pane"),
3525                )
3526                .anchor(Corner::TopRight)
3527                .with_handle(pane.split_item_context_menu_handle.clone())
3528                .menu(move |window, cx| {
3529                    ContextMenu::build(window, cx, |menu, _, _| {
3530                        menu.action("Split Right", SplitRight.boxed_clone())
3531                            .action("Split Left", SplitLeft.boxed_clone())
3532                            .action("Split Up", SplitUp.boxed_clone())
3533                            .action("Split Down", SplitDown.boxed_clone())
3534                    })
3535                    .into()
3536                }),
3537        )
3538        .child({
3539            let zoomed = pane.is_zoomed();
3540            IconButton::new("toggle_zoom", IconName::Maximize)
3541                .icon_size(IconSize::Small)
3542                .toggle_state(zoomed)
3543                .selected_icon(IconName::Minimize)
3544                .on_click(cx.listener(|pane, _, window, cx| {
3545                    pane.toggle_zoom(&crate::ToggleZoom, window, cx);
3546                }))
3547                .tooltip(move |window, cx| {
3548                    Tooltip::for_action(
3549                        if zoomed { "Zoom Out" } else { "Zoom In" },
3550                        &ToggleZoom,
3551                        window,
3552                        cx,
3553                    )
3554                })
3555        })
3556        .into_any_element()
3557        .into();
3558    (None, right_children)
3559}
3560
3561impl Focusable for Pane {
3562    fn focus_handle(&self, _cx: &App) -> FocusHandle {
3563        self.focus_handle.clone()
3564    }
3565}
3566
3567impl Render for Pane {
3568    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3569        let mut key_context = KeyContext::new_with_defaults();
3570        key_context.add("Pane");
3571        if self.active_item().is_none() {
3572            key_context.add("EmptyPane");
3573        }
3574
3575        let should_display_tab_bar = self.should_display_tab_bar.clone();
3576        let display_tab_bar = should_display_tab_bar(window, cx);
3577        let Some(project) = self.project.upgrade() else {
3578            return div().track_focus(&self.focus_handle(cx));
3579        };
3580        let is_local = project.read(cx).is_local();
3581
3582        v_flex()
3583            .key_context(key_context)
3584            .track_focus(&self.focus_handle(cx))
3585            .size_full()
3586            .flex_none()
3587            .overflow_hidden()
3588            .on_action(
3589                cx.listener(|pane, _: &SplitLeft, _, cx| pane.split(SplitDirection::Left, cx)),
3590            )
3591            .on_action(cx.listener(|pane, _: &SplitUp, _, cx| pane.split(SplitDirection::Up, cx)))
3592            .on_action(cx.listener(|pane, _: &SplitHorizontal, _, cx| {
3593                pane.split(SplitDirection::horizontal(cx), cx)
3594            }))
3595            .on_action(cx.listener(|pane, _: &SplitVertical, _, cx| {
3596                pane.split(SplitDirection::vertical(cx), cx)
3597            }))
3598            .on_action(
3599                cx.listener(|pane, _: &SplitRight, _, cx| pane.split(SplitDirection::Right, cx)),
3600            )
3601            .on_action(
3602                cx.listener(|pane, _: &SplitDown, _, cx| pane.split(SplitDirection::Down, cx)),
3603            )
3604            .on_action(cx.listener(|pane, _: &SplitAndMoveUp, _, cx| {
3605                pane.split_and_move(SplitDirection::Up, cx)
3606            }))
3607            .on_action(cx.listener(|pane, _: &SplitAndMoveDown, _, cx| {
3608                pane.split_and_move(SplitDirection::Down, cx)
3609            }))
3610            .on_action(cx.listener(|pane, _: &SplitAndMoveLeft, _, cx| {
3611                pane.split_and_move(SplitDirection::Left, cx)
3612            }))
3613            .on_action(cx.listener(|pane, _: &SplitAndMoveRight, _, cx| {
3614                pane.split_and_move(SplitDirection::Right, cx)
3615            }))
3616            .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
3617                cx.emit(Event::JoinIntoNext);
3618            }))
3619            .on_action(cx.listener(|_, _: &JoinAll, _, cx| {
3620                cx.emit(Event::JoinAll);
3621            }))
3622            .on_action(cx.listener(Pane::toggle_zoom))
3623            .on_action(cx.listener(Self::navigate_backward))
3624            .on_action(cx.listener(Self::navigate_forward))
3625            .on_action(
3626                cx.listener(|pane: &mut Pane, action: &ActivateItem, window, cx| {
3627                    pane.activate_item(
3628                        action.0.min(pane.items.len().saturating_sub(1)),
3629                        true,
3630                        true,
3631                        window,
3632                        cx,
3633                    );
3634                }),
3635            )
3636            .on_action(cx.listener(Self::alternate_file))
3637            .on_action(cx.listener(Self::activate_last_item))
3638            .on_action(cx.listener(Self::activate_previous_item))
3639            .on_action(cx.listener(Self::activate_next_item))
3640            .on_action(cx.listener(Self::swap_item_left))
3641            .on_action(cx.listener(Self::swap_item_right))
3642            .on_action(cx.listener(Self::toggle_pin_tab))
3643            .on_action(cx.listener(Self::unpin_all_tabs))
3644            .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
3645                this.on_action(cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, _, cx| {
3646                    if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
3647                        if pane.is_active_preview_item(active_item_id) {
3648                            pane.set_preview_item_id(None, cx);
3649                        } else {
3650                            pane.set_preview_item_id(Some(active_item_id), cx);
3651                        }
3652                    }
3653                }))
3654            })
3655            .on_action(
3656                cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
3657                    pane.close_active_item(action, window, cx)
3658                        .detach_and_log_err(cx)
3659                }),
3660            )
3661            .on_action(
3662                cx.listener(|pane: &mut Self, action: &CloseOtherItems, window, cx| {
3663                    pane.close_other_items(action, None, window, cx)
3664                        .detach_and_log_err(cx);
3665                }),
3666            )
3667            .on_action(
3668                cx.listener(|pane: &mut Self, action: &CloseCleanItems, window, cx| {
3669                    pane.close_clean_items(action, window, cx)
3670                        .detach_and_log_err(cx)
3671                }),
3672            )
3673            .on_action(cx.listener(
3674                |pane: &mut Self, action: &CloseItemsToTheLeft, window, cx| {
3675                    pane.close_items_to_the_left_by_id(None, action, window, cx)
3676                        .detach_and_log_err(cx)
3677                },
3678            ))
3679            .on_action(cx.listener(
3680                |pane: &mut Self, action: &CloseItemsToTheRight, window, cx| {
3681                    pane.close_items_to_the_right_by_id(None, action, window, cx)
3682                        .detach_and_log_err(cx)
3683                },
3684            ))
3685            .on_action(
3686                cx.listener(|pane: &mut Self, action: &CloseAllItems, window, cx| {
3687                    pane.close_all_items(action, window, cx)
3688                        .detach_and_log_err(cx)
3689                }),
3690            )
3691            .on_action(
3692                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, _, cx| {
3693                    let entry_id = action
3694                        .entry_id
3695                        .map(ProjectEntryId::from_proto)
3696                        .or_else(|| pane.active_item()?.project_entry_ids(cx).first().copied());
3697                    if let Some(entry_id) = entry_id {
3698                        pane.project
3699                            .update(cx, |_, cx| {
3700                                cx.emit(project::Event::RevealInProjectPanel(entry_id))
3701                            })
3702                            .ok();
3703                    }
3704                }),
3705            )
3706            .on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
3707                if cx.stop_active_drag(window) {
3708                } else {
3709                    cx.propagate();
3710                }
3711            }))
3712            .when(self.active_item().is_some() && display_tab_bar, |pane| {
3713                pane.child((self.render_tab_bar.clone())(self, window, cx))
3714            })
3715            .child({
3716                let has_worktrees = project.read(cx).visible_worktrees(cx).next().is_some();
3717                // main content
3718                div()
3719                    .flex_1()
3720                    .relative()
3721                    .group("")
3722                    .overflow_hidden()
3723                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
3724                    .on_drag_move::<DraggedSelection>(cx.listener(Self::handle_drag_move))
3725                    .when(is_local, |div| {
3726                        div.on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
3727                    })
3728                    .map(|div| {
3729                        if let Some(item) = self.active_item() {
3730                            div.id("pane_placeholder")
3731                                .v_flex()
3732                                .size_full()
3733                                .overflow_hidden()
3734                                .child(self.toolbar.clone())
3735                                .child(item.to_any())
3736                        } else {
3737                            let placeholder = div
3738                                .id("pane_placeholder")
3739                                .h_flex()
3740                                .size_full()
3741                                .justify_center()
3742                                .on_click(cx.listener(
3743                                    move |this, event: &ClickEvent, window, cx| {
3744                                        if event.click_count() == 2 {
3745                                            window.dispatch_action(
3746                                                this.double_click_dispatch_action.boxed_clone(),
3747                                                cx,
3748                                            );
3749                                        }
3750                                    },
3751                                ));
3752                            if has_worktrees {
3753                                placeholder
3754                            } else {
3755                                placeholder.child(
3756                                    Label::new("Open a file or project to get started.")
3757                                        .color(Color::Muted),
3758                                )
3759                            }
3760                        }
3761                    })
3762                    .child(
3763                        // drag target
3764                        div()
3765                            .invisible()
3766                            .absolute()
3767                            .bg(cx.theme().colors().drop_target_background)
3768                            .group_drag_over::<DraggedTab>("", |style| style.visible())
3769                            .group_drag_over::<DraggedSelection>("", |style| style.visible())
3770                            .when(is_local, |div| {
3771                                div.group_drag_over::<ExternalPaths>("", |style| style.visible())
3772                            })
3773                            .when_some(self.can_drop_predicate.clone(), |this, p| {
3774                                this.can_drop(move |a, window, cx| p(a, window, cx))
3775                            })
3776                            .on_drop(cx.listener(move |this, dragged_tab, window, cx| {
3777                                this.handle_tab_drop(
3778                                    dragged_tab,
3779                                    this.active_item_index(),
3780                                    window,
3781                                    cx,
3782                                )
3783                            }))
3784                            .on_drop(cx.listener(
3785                                move |this, selection: &DraggedSelection, window, cx| {
3786                                    this.handle_dragged_selection_drop(selection, None, window, cx)
3787                                },
3788                            ))
3789                            .on_drop(cx.listener(move |this, paths, window, cx| {
3790                                this.handle_external_paths_drop(paths, window, cx)
3791                            }))
3792                            .map(|div| {
3793                                let size = DefiniteLength::Fraction(0.5);
3794                                match self.drag_split_direction {
3795                                    None => div.top_0().right_0().bottom_0().left_0(),
3796                                    Some(SplitDirection::Up) => {
3797                                        div.top_0().left_0().right_0().h(size)
3798                                    }
3799                                    Some(SplitDirection::Down) => {
3800                                        div.left_0().bottom_0().right_0().h(size)
3801                                    }
3802                                    Some(SplitDirection::Left) => {
3803                                        div.top_0().left_0().bottom_0().w(size)
3804                                    }
3805                                    Some(SplitDirection::Right) => {
3806                                        div.top_0().bottom_0().right_0().w(size)
3807                                    }
3808                                }
3809                            }),
3810                    )
3811            })
3812            .on_mouse_down(
3813                MouseButton::Navigate(NavigationDirection::Back),
3814                cx.listener(|pane, _, window, cx| {
3815                    if let Some(workspace) = pane.workspace.upgrade() {
3816                        let pane = cx.entity().downgrade();
3817                        window.defer(cx, move |window, cx| {
3818                            workspace.update(cx, |workspace, cx| {
3819                                workspace.go_back(pane, window, cx).detach_and_log_err(cx)
3820                            })
3821                        })
3822                    }
3823                }),
3824            )
3825            .on_mouse_down(
3826                MouseButton::Navigate(NavigationDirection::Forward),
3827                cx.listener(|pane, _, window, cx| {
3828                    if let Some(workspace) = pane.workspace.upgrade() {
3829                        let pane = cx.entity().downgrade();
3830                        window.defer(cx, move |window, cx| {
3831                            workspace.update(cx, |workspace, cx| {
3832                                workspace
3833                                    .go_forward(pane, window, cx)
3834                                    .detach_and_log_err(cx)
3835                            })
3836                        })
3837                    }
3838                }),
3839            )
3840    }
3841}
3842
3843impl ItemNavHistory {
3844    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut App) {
3845        if self
3846            .item
3847            .upgrade()
3848            .is_some_and(|item| item.include_in_nav_history())
3849        {
3850            self.history
3851                .push(data, self.item.clone(), self.is_preview, cx);
3852        }
3853    }
3854
3855    pub fn pop_backward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
3856        self.history.pop(NavigationMode::GoingBack, cx)
3857    }
3858
3859    pub fn pop_forward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
3860        self.history.pop(NavigationMode::GoingForward, cx)
3861    }
3862}
3863
3864impl NavHistory {
3865    pub fn for_each_entry(
3866        &self,
3867        cx: &App,
3868        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
3869    ) {
3870        let borrowed_history = self.0.lock();
3871        borrowed_history
3872            .forward_stack
3873            .iter()
3874            .chain(borrowed_history.backward_stack.iter())
3875            .chain(borrowed_history.closed_stack.iter())
3876            .for_each(|entry| {
3877                if let Some(project_and_abs_path) =
3878                    borrowed_history.paths_by_item.get(&entry.item.id())
3879                {
3880                    f(entry, project_and_abs_path.clone());
3881                } else if let Some(item) = entry.item.upgrade()
3882                    && let Some(path) = item.project_path(cx)
3883                {
3884                    f(entry, (path, None));
3885                }
3886            })
3887    }
3888
3889    pub fn set_mode(&mut self, mode: NavigationMode) {
3890        self.0.lock().mode = mode;
3891    }
3892
3893    pub fn mode(&self) -> NavigationMode {
3894        self.0.lock().mode
3895    }
3896
3897    pub fn disable(&mut self) {
3898        self.0.lock().mode = NavigationMode::Disabled;
3899    }
3900
3901    pub fn enable(&mut self) {
3902        self.0.lock().mode = NavigationMode::Normal;
3903    }
3904
3905    pub fn pop(&mut self, mode: NavigationMode, cx: &mut App) -> Option<NavigationEntry> {
3906        let mut state = self.0.lock();
3907        let entry = match mode {
3908            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
3909                return None;
3910            }
3911            NavigationMode::GoingBack => &mut state.backward_stack,
3912            NavigationMode::GoingForward => &mut state.forward_stack,
3913            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
3914        }
3915        .pop_back();
3916        if entry.is_some() {
3917            state.did_update(cx);
3918        }
3919        entry
3920    }
3921
3922    pub fn push<D: 'static + Send + Any>(
3923        &mut self,
3924        data: Option<D>,
3925        item: Arc<dyn WeakItemHandle>,
3926        is_preview: bool,
3927        cx: &mut App,
3928    ) {
3929        let state = &mut *self.0.lock();
3930        match state.mode {
3931            NavigationMode::Disabled => {}
3932            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
3933                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3934                    state.backward_stack.pop_front();
3935                }
3936                state.backward_stack.push_back(NavigationEntry {
3937                    item,
3938                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3939                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3940                    is_preview,
3941                });
3942                state.forward_stack.clear();
3943            }
3944            NavigationMode::GoingBack => {
3945                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3946                    state.forward_stack.pop_front();
3947                }
3948                state.forward_stack.push_back(NavigationEntry {
3949                    item,
3950                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3951                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3952                    is_preview,
3953                });
3954            }
3955            NavigationMode::GoingForward => {
3956                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3957                    state.backward_stack.pop_front();
3958                }
3959                state.backward_stack.push_back(NavigationEntry {
3960                    item,
3961                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3962                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3963                    is_preview,
3964                });
3965            }
3966            NavigationMode::ClosingItem => {
3967                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3968                    state.closed_stack.pop_front();
3969                }
3970                state.closed_stack.push_back(NavigationEntry {
3971                    item,
3972                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3973                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3974                    is_preview,
3975                });
3976            }
3977        }
3978        state.did_update(cx);
3979    }
3980
3981    pub fn remove_item(&mut self, item_id: EntityId) {
3982        let mut state = self.0.lock();
3983        state.paths_by_item.remove(&item_id);
3984        state
3985            .backward_stack
3986            .retain(|entry| entry.item.id() != item_id);
3987        state
3988            .forward_stack
3989            .retain(|entry| entry.item.id() != item_id);
3990        state
3991            .closed_stack
3992            .retain(|entry| entry.item.id() != item_id);
3993    }
3994
3995    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
3996        self.0.lock().paths_by_item.get(&item_id).cloned()
3997    }
3998}
3999
4000impl NavHistoryState {
4001    pub fn did_update(&self, cx: &mut App) {
4002        if let Some(pane) = self.pane.upgrade() {
4003            cx.defer(move |cx| {
4004                pane.update(cx, |pane, cx| pane.history_updated(cx));
4005            });
4006        }
4007    }
4008}
4009
4010fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
4011    let path = buffer_path
4012        .as_ref()
4013        .and_then(|p| {
4014            p.path
4015                .to_str()
4016                .and_then(|s| if s.is_empty() { None } else { Some(s) })
4017        })
4018        .unwrap_or("This buffer");
4019    let path = truncate_and_remove_front(path, 80);
4020    format!("{path} contains unsaved edits. Do you want to save it?")
4021}
4022
4023pub fn tab_details(items: &[Box<dyn ItemHandle>], _window: &Window, cx: &App) -> Vec<usize> {
4024    let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
4025    let mut tab_descriptions = HashMap::default();
4026    let mut done = false;
4027    while !done {
4028        done = true;
4029
4030        // Store item indices by their tab description.
4031        for (ix, (item, detail)) in items.iter().zip(&tab_details).enumerate() {
4032            let description = item.tab_content_text(*detail, cx);
4033            if *detail == 0 || description != item.tab_content_text(detail - 1, cx) {
4034                tab_descriptions
4035                    .entry(description)
4036                    .or_insert(Vec::new())
4037                    .push(ix);
4038            }
4039        }
4040
4041        // If two or more items have the same tab description, increase their level
4042        // of detail and try again.
4043        for (_, item_ixs) in tab_descriptions.drain() {
4044            if item_ixs.len() > 1 {
4045                done = false;
4046                for ix in item_ixs {
4047                    tab_details[ix] += 1;
4048                }
4049            }
4050        }
4051    }
4052
4053    tab_details
4054}
4055
4056pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &App) -> Option<Indicator> {
4057    maybe!({
4058        let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
4059            (true, _) => Color::Warning,
4060            (_, true) => Color::Accent,
4061            (false, false) => return None,
4062        };
4063
4064        Some(Indicator::dot().color(indicator_color))
4065    })
4066}
4067
4068impl Render for DraggedTab {
4069    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4070        let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
4071        let label = self.item.tab_content(
4072            TabContentParams {
4073                detail: Some(self.detail),
4074                selected: false,
4075                preview: false,
4076                deemphasized: false,
4077            },
4078            window,
4079            cx,
4080        );
4081        Tab::new("")
4082            .toggle_state(self.is_active)
4083            .child(label)
4084            .render(window, cx)
4085            .font(ui_font)
4086    }
4087}
4088
4089#[cfg(test)]
4090mod tests {
4091    use std::num::NonZero;
4092
4093    use super::*;
4094    use crate::item::test::{TestItem, TestProjectItem};
4095    use gpui::{TestAppContext, VisualTestContext};
4096    use project::FakeFs;
4097    use settings::SettingsStore;
4098    use theme::LoadThemes;
4099    use util::TryFutureExt;
4100
4101    #[gpui::test]
4102    async fn test_add_item_capped_to_max_tabs(cx: &mut TestAppContext) {
4103        init_test(cx);
4104        let fs = FakeFs::new(cx.executor());
4105
4106        let project = Project::test(fs, None, cx).await;
4107        let (workspace, cx) =
4108            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4109        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4110
4111        for i in 0..7 {
4112            add_labeled_item(&pane, format!("{}", i).as_str(), false, cx);
4113        }
4114
4115        set_max_tabs(cx, Some(5));
4116        add_labeled_item(&pane, "7", false, cx);
4117        // Remove items to respect the max tab cap.
4118        assert_item_labels(&pane, ["3", "4", "5", "6", "7*"], cx);
4119        pane.update_in(cx, |pane, window, cx| {
4120            pane.activate_item(0, false, false, window, cx);
4121        });
4122        add_labeled_item(&pane, "X", false, cx);
4123        // Respect activation order.
4124        assert_item_labels(&pane, ["3", "X*", "5", "6", "7"], cx);
4125
4126        for i in 0..7 {
4127            add_labeled_item(&pane, format!("D{}", i).as_str(), true, cx);
4128        }
4129        // Keeps dirty items, even over max tab cap.
4130        assert_item_labels(
4131            &pane,
4132            ["D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6*^"],
4133            cx,
4134        );
4135
4136        set_max_tabs(cx, None);
4137        for i in 0..7 {
4138            add_labeled_item(&pane, format!("N{}", i).as_str(), false, cx);
4139        }
4140        // No cap when max tabs is None.
4141        assert_item_labels(
4142            &pane,
4143            [
4144                "D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6^", "N0", "N1", "N2", "N3", "N4",
4145                "N5", "N6*",
4146            ],
4147            cx,
4148        );
4149    }
4150
4151    #[gpui::test]
4152    async fn test_reduce_max_tabs_closes_existing_items(cx: &mut TestAppContext) {
4153        init_test(cx);
4154        let fs = FakeFs::new(cx.executor());
4155
4156        let project = Project::test(fs, None, cx).await;
4157        let (workspace, cx) =
4158            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4159        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4160
4161        add_labeled_item(&pane, "A", false, cx);
4162        add_labeled_item(&pane, "B", false, cx);
4163        let item_c = add_labeled_item(&pane, "C", false, cx);
4164        let item_d = add_labeled_item(&pane, "D", false, cx);
4165        add_labeled_item(&pane, "E", false, cx);
4166        add_labeled_item(&pane, "Settings", false, cx);
4167        assert_item_labels(&pane, ["A", "B", "C", "D", "E", "Settings*"], cx);
4168
4169        set_max_tabs(cx, Some(5));
4170        assert_item_labels(&pane, ["B", "C", "D", "E", "Settings*"], cx);
4171
4172        set_max_tabs(cx, Some(4));
4173        assert_item_labels(&pane, ["C", "D", "E", "Settings*"], cx);
4174
4175        pane.update_in(cx, |pane, window, cx| {
4176            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4177            pane.pin_tab_at(ix, window, cx);
4178
4179            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4180            pane.pin_tab_at(ix, window, cx);
4181        });
4182        assert_item_labels(&pane, ["C!", "D!", "E", "Settings*"], cx);
4183
4184        set_max_tabs(cx, Some(2));
4185        assert_item_labels(&pane, ["C!", "D!", "Settings*"], cx);
4186    }
4187
4188    #[gpui::test]
4189    async fn test_allow_pinning_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4190        init_test(cx);
4191        let fs = FakeFs::new(cx.executor());
4192
4193        let project = Project::test(fs, None, cx).await;
4194        let (workspace, cx) =
4195            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4196        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4197
4198        set_max_tabs(cx, Some(1));
4199        let item_a = add_labeled_item(&pane, "A", true, cx);
4200
4201        pane.update_in(cx, |pane, window, cx| {
4202            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4203            pane.pin_tab_at(ix, window, cx);
4204        });
4205        assert_item_labels(&pane, ["A*^!"], cx);
4206    }
4207
4208    #[gpui::test]
4209    async fn test_allow_pinning_non_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4210        init_test(cx);
4211        let fs = FakeFs::new(cx.executor());
4212
4213        let project = Project::test(fs, None, cx).await;
4214        let (workspace, cx) =
4215            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4216        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4217
4218        set_max_tabs(cx, Some(1));
4219        let item_a = add_labeled_item(&pane, "A", false, cx);
4220
4221        pane.update_in(cx, |pane, window, cx| {
4222            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4223            pane.pin_tab_at(ix, window, cx);
4224        });
4225        assert_item_labels(&pane, ["A*!"], cx);
4226    }
4227
4228    #[gpui::test]
4229    async fn test_pin_tabs_incrementally_at_max_capacity(cx: &mut TestAppContext) {
4230        init_test(cx);
4231        let fs = FakeFs::new(cx.executor());
4232
4233        let project = Project::test(fs, None, cx).await;
4234        let (workspace, cx) =
4235            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4236        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4237
4238        set_max_tabs(cx, Some(3));
4239
4240        let item_a = add_labeled_item(&pane, "A", false, cx);
4241        assert_item_labels(&pane, ["A*"], cx);
4242
4243        pane.update_in(cx, |pane, window, cx| {
4244            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4245            pane.pin_tab_at(ix, window, cx);
4246        });
4247        assert_item_labels(&pane, ["A*!"], cx);
4248
4249        let item_b = add_labeled_item(&pane, "B", false, cx);
4250        assert_item_labels(&pane, ["A!", "B*"], cx);
4251
4252        pane.update_in(cx, |pane, window, cx| {
4253            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4254            pane.pin_tab_at(ix, window, cx);
4255        });
4256        assert_item_labels(&pane, ["A!", "B*!"], cx);
4257
4258        let item_c = add_labeled_item(&pane, "C", false, cx);
4259        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4260
4261        pane.update_in(cx, |pane, window, cx| {
4262            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4263            pane.pin_tab_at(ix, window, cx);
4264        });
4265        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4266    }
4267
4268    #[gpui::test]
4269    async fn test_pin_tabs_left_to_right_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4270        init_test(cx);
4271        let fs = FakeFs::new(cx.executor());
4272
4273        let project = Project::test(fs, None, cx).await;
4274        let (workspace, cx) =
4275            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4276        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4277
4278        set_max_tabs(cx, Some(3));
4279
4280        let item_a = add_labeled_item(&pane, "A", false, cx);
4281        assert_item_labels(&pane, ["A*"], cx);
4282
4283        let item_b = add_labeled_item(&pane, "B", false, cx);
4284        assert_item_labels(&pane, ["A", "B*"], cx);
4285
4286        let item_c = add_labeled_item(&pane, "C", false, cx);
4287        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4288
4289        pane.update_in(cx, |pane, window, cx| {
4290            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4291            pane.pin_tab_at(ix, window, cx);
4292        });
4293        assert_item_labels(&pane, ["A!", "B", "C*"], cx);
4294
4295        pane.update_in(cx, |pane, window, cx| {
4296            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4297            pane.pin_tab_at(ix, window, cx);
4298        });
4299        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4300
4301        pane.update_in(cx, |pane, window, cx| {
4302            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4303            pane.pin_tab_at(ix, window, cx);
4304        });
4305        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4306    }
4307
4308    #[gpui::test]
4309    async fn test_pin_tabs_right_to_left_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4310        init_test(cx);
4311        let fs = FakeFs::new(cx.executor());
4312
4313        let project = Project::test(fs, None, cx).await;
4314        let (workspace, cx) =
4315            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4316        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4317
4318        set_max_tabs(cx, Some(3));
4319
4320        let item_a = add_labeled_item(&pane, "A", false, cx);
4321        assert_item_labels(&pane, ["A*"], cx);
4322
4323        let item_b = add_labeled_item(&pane, "B", false, cx);
4324        assert_item_labels(&pane, ["A", "B*"], cx);
4325
4326        let item_c = add_labeled_item(&pane, "C", false, cx);
4327        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4328
4329        pane.update_in(cx, |pane, window, cx| {
4330            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4331            pane.pin_tab_at(ix, window, cx);
4332        });
4333        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4334
4335        pane.update_in(cx, |pane, window, cx| {
4336            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4337            pane.pin_tab_at(ix, window, cx);
4338        });
4339        assert_item_labels(&pane, ["C*!", "B!", "A"], cx);
4340
4341        pane.update_in(cx, |pane, window, cx| {
4342            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4343            pane.pin_tab_at(ix, window, cx);
4344        });
4345        assert_item_labels(&pane, ["C*!", "B!", "A!"], cx);
4346    }
4347
4348    #[gpui::test]
4349    async fn test_pinned_tabs_never_closed_at_max_tabs(cx: &mut TestAppContext) {
4350        init_test(cx);
4351        let fs = FakeFs::new(cx.executor());
4352
4353        let project = Project::test(fs, None, cx).await;
4354        let (workspace, cx) =
4355            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4356        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4357
4358        let item_a = add_labeled_item(&pane, "A", false, cx);
4359        pane.update_in(cx, |pane, window, cx| {
4360            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4361            pane.pin_tab_at(ix, window, cx);
4362        });
4363
4364        let item_b = add_labeled_item(&pane, "B", false, cx);
4365        pane.update_in(cx, |pane, window, cx| {
4366            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4367            pane.pin_tab_at(ix, window, cx);
4368        });
4369
4370        add_labeled_item(&pane, "C", false, cx);
4371        add_labeled_item(&pane, "D", false, cx);
4372        add_labeled_item(&pane, "E", false, cx);
4373        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
4374
4375        set_max_tabs(cx, Some(3));
4376        add_labeled_item(&pane, "F", false, cx);
4377        assert_item_labels(&pane, ["A!", "B!", "F*"], cx);
4378
4379        add_labeled_item(&pane, "G", false, cx);
4380        assert_item_labels(&pane, ["A!", "B!", "G*"], cx);
4381
4382        add_labeled_item(&pane, "H", false, cx);
4383        assert_item_labels(&pane, ["A!", "B!", "H*"], cx);
4384    }
4385
4386    #[gpui::test]
4387    async fn test_always_allows_one_unpinned_item_over_max_tabs_regardless_of_pinned_count(
4388        cx: &mut TestAppContext,
4389    ) {
4390        init_test(cx);
4391        let fs = FakeFs::new(cx.executor());
4392
4393        let project = Project::test(fs, None, cx).await;
4394        let (workspace, cx) =
4395            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4396        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4397
4398        set_max_tabs(cx, Some(3));
4399
4400        let item_a = add_labeled_item(&pane, "A", false, cx);
4401        pane.update_in(cx, |pane, window, cx| {
4402            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4403            pane.pin_tab_at(ix, window, cx);
4404        });
4405
4406        let item_b = add_labeled_item(&pane, "B", false, cx);
4407        pane.update_in(cx, |pane, window, cx| {
4408            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4409            pane.pin_tab_at(ix, window, cx);
4410        });
4411
4412        let item_c = add_labeled_item(&pane, "C", false, cx);
4413        pane.update_in(cx, |pane, window, cx| {
4414            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4415            pane.pin_tab_at(ix, window, cx);
4416        });
4417
4418        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4419
4420        let item_d = add_labeled_item(&pane, "D", false, cx);
4421        assert_item_labels(&pane, ["A!", "B!", "C!", "D*"], cx);
4422
4423        pane.update_in(cx, |pane, window, cx| {
4424            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4425            pane.pin_tab_at(ix, window, cx);
4426        });
4427        assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
4428
4429        add_labeled_item(&pane, "E", false, cx);
4430        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "E*"], cx);
4431
4432        add_labeled_item(&pane, "F", false, cx);
4433        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "F*"], cx);
4434    }
4435
4436    #[gpui::test]
4437    async fn test_can_open_one_item_when_all_tabs_are_dirty_at_max(cx: &mut TestAppContext) {
4438        init_test(cx);
4439        let fs = FakeFs::new(cx.executor());
4440
4441        let project = Project::test(fs, None, cx).await;
4442        let (workspace, cx) =
4443            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4444        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4445
4446        set_max_tabs(cx, Some(3));
4447
4448        add_labeled_item(&pane, "A", true, cx);
4449        assert_item_labels(&pane, ["A*^"], cx);
4450
4451        add_labeled_item(&pane, "B", true, cx);
4452        assert_item_labels(&pane, ["A^", "B*^"], cx);
4453
4454        add_labeled_item(&pane, "C", true, cx);
4455        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
4456
4457        add_labeled_item(&pane, "D", false, cx);
4458        assert_item_labels(&pane, ["A^", "B^", "C^", "D*"], cx);
4459
4460        add_labeled_item(&pane, "E", false, cx);
4461        assert_item_labels(&pane, ["A^", "B^", "C^", "E*"], cx);
4462
4463        add_labeled_item(&pane, "F", false, cx);
4464        assert_item_labels(&pane, ["A^", "B^", "C^", "F*"], cx);
4465
4466        add_labeled_item(&pane, "G", true, cx);
4467        assert_item_labels(&pane, ["A^", "B^", "C^", "G*^"], cx);
4468    }
4469
4470    #[gpui::test]
4471    async fn test_toggle_pin_tab(cx: &mut TestAppContext) {
4472        init_test(cx);
4473        let fs = FakeFs::new(cx.executor());
4474
4475        let project = Project::test(fs, None, cx).await;
4476        let (workspace, cx) =
4477            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4478        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4479
4480        set_labeled_items(&pane, ["A", "B*", "C"], cx);
4481        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4482
4483        pane.update_in(cx, |pane, window, cx| {
4484            pane.toggle_pin_tab(&TogglePinTab, window, cx);
4485        });
4486        assert_item_labels(&pane, ["B*!", "A", "C"], cx);
4487
4488        pane.update_in(cx, |pane, window, cx| {
4489            pane.toggle_pin_tab(&TogglePinTab, window, cx);
4490        });
4491        assert_item_labels(&pane, ["B*", "A", "C"], cx);
4492    }
4493
4494    #[gpui::test]
4495    async fn test_unpin_all_tabs(cx: &mut TestAppContext) {
4496        init_test(cx);
4497        let fs = FakeFs::new(cx.executor());
4498
4499        let project = Project::test(fs, None, cx).await;
4500        let (workspace, cx) =
4501            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4502        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4503
4504        // Unpin all, in an empty pane
4505        pane.update_in(cx, |pane, window, cx| {
4506            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4507        });
4508
4509        assert_item_labels(&pane, [], cx);
4510
4511        let item_a = add_labeled_item(&pane, "A", false, cx);
4512        let item_b = add_labeled_item(&pane, "B", false, cx);
4513        let item_c = add_labeled_item(&pane, "C", false, cx);
4514        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4515
4516        // Unpin all, when no tabs are pinned
4517        pane.update_in(cx, |pane, window, cx| {
4518            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4519        });
4520
4521        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4522
4523        // Pin inactive tabs only
4524        pane.update_in(cx, |pane, window, cx| {
4525            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4526            pane.pin_tab_at(ix, window, cx);
4527
4528            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4529            pane.pin_tab_at(ix, window, cx);
4530        });
4531        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4532
4533        pane.update_in(cx, |pane, window, cx| {
4534            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4535        });
4536
4537        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4538
4539        // Pin all tabs
4540        pane.update_in(cx, |pane, window, cx| {
4541            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4542            pane.pin_tab_at(ix, window, cx);
4543
4544            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4545            pane.pin_tab_at(ix, window, cx);
4546
4547            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4548            pane.pin_tab_at(ix, window, cx);
4549        });
4550        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4551
4552        // Activate middle tab
4553        pane.update_in(cx, |pane, window, cx| {
4554            pane.activate_item(1, false, false, window, cx);
4555        });
4556        assert_item_labels(&pane, ["A!", "B*!", "C!"], cx);
4557
4558        pane.update_in(cx, |pane, window, cx| {
4559            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4560        });
4561
4562        // Order has not changed
4563        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4564    }
4565
4566    #[gpui::test]
4567    async fn test_pinning_active_tab_without_position_change_maintains_focus(
4568        cx: &mut TestAppContext,
4569    ) {
4570        init_test(cx);
4571        let fs = FakeFs::new(cx.executor());
4572
4573        let project = Project::test(fs, None, cx).await;
4574        let (workspace, cx) =
4575            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4576        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4577
4578        // Add A
4579        let item_a = add_labeled_item(&pane, "A", false, cx);
4580        assert_item_labels(&pane, ["A*"], cx);
4581
4582        // Add B
4583        add_labeled_item(&pane, "B", false, cx);
4584        assert_item_labels(&pane, ["A", "B*"], cx);
4585
4586        // Activate A again
4587        pane.update_in(cx, |pane, window, cx| {
4588            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4589            pane.activate_item(ix, true, true, window, cx);
4590        });
4591        assert_item_labels(&pane, ["A*", "B"], cx);
4592
4593        // Pin A - remains active
4594        pane.update_in(cx, |pane, window, cx| {
4595            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4596            pane.pin_tab_at(ix, window, cx);
4597        });
4598        assert_item_labels(&pane, ["A*!", "B"], cx);
4599
4600        // Unpin A - remain active
4601        pane.update_in(cx, |pane, window, cx| {
4602            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4603            pane.unpin_tab_at(ix, window, cx);
4604        });
4605        assert_item_labels(&pane, ["A*", "B"], cx);
4606    }
4607
4608    #[gpui::test]
4609    async fn test_pinning_active_tab_with_position_change_maintains_focus(cx: &mut TestAppContext) {
4610        init_test(cx);
4611        let fs = FakeFs::new(cx.executor());
4612
4613        let project = Project::test(fs, None, cx).await;
4614        let (workspace, cx) =
4615            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4616        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4617
4618        // Add A, B, C
4619        add_labeled_item(&pane, "A", false, cx);
4620        add_labeled_item(&pane, "B", false, cx);
4621        let item_c = add_labeled_item(&pane, "C", false, cx);
4622        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4623
4624        // Pin C - moves to pinned area, remains active
4625        pane.update_in(cx, |pane, window, cx| {
4626            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4627            pane.pin_tab_at(ix, window, cx);
4628        });
4629        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4630
4631        // Unpin C - moves after pinned area, remains active
4632        pane.update_in(cx, |pane, window, cx| {
4633            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4634            pane.unpin_tab_at(ix, window, cx);
4635        });
4636        assert_item_labels(&pane, ["C*", "A", "B"], cx);
4637    }
4638
4639    #[gpui::test]
4640    async fn test_pinning_inactive_tab_without_position_change_preserves_existing_focus(
4641        cx: &mut TestAppContext,
4642    ) {
4643        init_test(cx);
4644        let fs = FakeFs::new(cx.executor());
4645
4646        let project = Project::test(fs, None, cx).await;
4647        let (workspace, cx) =
4648            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4649        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4650
4651        // Add A, B
4652        let item_a = add_labeled_item(&pane, "A", false, cx);
4653        add_labeled_item(&pane, "B", false, cx);
4654        assert_item_labels(&pane, ["A", "B*"], cx);
4655
4656        // Pin A - already in pinned area, B remains active
4657        pane.update_in(cx, |pane, window, cx| {
4658            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4659            pane.pin_tab_at(ix, window, cx);
4660        });
4661        assert_item_labels(&pane, ["A!", "B*"], cx);
4662
4663        // Unpin A - stays in place, B remains active
4664        pane.update_in(cx, |pane, window, cx| {
4665            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4666            pane.unpin_tab_at(ix, window, cx);
4667        });
4668        assert_item_labels(&pane, ["A", "B*"], cx);
4669    }
4670
4671    #[gpui::test]
4672    async fn test_pinning_inactive_tab_with_position_change_preserves_existing_focus(
4673        cx: &mut TestAppContext,
4674    ) {
4675        init_test(cx);
4676        let fs = FakeFs::new(cx.executor());
4677
4678        let project = Project::test(fs, None, cx).await;
4679        let (workspace, cx) =
4680            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4681        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4682
4683        // Add A, B, C
4684        add_labeled_item(&pane, "A", false, cx);
4685        let item_b = add_labeled_item(&pane, "B", false, cx);
4686        let item_c = add_labeled_item(&pane, "C", false, cx);
4687        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4688
4689        // Activate B
4690        pane.update_in(cx, |pane, window, cx| {
4691            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4692            pane.activate_item(ix, true, true, window, cx);
4693        });
4694        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4695
4696        // Pin C - moves to pinned area, B remains active
4697        pane.update_in(cx, |pane, window, cx| {
4698            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4699            pane.pin_tab_at(ix, window, cx);
4700        });
4701        assert_item_labels(&pane, ["C!", "A", "B*"], cx);
4702
4703        // Unpin C - moves after pinned area, B remains active
4704        pane.update_in(cx, |pane, window, cx| {
4705            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4706            pane.unpin_tab_at(ix, window, cx);
4707        });
4708        assert_item_labels(&pane, ["C", "A", "B*"], cx);
4709    }
4710
4711    #[gpui::test]
4712    async fn test_drag_unpinned_tab_to_split_creates_pane_with_unpinned_tab(
4713        cx: &mut TestAppContext,
4714    ) {
4715        init_test(cx);
4716        let fs = FakeFs::new(cx.executor());
4717
4718        let project = Project::test(fs, None, cx).await;
4719        let (workspace, cx) =
4720            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4721        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4722
4723        // Add A, B. Pin B. Activate A
4724        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4725        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4726
4727        pane_a.update_in(cx, |pane, window, cx| {
4728            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4729            pane.pin_tab_at(ix, window, cx);
4730
4731            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4732            pane.activate_item(ix, true, true, window, cx);
4733        });
4734
4735        // Drag A to create new split
4736        pane_a.update_in(cx, |pane, window, cx| {
4737            pane.drag_split_direction = Some(SplitDirection::Right);
4738
4739            let dragged_tab = DraggedTab {
4740                pane: pane_a.clone(),
4741                item: item_a.boxed_clone(),
4742                ix: 0,
4743                detail: 0,
4744                is_active: true,
4745            };
4746            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4747        });
4748
4749        // A should be moved to new pane. B should remain pinned, A should not be pinned
4750        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
4751            let panes = workspace.panes();
4752            (panes[0].clone(), panes[1].clone())
4753        });
4754        assert_item_labels(&pane_a, ["B*!"], cx);
4755        assert_item_labels(&pane_b, ["A*"], cx);
4756    }
4757
4758    #[gpui::test]
4759    async fn test_drag_pinned_tab_to_split_creates_pane_with_pinned_tab(cx: &mut TestAppContext) {
4760        init_test(cx);
4761        let fs = FakeFs::new(cx.executor());
4762
4763        let project = Project::test(fs, None, cx).await;
4764        let (workspace, cx) =
4765            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4766        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4767
4768        // Add A, B. Pin both. Activate A
4769        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4770        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4771
4772        pane_a.update_in(cx, |pane, window, cx| {
4773            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4774            pane.pin_tab_at(ix, window, cx);
4775
4776            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4777            pane.pin_tab_at(ix, window, cx);
4778
4779            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4780            pane.activate_item(ix, true, true, window, cx);
4781        });
4782        assert_item_labels(&pane_a, ["A*!", "B!"], cx);
4783
4784        // Drag A to create new split
4785        pane_a.update_in(cx, |pane, window, cx| {
4786            pane.drag_split_direction = Some(SplitDirection::Right);
4787
4788            let dragged_tab = DraggedTab {
4789                pane: pane_a.clone(),
4790                item: item_a.boxed_clone(),
4791                ix: 0,
4792                detail: 0,
4793                is_active: true,
4794            };
4795            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4796        });
4797
4798        // A should be moved to new pane. Both A and B should still be pinned
4799        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
4800            let panes = workspace.panes();
4801            (panes[0].clone(), panes[1].clone())
4802        });
4803        assert_item_labels(&pane_a, ["B*!"], cx);
4804        assert_item_labels(&pane_b, ["A*!"], cx);
4805    }
4806
4807    #[gpui::test]
4808    async fn test_drag_pinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
4809        init_test(cx);
4810        let fs = FakeFs::new(cx.executor());
4811
4812        let project = Project::test(fs, None, cx).await;
4813        let (workspace, cx) =
4814            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4815        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4816
4817        // Add A to pane A and pin
4818        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4819        pane_a.update_in(cx, |pane, window, cx| {
4820            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4821            pane.pin_tab_at(ix, window, cx);
4822        });
4823        assert_item_labels(&pane_a, ["A*!"], cx);
4824
4825        // Add B to pane B and pin
4826        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4827            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4828        });
4829        let item_b = add_labeled_item(&pane_b, "B", false, cx);
4830        pane_b.update_in(cx, |pane, window, cx| {
4831            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4832            pane.pin_tab_at(ix, window, cx);
4833        });
4834        assert_item_labels(&pane_b, ["B*!"], cx);
4835
4836        // Move A from pane A to pane B's pinned region
4837        pane_b.update_in(cx, |pane, window, cx| {
4838            let dragged_tab = DraggedTab {
4839                pane: pane_a.clone(),
4840                item: item_a.boxed_clone(),
4841                ix: 0,
4842                detail: 0,
4843                is_active: true,
4844            };
4845            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4846        });
4847
4848        // A should stay pinned
4849        assert_item_labels(&pane_a, [], cx);
4850        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
4851    }
4852
4853    #[gpui::test]
4854    async fn test_drag_pinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
4855        init_test(cx);
4856        let fs = FakeFs::new(cx.executor());
4857
4858        let project = Project::test(fs, None, cx).await;
4859        let (workspace, cx) =
4860            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4861        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4862
4863        // Add A to pane A and pin
4864        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4865        pane_a.update_in(cx, |pane, window, cx| {
4866            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4867            pane.pin_tab_at(ix, window, cx);
4868        });
4869        assert_item_labels(&pane_a, ["A*!"], cx);
4870
4871        // Create pane B with pinned item B
4872        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4873            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4874        });
4875        let item_b = add_labeled_item(&pane_b, "B", false, cx);
4876        assert_item_labels(&pane_b, ["B*"], cx);
4877
4878        pane_b.update_in(cx, |pane, window, cx| {
4879            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4880            pane.pin_tab_at(ix, window, cx);
4881        });
4882        assert_item_labels(&pane_b, ["B*!"], cx);
4883
4884        // Move A from pane A to pane B's unpinned region
4885        pane_b.update_in(cx, |pane, window, cx| {
4886            let dragged_tab = DraggedTab {
4887                pane: pane_a.clone(),
4888                item: item_a.boxed_clone(),
4889                ix: 0,
4890                detail: 0,
4891                is_active: true,
4892            };
4893            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
4894        });
4895
4896        // A should become pinned
4897        assert_item_labels(&pane_a, [], cx);
4898        assert_item_labels(&pane_b, ["B!", "A*"], cx);
4899    }
4900
4901    #[gpui::test]
4902    async fn test_drag_pinned_tab_into_existing_panes_first_position_with_no_pinned_tabs(
4903        cx: &mut TestAppContext,
4904    ) {
4905        init_test(cx);
4906        let fs = FakeFs::new(cx.executor());
4907
4908        let project = Project::test(fs, None, cx).await;
4909        let (workspace, cx) =
4910            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4911        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4912
4913        // Add A to pane A and pin
4914        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4915        pane_a.update_in(cx, |pane, window, cx| {
4916            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4917            pane.pin_tab_at(ix, window, cx);
4918        });
4919        assert_item_labels(&pane_a, ["A*!"], cx);
4920
4921        // Add B to pane B
4922        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4923            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4924        });
4925        add_labeled_item(&pane_b, "B", false, cx);
4926        assert_item_labels(&pane_b, ["B*"], cx);
4927
4928        // Move A from pane A to position 0 in pane B, indicating it should stay pinned
4929        pane_b.update_in(cx, |pane, window, cx| {
4930            let dragged_tab = DraggedTab {
4931                pane: pane_a.clone(),
4932                item: item_a.boxed_clone(),
4933                ix: 0,
4934                detail: 0,
4935                is_active: true,
4936            };
4937            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4938        });
4939
4940        // A should stay pinned
4941        assert_item_labels(&pane_a, [], cx);
4942        assert_item_labels(&pane_b, ["A*!", "B"], cx);
4943    }
4944
4945    #[gpui::test]
4946    async fn test_drag_pinned_tab_into_existing_pane_at_max_capacity_closes_unpinned_tabs(
4947        cx: &mut TestAppContext,
4948    ) {
4949        init_test(cx);
4950        let fs = FakeFs::new(cx.executor());
4951
4952        let project = Project::test(fs, None, cx).await;
4953        let (workspace, cx) =
4954            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4955        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4956        set_max_tabs(cx, Some(2));
4957
4958        // Add A, B to pane A. Pin both
4959        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4960        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4961        pane_a.update_in(cx, |pane, window, cx| {
4962            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4963            pane.pin_tab_at(ix, window, cx);
4964
4965            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4966            pane.pin_tab_at(ix, window, cx);
4967        });
4968        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
4969
4970        // Add C, D to pane B. Pin both
4971        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4972            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4973        });
4974        let item_c = add_labeled_item(&pane_b, "C", false, cx);
4975        let item_d = add_labeled_item(&pane_b, "D", false, cx);
4976        pane_b.update_in(cx, |pane, window, cx| {
4977            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4978            pane.pin_tab_at(ix, window, cx);
4979
4980            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4981            pane.pin_tab_at(ix, window, cx);
4982        });
4983        assert_item_labels(&pane_b, ["C!", "D*!"], cx);
4984
4985        // Add a third unpinned item to pane B (exceeds max tabs), but is allowed,
4986        // as we allow 1 tab over max if the others are pinned or dirty
4987        add_labeled_item(&pane_b, "E", false, cx);
4988        assert_item_labels(&pane_b, ["C!", "D!", "E*"], cx);
4989
4990        // Drag pinned A from pane A to position 0 in pane B
4991        pane_b.update_in(cx, |pane, window, cx| {
4992            let dragged_tab = DraggedTab {
4993                pane: pane_a.clone(),
4994                item: item_a.boxed_clone(),
4995                ix: 0,
4996                detail: 0,
4997                is_active: true,
4998            };
4999            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5000        });
5001
5002        // E (unpinned) should be closed, leaving 3 pinned items
5003        assert_item_labels(&pane_a, ["B*!"], cx);
5004        assert_item_labels(&pane_b, ["A*!", "C!", "D!"], cx);
5005    }
5006
5007    #[gpui::test]
5008    async fn test_drag_last_pinned_tab_to_same_position_stays_pinned(cx: &mut TestAppContext) {
5009        init_test(cx);
5010        let fs = FakeFs::new(cx.executor());
5011
5012        let project = Project::test(fs, None, cx).await;
5013        let (workspace, cx) =
5014            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5015        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5016
5017        // Add A to pane A and pin it
5018        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5019        pane_a.update_in(cx, |pane, window, cx| {
5020            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5021            pane.pin_tab_at(ix, window, cx);
5022        });
5023        assert_item_labels(&pane_a, ["A*!"], cx);
5024
5025        // Drag pinned A to position 1 (directly to the right) in the same pane
5026        pane_a.update_in(cx, |pane, window, cx| {
5027            let dragged_tab = DraggedTab {
5028                pane: pane_a.clone(),
5029                item: item_a.boxed_clone(),
5030                ix: 0,
5031                detail: 0,
5032                is_active: true,
5033            };
5034            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5035        });
5036
5037        // A should still be pinned and active
5038        assert_item_labels(&pane_a, ["A*!"], cx);
5039    }
5040
5041    #[gpui::test]
5042    async fn test_drag_pinned_tab_beyond_last_pinned_tab_in_same_pane_stays_pinned(
5043        cx: &mut TestAppContext,
5044    ) {
5045        init_test(cx);
5046        let fs = FakeFs::new(cx.executor());
5047
5048        let project = Project::test(fs, None, cx).await;
5049        let (workspace, cx) =
5050            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5051        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5052
5053        // Add A, B to pane A and pin both
5054        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5055        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5056        pane_a.update_in(cx, |pane, window, cx| {
5057            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5058            pane.pin_tab_at(ix, window, cx);
5059
5060            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5061            pane.pin_tab_at(ix, window, cx);
5062        });
5063        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5064
5065        // Drag pinned A right of B in the same pane
5066        pane_a.update_in(cx, |pane, window, cx| {
5067            let dragged_tab = DraggedTab {
5068                pane: pane_a.clone(),
5069                item: item_a.boxed_clone(),
5070                ix: 0,
5071                detail: 0,
5072                is_active: true,
5073            };
5074            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5075        });
5076
5077        // A stays pinned
5078        assert_item_labels(&pane_a, ["B!", "A*!"], cx);
5079    }
5080
5081    #[gpui::test]
5082    async fn test_dragging_pinned_tab_onto_unpinned_tab_reduces_unpinned_tab_count(
5083        cx: &mut TestAppContext,
5084    ) {
5085        init_test(cx);
5086        let fs = FakeFs::new(cx.executor());
5087
5088        let project = Project::test(fs, None, cx).await;
5089        let (workspace, cx) =
5090            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5091        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5092
5093        // Add A, B to pane A and pin A
5094        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5095        add_labeled_item(&pane_a, "B", false, cx);
5096        pane_a.update_in(cx, |pane, window, cx| {
5097            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5098            pane.pin_tab_at(ix, window, cx);
5099        });
5100        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5101
5102        // Drag pinned A on top of B in the same pane, which changes tab order to B, A
5103        pane_a.update_in(cx, |pane, window, cx| {
5104            let dragged_tab = DraggedTab {
5105                pane: pane_a.clone(),
5106                item: item_a.boxed_clone(),
5107                ix: 0,
5108                detail: 0,
5109                is_active: true,
5110            };
5111            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5112        });
5113
5114        // Neither are pinned
5115        assert_item_labels(&pane_a, ["B", "A*"], cx);
5116    }
5117
5118    #[gpui::test]
5119    async fn test_drag_pinned_tab_beyond_unpinned_tab_in_same_pane_becomes_unpinned(
5120        cx: &mut TestAppContext,
5121    ) {
5122        init_test(cx);
5123        let fs = FakeFs::new(cx.executor());
5124
5125        let project = Project::test(fs, None, cx).await;
5126        let (workspace, cx) =
5127            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5128        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5129
5130        // Add A, B to pane A and pin A
5131        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5132        add_labeled_item(&pane_a, "B", false, cx);
5133        pane_a.update_in(cx, |pane, window, cx| {
5134            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5135            pane.pin_tab_at(ix, window, cx);
5136        });
5137        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5138
5139        // Drag pinned A right of B in the same pane
5140        pane_a.update_in(cx, |pane, window, cx| {
5141            let dragged_tab = DraggedTab {
5142                pane: pane_a.clone(),
5143                item: item_a.boxed_clone(),
5144                ix: 0,
5145                detail: 0,
5146                is_active: true,
5147            };
5148            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5149        });
5150
5151        // A becomes unpinned
5152        assert_item_labels(&pane_a, ["B", "A*"], cx);
5153    }
5154
5155    #[gpui::test]
5156    async fn test_drag_unpinned_tab_in_front_of_pinned_tab_in_same_pane_becomes_pinned(
5157        cx: &mut TestAppContext,
5158    ) {
5159        init_test(cx);
5160        let fs = FakeFs::new(cx.executor());
5161
5162        let project = Project::test(fs, None, cx).await;
5163        let (workspace, cx) =
5164            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5165        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5166
5167        // Add A, B to pane A and pin A
5168        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5169        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5170        pane_a.update_in(cx, |pane, window, cx| {
5171            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5172            pane.pin_tab_at(ix, window, cx);
5173        });
5174        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5175
5176        // Drag pinned B left of A in the same pane
5177        pane_a.update_in(cx, |pane, window, cx| {
5178            let dragged_tab = DraggedTab {
5179                pane: pane_a.clone(),
5180                item: item_b.boxed_clone(),
5181                ix: 1,
5182                detail: 0,
5183                is_active: true,
5184            };
5185            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5186        });
5187
5188        // A becomes unpinned
5189        assert_item_labels(&pane_a, ["B*!", "A!"], cx);
5190    }
5191
5192    #[gpui::test]
5193    async fn test_drag_unpinned_tab_to_the_pinned_region_stays_pinned(cx: &mut TestAppContext) {
5194        init_test(cx);
5195        let fs = FakeFs::new(cx.executor());
5196
5197        let project = Project::test(fs, None, cx).await;
5198        let (workspace, cx) =
5199            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5200        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5201
5202        // Add A, B, C to pane A and pin A
5203        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5204        add_labeled_item(&pane_a, "B", false, cx);
5205        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5206        pane_a.update_in(cx, |pane, window, cx| {
5207            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5208            pane.pin_tab_at(ix, window, cx);
5209        });
5210        assert_item_labels(&pane_a, ["A!", "B", "C*"], cx);
5211
5212        // Drag pinned C left of B in the same pane
5213        pane_a.update_in(cx, |pane, window, cx| {
5214            let dragged_tab = DraggedTab {
5215                pane: pane_a.clone(),
5216                item: item_c.boxed_clone(),
5217                ix: 2,
5218                detail: 0,
5219                is_active: true,
5220            };
5221            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5222        });
5223
5224        // A stays pinned, B and C remain unpinned
5225        assert_item_labels(&pane_a, ["A!", "C*", "B"], cx);
5226    }
5227
5228    #[gpui::test]
5229    async fn test_drag_unpinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5230        init_test(cx);
5231        let fs = FakeFs::new(cx.executor());
5232
5233        let project = Project::test(fs, None, cx).await;
5234        let (workspace, cx) =
5235            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5236        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5237
5238        // Add unpinned item A to pane A
5239        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5240        assert_item_labels(&pane_a, ["A*"], cx);
5241
5242        // Create pane B with pinned item B
5243        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5244            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5245        });
5246        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5247        pane_b.update_in(cx, |pane, window, cx| {
5248            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5249            pane.pin_tab_at(ix, window, cx);
5250        });
5251        assert_item_labels(&pane_b, ["B*!"], cx);
5252
5253        // Move A from pane A to pane B's pinned region
5254        pane_b.update_in(cx, |pane, window, cx| {
5255            let dragged_tab = DraggedTab {
5256                pane: pane_a.clone(),
5257                item: item_a.boxed_clone(),
5258                ix: 0,
5259                detail: 0,
5260                is_active: true,
5261            };
5262            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5263        });
5264
5265        // A should become pinned since it was dropped in the pinned region
5266        assert_item_labels(&pane_a, [], cx);
5267        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5268    }
5269
5270    #[gpui::test]
5271    async fn test_drag_unpinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5272        init_test(cx);
5273        let fs = FakeFs::new(cx.executor());
5274
5275        let project = Project::test(fs, None, cx).await;
5276        let (workspace, cx) =
5277            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5278        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5279
5280        // Add unpinned item A to pane A
5281        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5282        assert_item_labels(&pane_a, ["A*"], cx);
5283
5284        // Create pane B with one pinned item B
5285        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5286            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5287        });
5288        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5289        pane_b.update_in(cx, |pane, window, cx| {
5290            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5291            pane.pin_tab_at(ix, window, cx);
5292        });
5293        assert_item_labels(&pane_b, ["B*!"], cx);
5294
5295        // Move A from pane A to pane B's unpinned region
5296        pane_b.update_in(cx, |pane, window, cx| {
5297            let dragged_tab = DraggedTab {
5298                pane: pane_a.clone(),
5299                item: item_a.boxed_clone(),
5300                ix: 0,
5301                detail: 0,
5302                is_active: true,
5303            };
5304            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5305        });
5306
5307        // A should remain unpinned since it was dropped outside the pinned region
5308        assert_item_labels(&pane_a, [], cx);
5309        assert_item_labels(&pane_b, ["B!", "A*"], cx);
5310    }
5311
5312    #[gpui::test]
5313    async fn test_drag_pinned_tab_throughout_entire_range_of_pinned_tabs_both_directions(
5314        cx: &mut TestAppContext,
5315    ) {
5316        init_test(cx);
5317        let fs = FakeFs::new(cx.executor());
5318
5319        let project = Project::test(fs, None, cx).await;
5320        let (workspace, cx) =
5321            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5322        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5323
5324        // Add A, B, C and pin all
5325        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5326        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5327        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5328        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5329
5330        pane_a.update_in(cx, |pane, window, cx| {
5331            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5332            pane.pin_tab_at(ix, window, cx);
5333
5334            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5335            pane.pin_tab_at(ix, window, cx);
5336
5337            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5338            pane.pin_tab_at(ix, window, cx);
5339        });
5340        assert_item_labels(&pane_a, ["A!", "B!", "C*!"], cx);
5341
5342        // Move A to right of B
5343        pane_a.update_in(cx, |pane, window, cx| {
5344            let dragged_tab = DraggedTab {
5345                pane: pane_a.clone(),
5346                item: item_a.boxed_clone(),
5347                ix: 0,
5348                detail: 0,
5349                is_active: true,
5350            };
5351            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5352        });
5353
5354        // A should be after B and all are pinned
5355        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5356
5357        // Move A to right of C
5358        pane_a.update_in(cx, |pane, window, cx| {
5359            let dragged_tab = DraggedTab {
5360                pane: pane_a.clone(),
5361                item: item_a.boxed_clone(),
5362                ix: 1,
5363                detail: 0,
5364                is_active: true,
5365            };
5366            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5367        });
5368
5369        // A should be after C and all are pinned
5370        assert_item_labels(&pane_a, ["B!", "C!", "A*!"], cx);
5371
5372        // Move A to left of C
5373        pane_a.update_in(cx, |pane, window, cx| {
5374            let dragged_tab = DraggedTab {
5375                pane: pane_a.clone(),
5376                item: item_a.boxed_clone(),
5377                ix: 2,
5378                detail: 0,
5379                is_active: true,
5380            };
5381            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5382        });
5383
5384        // A should be before C and all are pinned
5385        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5386
5387        // Move A to left of B
5388        pane_a.update_in(cx, |pane, window, cx| {
5389            let dragged_tab = DraggedTab {
5390                pane: pane_a.clone(),
5391                item: item_a.boxed_clone(),
5392                ix: 1,
5393                detail: 0,
5394                is_active: true,
5395            };
5396            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5397        });
5398
5399        // A should be before B and all are pinned
5400        assert_item_labels(&pane_a, ["A*!", "B!", "C!"], cx);
5401    }
5402
5403    #[gpui::test]
5404    async fn test_drag_first_tab_to_last_position(cx: &mut TestAppContext) {
5405        init_test(cx);
5406        let fs = FakeFs::new(cx.executor());
5407
5408        let project = Project::test(fs, None, cx).await;
5409        let (workspace, cx) =
5410            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5411        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5412
5413        // Add A, B, C
5414        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5415        add_labeled_item(&pane_a, "B", false, cx);
5416        add_labeled_item(&pane_a, "C", false, cx);
5417        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5418
5419        // Move A to the end
5420        pane_a.update_in(cx, |pane, window, cx| {
5421            let dragged_tab = DraggedTab {
5422                pane: pane_a.clone(),
5423                item: item_a.boxed_clone(),
5424                ix: 0,
5425                detail: 0,
5426                is_active: true,
5427            };
5428            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5429        });
5430
5431        // A should be at the end
5432        assert_item_labels(&pane_a, ["B", "C", "A*"], cx);
5433    }
5434
5435    #[gpui::test]
5436    async fn test_drag_last_tab_to_first_position(cx: &mut TestAppContext) {
5437        init_test(cx);
5438        let fs = FakeFs::new(cx.executor());
5439
5440        let project = Project::test(fs, None, cx).await;
5441        let (workspace, cx) =
5442            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5443        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5444
5445        // Add A, B, C
5446        add_labeled_item(&pane_a, "A", false, cx);
5447        add_labeled_item(&pane_a, "B", false, cx);
5448        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5449        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5450
5451        // Move C to the beginning
5452        pane_a.update_in(cx, |pane, window, cx| {
5453            let dragged_tab = DraggedTab {
5454                pane: pane_a.clone(),
5455                item: item_c.boxed_clone(),
5456                ix: 2,
5457                detail: 0,
5458                is_active: true,
5459            };
5460            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5461        });
5462
5463        // C should be at the beginning
5464        assert_item_labels(&pane_a, ["C*", "A", "B"], cx);
5465    }
5466
5467    #[gpui::test]
5468    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
5469        init_test(cx);
5470        let fs = FakeFs::new(cx.executor());
5471
5472        let project = Project::test(fs, None, cx).await;
5473        let (workspace, cx) =
5474            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5475        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5476
5477        // 1. Add with a destination index
5478        //   a. Add before the active item
5479        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5480        pane.update_in(cx, |pane, window, cx| {
5481            pane.add_item(
5482                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5483                false,
5484                false,
5485                Some(0),
5486                window,
5487                cx,
5488            );
5489        });
5490        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5491
5492        //   b. Add after the active item
5493        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5494        pane.update_in(cx, |pane, window, cx| {
5495            pane.add_item(
5496                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5497                false,
5498                false,
5499                Some(2),
5500                window,
5501                cx,
5502            );
5503        });
5504        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5505
5506        //   c. Add at the end of the item list (including off the length)
5507        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5508        pane.update_in(cx, |pane, window, cx| {
5509            pane.add_item(
5510                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5511                false,
5512                false,
5513                Some(5),
5514                window,
5515                cx,
5516            );
5517        });
5518        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5519
5520        // 2. Add without a destination index
5521        //   a. Add with active item at the start of the item list
5522        set_labeled_items(&pane, ["A*", "B", "C"], cx);
5523        pane.update_in(cx, |pane, window, cx| {
5524            pane.add_item(
5525                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5526                false,
5527                false,
5528                None,
5529                window,
5530                cx,
5531            );
5532        });
5533        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
5534
5535        //   b. Add with active item at the end of the item list
5536        set_labeled_items(&pane, ["A", "B", "C*"], cx);
5537        pane.update_in(cx, |pane, window, cx| {
5538            pane.add_item(
5539                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5540                false,
5541                false,
5542                None,
5543                window,
5544                cx,
5545            );
5546        });
5547        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5548    }
5549
5550    #[gpui::test]
5551    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
5552        init_test(cx);
5553        let fs = FakeFs::new(cx.executor());
5554
5555        let project = Project::test(fs, None, cx).await;
5556        let (workspace, cx) =
5557            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5558        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5559
5560        // 1. Add with a destination index
5561        //   1a. Add before the active item
5562        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5563        pane.update_in(cx, |pane, window, cx| {
5564            pane.add_item(d, false, false, Some(0), window, cx);
5565        });
5566        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5567
5568        //   1b. Add after the active item
5569        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5570        pane.update_in(cx, |pane, window, cx| {
5571            pane.add_item(d, false, false, Some(2), window, cx);
5572        });
5573        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5574
5575        //   1c. Add at the end of the item list (including off the length)
5576        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5577        pane.update_in(cx, |pane, window, cx| {
5578            pane.add_item(a, false, false, Some(5), window, cx);
5579        });
5580        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5581
5582        //   1d. Add same item to active index
5583        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5584        pane.update_in(cx, |pane, window, cx| {
5585            pane.add_item(b, false, false, Some(1), window, cx);
5586        });
5587        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5588
5589        //   1e. Add item to index after same item in last position
5590        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5591        pane.update_in(cx, |pane, window, cx| {
5592            pane.add_item(c, false, false, Some(2), window, cx);
5593        });
5594        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5595
5596        // 2. Add without a destination index
5597        //   2a. Add with active item at the start of the item list
5598        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
5599        pane.update_in(cx, |pane, window, cx| {
5600            pane.add_item(d, false, false, None, window, cx);
5601        });
5602        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
5603
5604        //   2b. Add with active item at the end of the item list
5605        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
5606        pane.update_in(cx, |pane, window, cx| {
5607            pane.add_item(a, false, false, None, window, cx);
5608        });
5609        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5610
5611        //   2c. Add active item to active item at end of list
5612        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
5613        pane.update_in(cx, |pane, window, cx| {
5614            pane.add_item(c, false, false, None, window, cx);
5615        });
5616        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5617
5618        //   2d. Add active item to active item at start of list
5619        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
5620        pane.update_in(cx, |pane, window, cx| {
5621            pane.add_item(a, false, false, None, window, cx);
5622        });
5623        assert_item_labels(&pane, ["A*", "B", "C"], cx);
5624    }
5625
5626    #[gpui::test]
5627    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
5628        init_test(cx);
5629        let fs = FakeFs::new(cx.executor());
5630
5631        let project = Project::test(fs, None, cx).await;
5632        let (workspace, cx) =
5633            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5634        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5635
5636        // singleton view
5637        pane.update_in(cx, |pane, window, cx| {
5638            pane.add_item(
5639                Box::new(cx.new(|cx| {
5640                    TestItem::new(cx)
5641                        .with_singleton(true)
5642                        .with_label("buffer 1")
5643                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
5644                })),
5645                false,
5646                false,
5647                None,
5648                window,
5649                cx,
5650            );
5651        });
5652        assert_item_labels(&pane, ["buffer 1*"], cx);
5653
5654        // new singleton view with the same project entry
5655        pane.update_in(cx, |pane, window, cx| {
5656            pane.add_item(
5657                Box::new(cx.new(|cx| {
5658                    TestItem::new(cx)
5659                        .with_singleton(true)
5660                        .with_label("buffer 1")
5661                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5662                })),
5663                false,
5664                false,
5665                None,
5666                window,
5667                cx,
5668            );
5669        });
5670        assert_item_labels(&pane, ["buffer 1*"], cx);
5671
5672        // new singleton view with different project entry
5673        pane.update_in(cx, |pane, window, cx| {
5674            pane.add_item(
5675                Box::new(cx.new(|cx| {
5676                    TestItem::new(cx)
5677                        .with_singleton(true)
5678                        .with_label("buffer 2")
5679                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
5680                })),
5681                false,
5682                false,
5683                None,
5684                window,
5685                cx,
5686            );
5687        });
5688        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
5689
5690        // new multibuffer view with the same project entry
5691        pane.update_in(cx, |pane, window, cx| {
5692            pane.add_item(
5693                Box::new(cx.new(|cx| {
5694                    TestItem::new(cx)
5695                        .with_singleton(false)
5696                        .with_label("multibuffer 1")
5697                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5698                })),
5699                false,
5700                false,
5701                None,
5702                window,
5703                cx,
5704            );
5705        });
5706        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
5707
5708        // another multibuffer view with the same project entry
5709        pane.update_in(cx, |pane, window, cx| {
5710            pane.add_item(
5711                Box::new(cx.new(|cx| {
5712                    TestItem::new(cx)
5713                        .with_singleton(false)
5714                        .with_label("multibuffer 1b")
5715                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5716                })),
5717                false,
5718                false,
5719                None,
5720                window,
5721                cx,
5722            );
5723        });
5724        assert_item_labels(
5725            &pane,
5726            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
5727            cx,
5728        );
5729    }
5730
5731    #[gpui::test]
5732    async fn test_remove_item_ordering_history(cx: &mut TestAppContext) {
5733        init_test(cx);
5734        let fs = FakeFs::new(cx.executor());
5735
5736        let project = Project::test(fs, None, cx).await;
5737        let (workspace, cx) =
5738            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5739        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5740
5741        add_labeled_item(&pane, "A", false, cx);
5742        add_labeled_item(&pane, "B", false, cx);
5743        add_labeled_item(&pane, "C", false, cx);
5744        add_labeled_item(&pane, "D", false, cx);
5745        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5746
5747        pane.update_in(cx, |pane, window, cx| {
5748            pane.activate_item(1, false, false, window, cx)
5749        });
5750        add_labeled_item(&pane, "1", false, cx);
5751        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5752
5753        pane.update_in(cx, |pane, window, cx| {
5754            pane.close_active_item(
5755                &CloseActiveItem {
5756                    save_intent: None,
5757                    close_pinned: false,
5758                },
5759                window,
5760                cx,
5761            )
5762        })
5763        .await
5764        .unwrap();
5765        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
5766
5767        pane.update_in(cx, |pane, window, cx| {
5768            pane.activate_item(3, false, false, window, cx)
5769        });
5770        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5771
5772        pane.update_in(cx, |pane, window, cx| {
5773            pane.close_active_item(
5774                &CloseActiveItem {
5775                    save_intent: None,
5776                    close_pinned: false,
5777                },
5778                window,
5779                cx,
5780            )
5781        })
5782        .await
5783        .unwrap();
5784        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5785
5786        pane.update_in(cx, |pane, window, cx| {
5787            pane.close_active_item(
5788                &CloseActiveItem {
5789                    save_intent: None,
5790                    close_pinned: false,
5791                },
5792                window,
5793                cx,
5794            )
5795        })
5796        .await
5797        .unwrap();
5798        assert_item_labels(&pane, ["A", "C*"], cx);
5799
5800        pane.update_in(cx, |pane, window, cx| {
5801            pane.close_active_item(
5802                &CloseActiveItem {
5803                    save_intent: None,
5804                    close_pinned: false,
5805                },
5806                window,
5807                cx,
5808            )
5809        })
5810        .await
5811        .unwrap();
5812        assert_item_labels(&pane, ["A*"], cx);
5813    }
5814
5815    #[gpui::test]
5816    async fn test_remove_item_ordering_neighbour(cx: &mut TestAppContext) {
5817        init_test(cx);
5818        cx.update_global::<SettingsStore, ()>(|s, cx| {
5819            s.update_user_settings(cx, |s| {
5820                s.tabs.get_or_insert_default().activate_on_close = Some(ActivateOnClose::Neighbour);
5821            });
5822        });
5823        let fs = FakeFs::new(cx.executor());
5824
5825        let project = Project::test(fs, None, cx).await;
5826        let (workspace, cx) =
5827            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5828        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5829
5830        add_labeled_item(&pane, "A", false, cx);
5831        add_labeled_item(&pane, "B", false, cx);
5832        add_labeled_item(&pane, "C", false, cx);
5833        add_labeled_item(&pane, "D", false, cx);
5834        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5835
5836        pane.update_in(cx, |pane, window, cx| {
5837            pane.activate_item(1, false, false, window, cx)
5838        });
5839        add_labeled_item(&pane, "1", false, cx);
5840        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5841
5842        pane.update_in(cx, |pane, window, cx| {
5843            pane.close_active_item(
5844                &CloseActiveItem {
5845                    save_intent: None,
5846                    close_pinned: false,
5847                },
5848                window,
5849                cx,
5850            )
5851        })
5852        .await
5853        .unwrap();
5854        assert_item_labels(&pane, ["A", "B", "C*", "D"], cx);
5855
5856        pane.update_in(cx, |pane, window, cx| {
5857            pane.activate_item(3, false, false, window, cx)
5858        });
5859        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5860
5861        pane.update_in(cx, |pane, window, cx| {
5862            pane.close_active_item(
5863                &CloseActiveItem {
5864                    save_intent: None,
5865                    close_pinned: false,
5866                },
5867                window,
5868                cx,
5869            )
5870        })
5871        .await
5872        .unwrap();
5873        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5874
5875        pane.update_in(cx, |pane, window, cx| {
5876            pane.close_active_item(
5877                &CloseActiveItem {
5878                    save_intent: None,
5879                    close_pinned: false,
5880                },
5881                window,
5882                cx,
5883            )
5884        })
5885        .await
5886        .unwrap();
5887        assert_item_labels(&pane, ["A", "B*"], cx);
5888
5889        pane.update_in(cx, |pane, window, cx| {
5890            pane.close_active_item(
5891                &CloseActiveItem {
5892                    save_intent: None,
5893                    close_pinned: false,
5894                },
5895                window,
5896                cx,
5897            )
5898        })
5899        .await
5900        .unwrap();
5901        assert_item_labels(&pane, ["A*"], cx);
5902    }
5903
5904    #[gpui::test]
5905    async fn test_remove_item_ordering_left_neighbour(cx: &mut TestAppContext) {
5906        init_test(cx);
5907        cx.update_global::<SettingsStore, ()>(|s, cx| {
5908            s.update_user_settings(cx, |s| {
5909                s.tabs.get_or_insert_default().activate_on_close =
5910                    Some(ActivateOnClose::LeftNeighbour);
5911            });
5912        });
5913        let fs = FakeFs::new(cx.executor());
5914
5915        let project = Project::test(fs, None, cx).await;
5916        let (workspace, cx) =
5917            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5918        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5919
5920        add_labeled_item(&pane, "A", false, cx);
5921        add_labeled_item(&pane, "B", false, cx);
5922        add_labeled_item(&pane, "C", false, cx);
5923        add_labeled_item(&pane, "D", false, cx);
5924        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5925
5926        pane.update_in(cx, |pane, window, cx| {
5927            pane.activate_item(1, false, false, window, cx)
5928        });
5929        add_labeled_item(&pane, "1", false, cx);
5930        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5931
5932        pane.update_in(cx, |pane, window, cx| {
5933            pane.close_active_item(
5934                &CloseActiveItem {
5935                    save_intent: None,
5936                    close_pinned: false,
5937                },
5938                window,
5939                cx,
5940            )
5941        })
5942        .await
5943        .unwrap();
5944        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
5945
5946        pane.update_in(cx, |pane, window, cx| {
5947            pane.activate_item(3, false, false, window, cx)
5948        });
5949        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5950
5951        pane.update_in(cx, |pane, window, cx| {
5952            pane.close_active_item(
5953                &CloseActiveItem {
5954                    save_intent: None,
5955                    close_pinned: false,
5956                },
5957                window,
5958                cx,
5959            )
5960        })
5961        .await
5962        .unwrap();
5963        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5964
5965        pane.update_in(cx, |pane, window, cx| {
5966            pane.activate_item(0, false, false, window, cx)
5967        });
5968        assert_item_labels(&pane, ["A*", "B", "C"], cx);
5969
5970        pane.update_in(cx, |pane, window, cx| {
5971            pane.close_active_item(
5972                &CloseActiveItem {
5973                    save_intent: None,
5974                    close_pinned: false,
5975                },
5976                window,
5977                cx,
5978            )
5979        })
5980        .await
5981        .unwrap();
5982        assert_item_labels(&pane, ["B*", "C"], cx);
5983
5984        pane.update_in(cx, |pane, window, cx| {
5985            pane.close_active_item(
5986                &CloseActiveItem {
5987                    save_intent: None,
5988                    close_pinned: false,
5989                },
5990                window,
5991                cx,
5992            )
5993        })
5994        .await
5995        .unwrap();
5996        assert_item_labels(&pane, ["C*"], cx);
5997    }
5998
5999    #[gpui::test]
6000    async fn test_close_inactive_items(cx: &mut TestAppContext) {
6001        init_test(cx);
6002        let fs = FakeFs::new(cx.executor());
6003
6004        let project = Project::test(fs, None, cx).await;
6005        let (workspace, cx) =
6006            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6007        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6008
6009        let item_a = add_labeled_item(&pane, "A", false, cx);
6010        pane.update_in(cx, |pane, window, cx| {
6011            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6012            pane.pin_tab_at(ix, window, cx);
6013        });
6014        assert_item_labels(&pane, ["A*!"], cx);
6015
6016        let item_b = add_labeled_item(&pane, "B", false, cx);
6017        pane.update_in(cx, |pane, window, cx| {
6018            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6019            pane.pin_tab_at(ix, window, cx);
6020        });
6021        assert_item_labels(&pane, ["A!", "B*!"], cx);
6022
6023        add_labeled_item(&pane, "C", false, cx);
6024        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
6025
6026        add_labeled_item(&pane, "D", false, cx);
6027        add_labeled_item(&pane, "E", false, cx);
6028        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
6029
6030        pane.update_in(cx, |pane, window, cx| {
6031            pane.close_other_items(
6032                &CloseOtherItems {
6033                    save_intent: None,
6034                    close_pinned: false,
6035                },
6036                None,
6037                window,
6038                cx,
6039            )
6040        })
6041        .await
6042        .unwrap();
6043        assert_item_labels(&pane, ["A!", "B!", "E*"], cx);
6044    }
6045
6046    #[gpui::test]
6047    async fn test_running_close_inactive_items_via_an_inactive_item(cx: &mut TestAppContext) {
6048        init_test(cx);
6049        let fs = FakeFs::new(cx.executor());
6050
6051        let project = Project::test(fs, None, cx).await;
6052        let (workspace, cx) =
6053            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6054        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6055
6056        add_labeled_item(&pane, "A", false, cx);
6057        assert_item_labels(&pane, ["A*"], cx);
6058
6059        let item_b = add_labeled_item(&pane, "B", false, cx);
6060        assert_item_labels(&pane, ["A", "B*"], cx);
6061
6062        add_labeled_item(&pane, "C", false, cx);
6063        add_labeled_item(&pane, "D", false, cx);
6064        add_labeled_item(&pane, "E", false, cx);
6065        assert_item_labels(&pane, ["A", "B", "C", "D", "E*"], cx);
6066
6067        pane.update_in(cx, |pane, window, cx| {
6068            pane.close_other_items(
6069                &CloseOtherItems {
6070                    save_intent: None,
6071                    close_pinned: false,
6072                },
6073                Some(item_b.item_id()),
6074                window,
6075                cx,
6076            )
6077        })
6078        .await
6079        .unwrap();
6080        assert_item_labels(&pane, ["B*"], cx);
6081    }
6082
6083    #[gpui::test]
6084    async fn test_close_clean_items(cx: &mut TestAppContext) {
6085        init_test(cx);
6086        let fs = FakeFs::new(cx.executor());
6087
6088        let project = Project::test(fs, None, cx).await;
6089        let (workspace, cx) =
6090            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6091        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6092
6093        add_labeled_item(&pane, "A", true, cx);
6094        add_labeled_item(&pane, "B", false, cx);
6095        add_labeled_item(&pane, "C", true, cx);
6096        add_labeled_item(&pane, "D", false, cx);
6097        add_labeled_item(&pane, "E", false, cx);
6098        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
6099
6100        pane.update_in(cx, |pane, window, cx| {
6101            pane.close_clean_items(
6102                &CloseCleanItems {
6103                    close_pinned: false,
6104                },
6105                window,
6106                cx,
6107            )
6108        })
6109        .await
6110        .unwrap();
6111        assert_item_labels(&pane, ["A^", "C*^"], cx);
6112    }
6113
6114    #[gpui::test]
6115    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
6116        init_test(cx);
6117        let fs = FakeFs::new(cx.executor());
6118
6119        let project = Project::test(fs, None, cx).await;
6120        let (workspace, cx) =
6121            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6122        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6123
6124        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6125
6126        pane.update_in(cx, |pane, window, cx| {
6127            pane.close_items_to_the_left_by_id(
6128                None,
6129                &CloseItemsToTheLeft {
6130                    close_pinned: false,
6131                },
6132                window,
6133                cx,
6134            )
6135        })
6136        .await
6137        .unwrap();
6138        assert_item_labels(&pane, ["C*", "D", "E"], cx);
6139    }
6140
6141    #[gpui::test]
6142    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
6143        init_test(cx);
6144        let fs = FakeFs::new(cx.executor());
6145
6146        let project = Project::test(fs, None, cx).await;
6147        let (workspace, cx) =
6148            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6149        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6150
6151        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6152
6153        pane.update_in(cx, |pane, window, cx| {
6154            pane.close_items_to_the_right_by_id(
6155                None,
6156                &CloseItemsToTheRight {
6157                    close_pinned: false,
6158                },
6159                window,
6160                cx,
6161            )
6162        })
6163        .await
6164        .unwrap();
6165        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6166    }
6167
6168    #[gpui::test]
6169    async fn test_close_all_items(cx: &mut TestAppContext) {
6170        init_test(cx);
6171        let fs = FakeFs::new(cx.executor());
6172
6173        let project = Project::test(fs, None, cx).await;
6174        let (workspace, cx) =
6175            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6176        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6177
6178        let item_a = add_labeled_item(&pane, "A", false, cx);
6179        add_labeled_item(&pane, "B", false, cx);
6180        add_labeled_item(&pane, "C", false, cx);
6181        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6182
6183        pane.update_in(cx, |pane, window, cx| {
6184            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6185            pane.pin_tab_at(ix, window, cx);
6186            pane.close_all_items(
6187                &CloseAllItems {
6188                    save_intent: None,
6189                    close_pinned: false,
6190                },
6191                window,
6192                cx,
6193            )
6194        })
6195        .await
6196        .unwrap();
6197        assert_item_labels(&pane, ["A*!"], cx);
6198
6199        pane.update_in(cx, |pane, window, cx| {
6200            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6201            pane.unpin_tab_at(ix, window, cx);
6202            pane.close_all_items(
6203                &CloseAllItems {
6204                    save_intent: None,
6205                    close_pinned: false,
6206                },
6207                window,
6208                cx,
6209            )
6210        })
6211        .await
6212        .unwrap();
6213
6214        assert_item_labels(&pane, [], cx);
6215
6216        add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6217            item.project_items
6218                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6219        });
6220        add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6221            item.project_items
6222                .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6223        });
6224        add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6225            item.project_items
6226                .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6227        });
6228        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6229
6230        let save = pane.update_in(cx, |pane, window, cx| {
6231            pane.close_all_items(
6232                &CloseAllItems {
6233                    save_intent: None,
6234                    close_pinned: false,
6235                },
6236                window,
6237                cx,
6238            )
6239        });
6240
6241        cx.executor().run_until_parked();
6242        cx.simulate_prompt_answer("Save all");
6243        save.await.unwrap();
6244        assert_item_labels(&pane, [], cx);
6245
6246        add_labeled_item(&pane, "A", true, cx);
6247        add_labeled_item(&pane, "B", true, cx);
6248        add_labeled_item(&pane, "C", true, cx);
6249        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6250        let save = pane.update_in(cx, |pane, window, cx| {
6251            pane.close_all_items(
6252                &CloseAllItems {
6253                    save_intent: None,
6254                    close_pinned: false,
6255                },
6256                window,
6257                cx,
6258            )
6259        });
6260
6261        cx.executor().run_until_parked();
6262        cx.simulate_prompt_answer("Discard all");
6263        save.await.unwrap();
6264        assert_item_labels(&pane, [], cx);
6265    }
6266
6267    #[gpui::test]
6268    async fn test_close_with_save_intent(cx: &mut TestAppContext) {
6269        init_test(cx);
6270        let fs = FakeFs::new(cx.executor());
6271
6272        let project = Project::test(fs, None, cx).await;
6273        let (workspace, cx) =
6274            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6275        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6276
6277        let a = cx.update(|_, cx| TestProjectItem::new_dirty(1, "A.txt", cx));
6278        let b = cx.update(|_, cx| TestProjectItem::new_dirty(1, "B.txt", cx));
6279        let c = cx.update(|_, cx| TestProjectItem::new_dirty(1, "C.txt", cx));
6280
6281        add_labeled_item(&pane, "AB", true, cx).update(cx, |item, _| {
6282            item.project_items.push(a.clone());
6283            item.project_items.push(b.clone());
6284        });
6285        add_labeled_item(&pane, "C", true, cx)
6286            .update(cx, |item, _| item.project_items.push(c.clone()));
6287        assert_item_labels(&pane, ["AB^", "C*^"], cx);
6288
6289        pane.update_in(cx, |pane, window, cx| {
6290            pane.close_all_items(
6291                &CloseAllItems {
6292                    save_intent: Some(SaveIntent::Save),
6293                    close_pinned: false,
6294                },
6295                window,
6296                cx,
6297            )
6298        })
6299        .await
6300        .unwrap();
6301
6302        assert_item_labels(&pane, [], cx);
6303        cx.update(|_, cx| {
6304            assert!(!a.read(cx).is_dirty);
6305            assert!(!b.read(cx).is_dirty);
6306            assert!(!c.read(cx).is_dirty);
6307        });
6308    }
6309
6310    #[gpui::test]
6311    async fn test_close_all_items_including_pinned(cx: &mut TestAppContext) {
6312        init_test(cx);
6313        let fs = FakeFs::new(cx.executor());
6314
6315        let project = Project::test(fs, None, cx).await;
6316        let (workspace, cx) =
6317            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6318        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6319
6320        let item_a = add_labeled_item(&pane, "A", false, cx);
6321        add_labeled_item(&pane, "B", false, cx);
6322        add_labeled_item(&pane, "C", false, cx);
6323        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6324
6325        pane.update_in(cx, |pane, window, cx| {
6326            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6327            pane.pin_tab_at(ix, window, cx);
6328            pane.close_all_items(
6329                &CloseAllItems {
6330                    save_intent: None,
6331                    close_pinned: true,
6332                },
6333                window,
6334                cx,
6335            )
6336        })
6337        .await
6338        .unwrap();
6339        assert_item_labels(&pane, [], cx);
6340    }
6341
6342    #[gpui::test]
6343    async fn test_close_pinned_tab_with_non_pinned_in_same_pane(cx: &mut TestAppContext) {
6344        init_test(cx);
6345        let fs = FakeFs::new(cx.executor());
6346        let project = Project::test(fs, None, cx).await;
6347        let (workspace, cx) =
6348            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6349
6350        // Non-pinned tabs in same pane
6351        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6352        add_labeled_item(&pane, "A", false, cx);
6353        add_labeled_item(&pane, "B", false, cx);
6354        add_labeled_item(&pane, "C", false, cx);
6355        pane.update_in(cx, |pane, window, cx| {
6356            pane.pin_tab_at(0, window, cx);
6357        });
6358        set_labeled_items(&pane, ["A*", "B", "C"], cx);
6359        pane.update_in(cx, |pane, window, cx| {
6360            pane.close_active_item(
6361                &CloseActiveItem {
6362                    save_intent: None,
6363                    close_pinned: false,
6364                },
6365                window,
6366                cx,
6367            )
6368            .unwrap();
6369        });
6370        // Non-pinned tab should be active
6371        assert_item_labels(&pane, ["A!", "B*", "C"], cx);
6372    }
6373
6374    #[gpui::test]
6375    async fn test_close_pinned_tab_with_non_pinned_in_different_pane(cx: &mut TestAppContext) {
6376        init_test(cx);
6377        let fs = FakeFs::new(cx.executor());
6378        let project = Project::test(fs, None, cx).await;
6379        let (workspace, cx) =
6380            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6381
6382        // No non-pinned tabs in same pane, non-pinned tabs in another pane
6383        let pane1 = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6384        let pane2 = workspace.update_in(cx, |workspace, window, cx| {
6385            workspace.split_pane(pane1.clone(), SplitDirection::Right, window, cx)
6386        });
6387        add_labeled_item(&pane1, "A", false, cx);
6388        pane1.update_in(cx, |pane, window, cx| {
6389            pane.pin_tab_at(0, window, cx);
6390        });
6391        set_labeled_items(&pane1, ["A*"], cx);
6392        add_labeled_item(&pane2, "B", false, cx);
6393        set_labeled_items(&pane2, ["B"], cx);
6394        pane1.update_in(cx, |pane, window, cx| {
6395            pane.close_active_item(
6396                &CloseActiveItem {
6397                    save_intent: None,
6398                    close_pinned: false,
6399                },
6400                window,
6401                cx,
6402            )
6403            .unwrap();
6404        });
6405        //  Non-pinned tab of other pane should be active
6406        assert_item_labels(&pane2, ["B*"], cx);
6407    }
6408
6409    #[gpui::test]
6410    async fn ensure_item_closing_actions_do_not_panic_when_no_items_exist(cx: &mut TestAppContext) {
6411        init_test(cx);
6412        let fs = FakeFs::new(cx.executor());
6413        let project = Project::test(fs, None, cx).await;
6414        let (workspace, cx) =
6415            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6416
6417        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6418        assert_item_labels(&pane, [], cx);
6419
6420        pane.update_in(cx, |pane, window, cx| {
6421            pane.close_active_item(
6422                &CloseActiveItem {
6423                    save_intent: None,
6424                    close_pinned: false,
6425                },
6426                window,
6427                cx,
6428            )
6429        })
6430        .await
6431        .unwrap();
6432
6433        pane.update_in(cx, |pane, window, cx| {
6434            pane.close_other_items(
6435                &CloseOtherItems {
6436                    save_intent: None,
6437                    close_pinned: false,
6438                },
6439                None,
6440                window,
6441                cx,
6442            )
6443        })
6444        .await
6445        .unwrap();
6446
6447        pane.update_in(cx, |pane, window, cx| {
6448            pane.close_all_items(
6449                &CloseAllItems {
6450                    save_intent: None,
6451                    close_pinned: false,
6452                },
6453                window,
6454                cx,
6455            )
6456        })
6457        .await
6458        .unwrap();
6459
6460        pane.update_in(cx, |pane, window, cx| {
6461            pane.close_clean_items(
6462                &CloseCleanItems {
6463                    close_pinned: false,
6464                },
6465                window,
6466                cx,
6467            )
6468        })
6469        .await
6470        .unwrap();
6471
6472        pane.update_in(cx, |pane, window, cx| {
6473            pane.close_items_to_the_right_by_id(
6474                None,
6475                &CloseItemsToTheRight {
6476                    close_pinned: false,
6477                },
6478                window,
6479                cx,
6480            )
6481        })
6482        .await
6483        .unwrap();
6484
6485        pane.update_in(cx, |pane, window, cx| {
6486            pane.close_items_to_the_left_by_id(
6487                None,
6488                &CloseItemsToTheLeft {
6489                    close_pinned: false,
6490                },
6491                window,
6492                cx,
6493            )
6494        })
6495        .await
6496        .unwrap();
6497    }
6498
6499    #[gpui::test]
6500    async fn test_item_swapping_actions(cx: &mut TestAppContext) {
6501        init_test(cx);
6502        let fs = FakeFs::new(cx.executor());
6503        let project = Project::test(fs, None, cx).await;
6504        let (workspace, cx) =
6505            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6506
6507        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6508        assert_item_labels(&pane, [], cx);
6509
6510        // Test that these actions do not panic
6511        pane.update_in(cx, |pane, window, cx| {
6512            pane.swap_item_right(&Default::default(), window, cx);
6513        });
6514
6515        pane.update_in(cx, |pane, window, cx| {
6516            pane.swap_item_left(&Default::default(), window, cx);
6517        });
6518
6519        add_labeled_item(&pane, "A", false, cx);
6520        add_labeled_item(&pane, "B", false, cx);
6521        add_labeled_item(&pane, "C", false, cx);
6522        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6523
6524        pane.update_in(cx, |pane, window, cx| {
6525            pane.swap_item_right(&Default::default(), window, cx);
6526        });
6527        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6528
6529        pane.update_in(cx, |pane, window, cx| {
6530            pane.swap_item_left(&Default::default(), window, cx);
6531        });
6532        assert_item_labels(&pane, ["A", "C*", "B"], cx);
6533
6534        pane.update_in(cx, |pane, window, cx| {
6535            pane.swap_item_left(&Default::default(), window, cx);
6536        });
6537        assert_item_labels(&pane, ["C*", "A", "B"], cx);
6538
6539        pane.update_in(cx, |pane, window, cx| {
6540            pane.swap_item_left(&Default::default(), window, cx);
6541        });
6542        assert_item_labels(&pane, ["C*", "A", "B"], cx);
6543
6544        pane.update_in(cx, |pane, window, cx| {
6545            pane.swap_item_right(&Default::default(), window, cx);
6546        });
6547        assert_item_labels(&pane, ["A", "C*", "B"], cx);
6548    }
6549
6550    fn init_test(cx: &mut TestAppContext) {
6551        cx.update(|cx| {
6552            let settings_store = SettingsStore::test(cx);
6553            cx.set_global(settings_store);
6554            theme::init(LoadThemes::JustBase, cx);
6555            crate::init_settings(cx);
6556            Project::init_settings(cx);
6557        });
6558    }
6559
6560    fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
6561        cx.update_global(|store: &mut SettingsStore, cx| {
6562            store.update_user_settings(cx, |settings| {
6563                settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
6564            });
6565        });
6566    }
6567
6568    fn add_labeled_item(
6569        pane: &Entity<Pane>,
6570        label: &str,
6571        is_dirty: bool,
6572        cx: &mut VisualTestContext,
6573    ) -> Box<Entity<TestItem>> {
6574        pane.update_in(cx, |pane, window, cx| {
6575            let labeled_item =
6576                Box::new(cx.new(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)));
6577            pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6578            labeled_item
6579        })
6580    }
6581
6582    fn set_labeled_items<const COUNT: usize>(
6583        pane: &Entity<Pane>,
6584        labels: [&str; COUNT],
6585        cx: &mut VisualTestContext,
6586    ) -> [Box<Entity<TestItem>>; COUNT] {
6587        pane.update_in(cx, |pane, window, cx| {
6588            pane.items.clear();
6589            let mut active_item_index = 0;
6590
6591            let mut index = 0;
6592            let items = labels.map(|mut label| {
6593                if label.ends_with('*') {
6594                    label = label.trim_end_matches('*');
6595                    active_item_index = index;
6596                }
6597
6598                let labeled_item = Box::new(cx.new(|cx| TestItem::new(cx).with_label(label)));
6599                pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6600                index += 1;
6601                labeled_item
6602            });
6603
6604            pane.activate_item(active_item_index, false, false, window, cx);
6605
6606            items
6607        })
6608    }
6609
6610    // Assert the item label, with the active item label suffixed with a '*'
6611    #[track_caller]
6612    fn assert_item_labels<const COUNT: usize>(
6613        pane: &Entity<Pane>,
6614        expected_states: [&str; COUNT],
6615        cx: &mut VisualTestContext,
6616    ) {
6617        let actual_states = pane.update(cx, |pane, cx| {
6618            pane.items
6619                .iter()
6620                .enumerate()
6621                .map(|(ix, item)| {
6622                    let mut state = item
6623                        .to_any()
6624                        .downcast::<TestItem>()
6625                        .unwrap()
6626                        .read(cx)
6627                        .label
6628                        .clone();
6629                    if ix == pane.active_item_index {
6630                        state.push('*');
6631                    }
6632                    if item.is_dirty(cx) {
6633                        state.push('^');
6634                    }
6635                    if pane.is_tab_pinned(ix) {
6636                        state.push('!');
6637                    }
6638                    state
6639                })
6640                .collect::<Vec<_>>()
6641        });
6642        assert_eq!(
6643            actual_states, expected_states,
6644            "pane items do not match expectation"
6645        );
6646    }
6647}