pane.rs

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