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