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.pinned_tab_count > 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        let from_ix = dragged_tab.ix;
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 moved_right = ix > from_ix;
3066                            let ix = if moved_right { ix - 1 } else { ix };
3067                            let is_pinned_in_to_pane = this.is_tab_pinned(ix);
3068
3069                            if !was_pinned_in_from_pane && is_pinned_in_to_pane {
3070                                this.pinned_tab_count += 1;
3071                            } else if was_pinned_in_from_pane && !is_pinned_in_to_pane {
3072                                this.pinned_tab_count -= 1;
3073                            }
3074                        } else if this.items.len() >= to_pane_old_length {
3075                            let is_pinned_in_to_pane = this.is_tab_pinned(ix);
3076                            let item_created_pane = to_pane_old_length == 0;
3077                            let is_first_position = ix == 0;
3078                            let was_dropped_at_beginning = item_created_pane || is_first_position;
3079                            let should_remain_pinned = is_pinned_in_to_pane
3080                                || (was_pinned_in_from_pane && was_dropped_at_beginning);
3081
3082                            if should_remain_pinned {
3083                                this.pinned_tab_count += 1;
3084                            }
3085                        }
3086                    });
3087                });
3088            })
3089            .log_err();
3090    }
3091
3092    fn handle_dragged_selection_drop(
3093        &mut self,
3094        dragged_selection: &DraggedSelection,
3095        dragged_onto: Option<usize>,
3096        window: &mut Window,
3097        cx: &mut Context<Self>,
3098    ) {
3099        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
3100            if let ControlFlow::Break(()) = custom_drop_handle(self, dragged_selection, window, cx)
3101            {
3102                return;
3103            }
3104        }
3105        self.handle_project_entry_drop(
3106            &dragged_selection.active_selection.entry_id,
3107            dragged_onto,
3108            window,
3109            cx,
3110        );
3111    }
3112
3113    fn handle_project_entry_drop(
3114        &mut self,
3115        project_entry_id: &ProjectEntryId,
3116        target: Option<usize>,
3117        window: &mut Window,
3118        cx: &mut Context<Self>,
3119    ) {
3120        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
3121            if let ControlFlow::Break(()) = custom_drop_handle(self, project_entry_id, window, cx) {
3122                return;
3123            }
3124        }
3125        let mut to_pane = cx.entity().clone();
3126        let split_direction = self.drag_split_direction;
3127        let project_entry_id = *project_entry_id;
3128        self.workspace
3129            .update(cx, |_, cx| {
3130                cx.defer_in(window, move |workspace, window, cx| {
3131                    if let Some(project_path) = workspace
3132                        .project()
3133                        .read(cx)
3134                        .path_for_entry(project_entry_id, cx)
3135                    {
3136                        let load_path_task = workspace.load_path(project_path.clone(), window, cx);
3137                        cx.spawn_in(window, async move |workspace, cx| {
3138                            if let Some((project_entry_id, build_item)) =
3139                                load_path_task.await.notify_async_err(cx)
3140                            {
3141                                let (to_pane, new_item_handle) = workspace
3142                                    .update_in(cx, |workspace, window, cx| {
3143                                        if let Some(split_direction) = split_direction {
3144                                            to_pane = workspace.split_pane(
3145                                                to_pane,
3146                                                split_direction,
3147                                                window,
3148                                                cx,
3149                                            );
3150                                        }
3151                                        let new_item_handle = to_pane.update(cx, |pane, cx| {
3152                                            pane.open_item(
3153                                                project_entry_id,
3154                                                project_path,
3155                                                true,
3156                                                false,
3157                                                true,
3158                                                target,
3159                                                window,
3160                                                cx,
3161                                                build_item,
3162                                            )
3163                                        });
3164                                        (to_pane, new_item_handle)
3165                                    })
3166                                    .log_err()?;
3167                                to_pane
3168                                    .update_in(cx, |this, window, cx| {
3169                                        let Some(index) = this.index_for_item(&*new_item_handle)
3170                                        else {
3171                                            return;
3172                                        };
3173
3174                                        if target.map_or(false, |target| this.is_tab_pinned(target))
3175                                        {
3176                                            this.pin_tab_at(index, window, cx);
3177                                        }
3178                                    })
3179                                    .ok()?
3180                            }
3181                            Some(())
3182                        })
3183                        .detach();
3184                    };
3185                });
3186            })
3187            .log_err();
3188    }
3189
3190    fn handle_external_paths_drop(
3191        &mut self,
3192        paths: &ExternalPaths,
3193        window: &mut Window,
3194        cx: &mut Context<Self>,
3195    ) {
3196        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
3197            if let ControlFlow::Break(()) = custom_drop_handle(self, paths, window, cx) {
3198                return;
3199            }
3200        }
3201        let mut to_pane = cx.entity().clone();
3202        let mut split_direction = self.drag_split_direction;
3203        let paths = paths.paths().to_vec();
3204        let is_remote = self
3205            .workspace
3206            .update(cx, |workspace, cx| {
3207                if workspace.project().read(cx).is_via_collab() {
3208                    workspace.show_error(
3209                        &anyhow::anyhow!("Cannot drop files on a remote project"),
3210                        cx,
3211                    );
3212                    true
3213                } else {
3214                    false
3215                }
3216            })
3217            .unwrap_or(true);
3218        if is_remote {
3219            return;
3220        }
3221
3222        self.workspace
3223            .update(cx, |workspace, cx| {
3224                let fs = Arc::clone(workspace.project().read(cx).fs());
3225                cx.spawn_in(window, async move |workspace, cx| {
3226                    let mut is_file_checks = FuturesUnordered::new();
3227                    for path in &paths {
3228                        is_file_checks.push(fs.is_file(path))
3229                    }
3230                    let mut has_files_to_open = false;
3231                    while let Some(is_file) = is_file_checks.next().await {
3232                        if is_file {
3233                            has_files_to_open = true;
3234                            break;
3235                        }
3236                    }
3237                    drop(is_file_checks);
3238                    if !has_files_to_open {
3239                        split_direction = None;
3240                    }
3241
3242                    if let Ok((open_task, to_pane)) =
3243                        workspace.update_in(cx, |workspace, window, cx| {
3244                            if let Some(split_direction) = split_direction {
3245                                to_pane =
3246                                    workspace.split_pane(to_pane, split_direction, window, cx);
3247                            }
3248                            (
3249                                workspace.open_paths(
3250                                    paths,
3251                                    OpenOptions {
3252                                        visible: Some(OpenVisible::OnlyDirectories),
3253                                        ..Default::default()
3254                                    },
3255                                    Some(to_pane.downgrade()),
3256                                    window,
3257                                    cx,
3258                                ),
3259                                to_pane,
3260                            )
3261                        })
3262                    {
3263                        let opened_items: Vec<_> = open_task.await;
3264                        _ = workspace.update_in(cx, |workspace, window, cx| {
3265                            for item in opened_items.into_iter().flatten() {
3266                                if let Err(e) = item {
3267                                    workspace.show_error(&e, cx);
3268                                }
3269                            }
3270                            if to_pane.read(cx).items_len() == 0 {
3271                                workspace.remove_pane(to_pane, None, window, cx);
3272                            }
3273                        });
3274                    }
3275                })
3276                .detach();
3277            })
3278            .log_err();
3279    }
3280
3281    pub fn display_nav_history_buttons(&mut self, display: Option<bool>) {
3282        self.display_nav_history_buttons = display;
3283    }
3284
3285    fn pinned_item_ids(&self) -> Vec<EntityId> {
3286        self.items
3287            .iter()
3288            .enumerate()
3289            .filter_map(|(index, item)| {
3290                if self.is_tab_pinned(index) {
3291                    return Some(item.item_id());
3292                }
3293
3294                None
3295            })
3296            .collect()
3297    }
3298
3299    fn clean_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3300        self.items()
3301            .filter_map(|item| {
3302                if !item.is_dirty(cx) {
3303                    return Some(item.item_id());
3304                }
3305
3306                None
3307            })
3308            .collect()
3309    }
3310
3311    fn to_the_side_item_ids(&self, item_id: EntityId, side: Side) -> Vec<EntityId> {
3312        match side {
3313            Side::Left => self
3314                .items()
3315                .take_while(|item| item.item_id() != item_id)
3316                .map(|item| item.item_id())
3317                .collect(),
3318            Side::Right => self
3319                .items()
3320                .rev()
3321                .take_while(|item| item.item_id() != item_id)
3322                .map(|item| item.item_id())
3323                .collect(),
3324        }
3325    }
3326
3327    pub fn drag_split_direction(&self) -> Option<SplitDirection> {
3328        self.drag_split_direction
3329    }
3330
3331    pub fn set_zoom_out_on_close(&mut self, zoom_out_on_close: bool) {
3332        self.zoom_out_on_close = zoom_out_on_close;
3333    }
3334}
3335
3336fn default_render_tab_bar_buttons(
3337    pane: &mut Pane,
3338    window: &mut Window,
3339    cx: &mut Context<Pane>,
3340) -> (Option<AnyElement>, Option<AnyElement>) {
3341    if !pane.has_focus(window, cx) && !pane.context_menu_focused(window, cx) {
3342        return (None, None);
3343    }
3344    // Ideally we would return a vec of elements here to pass directly to the [TabBar]'s
3345    // `end_slot`, but due to needing a view here that isn't possible.
3346    let right_children = h_flex()
3347        // Instead we need to replicate the spacing from the [TabBar]'s `end_slot` here.
3348        .gap(DynamicSpacing::Base04.rems(cx))
3349        .child(
3350            PopoverMenu::new("pane-tab-bar-popover-menu")
3351                .trigger_with_tooltip(
3352                    IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
3353                    Tooltip::text("New..."),
3354                )
3355                .anchor(Corner::TopRight)
3356                .with_handle(pane.new_item_context_menu_handle.clone())
3357                .menu(move |window, cx| {
3358                    Some(ContextMenu::build(window, cx, |menu, _, _| {
3359                        menu.action("New File", NewFile.boxed_clone())
3360                            .action("Open File", ToggleFileFinder::default().boxed_clone())
3361                            .separator()
3362                            .action(
3363                                "Search Project",
3364                                DeploySearch {
3365                                    replace_enabled: false,
3366                                    included_files: None,
3367                                    excluded_files: None,
3368                                }
3369                                .boxed_clone(),
3370                            )
3371                            .action("Search Symbols", ToggleProjectSymbols.boxed_clone())
3372                            .separator()
3373                            .action("New Terminal", NewTerminal.boxed_clone())
3374                    }))
3375                }),
3376        )
3377        .child(
3378            PopoverMenu::new("pane-tab-bar-split")
3379                .trigger_with_tooltip(
3380                    IconButton::new("split", IconName::Split).icon_size(IconSize::Small),
3381                    Tooltip::text("Split Pane"),
3382                )
3383                .anchor(Corner::TopRight)
3384                .with_handle(pane.split_item_context_menu_handle.clone())
3385                .menu(move |window, cx| {
3386                    ContextMenu::build(window, cx, |menu, _, _| {
3387                        menu.action("Split Right", SplitRight.boxed_clone())
3388                            .action("Split Left", SplitLeft.boxed_clone())
3389                            .action("Split Up", SplitUp.boxed_clone())
3390                            .action("Split Down", SplitDown.boxed_clone())
3391                    })
3392                    .into()
3393                }),
3394        )
3395        .child({
3396            let zoomed = pane.is_zoomed();
3397            IconButton::new("toggle_zoom", IconName::Maximize)
3398                .icon_size(IconSize::Small)
3399                .toggle_state(zoomed)
3400                .selected_icon(IconName::Minimize)
3401                .on_click(cx.listener(|pane, _, window, cx| {
3402                    pane.toggle_zoom(&crate::ToggleZoom, window, cx);
3403                }))
3404                .tooltip(move |window, cx| {
3405                    Tooltip::for_action(
3406                        if zoomed { "Zoom Out" } else { "Zoom In" },
3407                        &ToggleZoom,
3408                        window,
3409                        cx,
3410                    )
3411                })
3412        })
3413        .into_any_element()
3414        .into();
3415    (None, right_children)
3416}
3417
3418impl Focusable for Pane {
3419    fn focus_handle(&self, _cx: &App) -> FocusHandle {
3420        self.focus_handle.clone()
3421    }
3422}
3423
3424impl Render for Pane {
3425    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3426        let mut key_context = KeyContext::new_with_defaults();
3427        key_context.add("Pane");
3428        if self.active_item().is_none() {
3429            key_context.add("EmptyPane");
3430        }
3431
3432        let should_display_tab_bar = self.should_display_tab_bar.clone();
3433        let display_tab_bar = should_display_tab_bar(window, cx);
3434        let Some(project) = self.project.upgrade() else {
3435            return div().track_focus(&self.focus_handle(cx));
3436        };
3437        let is_local = project.read(cx).is_local();
3438
3439        v_flex()
3440            .key_context(key_context)
3441            .track_focus(&self.focus_handle(cx))
3442            .size_full()
3443            .flex_none()
3444            .overflow_hidden()
3445            .on_action(cx.listener(|pane, _: &AlternateFile, window, cx| {
3446                pane.alternate_file(window, cx);
3447            }))
3448            .on_action(
3449                cx.listener(|pane, _: &SplitLeft, _, cx| pane.split(SplitDirection::Left, cx)),
3450            )
3451            .on_action(cx.listener(|pane, _: &SplitUp, _, cx| pane.split(SplitDirection::Up, cx)))
3452            .on_action(cx.listener(|pane, _: &SplitHorizontal, _, cx| {
3453                pane.split(SplitDirection::horizontal(cx), cx)
3454            }))
3455            .on_action(cx.listener(|pane, _: &SplitVertical, _, cx| {
3456                pane.split(SplitDirection::vertical(cx), cx)
3457            }))
3458            .on_action(
3459                cx.listener(|pane, _: &SplitRight, _, cx| pane.split(SplitDirection::Right, cx)),
3460            )
3461            .on_action(
3462                cx.listener(|pane, _: &SplitDown, _, cx| pane.split(SplitDirection::Down, cx)),
3463            )
3464            .on_action(
3465                cx.listener(|pane, _: &GoBack, window, cx| pane.navigate_backward(window, cx)),
3466            )
3467            .on_action(
3468                cx.listener(|pane, _: &GoForward, window, cx| pane.navigate_forward(window, cx)),
3469            )
3470            .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
3471                cx.emit(Event::JoinIntoNext);
3472            }))
3473            .on_action(cx.listener(|_, _: &JoinAll, _, cx| {
3474                cx.emit(Event::JoinAll);
3475            }))
3476            .on_action(cx.listener(Pane::toggle_zoom))
3477            .on_action(
3478                cx.listener(|pane: &mut Pane, action: &ActivateItem, window, cx| {
3479                    pane.activate_item(
3480                        action.0.min(pane.items.len().saturating_sub(1)),
3481                        true,
3482                        true,
3483                        window,
3484                        cx,
3485                    );
3486                }),
3487            )
3488            .on_action(
3489                cx.listener(|pane: &mut Pane, _: &ActivateLastItem, window, cx| {
3490                    pane.activate_item(pane.items.len().saturating_sub(1), true, true, window, cx);
3491                }),
3492            )
3493            .on_action(
3494                cx.listener(|pane: &mut Pane, _: &ActivatePreviousItem, window, cx| {
3495                    pane.activate_prev_item(true, window, cx);
3496                }),
3497            )
3498            .on_action(
3499                cx.listener(|pane: &mut Pane, _: &ActivateNextItem, window, cx| {
3500                    pane.activate_next_item(true, window, cx);
3501                }),
3502            )
3503            .on_action(
3504                cx.listener(|pane, _: &SwapItemLeft, window, cx| pane.swap_item_left(window, cx)),
3505            )
3506            .on_action(
3507                cx.listener(|pane, _: &SwapItemRight, window, cx| pane.swap_item_right(window, cx)),
3508            )
3509            .on_action(cx.listener(|pane, action, window, cx| {
3510                pane.toggle_pin_tab(action, window, cx);
3511            }))
3512            .on_action(cx.listener(|pane, action, window, cx| {
3513                pane.unpin_all_tabs(action, window, cx);
3514            }))
3515            .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
3516                this.on_action(cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, _, cx| {
3517                    if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
3518                        if pane.is_active_preview_item(active_item_id) {
3519                            pane.set_preview_item_id(None, cx);
3520                        } else {
3521                            pane.set_preview_item_id(Some(active_item_id), cx);
3522                        }
3523                    }
3524                }))
3525            })
3526            .on_action(
3527                cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
3528                    pane.close_active_item(action, window, cx)
3529                        .detach_and_log_err(cx)
3530                }),
3531            )
3532            .on_action(
3533                cx.listener(|pane: &mut Self, action: &CloseOtherItems, window, cx| {
3534                    pane.close_other_items(action, None, window, cx)
3535                        .detach_and_log_err(cx);
3536                }),
3537            )
3538            .on_action(
3539                cx.listener(|pane: &mut Self, action: &CloseCleanItems, window, cx| {
3540                    pane.close_clean_items(action, window, cx)
3541                        .detach_and_log_err(cx)
3542                }),
3543            )
3544            .on_action(cx.listener(
3545                |pane: &mut Self, action: &CloseItemsToTheLeft, window, cx| {
3546                    pane.close_items_to_the_left_by_id(None, action, window, cx)
3547                        .detach_and_log_err(cx)
3548                },
3549            ))
3550            .on_action(cx.listener(
3551                |pane: &mut Self, action: &CloseItemsToTheRight, window, cx| {
3552                    pane.close_items_to_the_right_by_id(None, action, window, cx)
3553                        .detach_and_log_err(cx)
3554                },
3555            ))
3556            .on_action(
3557                cx.listener(|pane: &mut Self, action: &CloseAllItems, window, cx| {
3558                    pane.close_all_items(action, window, cx)
3559                        .detach_and_log_err(cx)
3560                }),
3561            )
3562            .on_action(
3563                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, _, cx| {
3564                    let entry_id = action
3565                        .entry_id
3566                        .map(ProjectEntryId::from_proto)
3567                        .or_else(|| pane.active_item()?.project_entry_ids(cx).first().copied());
3568                    if let Some(entry_id) = entry_id {
3569                        pane.project
3570                            .update(cx, |_, cx| {
3571                                cx.emit(project::Event::RevealInProjectPanel(entry_id))
3572                            })
3573                            .ok();
3574                    }
3575                }),
3576            )
3577            .on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
3578                if cx.stop_active_drag(window) {
3579                    return;
3580                } else {
3581                    cx.propagate();
3582                }
3583            }))
3584            .when(self.active_item().is_some() && display_tab_bar, |pane| {
3585                pane.child((self.render_tab_bar.clone())(self, window, cx))
3586            })
3587            .child({
3588                let has_worktrees = project.read(cx).visible_worktrees(cx).next().is_some();
3589                // main content
3590                div()
3591                    .flex_1()
3592                    .relative()
3593                    .group("")
3594                    .overflow_hidden()
3595                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
3596                    .on_drag_move::<DraggedSelection>(cx.listener(Self::handle_drag_move))
3597                    .when(is_local, |div| {
3598                        div.on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
3599                    })
3600                    .map(|div| {
3601                        if let Some(item) = self.active_item() {
3602                            div.id("pane_placeholder")
3603                                .v_flex()
3604                                .size_full()
3605                                .overflow_hidden()
3606                                .child(self.toolbar.clone())
3607                                .child(item.to_any())
3608                        } else {
3609                            let placeholder = div
3610                                .id("pane_placeholder")
3611                                .h_flex()
3612                                .size_full()
3613                                .justify_center()
3614                                .on_click(cx.listener(
3615                                    move |this, event: &ClickEvent, window, cx| {
3616                                        if event.up.click_count == 2 {
3617                                            window.dispatch_action(
3618                                                this.double_click_dispatch_action.boxed_clone(),
3619                                                cx,
3620                                            );
3621                                        }
3622                                    },
3623                                ));
3624                            if has_worktrees {
3625                                placeholder
3626                            } else {
3627                                placeholder.child(
3628                                    Label::new("Open a file or project to get started.")
3629                                        .color(Color::Muted),
3630                                )
3631                            }
3632                        }
3633                    })
3634                    .child(
3635                        // drag target
3636                        div()
3637                            .invisible()
3638                            .absolute()
3639                            .bg(cx.theme().colors().drop_target_background)
3640                            .group_drag_over::<DraggedTab>("", |style| style.visible())
3641                            .group_drag_over::<DraggedSelection>("", |style| style.visible())
3642                            .when(is_local, |div| {
3643                                div.group_drag_over::<ExternalPaths>("", |style| style.visible())
3644                            })
3645                            .when_some(self.can_drop_predicate.clone(), |this, p| {
3646                                this.can_drop(move |a, window, cx| p(a, window, cx))
3647                            })
3648                            .on_drop(cx.listener(move |this, dragged_tab, window, cx| {
3649                                this.handle_tab_drop(
3650                                    dragged_tab,
3651                                    this.active_item_index(),
3652                                    window,
3653                                    cx,
3654                                )
3655                            }))
3656                            .on_drop(cx.listener(
3657                                move |this, selection: &DraggedSelection, window, cx| {
3658                                    this.handle_dragged_selection_drop(selection, None, window, cx)
3659                                },
3660                            ))
3661                            .on_drop(cx.listener(move |this, paths, window, cx| {
3662                                this.handle_external_paths_drop(paths, window, cx)
3663                            }))
3664                            .map(|div| {
3665                                let size = DefiniteLength::Fraction(0.5);
3666                                match self.drag_split_direction {
3667                                    None => div.top_0().right_0().bottom_0().left_0(),
3668                                    Some(SplitDirection::Up) => {
3669                                        div.top_0().left_0().right_0().h(size)
3670                                    }
3671                                    Some(SplitDirection::Down) => {
3672                                        div.left_0().bottom_0().right_0().h(size)
3673                                    }
3674                                    Some(SplitDirection::Left) => {
3675                                        div.top_0().left_0().bottom_0().w(size)
3676                                    }
3677                                    Some(SplitDirection::Right) => {
3678                                        div.top_0().bottom_0().right_0().w(size)
3679                                    }
3680                                }
3681                            }),
3682                    )
3683            })
3684            .on_mouse_down(
3685                MouseButton::Navigate(NavigationDirection::Back),
3686                cx.listener(|pane, _, window, cx| {
3687                    if let Some(workspace) = pane.workspace.upgrade() {
3688                        let pane = cx.entity().downgrade();
3689                        window.defer(cx, move |window, cx| {
3690                            workspace.update(cx, |workspace, cx| {
3691                                workspace.go_back(pane, window, cx).detach_and_log_err(cx)
3692                            })
3693                        })
3694                    }
3695                }),
3696            )
3697            .on_mouse_down(
3698                MouseButton::Navigate(NavigationDirection::Forward),
3699                cx.listener(|pane, _, window, cx| {
3700                    if let Some(workspace) = pane.workspace.upgrade() {
3701                        let pane = cx.entity().downgrade();
3702                        window.defer(cx, move |window, cx| {
3703                            workspace.update(cx, |workspace, cx| {
3704                                workspace
3705                                    .go_forward(pane, window, cx)
3706                                    .detach_and_log_err(cx)
3707                            })
3708                        })
3709                    }
3710                }),
3711            )
3712    }
3713}
3714
3715impl ItemNavHistory {
3716    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut App) {
3717        if self
3718            .item
3719            .upgrade()
3720            .is_some_and(|item| item.include_in_nav_history())
3721        {
3722            self.history
3723                .push(data, self.item.clone(), self.is_preview, cx);
3724        }
3725    }
3726
3727    pub fn pop_backward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
3728        self.history.pop(NavigationMode::GoingBack, cx)
3729    }
3730
3731    pub fn pop_forward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
3732        self.history.pop(NavigationMode::GoingForward, cx)
3733    }
3734}
3735
3736impl NavHistory {
3737    pub fn for_each_entry(
3738        &self,
3739        cx: &App,
3740        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
3741    ) {
3742        let borrowed_history = self.0.lock();
3743        borrowed_history
3744            .forward_stack
3745            .iter()
3746            .chain(borrowed_history.backward_stack.iter())
3747            .chain(borrowed_history.closed_stack.iter())
3748            .for_each(|entry| {
3749                if let Some(project_and_abs_path) =
3750                    borrowed_history.paths_by_item.get(&entry.item.id())
3751                {
3752                    f(entry, project_and_abs_path.clone());
3753                } else if let Some(item) = entry.item.upgrade() {
3754                    if let Some(path) = item.project_path(cx) {
3755                        f(entry, (path, None));
3756                    }
3757                }
3758            })
3759    }
3760
3761    pub fn set_mode(&mut self, mode: NavigationMode) {
3762        self.0.lock().mode = mode;
3763    }
3764
3765    pub fn mode(&self) -> NavigationMode {
3766        self.0.lock().mode
3767    }
3768
3769    pub fn disable(&mut self) {
3770        self.0.lock().mode = NavigationMode::Disabled;
3771    }
3772
3773    pub fn enable(&mut self) {
3774        self.0.lock().mode = NavigationMode::Normal;
3775    }
3776
3777    pub fn pop(&mut self, mode: NavigationMode, cx: &mut App) -> Option<NavigationEntry> {
3778        let mut state = self.0.lock();
3779        let entry = match mode {
3780            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
3781                return None;
3782            }
3783            NavigationMode::GoingBack => &mut state.backward_stack,
3784            NavigationMode::GoingForward => &mut state.forward_stack,
3785            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
3786        }
3787        .pop_back();
3788        if entry.is_some() {
3789            state.did_update(cx);
3790        }
3791        entry
3792    }
3793
3794    pub fn push<D: 'static + Send + Any>(
3795        &mut self,
3796        data: Option<D>,
3797        item: Arc<dyn WeakItemHandle>,
3798        is_preview: bool,
3799        cx: &mut App,
3800    ) {
3801        let state = &mut *self.0.lock();
3802        match state.mode {
3803            NavigationMode::Disabled => {}
3804            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
3805                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3806                    state.backward_stack.pop_front();
3807                }
3808                state.backward_stack.push_back(NavigationEntry {
3809                    item,
3810                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3811                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3812                    is_preview,
3813                });
3814                state.forward_stack.clear();
3815            }
3816            NavigationMode::GoingBack => {
3817                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3818                    state.forward_stack.pop_front();
3819                }
3820                state.forward_stack.push_back(NavigationEntry {
3821                    item,
3822                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3823                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3824                    is_preview,
3825                });
3826            }
3827            NavigationMode::GoingForward => {
3828                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3829                    state.backward_stack.pop_front();
3830                }
3831                state.backward_stack.push_back(NavigationEntry {
3832                    item,
3833                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3834                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3835                    is_preview,
3836                });
3837            }
3838            NavigationMode::ClosingItem => {
3839                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3840                    state.closed_stack.pop_front();
3841                }
3842                state.closed_stack.push_back(NavigationEntry {
3843                    item,
3844                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3845                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3846                    is_preview,
3847                });
3848            }
3849        }
3850        state.did_update(cx);
3851    }
3852
3853    pub fn remove_item(&mut self, item_id: EntityId) {
3854        let mut state = self.0.lock();
3855        state.paths_by_item.remove(&item_id);
3856        state
3857            .backward_stack
3858            .retain(|entry| entry.item.id() != item_id);
3859        state
3860            .forward_stack
3861            .retain(|entry| entry.item.id() != item_id);
3862        state
3863            .closed_stack
3864            .retain(|entry| entry.item.id() != item_id);
3865    }
3866
3867    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
3868        self.0.lock().paths_by_item.get(&item_id).cloned()
3869    }
3870}
3871
3872impl NavHistoryState {
3873    pub fn did_update(&self, cx: &mut App) {
3874        if let Some(pane) = self.pane.upgrade() {
3875            cx.defer(move |cx| {
3876                pane.update(cx, |pane, cx| pane.history_updated(cx));
3877            });
3878        }
3879    }
3880}
3881
3882fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
3883    let path = buffer_path
3884        .as_ref()
3885        .and_then(|p| {
3886            p.path
3887                .to_str()
3888                .and_then(|s| if s.is_empty() { None } else { Some(s) })
3889        })
3890        .unwrap_or("This buffer");
3891    let path = truncate_and_remove_front(path, 80);
3892    format!("{path} contains unsaved edits. Do you want to save it?")
3893}
3894
3895pub fn tab_details(items: &[Box<dyn ItemHandle>], _window: &Window, cx: &App) -> Vec<usize> {
3896    let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
3897    let mut tab_descriptions = HashMap::default();
3898    let mut done = false;
3899    while !done {
3900        done = true;
3901
3902        // Store item indices by their tab description.
3903        for (ix, (item, detail)) in items.iter().zip(&tab_details).enumerate() {
3904            let description = item.tab_content_text(*detail, cx);
3905            if *detail == 0 || description != item.tab_content_text(detail - 1, cx) {
3906                tab_descriptions
3907                    .entry(description)
3908                    .or_insert(Vec::new())
3909                    .push(ix);
3910            }
3911        }
3912
3913        // If two or more items have the same tab description, increase their level
3914        // of detail and try again.
3915        for (_, item_ixs) in tab_descriptions.drain() {
3916            if item_ixs.len() > 1 {
3917                done = false;
3918                for ix in item_ixs {
3919                    tab_details[ix] += 1;
3920                }
3921            }
3922        }
3923    }
3924
3925    tab_details
3926}
3927
3928pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &App) -> Option<Indicator> {
3929    maybe!({
3930        let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
3931            (true, _) => Color::Warning,
3932            (_, true) => Color::Accent,
3933            (false, false) => return None,
3934        };
3935
3936        Some(Indicator::dot().color(indicator_color))
3937    })
3938}
3939
3940impl Render for DraggedTab {
3941    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3942        let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
3943        let label = self.item.tab_content(
3944            TabContentParams {
3945                detail: Some(self.detail),
3946                selected: false,
3947                preview: false,
3948                deemphasized: false,
3949            },
3950            window,
3951            cx,
3952        );
3953        Tab::new("")
3954            .toggle_state(self.is_active)
3955            .child(label)
3956            .render(window, cx)
3957            .font(ui_font)
3958    }
3959}
3960
3961#[cfg(test)]
3962mod tests {
3963    use std::num::NonZero;
3964
3965    use super::*;
3966    use crate::item::test::{TestItem, TestProjectItem};
3967    use gpui::{TestAppContext, VisualTestContext};
3968    use project::FakeFs;
3969    use settings::SettingsStore;
3970    use theme::LoadThemes;
3971    use util::TryFutureExt;
3972
3973    #[gpui::test]
3974    async fn test_add_item_capped_to_max_tabs(cx: &mut TestAppContext) {
3975        init_test(cx);
3976        let fs = FakeFs::new(cx.executor());
3977
3978        let project = Project::test(fs, None, cx).await;
3979        let (workspace, cx) =
3980            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
3981        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3982
3983        for i in 0..7 {
3984            add_labeled_item(&pane, format!("{}", i).as_str(), false, cx);
3985        }
3986
3987        set_max_tabs(cx, Some(5));
3988        add_labeled_item(&pane, "7", false, cx);
3989        // Remove items to respect the max tab cap.
3990        assert_item_labels(&pane, ["3", "4", "5", "6", "7*"], cx);
3991        pane.update_in(cx, |pane, window, cx| {
3992            pane.activate_item(0, false, false, window, cx);
3993        });
3994        add_labeled_item(&pane, "X", false, cx);
3995        // Respect activation order.
3996        assert_item_labels(&pane, ["3", "X*", "5", "6", "7"], cx);
3997
3998        for i in 0..7 {
3999            add_labeled_item(&pane, format!("D{}", i).as_str(), true, cx);
4000        }
4001        // Keeps dirty items, even over max tab cap.
4002        assert_item_labels(
4003            &pane,
4004            ["D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6*^"],
4005            cx,
4006        );
4007
4008        set_max_tabs(cx, None);
4009        for i in 0..7 {
4010            add_labeled_item(&pane, format!("N{}", i).as_str(), false, cx);
4011        }
4012        // No cap when max tabs is None.
4013        assert_item_labels(
4014            &pane,
4015            [
4016                "D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6^", "N0", "N1", "N2", "N3", "N4",
4017                "N5", "N6*",
4018            ],
4019            cx,
4020        );
4021    }
4022
4023    #[gpui::test]
4024    async fn test_reduce_max_tabs_closes_existing_items(cx: &mut TestAppContext) {
4025        init_test(cx);
4026        let fs = FakeFs::new(cx.executor());
4027
4028        let project = Project::test(fs, None, cx).await;
4029        let (workspace, cx) =
4030            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4031        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4032
4033        add_labeled_item(&pane, "A", false, cx);
4034        add_labeled_item(&pane, "B", false, cx);
4035        let item_c = add_labeled_item(&pane, "C", false, cx);
4036        let item_d = add_labeled_item(&pane, "D", false, cx);
4037        add_labeled_item(&pane, "E", false, cx);
4038        add_labeled_item(&pane, "Settings", false, cx);
4039        assert_item_labels(&pane, ["A", "B", "C", "D", "E", "Settings*"], cx);
4040
4041        set_max_tabs(cx, Some(5));
4042        assert_item_labels(&pane, ["B", "C", "D", "E", "Settings*"], cx);
4043
4044        set_max_tabs(cx, Some(4));
4045        assert_item_labels(&pane, ["C", "D", "E", "Settings*"], cx);
4046
4047        pane.update_in(cx, |pane, window, cx| {
4048            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4049            pane.pin_tab_at(ix, window, cx);
4050
4051            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4052            pane.pin_tab_at(ix, window, cx);
4053        });
4054        assert_item_labels(&pane, ["C!", "D!", "E", "Settings*"], cx);
4055
4056        set_max_tabs(cx, Some(2));
4057        assert_item_labels(&pane, ["C!", "D!", "Settings*"], cx);
4058    }
4059
4060    #[gpui::test]
4061    async fn test_allow_pinning_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4062        init_test(cx);
4063        let fs = FakeFs::new(cx.executor());
4064
4065        let project = Project::test(fs, None, cx).await;
4066        let (workspace, cx) =
4067            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4068        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4069
4070        set_max_tabs(cx, Some(1));
4071        let item_a = add_labeled_item(&pane, "A", true, cx);
4072
4073        pane.update_in(cx, |pane, window, cx| {
4074            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4075            pane.pin_tab_at(ix, window, cx);
4076        });
4077        assert_item_labels(&pane, ["A*^!"], cx);
4078    }
4079
4080    #[gpui::test]
4081    async fn test_allow_pinning_non_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4082        init_test(cx);
4083        let fs = FakeFs::new(cx.executor());
4084
4085        let project = Project::test(fs, None, cx).await;
4086        let (workspace, cx) =
4087            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4088        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4089
4090        set_max_tabs(cx, Some(1));
4091        let item_a = add_labeled_item(&pane, "A", false, cx);
4092
4093        pane.update_in(cx, |pane, window, cx| {
4094            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4095            pane.pin_tab_at(ix, window, cx);
4096        });
4097        assert_item_labels(&pane, ["A*!"], cx);
4098    }
4099
4100    #[gpui::test]
4101    async fn test_pin_tabs_incrementally_at_max_capacity(cx: &mut TestAppContext) {
4102        init_test(cx);
4103        let fs = FakeFs::new(cx.executor());
4104
4105        let project = Project::test(fs, None, cx).await;
4106        let (workspace, cx) =
4107            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4108        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4109
4110        set_max_tabs(cx, Some(3));
4111
4112        let item_a = add_labeled_item(&pane, "A", false, cx);
4113        assert_item_labels(&pane, ["A*"], cx);
4114
4115        pane.update_in(cx, |pane, window, cx| {
4116            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4117            pane.pin_tab_at(ix, window, cx);
4118        });
4119        assert_item_labels(&pane, ["A*!"], cx);
4120
4121        let item_b = add_labeled_item(&pane, "B", false, cx);
4122        assert_item_labels(&pane, ["A!", "B*"], cx);
4123
4124        pane.update_in(cx, |pane, window, cx| {
4125            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4126            pane.pin_tab_at(ix, window, cx);
4127        });
4128        assert_item_labels(&pane, ["A!", "B*!"], cx);
4129
4130        let item_c = add_labeled_item(&pane, "C", false, cx);
4131        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4132
4133        pane.update_in(cx, |pane, window, cx| {
4134            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4135            pane.pin_tab_at(ix, window, cx);
4136        });
4137        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4138    }
4139
4140    #[gpui::test]
4141    async fn test_pin_tabs_left_to_right_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4142        init_test(cx);
4143        let fs = FakeFs::new(cx.executor());
4144
4145        let project = Project::test(fs, None, cx).await;
4146        let (workspace, cx) =
4147            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4148        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4149
4150        set_max_tabs(cx, Some(3));
4151
4152        let item_a = add_labeled_item(&pane, "A", false, cx);
4153        assert_item_labels(&pane, ["A*"], cx);
4154
4155        let item_b = add_labeled_item(&pane, "B", false, cx);
4156        assert_item_labels(&pane, ["A", "B*"], cx);
4157
4158        let item_c = add_labeled_item(&pane, "C", false, cx);
4159        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4160
4161        pane.update_in(cx, |pane, window, cx| {
4162            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4163            pane.pin_tab_at(ix, window, cx);
4164        });
4165        assert_item_labels(&pane, ["A!", "B", "C*"], cx);
4166
4167        pane.update_in(cx, |pane, window, cx| {
4168            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4169            pane.pin_tab_at(ix, window, cx);
4170        });
4171        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4172
4173        pane.update_in(cx, |pane, window, cx| {
4174            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4175            pane.pin_tab_at(ix, window, cx);
4176        });
4177        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4178    }
4179
4180    #[gpui::test]
4181    async fn test_pin_tabs_right_to_left_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4182        init_test(cx);
4183        let fs = FakeFs::new(cx.executor());
4184
4185        let project = Project::test(fs, None, cx).await;
4186        let (workspace, cx) =
4187            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4188        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4189
4190        set_max_tabs(cx, Some(3));
4191
4192        let item_a = add_labeled_item(&pane, "A", false, cx);
4193        assert_item_labels(&pane, ["A*"], cx);
4194
4195        let item_b = add_labeled_item(&pane, "B", false, cx);
4196        assert_item_labels(&pane, ["A", "B*"], cx);
4197
4198        let item_c = add_labeled_item(&pane, "C", false, cx);
4199        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4200
4201        pane.update_in(cx, |pane, window, cx| {
4202            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4203            pane.pin_tab_at(ix, window, cx);
4204        });
4205        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4206
4207        pane.update_in(cx, |pane, window, cx| {
4208            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4209            pane.pin_tab_at(ix, window, cx);
4210        });
4211        assert_item_labels(&pane, ["C*!", "B!", "A"], cx);
4212
4213        pane.update_in(cx, |pane, window, cx| {
4214            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4215            pane.pin_tab_at(ix, window, cx);
4216        });
4217        assert_item_labels(&pane, ["C*!", "B!", "A!"], cx);
4218    }
4219
4220    #[gpui::test]
4221    async fn test_pinned_tabs_never_closed_at_max_tabs(cx: &mut TestAppContext) {
4222        init_test(cx);
4223        let fs = FakeFs::new(cx.executor());
4224
4225        let project = Project::test(fs, None, cx).await;
4226        let (workspace, cx) =
4227            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4228        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4229
4230        let item_a = add_labeled_item(&pane, "A", false, cx);
4231        pane.update_in(cx, |pane, window, cx| {
4232            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4233            pane.pin_tab_at(ix, window, cx);
4234        });
4235
4236        let item_b = add_labeled_item(&pane, "B", false, cx);
4237        pane.update_in(cx, |pane, window, cx| {
4238            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4239            pane.pin_tab_at(ix, window, cx);
4240        });
4241
4242        add_labeled_item(&pane, "C", false, cx);
4243        add_labeled_item(&pane, "D", false, cx);
4244        add_labeled_item(&pane, "E", false, cx);
4245        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
4246
4247        set_max_tabs(cx, Some(3));
4248        add_labeled_item(&pane, "F", false, cx);
4249        assert_item_labels(&pane, ["A!", "B!", "F*"], cx);
4250
4251        add_labeled_item(&pane, "G", false, cx);
4252        assert_item_labels(&pane, ["A!", "B!", "G*"], cx);
4253
4254        add_labeled_item(&pane, "H", false, cx);
4255        assert_item_labels(&pane, ["A!", "B!", "H*"], cx);
4256    }
4257
4258    #[gpui::test]
4259    async fn test_always_allows_one_unpinned_item_over_max_tabs_regardless_of_pinned_count(
4260        cx: &mut TestAppContext,
4261    ) {
4262        init_test(cx);
4263        let fs = FakeFs::new(cx.executor());
4264
4265        let project = Project::test(fs, None, cx).await;
4266        let (workspace, cx) =
4267            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4268        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4269
4270        set_max_tabs(cx, Some(3));
4271
4272        let item_a = add_labeled_item(&pane, "A", false, cx);
4273        pane.update_in(cx, |pane, window, cx| {
4274            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4275            pane.pin_tab_at(ix, window, cx);
4276        });
4277
4278        let item_b = add_labeled_item(&pane, "B", false, cx);
4279        pane.update_in(cx, |pane, window, cx| {
4280            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4281            pane.pin_tab_at(ix, window, cx);
4282        });
4283
4284        let item_c = add_labeled_item(&pane, "C", false, cx);
4285        pane.update_in(cx, |pane, window, cx| {
4286            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4287            pane.pin_tab_at(ix, window, cx);
4288        });
4289
4290        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4291
4292        let item_d = add_labeled_item(&pane, "D", false, cx);
4293        assert_item_labels(&pane, ["A!", "B!", "C!", "D*"], cx);
4294
4295        pane.update_in(cx, |pane, window, cx| {
4296            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4297            pane.pin_tab_at(ix, window, cx);
4298        });
4299        assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
4300
4301        add_labeled_item(&pane, "E", false, cx);
4302        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "E*"], cx);
4303
4304        add_labeled_item(&pane, "F", false, cx);
4305        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "F*"], cx);
4306    }
4307
4308    #[gpui::test]
4309    async fn test_can_open_one_item_when_all_tabs_are_dirty_at_max(cx: &mut TestAppContext) {
4310        init_test(cx);
4311        let fs = FakeFs::new(cx.executor());
4312
4313        let project = Project::test(fs, None, cx).await;
4314        let (workspace, cx) =
4315            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4316        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4317
4318        set_max_tabs(cx, Some(3));
4319
4320        add_labeled_item(&pane, "A", true, cx);
4321        assert_item_labels(&pane, ["A*^"], cx);
4322
4323        add_labeled_item(&pane, "B", true, cx);
4324        assert_item_labels(&pane, ["A^", "B*^"], cx);
4325
4326        add_labeled_item(&pane, "C", true, cx);
4327        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
4328
4329        add_labeled_item(&pane, "D", false, cx);
4330        assert_item_labels(&pane, ["A^", "B^", "C^", "D*"], cx);
4331
4332        add_labeled_item(&pane, "E", false, cx);
4333        assert_item_labels(&pane, ["A^", "B^", "C^", "E*"], cx);
4334
4335        add_labeled_item(&pane, "F", false, cx);
4336        assert_item_labels(&pane, ["A^", "B^", "C^", "F*"], cx);
4337
4338        add_labeled_item(&pane, "G", true, cx);
4339        assert_item_labels(&pane, ["A^", "B^", "C^", "G*^"], cx);
4340    }
4341
4342    #[gpui::test]
4343    async fn test_toggle_pin_tab(cx: &mut TestAppContext) {
4344        init_test(cx);
4345        let fs = FakeFs::new(cx.executor());
4346
4347        let project = Project::test(fs, None, cx).await;
4348        let (workspace, cx) =
4349            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4350        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4351
4352        set_labeled_items(&pane, ["A", "B*", "C"], cx);
4353        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4354
4355        pane.update_in(cx, |pane, window, cx| {
4356            pane.toggle_pin_tab(&TogglePinTab, window, cx);
4357        });
4358        assert_item_labels(&pane, ["B*!", "A", "C"], cx);
4359
4360        pane.update_in(cx, |pane, window, cx| {
4361            pane.toggle_pin_tab(&TogglePinTab, window, cx);
4362        });
4363        assert_item_labels(&pane, ["B*", "A", "C"], cx);
4364    }
4365
4366    #[gpui::test]
4367    async fn test_unpin_all_tabs(cx: &mut TestAppContext) {
4368        init_test(cx);
4369        let fs = FakeFs::new(cx.executor());
4370
4371        let project = Project::test(fs, None, cx).await;
4372        let (workspace, cx) =
4373            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4374        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4375
4376        // Unpin all, in an empty pane
4377        pane.update_in(cx, |pane, window, cx| {
4378            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4379        });
4380
4381        assert_item_labels(&pane, [], cx);
4382
4383        let item_a = add_labeled_item(&pane, "A", false, cx);
4384        let item_b = add_labeled_item(&pane, "B", false, cx);
4385        let item_c = add_labeled_item(&pane, "C", false, cx);
4386        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4387
4388        // Unpin all, when no tabs are pinned
4389        pane.update_in(cx, |pane, window, cx| {
4390            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4391        });
4392
4393        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4394
4395        // Pin inactive tabs only
4396        pane.update_in(cx, |pane, window, cx| {
4397            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4398            pane.pin_tab_at(ix, window, cx);
4399
4400            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4401            pane.pin_tab_at(ix, window, cx);
4402        });
4403        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4404
4405        pane.update_in(cx, |pane, window, cx| {
4406            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4407        });
4408
4409        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4410
4411        // Pin all tabs
4412        pane.update_in(cx, |pane, window, cx| {
4413            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4414            pane.pin_tab_at(ix, window, cx);
4415
4416            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4417            pane.pin_tab_at(ix, window, cx);
4418
4419            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4420            pane.pin_tab_at(ix, window, cx);
4421        });
4422        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4423
4424        // Activate middle tab
4425        pane.update_in(cx, |pane, window, cx| {
4426            pane.activate_item(1, false, false, window, cx);
4427        });
4428        assert_item_labels(&pane, ["A!", "B*!", "C!"], cx);
4429
4430        pane.update_in(cx, |pane, window, cx| {
4431            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4432        });
4433
4434        // Order has not changed
4435        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4436    }
4437
4438    #[gpui::test]
4439    async fn test_pinning_active_tab_without_position_change_maintains_focus(
4440        cx: &mut TestAppContext,
4441    ) {
4442        init_test(cx);
4443        let fs = FakeFs::new(cx.executor());
4444
4445        let project = Project::test(fs, None, cx).await;
4446        let (workspace, cx) =
4447            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4448        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4449
4450        // Add A
4451        let item_a = add_labeled_item(&pane, "A", false, cx);
4452        assert_item_labels(&pane, ["A*"], cx);
4453
4454        // Add B
4455        add_labeled_item(&pane, "B", false, cx);
4456        assert_item_labels(&pane, ["A", "B*"], cx);
4457
4458        // Activate A again
4459        pane.update_in(cx, |pane, window, cx| {
4460            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4461            pane.activate_item(ix, true, true, window, cx);
4462        });
4463        assert_item_labels(&pane, ["A*", "B"], cx);
4464
4465        // Pin A - remains active
4466        pane.update_in(cx, |pane, window, cx| {
4467            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4468            pane.pin_tab_at(ix, window, cx);
4469        });
4470        assert_item_labels(&pane, ["A*!", "B"], cx);
4471
4472        // Unpin A - remain active
4473        pane.update_in(cx, |pane, window, cx| {
4474            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4475            pane.unpin_tab_at(ix, window, cx);
4476        });
4477        assert_item_labels(&pane, ["A*", "B"], cx);
4478    }
4479
4480    #[gpui::test]
4481    async fn test_pinning_active_tab_with_position_change_maintains_focus(cx: &mut TestAppContext) {
4482        init_test(cx);
4483        let fs = FakeFs::new(cx.executor());
4484
4485        let project = Project::test(fs, None, cx).await;
4486        let (workspace, cx) =
4487            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4488        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4489
4490        // Add A, B, C
4491        add_labeled_item(&pane, "A", false, cx);
4492        add_labeled_item(&pane, "B", false, cx);
4493        let item_c = add_labeled_item(&pane, "C", false, cx);
4494        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4495
4496        // Pin C - moves to pinned area, remains active
4497        pane.update_in(cx, |pane, window, cx| {
4498            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4499            pane.pin_tab_at(ix, window, cx);
4500        });
4501        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4502
4503        // Unpin C - moves after pinned area, remains active
4504        pane.update_in(cx, |pane, window, cx| {
4505            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4506            pane.unpin_tab_at(ix, window, cx);
4507        });
4508        assert_item_labels(&pane, ["C*", "A", "B"], cx);
4509    }
4510
4511    #[gpui::test]
4512    async fn test_pinning_inactive_tab_without_position_change_preserves_existing_focus(
4513        cx: &mut TestAppContext,
4514    ) {
4515        init_test(cx);
4516        let fs = FakeFs::new(cx.executor());
4517
4518        let project = Project::test(fs, None, cx).await;
4519        let (workspace, cx) =
4520            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4521        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4522
4523        // Add A, B
4524        let item_a = add_labeled_item(&pane, "A", false, cx);
4525        add_labeled_item(&pane, "B", false, cx);
4526        assert_item_labels(&pane, ["A", "B*"], cx);
4527
4528        // Pin A - already in pinned area, B remains active
4529        pane.update_in(cx, |pane, window, cx| {
4530            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4531            pane.pin_tab_at(ix, window, cx);
4532        });
4533        assert_item_labels(&pane, ["A!", "B*"], cx);
4534
4535        // Unpin A - stays in place, B remains active
4536        pane.update_in(cx, |pane, window, cx| {
4537            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4538            pane.unpin_tab_at(ix, window, cx);
4539        });
4540        assert_item_labels(&pane, ["A", "B*"], cx);
4541    }
4542
4543    #[gpui::test]
4544    async fn test_pinning_inactive_tab_with_position_change_preserves_existing_focus(
4545        cx: &mut TestAppContext,
4546    ) {
4547        init_test(cx);
4548        let fs = FakeFs::new(cx.executor());
4549
4550        let project = Project::test(fs, None, cx).await;
4551        let (workspace, cx) =
4552            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4553        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4554
4555        // Add A, B, C
4556        add_labeled_item(&pane, "A", false, cx);
4557        let item_b = add_labeled_item(&pane, "B", false, cx);
4558        let item_c = add_labeled_item(&pane, "C", false, cx);
4559        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4560
4561        // Activate B
4562        pane.update_in(cx, |pane, window, cx| {
4563            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4564            pane.activate_item(ix, true, true, window, cx);
4565        });
4566        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4567
4568        // Pin C - moves to pinned area, B remains active
4569        pane.update_in(cx, |pane, window, cx| {
4570            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4571            pane.pin_tab_at(ix, window, cx);
4572        });
4573        assert_item_labels(&pane, ["C!", "A", "B*"], cx);
4574
4575        // Unpin C - moves after pinned area, B remains active
4576        pane.update_in(cx, |pane, window, cx| {
4577            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4578            pane.unpin_tab_at(ix, window, cx);
4579        });
4580        assert_item_labels(&pane, ["C", "A", "B*"], cx);
4581    }
4582
4583    #[gpui::test]
4584    async fn test_drag_unpinned_tab_to_split_creates_pane_with_unpinned_tab(
4585        cx: &mut TestAppContext,
4586    ) {
4587        init_test(cx);
4588        let fs = FakeFs::new(cx.executor());
4589
4590        let project = Project::test(fs, None, cx).await;
4591        let (workspace, cx) =
4592            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4593        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4594
4595        // Add A, B. Pin B. Activate A
4596        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4597        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4598
4599        pane_a.update_in(cx, |pane, window, cx| {
4600            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4601            pane.pin_tab_at(ix, window, cx);
4602
4603            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4604            pane.activate_item(ix, true, true, window, cx);
4605        });
4606
4607        // Drag A to create new split
4608        pane_a.update_in(cx, |pane, window, cx| {
4609            pane.drag_split_direction = Some(SplitDirection::Right);
4610
4611            let dragged_tab = DraggedTab {
4612                pane: pane_a.clone(),
4613                item: item_a.boxed_clone(),
4614                ix: 0,
4615                detail: 0,
4616                is_active: true,
4617            };
4618            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4619        });
4620
4621        // A should be moved to new pane. B should remain pinned, A should not be pinned
4622        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
4623            let panes = workspace.panes();
4624            (panes[0].clone(), panes[1].clone())
4625        });
4626        assert_item_labels(&pane_a, ["B*!"], cx);
4627        assert_item_labels(&pane_b, ["A*"], cx);
4628    }
4629
4630    #[gpui::test]
4631    async fn test_drag_pinned_tab_to_split_creates_pane_with_pinned_tab(cx: &mut TestAppContext) {
4632        init_test(cx);
4633        let fs = FakeFs::new(cx.executor());
4634
4635        let project = Project::test(fs, None, cx).await;
4636        let (workspace, cx) =
4637            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4638        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4639
4640        // Add A, B. Pin both. Activate A
4641        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4642        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4643
4644        pane_a.update_in(cx, |pane, window, cx| {
4645            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4646            pane.pin_tab_at(ix, window, cx);
4647
4648            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4649            pane.pin_tab_at(ix, window, cx);
4650
4651            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4652            pane.activate_item(ix, true, true, window, cx);
4653        });
4654        assert_item_labels(&pane_a, ["A*!", "B!"], cx);
4655
4656        // Drag A to create new split
4657        pane_a.update_in(cx, |pane, window, cx| {
4658            pane.drag_split_direction = Some(SplitDirection::Right);
4659
4660            let dragged_tab = DraggedTab {
4661                pane: pane_a.clone(),
4662                item: item_a.boxed_clone(),
4663                ix: 0,
4664                detail: 0,
4665                is_active: true,
4666            };
4667            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4668        });
4669
4670        // A should be moved to new pane. Both A and B should still be pinned
4671        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
4672            let panes = workspace.panes();
4673            (panes[0].clone(), panes[1].clone())
4674        });
4675        assert_item_labels(&pane_a, ["B*!"], cx);
4676        assert_item_labels(&pane_b, ["A*!"], cx);
4677    }
4678
4679    #[gpui::test]
4680    async fn test_drag_pinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
4681        init_test(cx);
4682        let fs = FakeFs::new(cx.executor());
4683
4684        let project = Project::test(fs, None, cx).await;
4685        let (workspace, cx) =
4686            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4687        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4688
4689        // Add A to pane A and pin
4690        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4691        pane_a.update_in(cx, |pane, window, cx| {
4692            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4693            pane.pin_tab_at(ix, window, cx);
4694        });
4695        assert_item_labels(&pane_a, ["A*!"], cx);
4696
4697        // Add B to pane B and pin
4698        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4699            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4700        });
4701        let item_b = add_labeled_item(&pane_b, "B", false, cx);
4702        pane_b.update_in(cx, |pane, window, cx| {
4703            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4704            pane.pin_tab_at(ix, window, cx);
4705        });
4706        assert_item_labels(&pane_b, ["B*!"], cx);
4707
4708        // Move A from pane A to pane B's pinned region
4709        pane_b.update_in(cx, |pane, window, cx| {
4710            let dragged_tab = DraggedTab {
4711                pane: pane_a.clone(),
4712                item: item_a.boxed_clone(),
4713                ix: 0,
4714                detail: 0,
4715                is_active: true,
4716            };
4717            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4718        });
4719
4720        // A should stay pinned
4721        assert_item_labels(&pane_a, [], cx);
4722        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
4723    }
4724
4725    #[gpui::test]
4726    async fn test_drag_pinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
4727        init_test(cx);
4728        let fs = FakeFs::new(cx.executor());
4729
4730        let project = Project::test(fs, None, cx).await;
4731        let (workspace, cx) =
4732            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4733        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4734
4735        // Add A to pane A and pin
4736        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4737        pane_a.update_in(cx, |pane, window, cx| {
4738            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4739            pane.pin_tab_at(ix, window, cx);
4740        });
4741        assert_item_labels(&pane_a, ["A*!"], cx);
4742
4743        // Create pane B with pinned item B
4744        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4745            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4746        });
4747        let item_b = add_labeled_item(&pane_b, "B", false, cx);
4748        assert_item_labels(&pane_b, ["B*"], cx);
4749
4750        pane_b.update_in(cx, |pane, window, cx| {
4751            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4752            pane.pin_tab_at(ix, window, cx);
4753        });
4754        assert_item_labels(&pane_b, ["B*!"], cx);
4755
4756        // Move A from pane A to pane B's unpinned region
4757        pane_b.update_in(cx, |pane, window, cx| {
4758            let dragged_tab = DraggedTab {
4759                pane: pane_a.clone(),
4760                item: item_a.boxed_clone(),
4761                ix: 0,
4762                detail: 0,
4763                is_active: true,
4764            };
4765            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
4766        });
4767
4768        // A should become pinned
4769        assert_item_labels(&pane_a, [], cx);
4770        assert_item_labels(&pane_b, ["B!", "A*"], cx);
4771    }
4772
4773    #[gpui::test]
4774    async fn test_drag_pinned_tab_into_existing_panes_first_position_with_no_pinned_tabs(
4775        cx: &mut TestAppContext,
4776    ) {
4777        init_test(cx);
4778        let fs = FakeFs::new(cx.executor());
4779
4780        let project = Project::test(fs, None, cx).await;
4781        let (workspace, cx) =
4782            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4783        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4784
4785        // Add A to pane A and pin
4786        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4787        pane_a.update_in(cx, |pane, window, cx| {
4788            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4789            pane.pin_tab_at(ix, window, cx);
4790        });
4791        assert_item_labels(&pane_a, ["A*!"], cx);
4792
4793        // Add B to pane B
4794        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4795            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4796        });
4797        add_labeled_item(&pane_b, "B", false, cx);
4798        assert_item_labels(&pane_b, ["B*"], cx);
4799
4800        // Move A from pane A to position 0 in pane B, indicating it should stay pinned
4801        pane_b.update_in(cx, |pane, window, cx| {
4802            let dragged_tab = DraggedTab {
4803                pane: pane_a.clone(),
4804                item: item_a.boxed_clone(),
4805                ix: 0,
4806                detail: 0,
4807                is_active: true,
4808            };
4809            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4810        });
4811
4812        // A should stay pinned
4813        assert_item_labels(&pane_a, [], cx);
4814        assert_item_labels(&pane_b, ["A*!", "B"], cx);
4815    }
4816
4817    #[gpui::test]
4818    async fn test_drag_pinned_tab_into_existing_pane_at_max_capacity_closes_unpinned_tabs(
4819        cx: &mut TestAppContext,
4820    ) {
4821        init_test(cx);
4822        let fs = FakeFs::new(cx.executor());
4823
4824        let project = Project::test(fs, None, cx).await;
4825        let (workspace, cx) =
4826            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4827        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4828        set_max_tabs(cx, Some(2));
4829
4830        // Add A, B to pane A. Pin both
4831        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4832        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4833        pane_a.update_in(cx, |pane, window, cx| {
4834            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4835            pane.pin_tab_at(ix, window, cx);
4836
4837            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4838            pane.pin_tab_at(ix, window, cx);
4839        });
4840        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
4841
4842        // Add C, D to pane B. Pin both
4843        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4844            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4845        });
4846        let item_c = add_labeled_item(&pane_b, "C", false, cx);
4847        let item_d = add_labeled_item(&pane_b, "D", false, cx);
4848        pane_b.update_in(cx, |pane, window, cx| {
4849            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4850            pane.pin_tab_at(ix, window, cx);
4851
4852            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4853            pane.pin_tab_at(ix, window, cx);
4854        });
4855        assert_item_labels(&pane_b, ["C!", "D*!"], cx);
4856
4857        // Add a third unpinned item to pane B (exceeds max tabs), but is allowed,
4858        // as we allow 1 tab over max if the others are pinned or dirty
4859        add_labeled_item(&pane_b, "E", false, cx);
4860        assert_item_labels(&pane_b, ["C!", "D!", "E*"], cx);
4861
4862        // Drag pinned A from pane A to position 0 in pane B
4863        pane_b.update_in(cx, |pane, window, cx| {
4864            let dragged_tab = DraggedTab {
4865                pane: pane_a.clone(),
4866                item: item_a.boxed_clone(),
4867                ix: 0,
4868                detail: 0,
4869                is_active: true,
4870            };
4871            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4872        });
4873
4874        // E (unpinned) should be closed, leaving 3 pinned items
4875        assert_item_labels(&pane_a, ["B*!"], cx);
4876        assert_item_labels(&pane_b, ["A*!", "C!", "D!"], cx);
4877    }
4878
4879    #[gpui::test]
4880    async fn test_drag_last_pinned_tab_to_same_position_stays_pinned(cx: &mut TestAppContext) {
4881        init_test(cx);
4882        let fs = FakeFs::new(cx.executor());
4883
4884        let project = Project::test(fs, None, cx).await;
4885        let (workspace, cx) =
4886            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4887        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4888
4889        // Add A to pane A and pin it
4890        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4891        pane_a.update_in(cx, |pane, window, cx| {
4892            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4893            pane.pin_tab_at(ix, window, cx);
4894        });
4895        assert_item_labels(&pane_a, ["A*!"], cx);
4896
4897        // Drag pinned A to position 1 (directly to the right) in the same pane
4898        pane_a.update_in(cx, |pane, window, cx| {
4899            let dragged_tab = DraggedTab {
4900                pane: pane_a.clone(),
4901                item: item_a.boxed_clone(),
4902                ix: 0,
4903                detail: 0,
4904                is_active: true,
4905            };
4906            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
4907        });
4908
4909        // A should still be pinned and active
4910        assert_item_labels(&pane_a, ["A*!"], cx);
4911    }
4912
4913    #[gpui::test]
4914    async fn test_drag_pinned_tab_beyond_last_pinned_tab_in_same_pane_stays_pinned(
4915        cx: &mut TestAppContext,
4916    ) {
4917        init_test(cx);
4918        let fs = FakeFs::new(cx.executor());
4919
4920        let project = Project::test(fs, None, cx).await;
4921        let (workspace, cx) =
4922            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4923        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4924
4925        // Add A, B to pane A and pin both
4926        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4927        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4928        pane_a.update_in(cx, |pane, window, cx| {
4929            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4930            pane.pin_tab_at(ix, window, cx);
4931
4932            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4933            pane.pin_tab_at(ix, window, cx);
4934        });
4935        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
4936
4937        // Drag pinned A right of B in the same pane
4938        pane_a.update_in(cx, |pane, window, cx| {
4939            let dragged_tab = DraggedTab {
4940                pane: pane_a.clone(),
4941                item: item_a.boxed_clone(),
4942                ix: 0,
4943                detail: 0,
4944                is_active: true,
4945            };
4946            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
4947        });
4948
4949        // A stays pinned
4950        assert_item_labels(&pane_a, ["B!", "A*!"], cx);
4951    }
4952
4953    #[gpui::test]
4954    async fn test_drag_pinned_tab_beyond_unpinned_tab_in_same_pane_becomes_unpinned(
4955        cx: &mut TestAppContext,
4956    ) {
4957        init_test(cx);
4958        let fs = FakeFs::new(cx.executor());
4959
4960        let project = Project::test(fs, None, cx).await;
4961        let (workspace, cx) =
4962            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4963        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4964
4965        // Add A, B to pane A and pin A
4966        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4967        add_labeled_item(&pane_a, "B", false, cx);
4968        pane_a.update_in(cx, |pane, window, cx| {
4969            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4970            pane.pin_tab_at(ix, window, cx);
4971        });
4972        assert_item_labels(&pane_a, ["A!", "B*"], cx);
4973
4974        // Drag pinned A right of B in the same pane
4975        pane_a.update_in(cx, |pane, window, cx| {
4976            let dragged_tab = DraggedTab {
4977                pane: pane_a.clone(),
4978                item: item_a.boxed_clone(),
4979                ix: 0,
4980                detail: 0,
4981                is_active: true,
4982            };
4983            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
4984        });
4985
4986        // A becomes unpinned
4987        assert_item_labels(&pane_a, ["B", "A*"], cx);
4988    }
4989
4990    #[gpui::test]
4991    async fn test_drag_unpinned_tab_in_front_of_pinned_tab_in_same_pane_becomes_pinned(
4992        cx: &mut TestAppContext,
4993    ) {
4994        init_test(cx);
4995        let fs = FakeFs::new(cx.executor());
4996
4997        let project = Project::test(fs, None, cx).await;
4998        let (workspace, cx) =
4999            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5000        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5001
5002        // Add A, B to pane A and pin A
5003        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5004        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5005        pane_a.update_in(cx, |pane, window, cx| {
5006            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5007            pane.pin_tab_at(ix, window, cx);
5008        });
5009        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5010
5011        // Drag pinned B left of A in the same pane
5012        pane_a.update_in(cx, |pane, window, cx| {
5013            let dragged_tab = DraggedTab {
5014                pane: pane_a.clone(),
5015                item: item_b.boxed_clone(),
5016                ix: 1,
5017                detail: 0,
5018                is_active: true,
5019            };
5020            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5021        });
5022
5023        // A becomes unpinned
5024        assert_item_labels(&pane_a, ["B*!", "A!"], cx);
5025    }
5026
5027    #[gpui::test]
5028    async fn test_drag_unpinned_tab_to_the_pinned_region_stays_pinned(cx: &mut TestAppContext) {
5029        init_test(cx);
5030        let fs = FakeFs::new(cx.executor());
5031
5032        let project = Project::test(fs, None, cx).await;
5033        let (workspace, cx) =
5034            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5035        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5036
5037        // Add A, B, C to pane A and pin A
5038        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5039        add_labeled_item(&pane_a, "B", false, cx);
5040        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5041        pane_a.update_in(cx, |pane, window, cx| {
5042            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5043            pane.pin_tab_at(ix, window, cx);
5044        });
5045        assert_item_labels(&pane_a, ["A!", "B", "C*"], cx);
5046
5047        // Drag pinned C left of B in the same pane
5048        pane_a.update_in(cx, |pane, window, cx| {
5049            let dragged_tab = DraggedTab {
5050                pane: pane_a.clone(),
5051                item: item_c.boxed_clone(),
5052                ix: 2,
5053                detail: 0,
5054                is_active: true,
5055            };
5056            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5057        });
5058
5059        // A stays pinned, B and C remain unpinned
5060        assert_item_labels(&pane_a, ["A!", "C*", "B"], cx);
5061    }
5062
5063    #[gpui::test]
5064    async fn test_drag_unpinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5065        init_test(cx);
5066        let fs = FakeFs::new(cx.executor());
5067
5068        let project = Project::test(fs, None, cx).await;
5069        let (workspace, cx) =
5070            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5071        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5072
5073        // Add unpinned item A to pane A
5074        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5075        assert_item_labels(&pane_a, ["A*"], cx);
5076
5077        // Create pane B with pinned item B
5078        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5079            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5080        });
5081        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5082        pane_b.update_in(cx, |pane, window, cx| {
5083            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5084            pane.pin_tab_at(ix, window, cx);
5085        });
5086        assert_item_labels(&pane_b, ["B*!"], cx);
5087
5088        // Move A from pane A to pane B's pinned region
5089        pane_b.update_in(cx, |pane, window, cx| {
5090            let dragged_tab = DraggedTab {
5091                pane: pane_a.clone(),
5092                item: item_a.boxed_clone(),
5093                ix: 0,
5094                detail: 0,
5095                is_active: true,
5096            };
5097            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5098        });
5099
5100        // A should become pinned since it was dropped in the pinned region
5101        assert_item_labels(&pane_a, [], cx);
5102        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5103    }
5104
5105    #[gpui::test]
5106    async fn test_drag_unpinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5107        init_test(cx);
5108        let fs = FakeFs::new(cx.executor());
5109
5110        let project = Project::test(fs, None, cx).await;
5111        let (workspace, cx) =
5112            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5113        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5114
5115        // Add unpinned item A to pane A
5116        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5117        assert_item_labels(&pane_a, ["A*"], cx);
5118
5119        // Create pane B with one pinned item B
5120        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5121            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5122        });
5123        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5124        pane_b.update_in(cx, |pane, window, cx| {
5125            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5126            pane.pin_tab_at(ix, window, cx);
5127        });
5128        assert_item_labels(&pane_b, ["B*!"], cx);
5129
5130        // Move A from pane A to pane B's unpinned region
5131        pane_b.update_in(cx, |pane, window, cx| {
5132            let dragged_tab = DraggedTab {
5133                pane: pane_a.clone(),
5134                item: item_a.boxed_clone(),
5135                ix: 0,
5136                detail: 0,
5137                is_active: true,
5138            };
5139            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5140        });
5141
5142        // A should remain unpinned since it was dropped outside the pinned region
5143        assert_item_labels(&pane_a, [], cx);
5144        assert_item_labels(&pane_b, ["B!", "A*"], cx);
5145    }
5146
5147    #[gpui::test]
5148    async fn test_drag_pinned_tab_throughout_entire_range_of_pinned_tabs_both_directions(
5149        cx: &mut TestAppContext,
5150    ) {
5151        init_test(cx);
5152        let fs = FakeFs::new(cx.executor());
5153
5154        let project = Project::test(fs, None, cx).await;
5155        let (workspace, cx) =
5156            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5157        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5158
5159        // Add A, B, C and pin all
5160        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5161        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5162        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5163        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5164
5165        pane_a.update_in(cx, |pane, window, cx| {
5166            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5167            pane.pin_tab_at(ix, window, cx);
5168
5169            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5170            pane.pin_tab_at(ix, window, cx);
5171
5172            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5173            pane.pin_tab_at(ix, window, cx);
5174        });
5175        assert_item_labels(&pane_a, ["A!", "B!", "C*!"], cx);
5176
5177        // Move A to right of B
5178        pane_a.update_in(cx, |pane, window, cx| {
5179            let dragged_tab = DraggedTab {
5180                pane: pane_a.clone(),
5181                item: item_a.boxed_clone(),
5182                ix: 0,
5183                detail: 0,
5184                is_active: true,
5185            };
5186            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5187        });
5188
5189        // A should be after B and all are pinned
5190        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5191
5192        // Move A to right of C
5193        pane_a.update_in(cx, |pane, window, cx| {
5194            let dragged_tab = DraggedTab {
5195                pane: pane_a.clone(),
5196                item: item_a.boxed_clone(),
5197                ix: 1,
5198                detail: 0,
5199                is_active: true,
5200            };
5201            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5202        });
5203
5204        // A should be after C and all are pinned
5205        assert_item_labels(&pane_a, ["B!", "C!", "A*!"], cx);
5206
5207        // Move A to left of C
5208        pane_a.update_in(cx, |pane, window, cx| {
5209            let dragged_tab = DraggedTab {
5210                pane: pane_a.clone(),
5211                item: item_a.boxed_clone(),
5212                ix: 2,
5213                detail: 0,
5214                is_active: true,
5215            };
5216            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5217        });
5218
5219        // A should be before C and all are pinned
5220        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5221
5222        // Move A to left of B
5223        pane_a.update_in(cx, |pane, window, cx| {
5224            let dragged_tab = DraggedTab {
5225                pane: pane_a.clone(),
5226                item: item_a.boxed_clone(),
5227                ix: 1,
5228                detail: 0,
5229                is_active: true,
5230            };
5231            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5232        });
5233
5234        // A should be before B and all are pinned
5235        assert_item_labels(&pane_a, ["A*!", "B!", "C!"], cx);
5236    }
5237
5238    #[gpui::test]
5239    async fn test_drag_first_tab_to_last_position(cx: &mut TestAppContext) {
5240        init_test(cx);
5241        let fs = FakeFs::new(cx.executor());
5242
5243        let project = Project::test(fs, None, cx).await;
5244        let (workspace, cx) =
5245            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5246        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5247
5248        // Add A, B, C
5249        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5250        add_labeled_item(&pane_a, "B", false, cx);
5251        add_labeled_item(&pane_a, "C", false, cx);
5252        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5253
5254        // Move A to the end
5255        pane_a.update_in(cx, |pane, window, cx| {
5256            let dragged_tab = DraggedTab {
5257                pane: pane_a.clone(),
5258                item: item_a.boxed_clone(),
5259                ix: 0,
5260                detail: 0,
5261                is_active: true,
5262            };
5263            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5264        });
5265
5266        // A should be at the end
5267        assert_item_labels(&pane_a, ["B", "C", "A*"], cx);
5268    }
5269
5270    #[gpui::test]
5271    async fn test_drag_last_tab_to_first_position(cx: &mut TestAppContext) {
5272        init_test(cx);
5273        let fs = FakeFs::new(cx.executor());
5274
5275        let project = Project::test(fs, None, cx).await;
5276        let (workspace, cx) =
5277            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5278        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5279
5280        // Add A, B, C
5281        add_labeled_item(&pane_a, "A", false, cx);
5282        add_labeled_item(&pane_a, "B", false, cx);
5283        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5284        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5285
5286        // Move C to the beginning
5287        pane_a.update_in(cx, |pane, window, cx| {
5288            let dragged_tab = DraggedTab {
5289                pane: pane_a.clone(),
5290                item: item_c.boxed_clone(),
5291                ix: 2,
5292                detail: 0,
5293                is_active: true,
5294            };
5295            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5296        });
5297
5298        // C should be at the beginning
5299        assert_item_labels(&pane_a, ["C*", "A", "B"], cx);
5300    }
5301
5302    #[gpui::test]
5303    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
5304        init_test(cx);
5305        let fs = FakeFs::new(cx.executor());
5306
5307        let project = Project::test(fs, None, cx).await;
5308        let (workspace, cx) =
5309            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5310        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5311
5312        // 1. Add with a destination index
5313        //   a. Add before the active item
5314        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5315        pane.update_in(cx, |pane, window, cx| {
5316            pane.add_item(
5317                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5318                false,
5319                false,
5320                Some(0),
5321                window,
5322                cx,
5323            );
5324        });
5325        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5326
5327        //   b. Add after the active item
5328        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5329        pane.update_in(cx, |pane, window, cx| {
5330            pane.add_item(
5331                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5332                false,
5333                false,
5334                Some(2),
5335                window,
5336                cx,
5337            );
5338        });
5339        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5340
5341        //   c. Add at the end of the item list (including off the length)
5342        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5343        pane.update_in(cx, |pane, window, cx| {
5344            pane.add_item(
5345                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5346                false,
5347                false,
5348                Some(5),
5349                window,
5350                cx,
5351            );
5352        });
5353        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5354
5355        // 2. Add without a destination index
5356        //   a. Add with active item at the start of the item list
5357        set_labeled_items(&pane, ["A*", "B", "C"], cx);
5358        pane.update_in(cx, |pane, window, cx| {
5359            pane.add_item(
5360                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5361                false,
5362                false,
5363                None,
5364                window,
5365                cx,
5366            );
5367        });
5368        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
5369
5370        //   b. Add with active item at the end of the item list
5371        set_labeled_items(&pane, ["A", "B", "C*"], cx);
5372        pane.update_in(cx, |pane, window, cx| {
5373            pane.add_item(
5374                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5375                false,
5376                false,
5377                None,
5378                window,
5379                cx,
5380            );
5381        });
5382        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5383    }
5384
5385    #[gpui::test]
5386    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
5387        init_test(cx);
5388        let fs = FakeFs::new(cx.executor());
5389
5390        let project = Project::test(fs, None, cx).await;
5391        let (workspace, cx) =
5392            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5393        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5394
5395        // 1. Add with a destination index
5396        //   1a. Add before the active item
5397        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5398        pane.update_in(cx, |pane, window, cx| {
5399            pane.add_item(d, false, false, Some(0), window, cx);
5400        });
5401        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5402
5403        //   1b. Add after the active item
5404        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5405        pane.update_in(cx, |pane, window, cx| {
5406            pane.add_item(d, false, false, Some(2), window, cx);
5407        });
5408        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5409
5410        //   1c. Add at the end of the item list (including off the length)
5411        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5412        pane.update_in(cx, |pane, window, cx| {
5413            pane.add_item(a, false, false, Some(5), window, cx);
5414        });
5415        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5416
5417        //   1d. Add same item to active index
5418        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5419        pane.update_in(cx, |pane, window, cx| {
5420            pane.add_item(b, false, false, Some(1), window, cx);
5421        });
5422        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5423
5424        //   1e. Add item to index after same item in last position
5425        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5426        pane.update_in(cx, |pane, window, cx| {
5427            pane.add_item(c, false, false, Some(2), window, cx);
5428        });
5429        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5430
5431        // 2. Add without a destination index
5432        //   2a. Add with active item at the start of the item list
5433        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
5434        pane.update_in(cx, |pane, window, cx| {
5435            pane.add_item(d, false, false, None, window, cx);
5436        });
5437        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
5438
5439        //   2b. Add with active item at the end of the item list
5440        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
5441        pane.update_in(cx, |pane, window, cx| {
5442            pane.add_item(a, false, false, None, window, cx);
5443        });
5444        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5445
5446        //   2c. Add active item to active item at end of list
5447        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
5448        pane.update_in(cx, |pane, window, cx| {
5449            pane.add_item(c, false, false, None, window, cx);
5450        });
5451        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5452
5453        //   2d. Add active item to active item at start of list
5454        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
5455        pane.update_in(cx, |pane, window, cx| {
5456            pane.add_item(a, false, false, None, window, cx);
5457        });
5458        assert_item_labels(&pane, ["A*", "B", "C"], cx);
5459    }
5460
5461    #[gpui::test]
5462    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
5463        init_test(cx);
5464        let fs = FakeFs::new(cx.executor());
5465
5466        let project = Project::test(fs, None, cx).await;
5467        let (workspace, cx) =
5468            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5469        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5470
5471        // singleton view
5472        pane.update_in(cx, |pane, window, cx| {
5473            pane.add_item(
5474                Box::new(cx.new(|cx| {
5475                    TestItem::new(cx)
5476                        .with_singleton(true)
5477                        .with_label("buffer 1")
5478                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
5479                })),
5480                false,
5481                false,
5482                None,
5483                window,
5484                cx,
5485            );
5486        });
5487        assert_item_labels(&pane, ["buffer 1*"], cx);
5488
5489        // new singleton view with the same project entry
5490        pane.update_in(cx, |pane, window, cx| {
5491            pane.add_item(
5492                Box::new(cx.new(|cx| {
5493                    TestItem::new(cx)
5494                        .with_singleton(true)
5495                        .with_label("buffer 1")
5496                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5497                })),
5498                false,
5499                false,
5500                None,
5501                window,
5502                cx,
5503            );
5504        });
5505        assert_item_labels(&pane, ["buffer 1*"], cx);
5506
5507        // new singleton view with different project entry
5508        pane.update_in(cx, |pane, window, cx| {
5509            pane.add_item(
5510                Box::new(cx.new(|cx| {
5511                    TestItem::new(cx)
5512                        .with_singleton(true)
5513                        .with_label("buffer 2")
5514                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
5515                })),
5516                false,
5517                false,
5518                None,
5519                window,
5520                cx,
5521            );
5522        });
5523        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
5524
5525        // new multibuffer view with the same project entry
5526        pane.update_in(cx, |pane, window, cx| {
5527            pane.add_item(
5528                Box::new(cx.new(|cx| {
5529                    TestItem::new(cx)
5530                        .with_singleton(false)
5531                        .with_label("multibuffer 1")
5532                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5533                })),
5534                false,
5535                false,
5536                None,
5537                window,
5538                cx,
5539            );
5540        });
5541        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
5542
5543        // another multibuffer view with the same project entry
5544        pane.update_in(cx, |pane, window, cx| {
5545            pane.add_item(
5546                Box::new(cx.new(|cx| {
5547                    TestItem::new(cx)
5548                        .with_singleton(false)
5549                        .with_label("multibuffer 1b")
5550                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5551                })),
5552                false,
5553                false,
5554                None,
5555                window,
5556                cx,
5557            );
5558        });
5559        assert_item_labels(
5560            &pane,
5561            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
5562            cx,
5563        );
5564    }
5565
5566    #[gpui::test]
5567    async fn test_remove_item_ordering_history(cx: &mut TestAppContext) {
5568        init_test(cx);
5569        let fs = FakeFs::new(cx.executor());
5570
5571        let project = Project::test(fs, None, cx).await;
5572        let (workspace, cx) =
5573            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5574        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5575
5576        add_labeled_item(&pane, "A", false, cx);
5577        add_labeled_item(&pane, "B", false, cx);
5578        add_labeled_item(&pane, "C", false, cx);
5579        add_labeled_item(&pane, "D", false, cx);
5580        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5581
5582        pane.update_in(cx, |pane, window, cx| {
5583            pane.activate_item(1, false, false, window, cx)
5584        });
5585        add_labeled_item(&pane, "1", false, cx);
5586        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5587
5588        pane.update_in(cx, |pane, window, cx| {
5589            pane.close_active_item(
5590                &CloseActiveItem {
5591                    save_intent: None,
5592                    close_pinned: false,
5593                },
5594                window,
5595                cx,
5596            )
5597        })
5598        .await
5599        .unwrap();
5600        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
5601
5602        pane.update_in(cx, |pane, window, cx| {
5603            pane.activate_item(3, false, false, window, cx)
5604        });
5605        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5606
5607        pane.update_in(cx, |pane, window, cx| {
5608            pane.close_active_item(
5609                &CloseActiveItem {
5610                    save_intent: None,
5611                    close_pinned: false,
5612                },
5613                window,
5614                cx,
5615            )
5616        })
5617        .await
5618        .unwrap();
5619        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5620
5621        pane.update_in(cx, |pane, window, cx| {
5622            pane.close_active_item(
5623                &CloseActiveItem {
5624                    save_intent: None,
5625                    close_pinned: false,
5626                },
5627                window,
5628                cx,
5629            )
5630        })
5631        .await
5632        .unwrap();
5633        assert_item_labels(&pane, ["A", "C*"], cx);
5634
5635        pane.update_in(cx, |pane, window, cx| {
5636            pane.close_active_item(
5637                &CloseActiveItem {
5638                    save_intent: None,
5639                    close_pinned: false,
5640                },
5641                window,
5642                cx,
5643            )
5644        })
5645        .await
5646        .unwrap();
5647        assert_item_labels(&pane, ["A*"], cx);
5648    }
5649
5650    #[gpui::test]
5651    async fn test_remove_item_ordering_neighbour(cx: &mut TestAppContext) {
5652        init_test(cx);
5653        cx.update_global::<SettingsStore, ()>(|s, cx| {
5654            s.update_user_settings::<ItemSettings>(cx, |s| {
5655                s.activate_on_close = Some(ActivateOnClose::Neighbour);
5656            });
5657        });
5658        let fs = FakeFs::new(cx.executor());
5659
5660        let project = Project::test(fs, None, cx).await;
5661        let (workspace, cx) =
5662            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5663        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5664
5665        add_labeled_item(&pane, "A", false, cx);
5666        add_labeled_item(&pane, "B", false, cx);
5667        add_labeled_item(&pane, "C", false, cx);
5668        add_labeled_item(&pane, "D", false, cx);
5669        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5670
5671        pane.update_in(cx, |pane, window, cx| {
5672            pane.activate_item(1, false, false, window, cx)
5673        });
5674        add_labeled_item(&pane, "1", false, cx);
5675        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5676
5677        pane.update_in(cx, |pane, window, cx| {
5678            pane.close_active_item(
5679                &CloseActiveItem {
5680                    save_intent: None,
5681                    close_pinned: false,
5682                },
5683                window,
5684                cx,
5685            )
5686        })
5687        .await
5688        .unwrap();
5689        assert_item_labels(&pane, ["A", "B", "C*", "D"], cx);
5690
5691        pane.update_in(cx, |pane, window, cx| {
5692            pane.activate_item(3, false, false, window, cx)
5693        });
5694        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5695
5696        pane.update_in(cx, |pane, window, cx| {
5697            pane.close_active_item(
5698                &CloseActiveItem {
5699                    save_intent: None,
5700                    close_pinned: false,
5701                },
5702                window,
5703                cx,
5704            )
5705        })
5706        .await
5707        .unwrap();
5708        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5709
5710        pane.update_in(cx, |pane, window, cx| {
5711            pane.close_active_item(
5712                &CloseActiveItem {
5713                    save_intent: None,
5714                    close_pinned: false,
5715                },
5716                window,
5717                cx,
5718            )
5719        })
5720        .await
5721        .unwrap();
5722        assert_item_labels(&pane, ["A", "B*"], cx);
5723
5724        pane.update_in(cx, |pane, window, cx| {
5725            pane.close_active_item(
5726                &CloseActiveItem {
5727                    save_intent: None,
5728                    close_pinned: false,
5729                },
5730                window,
5731                cx,
5732            )
5733        })
5734        .await
5735        .unwrap();
5736        assert_item_labels(&pane, ["A*"], cx);
5737    }
5738
5739    #[gpui::test]
5740    async fn test_remove_item_ordering_left_neighbour(cx: &mut TestAppContext) {
5741        init_test(cx);
5742        cx.update_global::<SettingsStore, ()>(|s, cx| {
5743            s.update_user_settings::<ItemSettings>(cx, |s| {
5744                s.activate_on_close = Some(ActivateOnClose::LeftNeighbour);
5745            });
5746        });
5747        let fs = FakeFs::new(cx.executor());
5748
5749        let project = Project::test(fs, None, cx).await;
5750        let (workspace, cx) =
5751            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5752        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5753
5754        add_labeled_item(&pane, "A", false, cx);
5755        add_labeled_item(&pane, "B", false, cx);
5756        add_labeled_item(&pane, "C", false, cx);
5757        add_labeled_item(&pane, "D", false, cx);
5758        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5759
5760        pane.update_in(cx, |pane, window, cx| {
5761            pane.activate_item(1, false, false, window, cx)
5762        });
5763        add_labeled_item(&pane, "1", false, cx);
5764        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5765
5766        pane.update_in(cx, |pane, window, cx| {
5767            pane.close_active_item(
5768                &CloseActiveItem {
5769                    save_intent: None,
5770                    close_pinned: false,
5771                },
5772                window,
5773                cx,
5774            )
5775        })
5776        .await
5777        .unwrap();
5778        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
5779
5780        pane.update_in(cx, |pane, window, cx| {
5781            pane.activate_item(3, false, false, window, cx)
5782        });
5783        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5784
5785        pane.update_in(cx, |pane, window, cx| {
5786            pane.close_active_item(
5787                &CloseActiveItem {
5788                    save_intent: None,
5789                    close_pinned: false,
5790                },
5791                window,
5792                cx,
5793            )
5794        })
5795        .await
5796        .unwrap();
5797        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5798
5799        pane.update_in(cx, |pane, window, cx| {
5800            pane.activate_item(0, false, false, window, cx)
5801        });
5802        assert_item_labels(&pane, ["A*", "B", "C"], cx);
5803
5804        pane.update_in(cx, |pane, window, cx| {
5805            pane.close_active_item(
5806                &CloseActiveItem {
5807                    save_intent: None,
5808                    close_pinned: false,
5809                },
5810                window,
5811                cx,
5812            )
5813        })
5814        .await
5815        .unwrap();
5816        assert_item_labels(&pane, ["B*", "C"], cx);
5817
5818        pane.update_in(cx, |pane, window, cx| {
5819            pane.close_active_item(
5820                &CloseActiveItem {
5821                    save_intent: None,
5822                    close_pinned: false,
5823                },
5824                window,
5825                cx,
5826            )
5827        })
5828        .await
5829        .unwrap();
5830        assert_item_labels(&pane, ["C*"], cx);
5831    }
5832
5833    #[gpui::test]
5834    async fn test_close_inactive_items(cx: &mut TestAppContext) {
5835        init_test(cx);
5836        let fs = FakeFs::new(cx.executor());
5837
5838        let project = Project::test(fs, None, cx).await;
5839        let (workspace, cx) =
5840            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5841        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5842
5843        let item_a = add_labeled_item(&pane, "A", false, cx);
5844        pane.update_in(cx, |pane, window, cx| {
5845            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5846            pane.pin_tab_at(ix, window, cx);
5847        });
5848        assert_item_labels(&pane, ["A*!"], cx);
5849
5850        let item_b = add_labeled_item(&pane, "B", false, cx);
5851        pane.update_in(cx, |pane, window, cx| {
5852            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5853            pane.pin_tab_at(ix, window, cx);
5854        });
5855        assert_item_labels(&pane, ["A!", "B*!"], cx);
5856
5857        add_labeled_item(&pane, "C", false, cx);
5858        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
5859
5860        add_labeled_item(&pane, "D", false, cx);
5861        add_labeled_item(&pane, "E", false, cx);
5862        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
5863
5864        pane.update_in(cx, |pane, window, cx| {
5865            pane.close_other_items(
5866                &CloseOtherItems {
5867                    save_intent: None,
5868                    close_pinned: false,
5869                },
5870                None,
5871                window,
5872                cx,
5873            )
5874        })
5875        .await
5876        .unwrap();
5877        assert_item_labels(&pane, ["A!", "B!", "E*"], cx);
5878    }
5879
5880    #[gpui::test]
5881    async fn test_running_close_inactive_items_via_an_inactive_item(cx: &mut TestAppContext) {
5882        init_test(cx);
5883        let fs = FakeFs::new(cx.executor());
5884
5885        let project = Project::test(fs, None, cx).await;
5886        let (workspace, cx) =
5887            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5888        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5889
5890        add_labeled_item(&pane, "A", false, cx);
5891        assert_item_labels(&pane, ["A*"], cx);
5892
5893        let item_b = add_labeled_item(&pane, "B", false, cx);
5894        assert_item_labels(&pane, ["A", "B*"], cx);
5895
5896        add_labeled_item(&pane, "C", false, cx);
5897        add_labeled_item(&pane, "D", false, cx);
5898        add_labeled_item(&pane, "E", false, cx);
5899        assert_item_labels(&pane, ["A", "B", "C", "D", "E*"], cx);
5900
5901        pane.update_in(cx, |pane, window, cx| {
5902            pane.close_other_items(
5903                &CloseOtherItems {
5904                    save_intent: None,
5905                    close_pinned: false,
5906                },
5907                Some(item_b.item_id()),
5908                window,
5909                cx,
5910            )
5911        })
5912        .await
5913        .unwrap();
5914        assert_item_labels(&pane, ["B*"], cx);
5915    }
5916
5917    #[gpui::test]
5918    async fn test_close_clean_items(cx: &mut TestAppContext) {
5919        init_test(cx);
5920        let fs = FakeFs::new(cx.executor());
5921
5922        let project = Project::test(fs, None, cx).await;
5923        let (workspace, cx) =
5924            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5925        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5926
5927        add_labeled_item(&pane, "A", true, cx);
5928        add_labeled_item(&pane, "B", false, cx);
5929        add_labeled_item(&pane, "C", true, cx);
5930        add_labeled_item(&pane, "D", false, cx);
5931        add_labeled_item(&pane, "E", false, cx);
5932        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
5933
5934        pane.update_in(cx, |pane, window, cx| {
5935            pane.close_clean_items(
5936                &CloseCleanItems {
5937                    close_pinned: false,
5938                },
5939                window,
5940                cx,
5941            )
5942        })
5943        .await
5944        .unwrap();
5945        assert_item_labels(&pane, ["A^", "C*^"], cx);
5946    }
5947
5948    #[gpui::test]
5949    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
5950        init_test(cx);
5951        let fs = FakeFs::new(cx.executor());
5952
5953        let project = Project::test(fs, None, cx).await;
5954        let (workspace, cx) =
5955            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5956        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5957
5958        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
5959
5960        pane.update_in(cx, |pane, window, cx| {
5961            pane.close_items_to_the_left_by_id(
5962                None,
5963                &CloseItemsToTheLeft {
5964                    close_pinned: false,
5965                },
5966                window,
5967                cx,
5968            )
5969        })
5970        .await
5971        .unwrap();
5972        assert_item_labels(&pane, ["C*", "D", "E"], cx);
5973    }
5974
5975    #[gpui::test]
5976    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
5977        init_test(cx);
5978        let fs = FakeFs::new(cx.executor());
5979
5980        let project = Project::test(fs, None, cx).await;
5981        let (workspace, cx) =
5982            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5983        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5984
5985        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
5986
5987        pane.update_in(cx, |pane, window, cx| {
5988            pane.close_items_to_the_right_by_id(
5989                None,
5990                &CloseItemsToTheRight {
5991                    close_pinned: false,
5992                },
5993                window,
5994                cx,
5995            )
5996        })
5997        .await
5998        .unwrap();
5999        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6000    }
6001
6002    #[gpui::test]
6003    async fn test_close_all_items(cx: &mut TestAppContext) {
6004        init_test(cx);
6005        let fs = FakeFs::new(cx.executor());
6006
6007        let project = Project::test(fs, None, cx).await;
6008        let (workspace, cx) =
6009            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6010        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6011
6012        let item_a = add_labeled_item(&pane, "A", false, cx);
6013        add_labeled_item(&pane, "B", false, cx);
6014        add_labeled_item(&pane, "C", false, cx);
6015        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6016
6017        pane.update_in(cx, |pane, window, cx| {
6018            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6019            pane.pin_tab_at(ix, window, cx);
6020            pane.close_all_items(
6021                &CloseAllItems {
6022                    save_intent: None,
6023                    close_pinned: false,
6024                },
6025                window,
6026                cx,
6027            )
6028        })
6029        .await
6030        .unwrap();
6031        assert_item_labels(&pane, ["A*!"], cx);
6032
6033        pane.update_in(cx, |pane, window, cx| {
6034            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6035            pane.unpin_tab_at(ix, window, cx);
6036            pane.close_all_items(
6037                &CloseAllItems {
6038                    save_intent: None,
6039                    close_pinned: false,
6040                },
6041                window,
6042                cx,
6043            )
6044        })
6045        .await
6046        .unwrap();
6047
6048        assert_item_labels(&pane, [], cx);
6049
6050        add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6051            item.project_items
6052                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6053        });
6054        add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6055            item.project_items
6056                .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6057        });
6058        add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6059            item.project_items
6060                .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6061        });
6062        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6063
6064        let save = pane.update_in(cx, |pane, window, cx| {
6065            pane.close_all_items(
6066                &CloseAllItems {
6067                    save_intent: None,
6068                    close_pinned: false,
6069                },
6070                window,
6071                cx,
6072            )
6073        });
6074
6075        cx.executor().run_until_parked();
6076        cx.simulate_prompt_answer("Save all");
6077        save.await.unwrap();
6078        assert_item_labels(&pane, [], cx);
6079
6080        add_labeled_item(&pane, "A", true, cx);
6081        add_labeled_item(&pane, "B", true, cx);
6082        add_labeled_item(&pane, "C", true, cx);
6083        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6084        let save = pane.update_in(cx, |pane, window, cx| {
6085            pane.close_all_items(
6086                &CloseAllItems {
6087                    save_intent: None,
6088                    close_pinned: false,
6089                },
6090                window,
6091                cx,
6092            )
6093        });
6094
6095        cx.executor().run_until_parked();
6096        cx.simulate_prompt_answer("Discard all");
6097        save.await.unwrap();
6098        assert_item_labels(&pane, [], cx);
6099    }
6100
6101    #[gpui::test]
6102    async fn test_close_with_save_intent(cx: &mut TestAppContext) {
6103        init_test(cx);
6104        let fs = FakeFs::new(cx.executor());
6105
6106        let project = Project::test(fs, None, cx).await;
6107        let (workspace, cx) =
6108            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6109        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6110
6111        let a = cx.update(|_, cx| TestProjectItem::new_dirty(1, "A.txt", cx));
6112        let b = cx.update(|_, cx| TestProjectItem::new_dirty(1, "B.txt", cx));
6113        let c = cx.update(|_, cx| TestProjectItem::new_dirty(1, "C.txt", cx));
6114
6115        add_labeled_item(&pane, "AB", true, cx).update(cx, |item, _| {
6116            item.project_items.push(a.clone());
6117            item.project_items.push(b.clone());
6118        });
6119        add_labeled_item(&pane, "C", true, cx)
6120            .update(cx, |item, _| item.project_items.push(c.clone()));
6121        assert_item_labels(&pane, ["AB^", "C*^"], cx);
6122
6123        pane.update_in(cx, |pane, window, cx| {
6124            pane.close_all_items(
6125                &CloseAllItems {
6126                    save_intent: Some(SaveIntent::Save),
6127                    close_pinned: false,
6128                },
6129                window,
6130                cx,
6131            )
6132        })
6133        .await
6134        .unwrap();
6135
6136        assert_item_labels(&pane, [], cx);
6137        cx.update(|_, cx| {
6138            assert!(!a.read(cx).is_dirty);
6139            assert!(!b.read(cx).is_dirty);
6140            assert!(!c.read(cx).is_dirty);
6141        });
6142    }
6143
6144    #[gpui::test]
6145    async fn test_close_all_items_including_pinned(cx: &mut TestAppContext) {
6146        init_test(cx);
6147        let fs = FakeFs::new(cx.executor());
6148
6149        let project = Project::test(fs, None, cx).await;
6150        let (workspace, cx) =
6151            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6152        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6153
6154        let item_a = add_labeled_item(&pane, "A", false, cx);
6155        add_labeled_item(&pane, "B", false, cx);
6156        add_labeled_item(&pane, "C", false, cx);
6157        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6158
6159        pane.update_in(cx, |pane, window, cx| {
6160            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6161            pane.pin_tab_at(ix, window, cx);
6162            pane.close_all_items(
6163                &CloseAllItems {
6164                    save_intent: None,
6165                    close_pinned: true,
6166                },
6167                window,
6168                cx,
6169            )
6170        })
6171        .await
6172        .unwrap();
6173        assert_item_labels(&pane, [], cx);
6174    }
6175
6176    #[gpui::test]
6177    async fn test_close_pinned_tab_with_non_pinned_in_same_pane(cx: &mut TestAppContext) {
6178        init_test(cx);
6179        let fs = FakeFs::new(cx.executor());
6180        let project = Project::test(fs, None, cx).await;
6181        let (workspace, cx) =
6182            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6183
6184        // Non-pinned tabs in same pane
6185        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6186        add_labeled_item(&pane, "A", false, cx);
6187        add_labeled_item(&pane, "B", false, cx);
6188        add_labeled_item(&pane, "C", false, cx);
6189        pane.update_in(cx, |pane, window, cx| {
6190            pane.pin_tab_at(0, window, cx);
6191        });
6192        set_labeled_items(&pane, ["A*", "B", "C"], cx);
6193        pane.update_in(cx, |pane, window, cx| {
6194            pane.close_active_item(
6195                &CloseActiveItem {
6196                    save_intent: None,
6197                    close_pinned: false,
6198                },
6199                window,
6200                cx,
6201            )
6202            .unwrap();
6203        });
6204        // Non-pinned tab should be active
6205        assert_item_labels(&pane, ["A!", "B*", "C"], cx);
6206    }
6207
6208    #[gpui::test]
6209    async fn test_close_pinned_tab_with_non_pinned_in_different_pane(cx: &mut TestAppContext) {
6210        init_test(cx);
6211        let fs = FakeFs::new(cx.executor());
6212        let project = Project::test(fs, None, cx).await;
6213        let (workspace, cx) =
6214            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6215
6216        // No non-pinned tabs in same pane, non-pinned tabs in another pane
6217        let pane1 = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6218        let pane2 = workspace.update_in(cx, |workspace, window, cx| {
6219            workspace.split_pane(pane1.clone(), SplitDirection::Right, window, cx)
6220        });
6221        add_labeled_item(&pane1, "A", false, cx);
6222        pane1.update_in(cx, |pane, window, cx| {
6223            pane.pin_tab_at(0, window, cx);
6224        });
6225        set_labeled_items(&pane1, ["A*"], cx);
6226        add_labeled_item(&pane2, "B", false, cx);
6227        set_labeled_items(&pane2, ["B"], cx);
6228        pane1.update_in(cx, |pane, window, cx| {
6229            pane.close_active_item(
6230                &CloseActiveItem {
6231                    save_intent: None,
6232                    close_pinned: false,
6233                },
6234                window,
6235                cx,
6236            )
6237            .unwrap();
6238        });
6239        //  Non-pinned tab of other pane should be active
6240        assert_item_labels(&pane2, ["B*"], cx);
6241    }
6242
6243    #[gpui::test]
6244    async fn ensure_item_closing_actions_do_not_panic_when_no_items_exist(cx: &mut TestAppContext) {
6245        init_test(cx);
6246        let fs = FakeFs::new(cx.executor());
6247        let project = Project::test(fs, None, cx).await;
6248        let (workspace, cx) =
6249            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6250
6251        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6252        assert_item_labels(&pane, [], cx);
6253
6254        pane.update_in(cx, |pane, window, cx| {
6255            pane.close_active_item(
6256                &CloseActiveItem {
6257                    save_intent: None,
6258                    close_pinned: false,
6259                },
6260                window,
6261                cx,
6262            )
6263        })
6264        .await
6265        .unwrap();
6266
6267        pane.update_in(cx, |pane, window, cx| {
6268            pane.close_other_items(
6269                &CloseOtherItems {
6270                    save_intent: None,
6271                    close_pinned: false,
6272                },
6273                None,
6274                window,
6275                cx,
6276            )
6277        })
6278        .await
6279        .unwrap();
6280
6281        pane.update_in(cx, |pane, window, cx| {
6282            pane.close_all_items(
6283                &CloseAllItems {
6284                    save_intent: None,
6285                    close_pinned: false,
6286                },
6287                window,
6288                cx,
6289            )
6290        })
6291        .await
6292        .unwrap();
6293
6294        pane.update_in(cx, |pane, window, cx| {
6295            pane.close_clean_items(
6296                &CloseCleanItems {
6297                    close_pinned: false,
6298                },
6299                window,
6300                cx,
6301            )
6302        })
6303        .await
6304        .unwrap();
6305
6306        pane.update_in(cx, |pane, window, cx| {
6307            pane.close_items_to_the_right_by_id(
6308                None,
6309                &CloseItemsToTheRight {
6310                    close_pinned: false,
6311                },
6312                window,
6313                cx,
6314            )
6315        })
6316        .await
6317        .unwrap();
6318
6319        pane.update_in(cx, |pane, window, cx| {
6320            pane.close_items_to_the_left_by_id(
6321                None,
6322                &CloseItemsToTheLeft {
6323                    close_pinned: false,
6324                },
6325                window,
6326                cx,
6327            )
6328        })
6329        .await
6330        .unwrap();
6331    }
6332
6333    fn init_test(cx: &mut TestAppContext) {
6334        cx.update(|cx| {
6335            let settings_store = SettingsStore::test(cx);
6336            cx.set_global(settings_store);
6337            theme::init(LoadThemes::JustBase, cx);
6338            crate::init_settings(cx);
6339            Project::init_settings(cx);
6340        });
6341    }
6342
6343    fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
6344        cx.update_global(|store: &mut SettingsStore, cx| {
6345            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
6346                settings.max_tabs = value.map(|v| NonZero::new(v).unwrap())
6347            });
6348        });
6349    }
6350
6351    fn add_labeled_item(
6352        pane: &Entity<Pane>,
6353        label: &str,
6354        is_dirty: bool,
6355        cx: &mut VisualTestContext,
6356    ) -> Box<Entity<TestItem>> {
6357        pane.update_in(cx, |pane, window, cx| {
6358            let labeled_item =
6359                Box::new(cx.new(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)));
6360            pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6361            labeled_item
6362        })
6363    }
6364
6365    fn set_labeled_items<const COUNT: usize>(
6366        pane: &Entity<Pane>,
6367        labels: [&str; COUNT],
6368        cx: &mut VisualTestContext,
6369    ) -> [Box<Entity<TestItem>>; COUNT] {
6370        pane.update_in(cx, |pane, window, cx| {
6371            pane.items.clear();
6372            let mut active_item_index = 0;
6373
6374            let mut index = 0;
6375            let items = labels.map(|mut label| {
6376                if label.ends_with('*') {
6377                    label = label.trim_end_matches('*');
6378                    active_item_index = index;
6379                }
6380
6381                let labeled_item = Box::new(cx.new(|cx| TestItem::new(cx).with_label(label)));
6382                pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6383                index += 1;
6384                labeled_item
6385            });
6386
6387            pane.activate_item(active_item_index, false, false, window, cx);
6388
6389            items
6390        })
6391    }
6392
6393    // Assert the item label, with the active item label suffixed with a '*'
6394    #[track_caller]
6395    fn assert_item_labels<const COUNT: usize>(
6396        pane: &Entity<Pane>,
6397        expected_states: [&str; COUNT],
6398        cx: &mut VisualTestContext,
6399    ) {
6400        let actual_states = pane.update(cx, |pane, cx| {
6401            pane.items
6402                .iter()
6403                .enumerate()
6404                .map(|(ix, item)| {
6405                    let mut state = item
6406                        .to_any()
6407                        .downcast::<TestItem>()
6408                        .unwrap()
6409                        .read(cx)
6410                        .label
6411                        .clone();
6412                    if ix == pane.active_item_index {
6413                        state.push('*');
6414                    }
6415                    if item.is_dirty(cx) {
6416                        state.push('^');
6417                    }
6418                    if pane.is_tab_pinned(ix) {
6419                        state.push('!');
6420                    }
6421                    state
6422                })
6423                .collect::<Vec<_>>()
6424        });
6425        assert_eq!(
6426            actual_states, expected_states,
6427            "pane items do not match expectation"
6428        );
6429    }
6430}