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