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