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