pane.rs

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