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, IsZero, 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().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 item_id = item.item_id();
2595        let is_first_item = ix == 0;
2596        let is_last_item = ix == self.items.len() - 1;
2597        let is_pinned = self.is_tab_pinned(ix);
2598        let position_relative_to_active_item = ix.cmp(&self.active_item_index);
2599
2600        let tab = Tab::new(ix)
2601            .position(if is_first_item {
2602                TabPosition::First
2603            } else if is_last_item {
2604                TabPosition::Last
2605            } else {
2606                TabPosition::Middle(position_relative_to_active_item)
2607            })
2608            .close_side(match close_side {
2609                ClosePosition::Left => ui::TabCloseSide::Start,
2610                ClosePosition::Right => ui::TabCloseSide::End,
2611            })
2612            .toggle_state(is_active)
2613            .on_click(cx.listener(move |pane: &mut Self, _, window, cx| {
2614                pane.activate_item(ix, true, true, window, cx)
2615            }))
2616            // TODO: This should be a click listener with the middle mouse button instead of a mouse down listener.
2617            .on_mouse_down(
2618                MouseButton::Middle,
2619                cx.listener(move |pane, _event, window, cx| {
2620                    pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2621                        .detach_and_log_err(cx);
2622                }),
2623            )
2624            .on_mouse_down(
2625                MouseButton::Left,
2626                cx.listener(move |pane, event: &MouseDownEvent, _, cx| {
2627                    if let Some(id) = pane.preview_item_id
2628                        && id == item_id
2629                        && event.click_count > 1
2630                    {
2631                        pane.set_preview_item_id(None, cx);
2632                    }
2633                }),
2634            )
2635            .on_drag(
2636                DraggedTab {
2637                    item: item.boxed_clone(),
2638                    pane: cx.entity(),
2639                    detail,
2640                    is_active,
2641                    ix,
2642                },
2643                |tab, _, _, cx| cx.new(|_| tab.clone()),
2644            )
2645            .drag_over::<DraggedTab>(move |tab, dragged_tab: &DraggedTab, _, cx| {
2646                let mut styled_tab = tab
2647                    .bg(cx.theme().colors().drop_target_background)
2648                    .border_color(cx.theme().colors().drop_target_border)
2649                    .border_0();
2650
2651                if ix < dragged_tab.ix {
2652                    styled_tab = styled_tab.border_l_2();
2653                } else if ix > dragged_tab.ix {
2654                    styled_tab = styled_tab.border_r_2();
2655                }
2656
2657                styled_tab
2658            })
2659            .drag_over::<DraggedSelection>(|tab, _, _, cx| {
2660                tab.bg(cx.theme().colors().drop_target_background)
2661            })
2662            .when_some(self.can_drop_predicate.clone(), |this, p| {
2663                this.can_drop(move |a, window, cx| p(a, window, cx))
2664            })
2665            .on_drop(
2666                cx.listener(move |this, dragged_tab: &DraggedTab, window, cx| {
2667                    this.drag_split_direction = None;
2668                    this.handle_tab_drop(dragged_tab, ix, window, cx)
2669                }),
2670            )
2671            .on_drop(
2672                cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2673                    this.drag_split_direction = None;
2674                    this.handle_dragged_selection_drop(selection, Some(ix), window, cx)
2675                }),
2676            )
2677            .on_drop(cx.listener(move |this, paths, window, cx| {
2678                this.drag_split_direction = None;
2679                this.handle_external_paths_drop(paths, window, cx)
2680            }))
2681            .when_some(item.tab_tooltip_content(cx), |tab, content| match content {
2682                TabTooltipContent::Text(text) => tab.tooltip(Tooltip::text(text)),
2683                TabTooltipContent::Custom(element_fn) => {
2684                    tab.tooltip(move |window, cx| element_fn(window, cx))
2685                }
2686            })
2687            .start_slot::<Indicator>(indicator)
2688            .map(|this| {
2689                let end_slot_action: &'static dyn Action;
2690                let end_slot_tooltip_text: &'static str;
2691                let end_slot = if is_pinned {
2692                    end_slot_action = &TogglePinTab;
2693                    end_slot_tooltip_text = "Unpin Tab";
2694                    IconButton::new("unpin tab", IconName::Pin)
2695                        .shape(IconButtonShape::Square)
2696                        .icon_color(Color::Muted)
2697                        .size(ButtonSize::None)
2698                        .icon_size(IconSize::Small)
2699                        .on_click(cx.listener(move |pane, _, window, cx| {
2700                            pane.unpin_tab_at(ix, window, cx);
2701                        }))
2702                } else {
2703                    end_slot_action = &CloseActiveItem {
2704                        save_intent: None,
2705                        close_pinned: false,
2706                    };
2707                    end_slot_tooltip_text = "Close Tab";
2708                    match show_close_button {
2709                        ShowCloseButton::Always => IconButton::new("close tab", IconName::Close),
2710                        ShowCloseButton::Hover => {
2711                            IconButton::new("close tab", IconName::Close).visible_on_hover("")
2712                        }
2713                        ShowCloseButton::Hidden => return this,
2714                    }
2715                    .shape(IconButtonShape::Square)
2716                    .icon_color(Color::Muted)
2717                    .size(ButtonSize::None)
2718                    .icon_size(IconSize::Small)
2719                    .on_click(cx.listener(move |pane, _, window, cx| {
2720                        pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2721                            .detach_and_log_err(cx);
2722                    }))
2723                }
2724                .map(|this| {
2725                    if is_active {
2726                        let focus_handle = focus_handle.clone();
2727                        this.tooltip(move |_window, cx| {
2728                            Tooltip::for_action_in(
2729                                end_slot_tooltip_text,
2730                                end_slot_action,
2731                                &focus_handle,
2732                                cx,
2733                            )
2734                        })
2735                    } else {
2736                        this.tooltip(Tooltip::text(end_slot_tooltip_text))
2737                    }
2738                });
2739                this.end_slot(end_slot)
2740            })
2741            .child(
2742                h_flex()
2743                    .gap_1()
2744                    .items_center()
2745                    .children(
2746                        std::iter::once(if let Some(decorated_icon) = decorated_icon {
2747                            Some(div().child(decorated_icon.into_any_element()))
2748                        } else {
2749                            icon.map(|icon| div().child(icon.into_any_element()))
2750                        })
2751                        .flatten(),
2752                    )
2753                    .child(label),
2754            );
2755
2756        let single_entry_to_resolve = (self.items[ix].buffer_kind(cx) == ItemBufferKind::Singleton)
2757            .then(|| self.items[ix].project_entry_ids(cx).get(0).copied())
2758            .flatten();
2759
2760        let total_items = self.items.len();
2761        let has_multibuffer_items = self
2762            .items
2763            .iter()
2764            .any(|item| item.buffer_kind(cx) == ItemBufferKind::Multibuffer);
2765        let has_items_to_left = ix > 0;
2766        let has_items_to_right = ix < total_items - 1;
2767        let has_clean_items = self.items.iter().any(|item| !item.is_dirty(cx));
2768        let is_pinned = self.is_tab_pinned(ix);
2769        let pane = cx.entity().downgrade();
2770        let menu_context = item.item_focus_handle(cx);
2771        right_click_menu(ix)
2772            .trigger(|_, _, _| tab)
2773            .menu(move |window, cx| {
2774                let pane = pane.clone();
2775                let menu_context = menu_context.clone();
2776                ContextMenu::build(window, cx, move |mut menu, window, cx| {
2777                    let close_active_item_action = CloseActiveItem {
2778                        save_intent: None,
2779                        close_pinned: true,
2780                    };
2781                    let close_inactive_items_action = CloseOtherItems {
2782                        save_intent: None,
2783                        close_pinned: false,
2784                    };
2785                    let close_multibuffers_action = CloseMultibufferItems {
2786                        save_intent: None,
2787                        close_pinned: false,
2788                    };
2789                    let close_items_to_the_left_action = CloseItemsToTheLeft {
2790                        close_pinned: false,
2791                    };
2792                    let close_items_to_the_right_action = CloseItemsToTheRight {
2793                        close_pinned: false,
2794                    };
2795                    let close_clean_items_action = CloseCleanItems {
2796                        close_pinned: false,
2797                    };
2798                    let close_all_items_action = CloseAllItems {
2799                        save_intent: None,
2800                        close_pinned: false,
2801                    };
2802                    if let Some(pane) = pane.upgrade() {
2803                        menu = menu
2804                            .entry(
2805                                "Close",
2806                                Some(Box::new(close_active_item_action)),
2807                                window.handler_for(&pane, move |pane, window, cx| {
2808                                    pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2809                                        .detach_and_log_err(cx);
2810                                }),
2811                            )
2812                            .item(ContextMenuItem::Entry(
2813                                ContextMenuEntry::new("Close Others")
2814                                    .action(Box::new(close_inactive_items_action.clone()))
2815                                    .disabled(total_items == 1)
2816                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2817                                        pane.close_other_items(
2818                                            &close_inactive_items_action,
2819                                            Some(item_id),
2820                                            window,
2821                                            cx,
2822                                        )
2823                                        .detach_and_log_err(cx);
2824                                    })),
2825                            ))
2826                            // We make this optional, instead of using disabled as to not overwhelm the context menu unnecessarily
2827                            .extend(has_multibuffer_items.then(|| {
2828                                ContextMenuItem::Entry(
2829                                    ContextMenuEntry::new("Close Multibuffers")
2830                                        .action(Box::new(close_multibuffers_action.clone()))
2831                                        .handler(window.handler_for(
2832                                            &pane,
2833                                            move |pane, window, cx| {
2834                                                pane.close_multibuffer_items(
2835                                                    &close_multibuffers_action,
2836                                                    window,
2837                                                    cx,
2838                                                )
2839                                                .detach_and_log_err(cx);
2840                                            },
2841                                        )),
2842                                )
2843                            }))
2844                            .separator()
2845                            .item(ContextMenuItem::Entry(
2846                                ContextMenuEntry::new("Close Left")
2847                                    .action(Box::new(close_items_to_the_left_action.clone()))
2848                                    .disabled(!has_items_to_left)
2849                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2850                                        pane.close_items_to_the_left_by_id(
2851                                            Some(item_id),
2852                                            &close_items_to_the_left_action,
2853                                            window,
2854                                            cx,
2855                                        )
2856                                        .detach_and_log_err(cx);
2857                                    })),
2858                            ))
2859                            .item(ContextMenuItem::Entry(
2860                                ContextMenuEntry::new("Close Right")
2861                                    .action(Box::new(close_items_to_the_right_action.clone()))
2862                                    .disabled(!has_items_to_right)
2863                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2864                                        pane.close_items_to_the_right_by_id(
2865                                            Some(item_id),
2866                                            &close_items_to_the_right_action,
2867                                            window,
2868                                            cx,
2869                                        )
2870                                        .detach_and_log_err(cx);
2871                                    })),
2872                            ))
2873                            .separator()
2874                            .item(ContextMenuItem::Entry(
2875                                ContextMenuEntry::new("Close Clean")
2876                                    .action(Box::new(close_clean_items_action.clone()))
2877                                    .disabled(!has_clean_items)
2878                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2879                                        pane.close_clean_items(
2880                                            &close_clean_items_action,
2881                                            window,
2882                                            cx,
2883                                        )
2884                                        .detach_and_log_err(cx)
2885                                    })),
2886                            ))
2887                            .entry(
2888                                "Close All",
2889                                Some(Box::new(close_all_items_action.clone())),
2890                                window.handler_for(&pane, move |pane, window, cx| {
2891                                    pane.close_all_items(&close_all_items_action, window, cx)
2892                                        .detach_and_log_err(cx)
2893                                }),
2894                            );
2895
2896                        let pin_tab_entries = |menu: ContextMenu| {
2897                            menu.separator().map(|this| {
2898                                if is_pinned {
2899                                    this.entry(
2900                                        "Unpin Tab",
2901                                        Some(TogglePinTab.boxed_clone()),
2902                                        window.handler_for(&pane, move |pane, window, cx| {
2903                                            pane.unpin_tab_at(ix, window, cx);
2904                                        }),
2905                                    )
2906                                } else {
2907                                    this.entry(
2908                                        "Pin Tab",
2909                                        Some(TogglePinTab.boxed_clone()),
2910                                        window.handler_for(&pane, move |pane, window, cx| {
2911                                            pane.pin_tab_at(ix, window, cx);
2912                                        }),
2913                                    )
2914                                }
2915                            })
2916                        };
2917                        if let Some(entry) = single_entry_to_resolve {
2918                            let project_path = pane
2919                                .read(cx)
2920                                .item_for_entry(entry, cx)
2921                                .and_then(|item| item.project_path(cx));
2922                            let worktree = project_path.as_ref().and_then(|project_path| {
2923                                pane.read(cx)
2924                                    .project
2925                                    .upgrade()?
2926                                    .read(cx)
2927                                    .worktree_for_id(project_path.worktree_id, cx)
2928                            });
2929                            let has_relative_path = worktree.as_ref().is_some_and(|worktree| {
2930                                worktree
2931                                    .read(cx)
2932                                    .root_entry()
2933                                    .is_some_and(|entry| entry.is_dir())
2934                            });
2935
2936                            let entry_abs_path = pane.read(cx).entry_abs_path(entry, cx);
2937                            let parent_abs_path = entry_abs_path
2938                                .as_deref()
2939                                .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
2940                            let relative_path = project_path
2941                                .map(|project_path| project_path.path)
2942                                .filter(|_| has_relative_path);
2943
2944                            let visible_in_project_panel = relative_path.is_some()
2945                                && worktree.is_some_and(|worktree| worktree.read(cx).is_visible());
2946
2947                            let entry_id = entry.to_proto();
2948                            menu = menu
2949                                .separator()
2950                                .when_some(entry_abs_path, |menu, abs_path| {
2951                                    menu.entry(
2952                                        "Copy Path",
2953                                        Some(Box::new(zed_actions::workspace::CopyPath)),
2954                                        window.handler_for(&pane, move |_, _, cx| {
2955                                            cx.write_to_clipboard(ClipboardItem::new_string(
2956                                                abs_path.to_string_lossy().into_owned(),
2957                                            ));
2958                                        }),
2959                                    )
2960                                })
2961                                .when_some(relative_path, |menu, relative_path| {
2962                                    menu.entry(
2963                                        "Copy Relative Path",
2964                                        Some(Box::new(zed_actions::workspace::CopyRelativePath)),
2965                                        window.handler_for(&pane, move |this, _, cx| {
2966                                            let Some(project) = this.project.upgrade() else {
2967                                                return;
2968                                            };
2969                                            let path_style = project
2970                                                .update(cx, |project, cx| project.path_style(cx));
2971                                            cx.write_to_clipboard(ClipboardItem::new_string(
2972                                                relative_path.display(path_style).to_string(),
2973                                            ));
2974                                        }),
2975                                    )
2976                                })
2977                                .map(pin_tab_entries)
2978                                .separator()
2979                                .when(visible_in_project_panel, |menu| {
2980                                    menu.entry(
2981                                        "Reveal In Project Panel",
2982                                        Some(Box::new(RevealInProjectPanel::default())),
2983                                        window.handler_for(&pane, move |pane, _, cx| {
2984                                            pane.project
2985                                                .update(cx, |_, cx| {
2986                                                    cx.emit(project::Event::RevealInProjectPanel(
2987                                                        ProjectEntryId::from_proto(entry_id),
2988                                                    ))
2989                                                })
2990                                                .ok();
2991                                        }),
2992                                    )
2993                                })
2994                                .when_some(parent_abs_path, |menu, parent_abs_path| {
2995                                    menu.entry(
2996                                        "Open in Terminal",
2997                                        Some(Box::new(OpenInTerminal)),
2998                                        window.handler_for(&pane, move |_, window, cx| {
2999                                            window.dispatch_action(
3000                                                OpenTerminal {
3001                                                    working_directory: parent_abs_path.clone(),
3002                                                }
3003                                                .boxed_clone(),
3004                                                cx,
3005                                            );
3006                                        }),
3007                                    )
3008                                });
3009                        } else {
3010                            menu = menu.map(pin_tab_entries);
3011                        }
3012                    }
3013
3014                    menu.context(menu_context)
3015                })
3016            })
3017    }
3018
3019    fn render_tab_bar(&mut self, window: &mut Window, cx: &mut Context<Pane>) -> AnyElement {
3020        let focus_handle = self.focus_handle.clone();
3021        let navigate_backward = IconButton::new("navigate_backward", IconName::ArrowLeft)
3022            .icon_size(IconSize::Small)
3023            .on_click({
3024                let entity = cx.entity();
3025                move |_, window, cx| {
3026                    entity.update(cx, |pane, cx| {
3027                        pane.navigate_backward(&Default::default(), window, cx)
3028                    })
3029                }
3030            })
3031            .disabled(!self.can_navigate_backward())
3032            .tooltip({
3033                let focus_handle = focus_handle.clone();
3034                move |_window, cx| Tooltip::for_action_in("Go Back", &GoBack, &focus_handle, cx)
3035            });
3036
3037        let navigate_forward = IconButton::new("navigate_forward", IconName::ArrowRight)
3038            .icon_size(IconSize::Small)
3039            .on_click({
3040                let entity = cx.entity();
3041                move |_, window, cx| {
3042                    entity.update(cx, |pane, cx| {
3043                        pane.navigate_forward(&Default::default(), window, cx)
3044                    })
3045                }
3046            })
3047            .disabled(!self.can_navigate_forward())
3048            .tooltip({
3049                let focus_handle = focus_handle.clone();
3050                move |_window, cx| {
3051                    Tooltip::for_action_in("Go Forward", &GoForward, &focus_handle, cx)
3052                }
3053            });
3054
3055        let mut tab_items = self
3056            .items
3057            .iter()
3058            .enumerate()
3059            .zip(tab_details(&self.items, window, cx))
3060            .map(|((ix, item), detail)| {
3061                self.render_tab(ix, &**item, detail, &focus_handle, window, cx)
3062            })
3063            .collect::<Vec<_>>();
3064        let tab_count = tab_items.len();
3065        if self.is_tab_pinned(tab_count) {
3066            log::warn!(
3067                "Pinned tab count ({}) exceeds actual tab count ({}). \
3068                This should not happen. If possible, add reproduction steps, \
3069                in a comment, to https://github.com/zed-industries/zed/issues/33342",
3070                self.pinned_tab_count,
3071                tab_count
3072            );
3073            self.pinned_tab_count = tab_count;
3074        }
3075        let unpinned_tabs = tab_items.split_off(self.pinned_tab_count);
3076        let pinned_tabs = tab_items;
3077        TabBar::new("tab_bar")
3078            .when(
3079                self.display_nav_history_buttons.unwrap_or_default(),
3080                |tab_bar| {
3081                    tab_bar
3082                        .start_child(navigate_backward)
3083                        .start_child(navigate_forward)
3084                },
3085            )
3086            .map(|tab_bar| {
3087                if self.show_tab_bar_buttons {
3088                    let render_tab_buttons = self.render_tab_bar_buttons.clone();
3089                    let (left_children, right_children) = render_tab_buttons(self, window, cx);
3090                    tab_bar
3091                        .start_children(left_children)
3092                        .end_children(right_children)
3093                } else {
3094                    tab_bar
3095                }
3096            })
3097            .children(pinned_tabs.len().ne(&0).then(|| {
3098                let max_scroll = self.tab_bar_scroll_handle.max_offset().width;
3099                // We need to check both because offset returns delta values even when the scroll handle is not scrollable
3100                let is_scrollable = !max_scroll.is_zero();
3101                let is_scrolled = self.tab_bar_scroll_handle.offset().x < px(0.);
3102                let has_active_unpinned_tab = self.active_item_index >= self.pinned_tab_count;
3103                h_flex()
3104                    .children(pinned_tabs)
3105                    .when(is_scrollable && is_scrolled, |this| {
3106                        this.when(has_active_unpinned_tab, |this| this.border_r_2())
3107                            .when(!has_active_unpinned_tab, |this| this.border_r_1())
3108                            .border_color(cx.theme().colors().border)
3109                    })
3110            }))
3111            .child(
3112                h_flex()
3113                    .id("unpinned tabs")
3114                    .overflow_x_scroll()
3115                    .w_full()
3116                    .track_scroll(&self.tab_bar_scroll_handle)
3117                    .on_scroll_wheel(cx.listener(|this, _, _, _| {
3118                        this.suppress_scroll = true;
3119                    }))
3120                    .children(unpinned_tabs)
3121                    .child(
3122                        div()
3123                            .id("tab_bar_drop_target")
3124                            .min_w_6()
3125                            // HACK: This empty child is currently necessary to force the drop target to appear
3126                            // despite us setting a min width above.
3127                            .child("")
3128                            // HACK: h_full doesn't occupy the complete height, using fixed height instead
3129                            .h(Tab::container_height(cx))
3130                            .flex_grow()
3131                            .drag_over::<DraggedTab>(|bar, _, _, cx| {
3132                                bar.bg(cx.theme().colors().drop_target_background)
3133                            })
3134                            .drag_over::<DraggedSelection>(|bar, _, _, cx| {
3135                                bar.bg(cx.theme().colors().drop_target_background)
3136                            })
3137                            .on_drop(cx.listener(
3138                                move |this, dragged_tab: &DraggedTab, window, cx| {
3139                                    this.drag_split_direction = None;
3140                                    this.handle_tab_drop(dragged_tab, this.items.len(), window, cx)
3141                                },
3142                            ))
3143                            .on_drop(cx.listener(
3144                                move |this, selection: &DraggedSelection, window, cx| {
3145                                    this.drag_split_direction = None;
3146                                    this.handle_project_entry_drop(
3147                                        &selection.active_selection.entry_id,
3148                                        Some(tab_count),
3149                                        window,
3150                                        cx,
3151                                    )
3152                                },
3153                            ))
3154                            .on_drop(cx.listener(move |this, paths, window, cx| {
3155                                this.drag_split_direction = None;
3156                                this.handle_external_paths_drop(paths, window, cx)
3157                            }))
3158                            .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
3159                                if event.click_count() == 2 {
3160                                    window.dispatch_action(
3161                                        this.double_click_dispatch_action.boxed_clone(),
3162                                        cx,
3163                                    );
3164                                }
3165                            })),
3166                    ),
3167            )
3168            .into_any_element()
3169    }
3170
3171    pub fn render_menu_overlay(menu: &Entity<ContextMenu>) -> Div {
3172        div().absolute().bottom_0().right_0().size_0().child(
3173            deferred(anchored().anchor(Corner::TopRight).child(menu.clone())).with_priority(1),
3174        )
3175    }
3176
3177    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut Context<Self>) {
3178        self.zoomed = zoomed;
3179        cx.notify();
3180    }
3181
3182    pub fn is_zoomed(&self) -> bool {
3183        self.zoomed
3184    }
3185
3186    fn handle_drag_move<T: 'static>(
3187        &mut self,
3188        event: &DragMoveEvent<T>,
3189        window: &mut Window,
3190        cx: &mut Context<Self>,
3191    ) {
3192        let can_split_predicate = self.can_split_predicate.take();
3193        let can_split = match &can_split_predicate {
3194            Some(can_split_predicate) => {
3195                can_split_predicate(self, event.dragged_item(), window, cx)
3196            }
3197            None => false,
3198        };
3199        self.can_split_predicate = can_split_predicate;
3200        if !can_split {
3201            return;
3202        }
3203
3204        let rect = event.bounds.size;
3205
3206        let size = event.bounds.size.width.min(event.bounds.size.height)
3207            * WorkspaceSettings::get_global(cx).drop_target_size;
3208
3209        let relative_cursor = Point::new(
3210            event.event.position.x - event.bounds.left(),
3211            event.event.position.y - event.bounds.top(),
3212        );
3213
3214        let direction = if relative_cursor.x < size
3215            || relative_cursor.x > rect.width - size
3216            || relative_cursor.y < size
3217            || relative_cursor.y > rect.height - size
3218        {
3219            [
3220                SplitDirection::Up,
3221                SplitDirection::Right,
3222                SplitDirection::Down,
3223                SplitDirection::Left,
3224            ]
3225            .iter()
3226            .min_by_key(|side| match side {
3227                SplitDirection::Up => relative_cursor.y,
3228                SplitDirection::Right => rect.width - relative_cursor.x,
3229                SplitDirection::Down => rect.height - relative_cursor.y,
3230                SplitDirection::Left => relative_cursor.x,
3231            })
3232            .cloned()
3233        } else {
3234            None
3235        };
3236
3237        if direction != self.drag_split_direction {
3238            self.drag_split_direction = direction;
3239        }
3240    }
3241
3242    pub fn handle_tab_drop(
3243        &mut self,
3244        dragged_tab: &DraggedTab,
3245        ix: usize,
3246        window: &mut Window,
3247        cx: &mut Context<Self>,
3248    ) {
3249        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3250            && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_tab, window, cx)
3251        {
3252            return;
3253        }
3254        let mut to_pane = cx.entity();
3255        let split_direction = self.drag_split_direction;
3256        let item_id = dragged_tab.item.item_id();
3257        if let Some(preview_item_id) = self.preview_item_id
3258            && item_id == preview_item_id
3259        {
3260            self.set_preview_item_id(None, cx);
3261        }
3262
3263        let is_clone = cfg!(target_os = "macos") && window.modifiers().alt
3264            || cfg!(not(target_os = "macos")) && window.modifiers().control;
3265
3266        let from_pane = dragged_tab.pane.clone();
3267
3268        self.workspace
3269            .update(cx, |_, cx| {
3270                cx.defer_in(window, move |workspace, window, cx| {
3271                    if let Some(split_direction) = split_direction {
3272                        to_pane = workspace.split_pane(to_pane, split_direction, window, cx);
3273                    }
3274                    let database_id = workspace.database_id();
3275                    let was_pinned_in_from_pane = from_pane.read_with(cx, |pane, _| {
3276                        pane.index_for_item_id(item_id)
3277                            .is_some_and(|ix| pane.is_tab_pinned(ix))
3278                    });
3279                    let to_pane_old_length = to_pane.read(cx).items.len();
3280                    if is_clone {
3281                        let Some(item) = from_pane
3282                            .read(cx)
3283                            .items()
3284                            .find(|item| item.item_id() == item_id)
3285                            .cloned()
3286                        else {
3287                            return;
3288                        };
3289                        if item.can_split(cx) {
3290                            let task = item.clone_on_split(database_id, window, cx);
3291                            let to_pane = to_pane.downgrade();
3292                            cx.spawn_in(window, async move |_, cx| {
3293                                if let Some(item) = task.await {
3294                                    to_pane
3295                                        .update_in(cx, |pane, window, cx| {
3296                                            pane.add_item(item, true, true, None, window, cx)
3297                                        })
3298                                        .ok();
3299                                }
3300                            })
3301                            .detach();
3302                        } else {
3303                            move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3304                        }
3305                    } else {
3306                        move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3307                    }
3308                    to_pane.update(cx, |this, _| {
3309                        if to_pane == from_pane {
3310                            let actual_ix = this
3311                                .items
3312                                .iter()
3313                                .position(|item| item.item_id() == item_id)
3314                                .unwrap_or(0);
3315
3316                            let is_pinned_in_to_pane = this.is_tab_pinned(actual_ix);
3317
3318                            if !was_pinned_in_from_pane && is_pinned_in_to_pane {
3319                                this.pinned_tab_count += 1;
3320                            } else if was_pinned_in_from_pane && !is_pinned_in_to_pane {
3321                                this.pinned_tab_count -= 1;
3322                            }
3323                        } else if this.items.len() >= to_pane_old_length {
3324                            let is_pinned_in_to_pane = this.is_tab_pinned(ix);
3325                            let item_created_pane = to_pane_old_length == 0;
3326                            let is_first_position = ix == 0;
3327                            let was_dropped_at_beginning = item_created_pane || is_first_position;
3328                            let should_remain_pinned = is_pinned_in_to_pane
3329                                || (was_pinned_in_from_pane && was_dropped_at_beginning);
3330
3331                            if should_remain_pinned {
3332                                this.pinned_tab_count += 1;
3333                            }
3334                        }
3335                    });
3336                });
3337            })
3338            .log_err();
3339    }
3340
3341    fn handle_dragged_selection_drop(
3342        &mut self,
3343        dragged_selection: &DraggedSelection,
3344        dragged_onto: Option<usize>,
3345        window: &mut Window,
3346        cx: &mut Context<Self>,
3347    ) {
3348        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3349            && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_selection, window, cx)
3350        {
3351            return;
3352        }
3353        self.handle_project_entry_drop(
3354            &dragged_selection.active_selection.entry_id,
3355            dragged_onto,
3356            window,
3357            cx,
3358        );
3359    }
3360
3361    fn handle_project_entry_drop(
3362        &mut self,
3363        project_entry_id: &ProjectEntryId,
3364        target: Option<usize>,
3365        window: &mut Window,
3366        cx: &mut Context<Self>,
3367    ) {
3368        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3369            && let ControlFlow::Break(()) = custom_drop_handle(self, project_entry_id, window, cx)
3370        {
3371            return;
3372        }
3373        let mut to_pane = cx.entity();
3374        let split_direction = self.drag_split_direction;
3375        let project_entry_id = *project_entry_id;
3376        self.workspace
3377            .update(cx, |_, cx| {
3378                cx.defer_in(window, move |workspace, window, cx| {
3379                    if let Some(project_path) = workspace
3380                        .project()
3381                        .read(cx)
3382                        .path_for_entry(project_entry_id, cx)
3383                    {
3384                        let load_path_task = workspace.load_path(project_path.clone(), window, cx);
3385                        cx.spawn_in(window, async move |workspace, cx| {
3386                            if let Some((project_entry_id, build_item)) =
3387                                load_path_task.await.notify_async_err(cx)
3388                            {
3389                                let (to_pane, new_item_handle) = workspace
3390                                    .update_in(cx, |workspace, window, cx| {
3391                                        if let Some(split_direction) = split_direction {
3392                                            to_pane = workspace.split_pane(
3393                                                to_pane,
3394                                                split_direction,
3395                                                window,
3396                                                cx,
3397                                            );
3398                                        }
3399                                        let new_item_handle = to_pane.update(cx, |pane, cx| {
3400                                            pane.open_item(
3401                                                project_entry_id,
3402                                                project_path,
3403                                                true,
3404                                                false,
3405                                                true,
3406                                                target,
3407                                                window,
3408                                                cx,
3409                                                build_item,
3410                                            )
3411                                        });
3412                                        (to_pane, new_item_handle)
3413                                    })
3414                                    .log_err()?;
3415                                to_pane
3416                                    .update_in(cx, |this, window, cx| {
3417                                        let Some(index) = this.index_for_item(&*new_item_handle)
3418                                        else {
3419                                            return;
3420                                        };
3421
3422                                        if target.is_some_and(|target| this.is_tab_pinned(target)) {
3423                                            this.pin_tab_at(index, window, cx);
3424                                        }
3425                                    })
3426                                    .ok()?
3427                            }
3428                            Some(())
3429                        })
3430                        .detach();
3431                    };
3432                });
3433            })
3434            .log_err();
3435    }
3436
3437    fn handle_external_paths_drop(
3438        &mut self,
3439        paths: &ExternalPaths,
3440        window: &mut Window,
3441        cx: &mut Context<Self>,
3442    ) {
3443        if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3444            && let ControlFlow::Break(()) = custom_drop_handle(self, paths, window, cx)
3445        {
3446            return;
3447        }
3448        let mut to_pane = cx.entity();
3449        let mut split_direction = self.drag_split_direction;
3450        let paths = paths.paths().to_vec();
3451        let is_remote = self
3452            .workspace
3453            .update(cx, |workspace, cx| {
3454                if workspace.project().read(cx).is_via_collab() {
3455                    workspace.show_error(
3456                        &anyhow::anyhow!("Cannot drop files on a remote project"),
3457                        cx,
3458                    );
3459                    true
3460                } else {
3461                    false
3462                }
3463            })
3464            .unwrap_or(true);
3465        if is_remote {
3466            return;
3467        }
3468
3469        self.workspace
3470            .update(cx, |workspace, cx| {
3471                let fs = Arc::clone(workspace.project().read(cx).fs());
3472                cx.spawn_in(window, async move |workspace, cx| {
3473                    let mut is_file_checks = FuturesUnordered::new();
3474                    for path in &paths {
3475                        is_file_checks.push(fs.is_file(path))
3476                    }
3477                    let mut has_files_to_open = false;
3478                    while let Some(is_file) = is_file_checks.next().await {
3479                        if is_file {
3480                            has_files_to_open = true;
3481                            break;
3482                        }
3483                    }
3484                    drop(is_file_checks);
3485                    if !has_files_to_open {
3486                        split_direction = None;
3487                    }
3488
3489                    if let Ok((open_task, to_pane)) =
3490                        workspace.update_in(cx, |workspace, window, cx| {
3491                            if let Some(split_direction) = split_direction {
3492                                to_pane =
3493                                    workspace.split_pane(to_pane, split_direction, window, cx);
3494                            }
3495                            (
3496                                workspace.open_paths(
3497                                    paths,
3498                                    OpenOptions {
3499                                        visible: Some(OpenVisible::OnlyDirectories),
3500                                        ..Default::default()
3501                                    },
3502                                    Some(to_pane.downgrade()),
3503                                    window,
3504                                    cx,
3505                                ),
3506                                to_pane,
3507                            )
3508                        })
3509                    {
3510                        let opened_items: Vec<_> = open_task.await;
3511                        _ = workspace.update_in(cx, |workspace, window, cx| {
3512                            for item in opened_items.into_iter().flatten() {
3513                                if let Err(e) = item {
3514                                    workspace.show_error(&e, cx);
3515                                }
3516                            }
3517                            if to_pane.read(cx).items_len() == 0 {
3518                                workspace.remove_pane(to_pane, None, window, cx);
3519                            }
3520                        });
3521                    }
3522                })
3523                .detach();
3524            })
3525            .log_err();
3526    }
3527
3528    pub fn display_nav_history_buttons(&mut self, display: Option<bool>) {
3529        self.display_nav_history_buttons = display;
3530    }
3531
3532    fn pinned_item_ids(&self) -> Vec<EntityId> {
3533        self.items
3534            .iter()
3535            .enumerate()
3536            .filter_map(|(index, item)| {
3537                if self.is_tab_pinned(index) {
3538                    return Some(item.item_id());
3539                }
3540
3541                None
3542            })
3543            .collect()
3544    }
3545
3546    fn clean_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3547        self.items()
3548            .filter_map(|item| {
3549                if !item.is_dirty(cx) {
3550                    return Some(item.item_id());
3551                }
3552
3553                None
3554            })
3555            .collect()
3556    }
3557
3558    fn to_the_side_item_ids(&self, item_id: EntityId, side: Side) -> Vec<EntityId> {
3559        match side {
3560            Side::Left => self
3561                .items()
3562                .take_while(|item| item.item_id() != item_id)
3563                .map(|item| item.item_id())
3564                .collect(),
3565            Side::Right => self
3566                .items()
3567                .rev()
3568                .take_while(|item| item.item_id() != item_id)
3569                .map(|item| item.item_id())
3570                .collect(),
3571        }
3572    }
3573
3574    fn multibuffer_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3575        self.items()
3576            .filter(|item| item.buffer_kind(cx) == ItemBufferKind::Multibuffer)
3577            .map(|item| item.item_id())
3578            .collect()
3579    }
3580
3581    pub fn drag_split_direction(&self) -> Option<SplitDirection> {
3582        self.drag_split_direction
3583    }
3584
3585    pub fn set_zoom_out_on_close(&mut self, zoom_out_on_close: bool) {
3586        self.zoom_out_on_close = zoom_out_on_close;
3587    }
3588}
3589
3590fn default_render_tab_bar_buttons(
3591    pane: &mut Pane,
3592    window: &mut Window,
3593    cx: &mut Context<Pane>,
3594) -> (Option<AnyElement>, Option<AnyElement>) {
3595    if !pane.has_focus(window, cx) && !pane.context_menu_focused(window, cx) {
3596        return (None, None);
3597    }
3598    let (can_clone, can_split_move) = match pane.active_item() {
3599        Some(active_item) if active_item.can_split(cx) => (true, false),
3600        Some(_) => (false, pane.items_len() > 1),
3601        None => (false, false),
3602    };
3603    // Ideally we would return a vec of elements here to pass directly to the [TabBar]'s
3604    // `end_slot`, but due to needing a view here that isn't possible.
3605    let right_children = h_flex()
3606        // Instead we need to replicate the spacing from the [TabBar]'s `end_slot` here.
3607        .gap(DynamicSpacing::Base04.rems(cx))
3608        .child(
3609            PopoverMenu::new("pane-tab-bar-popover-menu")
3610                .trigger_with_tooltip(
3611                    IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
3612                    Tooltip::text("New..."),
3613                )
3614                .anchor(Corner::TopRight)
3615                .with_handle(pane.new_item_context_menu_handle.clone())
3616                .menu(move |window, cx| {
3617                    Some(ContextMenu::build(window, cx, |menu, _, _| {
3618                        menu.action("New File", NewFile.boxed_clone())
3619                            .action("Open File", ToggleFileFinder::default().boxed_clone())
3620                            .separator()
3621                            .action(
3622                                "Search Project",
3623                                DeploySearch {
3624                                    replace_enabled: false,
3625                                    included_files: None,
3626                                    excluded_files: None,
3627                                }
3628                                .boxed_clone(),
3629                            )
3630                            .action("Search Symbols", ToggleProjectSymbols.boxed_clone())
3631                            .separator()
3632                            .action("New Terminal", NewTerminal.boxed_clone())
3633                    }))
3634                }),
3635        )
3636        .child(
3637            PopoverMenu::new("pane-tab-bar-split")
3638                .trigger_with_tooltip(
3639                    IconButton::new("split", IconName::Split)
3640                        .icon_size(IconSize::Small)
3641                        .disabled(!can_clone && !can_split_move),
3642                    Tooltip::text("Split Pane"),
3643                )
3644                .anchor(Corner::TopRight)
3645                .with_handle(pane.split_item_context_menu_handle.clone())
3646                .menu(move |window, cx| {
3647                    ContextMenu::build(window, cx, |menu, _, _| {
3648                        if can_split_move {
3649                            menu.action("Split Right", SplitAndMoveRight.boxed_clone())
3650                                .action("Split Left", SplitAndMoveLeft.boxed_clone())
3651                                .action("Split Up", SplitAndMoveUp.boxed_clone())
3652                                .action("Split Down", SplitAndMoveDown.boxed_clone())
3653                        } else {
3654                            menu.action("Split Right", SplitRight.boxed_clone())
3655                                .action("Split Left", SplitLeft.boxed_clone())
3656                                .action("Split Up", SplitUp.boxed_clone())
3657                                .action("Split Down", SplitDown.boxed_clone())
3658                        }
3659                    })
3660                    .into()
3661                }),
3662        )
3663        .child({
3664            let zoomed = pane.is_zoomed();
3665            IconButton::new("toggle_zoom", IconName::Maximize)
3666                .icon_size(IconSize::Small)
3667                .toggle_state(zoomed)
3668                .selected_icon(IconName::Minimize)
3669                .on_click(cx.listener(|pane, _, window, cx| {
3670                    pane.toggle_zoom(&crate::ToggleZoom, window, cx);
3671                }))
3672                .tooltip(move |_window, cx| {
3673                    Tooltip::for_action(
3674                        if zoomed { "Zoom Out" } else { "Zoom In" },
3675                        &ToggleZoom,
3676                        cx,
3677                    )
3678                })
3679        })
3680        .into_any_element()
3681        .into();
3682    (None, right_children)
3683}
3684
3685impl Focusable for Pane {
3686    fn focus_handle(&self, _cx: &App) -> FocusHandle {
3687        self.focus_handle.clone()
3688    }
3689}
3690
3691impl Render for Pane {
3692    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3693        let mut key_context = KeyContext::new_with_defaults();
3694        key_context.add("Pane");
3695        if self.active_item().is_none() {
3696            key_context.add("EmptyPane");
3697        }
3698
3699        self.toolbar
3700            .read(cx)
3701            .contribute_context(&mut key_context, cx);
3702
3703        let should_display_tab_bar = self.should_display_tab_bar.clone();
3704        let display_tab_bar = should_display_tab_bar(window, cx);
3705        let Some(project) = self.project.upgrade() else {
3706            return div().track_focus(&self.focus_handle(cx));
3707        };
3708        let is_local = project.read(cx).is_local();
3709
3710        v_flex()
3711            .key_context(key_context)
3712            .track_focus(&self.focus_handle(cx))
3713            .size_full()
3714            .flex_none()
3715            .overflow_hidden()
3716            .on_action(
3717                cx.listener(|pane, _: &SplitLeft, _, cx| pane.split(SplitDirection::Left, cx)),
3718            )
3719            .on_action(cx.listener(|pane, _: &SplitUp, _, cx| pane.split(SplitDirection::Up, cx)))
3720            .on_action(cx.listener(|pane, _: &SplitHorizontal, _, cx| {
3721                pane.split(SplitDirection::horizontal(cx), cx)
3722            }))
3723            .on_action(cx.listener(|pane, _: &SplitVertical, _, cx| {
3724                pane.split(SplitDirection::vertical(cx), cx)
3725            }))
3726            .on_action(
3727                cx.listener(|pane, _: &SplitRight, _, cx| pane.split(SplitDirection::Right, cx)),
3728            )
3729            .on_action(
3730                cx.listener(|pane, _: &SplitDown, _, cx| pane.split(SplitDirection::Down, cx)),
3731            )
3732            .on_action(cx.listener(|pane, _: &SplitAndMoveUp, _, cx| {
3733                pane.split_and_move(SplitDirection::Up, cx)
3734            }))
3735            .on_action(cx.listener(|pane, _: &SplitAndMoveDown, _, cx| {
3736                pane.split_and_move(SplitDirection::Down, cx)
3737            }))
3738            .on_action(cx.listener(|pane, _: &SplitAndMoveLeft, _, cx| {
3739                pane.split_and_move(SplitDirection::Left, cx)
3740            }))
3741            .on_action(cx.listener(|pane, _: &SplitAndMoveRight, _, cx| {
3742                pane.split_and_move(SplitDirection::Right, cx)
3743            }))
3744            .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
3745                cx.emit(Event::JoinIntoNext);
3746            }))
3747            .on_action(cx.listener(|_, _: &JoinAll, _, cx| {
3748                cx.emit(Event::JoinAll);
3749            }))
3750            .on_action(cx.listener(Pane::toggle_zoom))
3751            .on_action(cx.listener(Self::navigate_backward))
3752            .on_action(cx.listener(Self::navigate_forward))
3753            .on_action(
3754                cx.listener(|pane: &mut Pane, action: &ActivateItem, window, cx| {
3755                    pane.activate_item(
3756                        action.0.min(pane.items.len().saturating_sub(1)),
3757                        true,
3758                        true,
3759                        window,
3760                        cx,
3761                    );
3762                }),
3763            )
3764            .on_action(cx.listener(Self::alternate_file))
3765            .on_action(cx.listener(Self::activate_last_item))
3766            .on_action(cx.listener(Self::activate_previous_item))
3767            .on_action(cx.listener(Self::activate_next_item))
3768            .on_action(cx.listener(Self::swap_item_left))
3769            .on_action(cx.listener(Self::swap_item_right))
3770            .on_action(cx.listener(Self::toggle_pin_tab))
3771            .on_action(cx.listener(Self::unpin_all_tabs))
3772            .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
3773                this.on_action(cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, _, cx| {
3774                    if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
3775                        if pane.is_active_preview_item(active_item_id) {
3776                            pane.set_preview_item_id(None, cx);
3777                        } else {
3778                            pane.set_preview_item_id(Some(active_item_id), cx);
3779                        }
3780                    }
3781                }))
3782            })
3783            .on_action(
3784                cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
3785                    pane.close_active_item(action, window, cx)
3786                        .detach_and_log_err(cx)
3787                }),
3788            )
3789            .on_action(
3790                cx.listener(|pane: &mut Self, action: &CloseOtherItems, window, cx| {
3791                    pane.close_other_items(action, None, window, cx)
3792                        .detach_and_log_err(cx);
3793                }),
3794            )
3795            .on_action(
3796                cx.listener(|pane: &mut Self, action: &CloseCleanItems, window, cx| {
3797                    pane.close_clean_items(action, window, cx)
3798                        .detach_and_log_err(cx)
3799                }),
3800            )
3801            .on_action(cx.listener(
3802                |pane: &mut Self, action: &CloseItemsToTheLeft, window, cx| {
3803                    pane.close_items_to_the_left_by_id(None, action, window, cx)
3804                        .detach_and_log_err(cx)
3805                },
3806            ))
3807            .on_action(cx.listener(
3808                |pane: &mut Self, action: &CloseItemsToTheRight, window, cx| {
3809                    pane.close_items_to_the_right_by_id(None, action, window, cx)
3810                        .detach_and_log_err(cx)
3811                },
3812            ))
3813            .on_action(
3814                cx.listener(|pane: &mut Self, action: &CloseAllItems, window, cx| {
3815                    pane.close_all_items(action, window, cx)
3816                        .detach_and_log_err(cx)
3817                }),
3818            )
3819            .on_action(cx.listener(
3820                |pane: &mut Self, action: &CloseMultibufferItems, window, cx| {
3821                    pane.close_multibuffer_items(action, window, cx)
3822                        .detach_and_log_err(cx)
3823                },
3824            ))
3825            .on_action(
3826                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, _, cx| {
3827                    let entry_id = action
3828                        .entry_id
3829                        .map(ProjectEntryId::from_proto)
3830                        .or_else(|| pane.active_item()?.project_entry_ids(cx).first().copied());
3831                    if let Some(entry_id) = entry_id {
3832                        pane.project
3833                            .update(cx, |_, cx| {
3834                                cx.emit(project::Event::RevealInProjectPanel(entry_id))
3835                            })
3836                            .ok();
3837                    }
3838                }),
3839            )
3840            .on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
3841                if cx.stop_active_drag(window) {
3842                } else {
3843                    cx.propagate();
3844                }
3845            }))
3846            .when(self.active_item().is_some() && display_tab_bar, |pane| {
3847                pane.child((self.render_tab_bar.clone())(self, window, cx))
3848            })
3849            .child({
3850                let has_worktrees = project.read(cx).visible_worktrees(cx).next().is_some();
3851                // main content
3852                div()
3853                    .flex_1()
3854                    .relative()
3855                    .group("")
3856                    .overflow_hidden()
3857                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
3858                    .on_drag_move::<DraggedSelection>(cx.listener(Self::handle_drag_move))
3859                    .when(is_local, |div| {
3860                        div.on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
3861                    })
3862                    .map(|div| {
3863                        if let Some(item) = self.active_item() {
3864                            div.id("pane_placeholder")
3865                                .v_flex()
3866                                .size_full()
3867                                .overflow_hidden()
3868                                .child(self.toolbar.clone())
3869                                .child(item.to_any())
3870                        } else {
3871                            let placeholder = div
3872                                .id("pane_placeholder")
3873                                .h_flex()
3874                                .size_full()
3875                                .justify_center()
3876                                .on_click(cx.listener(
3877                                    move |this, event: &ClickEvent, window, cx| {
3878                                        if event.click_count() == 2 {
3879                                            window.dispatch_action(
3880                                                this.double_click_dispatch_action.boxed_clone(),
3881                                                cx,
3882                                            );
3883                                        }
3884                                    },
3885                                ));
3886                            if has_worktrees {
3887                                placeholder
3888                            } else {
3889                                placeholder.child(
3890                                    Label::new("Open a file or project to get started.")
3891                                        .color(Color::Muted),
3892                                )
3893                            }
3894                        }
3895                    })
3896                    .child(
3897                        // drag target
3898                        div()
3899                            .invisible()
3900                            .absolute()
3901                            .bg(cx.theme().colors().drop_target_background)
3902                            .group_drag_over::<DraggedTab>("", |style| style.visible())
3903                            .group_drag_over::<DraggedSelection>("", |style| style.visible())
3904                            .when(is_local, |div| {
3905                                div.group_drag_over::<ExternalPaths>("", |style| style.visible())
3906                            })
3907                            .when_some(self.can_drop_predicate.clone(), |this, p| {
3908                                this.can_drop(move |a, window, cx| p(a, window, cx))
3909                            })
3910                            .on_drop(cx.listener(move |this, dragged_tab, window, cx| {
3911                                this.handle_tab_drop(
3912                                    dragged_tab,
3913                                    this.active_item_index(),
3914                                    window,
3915                                    cx,
3916                                )
3917                            }))
3918                            .on_drop(cx.listener(
3919                                move |this, selection: &DraggedSelection, window, cx| {
3920                                    this.handle_dragged_selection_drop(selection, None, window, cx)
3921                                },
3922                            ))
3923                            .on_drop(cx.listener(move |this, paths, window, cx| {
3924                                this.handle_external_paths_drop(paths, window, cx)
3925                            }))
3926                            .map(|div| {
3927                                let size = DefiniteLength::Fraction(0.5);
3928                                match self.drag_split_direction {
3929                                    None => div.top_0().right_0().bottom_0().left_0(),
3930                                    Some(SplitDirection::Up) => {
3931                                        div.top_0().left_0().right_0().h(size)
3932                                    }
3933                                    Some(SplitDirection::Down) => {
3934                                        div.left_0().bottom_0().right_0().h(size)
3935                                    }
3936                                    Some(SplitDirection::Left) => {
3937                                        div.top_0().left_0().bottom_0().w(size)
3938                                    }
3939                                    Some(SplitDirection::Right) => {
3940                                        div.top_0().bottom_0().right_0().w(size)
3941                                    }
3942                                }
3943                            }),
3944                    )
3945            })
3946            .on_mouse_down(
3947                MouseButton::Navigate(NavigationDirection::Back),
3948                cx.listener(|pane, _, window, cx| {
3949                    if let Some(workspace) = pane.workspace.upgrade() {
3950                        let pane = cx.entity().downgrade();
3951                        window.defer(cx, move |window, cx| {
3952                            workspace.update(cx, |workspace, cx| {
3953                                workspace.go_back(pane, window, cx).detach_and_log_err(cx)
3954                            })
3955                        })
3956                    }
3957                }),
3958            )
3959            .on_mouse_down(
3960                MouseButton::Navigate(NavigationDirection::Forward),
3961                cx.listener(|pane, _, window, cx| {
3962                    if let Some(workspace) = pane.workspace.upgrade() {
3963                        let pane = cx.entity().downgrade();
3964                        window.defer(cx, move |window, cx| {
3965                            workspace.update(cx, |workspace, cx| {
3966                                workspace
3967                                    .go_forward(pane, window, cx)
3968                                    .detach_and_log_err(cx)
3969                            })
3970                        })
3971                    }
3972                }),
3973            )
3974    }
3975}
3976
3977impl ItemNavHistory {
3978    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut App) {
3979        if self
3980            .item
3981            .upgrade()
3982            .is_some_and(|item| item.include_in_nav_history())
3983        {
3984            self.history
3985                .push(data, self.item.clone(), self.is_preview, cx);
3986        }
3987    }
3988
3989    pub fn pop_backward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
3990        self.history.pop(NavigationMode::GoingBack, cx)
3991    }
3992
3993    pub fn pop_forward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
3994        self.history.pop(NavigationMode::GoingForward, cx)
3995    }
3996}
3997
3998impl NavHistory {
3999    pub fn for_each_entry(
4000        &self,
4001        cx: &App,
4002        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
4003    ) {
4004        let borrowed_history = self.0.lock();
4005        borrowed_history
4006            .forward_stack
4007            .iter()
4008            .chain(borrowed_history.backward_stack.iter())
4009            .chain(borrowed_history.closed_stack.iter())
4010            .for_each(|entry| {
4011                if let Some(project_and_abs_path) =
4012                    borrowed_history.paths_by_item.get(&entry.item.id())
4013                {
4014                    f(entry, project_and_abs_path.clone());
4015                } else if let Some(item) = entry.item.upgrade()
4016                    && let Some(path) = item.project_path(cx)
4017                {
4018                    f(entry, (path, None));
4019                }
4020            })
4021    }
4022
4023    pub fn set_mode(&mut self, mode: NavigationMode) {
4024        self.0.lock().mode = mode;
4025    }
4026
4027    pub fn mode(&self) -> NavigationMode {
4028        self.0.lock().mode
4029    }
4030
4031    pub fn disable(&mut self) {
4032        self.0.lock().mode = NavigationMode::Disabled;
4033    }
4034
4035    pub fn enable(&mut self) {
4036        self.0.lock().mode = NavigationMode::Normal;
4037    }
4038
4039    pub fn clear(&mut self, cx: &mut App) {
4040        let mut state = self.0.lock();
4041
4042        if state.backward_stack.is_empty()
4043            && state.forward_stack.is_empty()
4044            && state.closed_stack.is_empty()
4045            && state.paths_by_item.is_empty()
4046        {
4047            return;
4048        }
4049
4050        state.mode = NavigationMode::Normal;
4051        state.backward_stack.clear();
4052        state.forward_stack.clear();
4053        state.closed_stack.clear();
4054        state.paths_by_item.clear();
4055        state.did_update(cx);
4056    }
4057
4058    pub fn pop(&mut self, mode: NavigationMode, cx: &mut App) -> Option<NavigationEntry> {
4059        let mut state = self.0.lock();
4060        let entry = match mode {
4061            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
4062                return None;
4063            }
4064            NavigationMode::GoingBack => &mut state.backward_stack,
4065            NavigationMode::GoingForward => &mut state.forward_stack,
4066            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
4067        }
4068        .pop_back();
4069        if entry.is_some() {
4070            state.did_update(cx);
4071        }
4072        entry
4073    }
4074
4075    pub fn push<D: 'static + Send + Any>(
4076        &mut self,
4077        data: Option<D>,
4078        item: Arc<dyn WeakItemHandle>,
4079        is_preview: bool,
4080        cx: &mut App,
4081    ) {
4082        let state = &mut *self.0.lock();
4083        match state.mode {
4084            NavigationMode::Disabled => {}
4085            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
4086                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4087                    state.backward_stack.pop_front();
4088                }
4089                state.backward_stack.push_back(NavigationEntry {
4090                    item,
4091                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4092                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4093                    is_preview,
4094                });
4095                state.forward_stack.clear();
4096            }
4097            NavigationMode::GoingBack => {
4098                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4099                    state.forward_stack.pop_front();
4100                }
4101                state.forward_stack.push_back(NavigationEntry {
4102                    item,
4103                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4104                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4105                    is_preview,
4106                });
4107            }
4108            NavigationMode::GoingForward => {
4109                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4110                    state.backward_stack.pop_front();
4111                }
4112                state.backward_stack.push_back(NavigationEntry {
4113                    item,
4114                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4115                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4116                    is_preview,
4117                });
4118            }
4119            NavigationMode::ClosingItem => {
4120                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4121                    state.closed_stack.pop_front();
4122                }
4123                state.closed_stack.push_back(NavigationEntry {
4124                    item,
4125                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4126                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4127                    is_preview,
4128                });
4129            }
4130        }
4131        state.did_update(cx);
4132    }
4133
4134    pub fn remove_item(&mut self, item_id: EntityId) {
4135        let mut state = self.0.lock();
4136        state.paths_by_item.remove(&item_id);
4137        state
4138            .backward_stack
4139            .retain(|entry| entry.item.id() != item_id);
4140        state
4141            .forward_stack
4142            .retain(|entry| entry.item.id() != item_id);
4143        state
4144            .closed_stack
4145            .retain(|entry| entry.item.id() != item_id);
4146    }
4147
4148    pub fn rename_item(
4149        &mut self,
4150        item_id: EntityId,
4151        project_path: ProjectPath,
4152        abs_path: Option<PathBuf>,
4153    ) {
4154        let mut state = self.0.lock();
4155        let path_for_item = state.paths_by_item.get_mut(&item_id);
4156        if let Some(path_for_item) = path_for_item {
4157            path_for_item.0 = project_path;
4158            path_for_item.1 = abs_path;
4159        }
4160    }
4161
4162    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
4163        self.0.lock().paths_by_item.get(&item_id).cloned()
4164    }
4165}
4166
4167impl NavHistoryState {
4168    pub fn did_update(&self, cx: &mut App) {
4169        if let Some(pane) = self.pane.upgrade() {
4170            cx.defer(move |cx| {
4171                pane.update(cx, |pane, cx| pane.history_updated(cx));
4172            });
4173        }
4174    }
4175}
4176
4177fn dirty_message_for(buffer_path: Option<ProjectPath>, path_style: PathStyle) -> String {
4178    let path = buffer_path
4179        .as_ref()
4180        .and_then(|p| {
4181            let path = p.path.display(path_style);
4182            if path.is_empty() { None } else { Some(path) }
4183        })
4184        .unwrap_or("This buffer".into());
4185    let path = truncate_and_remove_front(&path, 80);
4186    format!("{path} contains unsaved edits. Do you want to save it?")
4187}
4188
4189pub fn tab_details(items: &[Box<dyn ItemHandle>], _window: &Window, cx: &App) -> Vec<usize> {
4190    let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
4191    let mut tab_descriptions = HashMap::default();
4192    let mut done = false;
4193    while !done {
4194        done = true;
4195
4196        // Store item indices by their tab description.
4197        for (ix, (item, detail)) in items.iter().zip(&tab_details).enumerate() {
4198            let description = item.tab_content_text(*detail, cx);
4199            if *detail == 0 || description != item.tab_content_text(detail - 1, cx) {
4200                tab_descriptions
4201                    .entry(description)
4202                    .or_insert(Vec::new())
4203                    .push(ix);
4204            }
4205        }
4206
4207        // If two or more items have the same tab description, increase their level
4208        // of detail and try again.
4209        for (_, item_ixs) in tab_descriptions.drain() {
4210            if item_ixs.len() > 1 {
4211                done = false;
4212                for ix in item_ixs {
4213                    tab_details[ix] += 1;
4214                }
4215            }
4216        }
4217    }
4218
4219    tab_details
4220}
4221
4222pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &App) -> Option<Indicator> {
4223    maybe!({
4224        let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
4225            (true, _) => Color::Warning,
4226            (_, true) => Color::Accent,
4227            (false, false) => return None,
4228        };
4229
4230        Some(Indicator::dot().color(indicator_color))
4231    })
4232}
4233
4234impl Render for DraggedTab {
4235    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4236        let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
4237        let label = self.item.tab_content(
4238            TabContentParams {
4239                detail: Some(self.detail),
4240                selected: false,
4241                preview: false,
4242                deemphasized: false,
4243            },
4244            window,
4245            cx,
4246        );
4247        Tab::new("")
4248            .toggle_state(self.is_active)
4249            .child(label)
4250            .render(window, cx)
4251            .font(ui_font)
4252    }
4253}
4254
4255#[cfg(test)]
4256mod tests {
4257    use std::num::NonZero;
4258
4259    use super::*;
4260    use crate::item::test::{TestItem, TestProjectItem};
4261    use gpui::{TestAppContext, VisualTestContext, size};
4262    use project::FakeFs;
4263    use settings::SettingsStore;
4264    use theme::LoadThemes;
4265    use util::TryFutureExt;
4266
4267    #[gpui::test]
4268    async fn test_add_item_capped_to_max_tabs(cx: &mut TestAppContext) {
4269        init_test(cx);
4270        let fs = FakeFs::new(cx.executor());
4271
4272        let project = Project::test(fs, None, cx).await;
4273        let (workspace, cx) =
4274            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4275        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4276
4277        for i in 0..7 {
4278            add_labeled_item(&pane, format!("{}", i).as_str(), false, cx);
4279        }
4280
4281        set_max_tabs(cx, Some(5));
4282        add_labeled_item(&pane, "7", false, cx);
4283        // Remove items to respect the max tab cap.
4284        assert_item_labels(&pane, ["3", "4", "5", "6", "7*"], cx);
4285        pane.update_in(cx, |pane, window, cx| {
4286            pane.activate_item(0, false, false, window, cx);
4287        });
4288        add_labeled_item(&pane, "X", false, cx);
4289        // Respect activation order.
4290        assert_item_labels(&pane, ["3", "X*", "5", "6", "7"], cx);
4291
4292        for i in 0..7 {
4293            add_labeled_item(&pane, format!("D{}", i).as_str(), true, cx);
4294        }
4295        // Keeps dirty items, even over max tab cap.
4296        assert_item_labels(
4297            &pane,
4298            ["D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6*^"],
4299            cx,
4300        );
4301
4302        set_max_tabs(cx, None);
4303        for i in 0..7 {
4304            add_labeled_item(&pane, format!("N{}", i).as_str(), false, cx);
4305        }
4306        // No cap when max tabs is None.
4307        assert_item_labels(
4308            &pane,
4309            [
4310                "D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6^", "N0", "N1", "N2", "N3", "N4",
4311                "N5", "N6*",
4312            ],
4313            cx,
4314        );
4315    }
4316
4317    #[gpui::test]
4318    async fn test_reduce_max_tabs_closes_existing_items(cx: &mut TestAppContext) {
4319        init_test(cx);
4320        let fs = FakeFs::new(cx.executor());
4321
4322        let project = Project::test(fs, None, cx).await;
4323        let (workspace, cx) =
4324            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4325        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4326
4327        add_labeled_item(&pane, "A", false, cx);
4328        add_labeled_item(&pane, "B", false, cx);
4329        let item_c = add_labeled_item(&pane, "C", false, cx);
4330        let item_d = add_labeled_item(&pane, "D", false, cx);
4331        add_labeled_item(&pane, "E", false, cx);
4332        add_labeled_item(&pane, "Settings", false, cx);
4333        assert_item_labels(&pane, ["A", "B", "C", "D", "E", "Settings*"], cx);
4334
4335        set_max_tabs(cx, Some(5));
4336        assert_item_labels(&pane, ["B", "C", "D", "E", "Settings*"], cx);
4337
4338        set_max_tabs(cx, Some(4));
4339        assert_item_labels(&pane, ["C", "D", "E", "Settings*"], cx);
4340
4341        pane.update_in(cx, |pane, window, cx| {
4342            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4343            pane.pin_tab_at(ix, window, cx);
4344
4345            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4346            pane.pin_tab_at(ix, window, cx);
4347        });
4348        assert_item_labels(&pane, ["C!", "D!", "E", "Settings*"], cx);
4349
4350        set_max_tabs(cx, Some(2));
4351        assert_item_labels(&pane, ["C!", "D!", "Settings*"], cx);
4352    }
4353
4354    #[gpui::test]
4355    async fn test_allow_pinning_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4356        init_test(cx);
4357        let fs = FakeFs::new(cx.executor());
4358
4359        let project = Project::test(fs, None, cx).await;
4360        let (workspace, cx) =
4361            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4362        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4363
4364        set_max_tabs(cx, Some(1));
4365        let item_a = add_labeled_item(&pane, "A", true, cx);
4366
4367        pane.update_in(cx, |pane, window, cx| {
4368            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4369            pane.pin_tab_at(ix, window, cx);
4370        });
4371        assert_item_labels(&pane, ["A*^!"], cx);
4372    }
4373
4374    #[gpui::test]
4375    async fn test_allow_pinning_non_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4376        init_test(cx);
4377        let fs = FakeFs::new(cx.executor());
4378
4379        let project = Project::test(fs, None, cx).await;
4380        let (workspace, cx) =
4381            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4382        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4383
4384        set_max_tabs(cx, Some(1));
4385        let item_a = add_labeled_item(&pane, "A", false, cx);
4386
4387        pane.update_in(cx, |pane, window, cx| {
4388            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4389            pane.pin_tab_at(ix, window, cx);
4390        });
4391        assert_item_labels(&pane, ["A*!"], cx);
4392    }
4393
4394    #[gpui::test]
4395    async fn test_pin_tabs_incrementally_at_max_capacity(cx: &mut TestAppContext) {
4396        init_test(cx);
4397        let fs = FakeFs::new(cx.executor());
4398
4399        let project = Project::test(fs, None, cx).await;
4400        let (workspace, cx) =
4401            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4402        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4403
4404        set_max_tabs(cx, Some(3));
4405
4406        let item_a = add_labeled_item(&pane, "A", false, cx);
4407        assert_item_labels(&pane, ["A*"], cx);
4408
4409        pane.update_in(cx, |pane, window, cx| {
4410            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4411            pane.pin_tab_at(ix, window, cx);
4412        });
4413        assert_item_labels(&pane, ["A*!"], cx);
4414
4415        let item_b = add_labeled_item(&pane, "B", false, cx);
4416        assert_item_labels(&pane, ["A!", "B*"], cx);
4417
4418        pane.update_in(cx, |pane, window, cx| {
4419            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4420            pane.pin_tab_at(ix, window, cx);
4421        });
4422        assert_item_labels(&pane, ["A!", "B*!"], cx);
4423
4424        let item_c = add_labeled_item(&pane, "C", false, cx);
4425        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4426
4427        pane.update_in(cx, |pane, window, cx| {
4428            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4429            pane.pin_tab_at(ix, window, cx);
4430        });
4431        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4432    }
4433
4434    #[gpui::test]
4435    async fn test_pin_tabs_left_to_right_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4436        init_test(cx);
4437        let fs = FakeFs::new(cx.executor());
4438
4439        let project = Project::test(fs, None, cx).await;
4440        let (workspace, cx) =
4441            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4442        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4443
4444        set_max_tabs(cx, Some(3));
4445
4446        let item_a = add_labeled_item(&pane, "A", false, cx);
4447        assert_item_labels(&pane, ["A*"], cx);
4448
4449        let item_b = add_labeled_item(&pane, "B", false, cx);
4450        assert_item_labels(&pane, ["A", "B*"], cx);
4451
4452        let item_c = add_labeled_item(&pane, "C", false, cx);
4453        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4454
4455        pane.update_in(cx, |pane, window, cx| {
4456            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4457            pane.pin_tab_at(ix, window, cx);
4458        });
4459        assert_item_labels(&pane, ["A!", "B", "C*"], cx);
4460
4461        pane.update_in(cx, |pane, window, cx| {
4462            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4463            pane.pin_tab_at(ix, window, cx);
4464        });
4465        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4466
4467        pane.update_in(cx, |pane, window, cx| {
4468            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4469            pane.pin_tab_at(ix, window, cx);
4470        });
4471        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4472    }
4473
4474    #[gpui::test]
4475    async fn test_pin_tabs_right_to_left_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4476        init_test(cx);
4477        let fs = FakeFs::new(cx.executor());
4478
4479        let project = Project::test(fs, None, cx).await;
4480        let (workspace, cx) =
4481            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4482        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4483
4484        set_max_tabs(cx, Some(3));
4485
4486        let item_a = add_labeled_item(&pane, "A", false, cx);
4487        assert_item_labels(&pane, ["A*"], cx);
4488
4489        let item_b = add_labeled_item(&pane, "B", false, cx);
4490        assert_item_labels(&pane, ["A", "B*"], cx);
4491
4492        let item_c = add_labeled_item(&pane, "C", false, cx);
4493        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4494
4495        pane.update_in(cx, |pane, window, cx| {
4496            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4497            pane.pin_tab_at(ix, window, cx);
4498        });
4499        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4500
4501        pane.update_in(cx, |pane, window, cx| {
4502            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4503            pane.pin_tab_at(ix, window, cx);
4504        });
4505        assert_item_labels(&pane, ["C*!", "B!", "A"], cx);
4506
4507        pane.update_in(cx, |pane, window, cx| {
4508            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4509            pane.pin_tab_at(ix, window, cx);
4510        });
4511        assert_item_labels(&pane, ["C*!", "B!", "A!"], cx);
4512    }
4513
4514    #[gpui::test]
4515    async fn test_pinned_tabs_never_closed_at_max_tabs(cx: &mut TestAppContext) {
4516        init_test(cx);
4517        let fs = FakeFs::new(cx.executor());
4518
4519        let project = Project::test(fs, None, cx).await;
4520        let (workspace, cx) =
4521            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4522        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4523
4524        let item_a = add_labeled_item(&pane, "A", false, cx);
4525        pane.update_in(cx, |pane, window, cx| {
4526            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4527            pane.pin_tab_at(ix, window, cx);
4528        });
4529
4530        let item_b = add_labeled_item(&pane, "B", false, cx);
4531        pane.update_in(cx, |pane, window, cx| {
4532            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4533            pane.pin_tab_at(ix, window, cx);
4534        });
4535
4536        add_labeled_item(&pane, "C", false, cx);
4537        add_labeled_item(&pane, "D", false, cx);
4538        add_labeled_item(&pane, "E", false, cx);
4539        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
4540
4541        set_max_tabs(cx, Some(3));
4542        add_labeled_item(&pane, "F", false, cx);
4543        assert_item_labels(&pane, ["A!", "B!", "F*"], cx);
4544
4545        add_labeled_item(&pane, "G", false, cx);
4546        assert_item_labels(&pane, ["A!", "B!", "G*"], cx);
4547
4548        add_labeled_item(&pane, "H", false, cx);
4549        assert_item_labels(&pane, ["A!", "B!", "H*"], cx);
4550    }
4551
4552    #[gpui::test]
4553    async fn test_always_allows_one_unpinned_item_over_max_tabs_regardless_of_pinned_count(
4554        cx: &mut TestAppContext,
4555    ) {
4556        init_test(cx);
4557        let fs = FakeFs::new(cx.executor());
4558
4559        let project = Project::test(fs, None, cx).await;
4560        let (workspace, cx) =
4561            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4562        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4563
4564        set_max_tabs(cx, Some(3));
4565
4566        let item_a = add_labeled_item(&pane, "A", false, cx);
4567        pane.update_in(cx, |pane, window, cx| {
4568            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4569            pane.pin_tab_at(ix, window, cx);
4570        });
4571
4572        let item_b = add_labeled_item(&pane, "B", false, cx);
4573        pane.update_in(cx, |pane, window, cx| {
4574            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4575            pane.pin_tab_at(ix, window, cx);
4576        });
4577
4578        let item_c = add_labeled_item(&pane, "C", false, cx);
4579        pane.update_in(cx, |pane, window, cx| {
4580            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4581            pane.pin_tab_at(ix, window, cx);
4582        });
4583
4584        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4585
4586        let item_d = add_labeled_item(&pane, "D", false, cx);
4587        assert_item_labels(&pane, ["A!", "B!", "C!", "D*"], cx);
4588
4589        pane.update_in(cx, |pane, window, cx| {
4590            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4591            pane.pin_tab_at(ix, window, cx);
4592        });
4593        assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
4594
4595        add_labeled_item(&pane, "E", false, cx);
4596        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "E*"], cx);
4597
4598        add_labeled_item(&pane, "F", false, cx);
4599        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "F*"], cx);
4600    }
4601
4602    #[gpui::test]
4603    async fn test_can_open_one_item_when_all_tabs_are_dirty_at_max(cx: &mut TestAppContext) {
4604        init_test(cx);
4605        let fs = FakeFs::new(cx.executor());
4606
4607        let project = Project::test(fs, None, cx).await;
4608        let (workspace, cx) =
4609            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4610        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4611
4612        set_max_tabs(cx, Some(3));
4613
4614        add_labeled_item(&pane, "A", true, cx);
4615        assert_item_labels(&pane, ["A*^"], cx);
4616
4617        add_labeled_item(&pane, "B", true, cx);
4618        assert_item_labels(&pane, ["A^", "B*^"], cx);
4619
4620        add_labeled_item(&pane, "C", true, cx);
4621        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
4622
4623        add_labeled_item(&pane, "D", false, cx);
4624        assert_item_labels(&pane, ["A^", "B^", "C^", "D*"], cx);
4625
4626        add_labeled_item(&pane, "E", false, cx);
4627        assert_item_labels(&pane, ["A^", "B^", "C^", "E*"], cx);
4628
4629        add_labeled_item(&pane, "F", false, cx);
4630        assert_item_labels(&pane, ["A^", "B^", "C^", "F*"], cx);
4631
4632        add_labeled_item(&pane, "G", true, cx);
4633        assert_item_labels(&pane, ["A^", "B^", "C^", "G*^"], cx);
4634    }
4635
4636    #[gpui::test]
4637    async fn test_toggle_pin_tab(cx: &mut TestAppContext) {
4638        init_test(cx);
4639        let fs = FakeFs::new(cx.executor());
4640
4641        let project = Project::test(fs, None, cx).await;
4642        let (workspace, cx) =
4643            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4644        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4645
4646        set_labeled_items(&pane, ["A", "B*", "C"], cx);
4647        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4648
4649        pane.update_in(cx, |pane, window, cx| {
4650            pane.toggle_pin_tab(&TogglePinTab, window, cx);
4651        });
4652        assert_item_labels(&pane, ["B*!", "A", "C"], cx);
4653
4654        pane.update_in(cx, |pane, window, cx| {
4655            pane.toggle_pin_tab(&TogglePinTab, window, cx);
4656        });
4657        assert_item_labels(&pane, ["B*", "A", "C"], cx);
4658    }
4659
4660    #[gpui::test]
4661    async fn test_unpin_all_tabs(cx: &mut TestAppContext) {
4662        init_test(cx);
4663        let fs = FakeFs::new(cx.executor());
4664
4665        let project = Project::test(fs, None, cx).await;
4666        let (workspace, cx) =
4667            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4668        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4669
4670        // Unpin all, in an empty pane
4671        pane.update_in(cx, |pane, window, cx| {
4672            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4673        });
4674
4675        assert_item_labels(&pane, [], cx);
4676
4677        let item_a = add_labeled_item(&pane, "A", false, cx);
4678        let item_b = add_labeled_item(&pane, "B", false, cx);
4679        let item_c = add_labeled_item(&pane, "C", false, cx);
4680        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4681
4682        // Unpin all, when no tabs are pinned
4683        pane.update_in(cx, |pane, window, cx| {
4684            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4685        });
4686
4687        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4688
4689        // Pin inactive tabs only
4690        pane.update_in(cx, |pane, window, cx| {
4691            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4692            pane.pin_tab_at(ix, window, cx);
4693
4694            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4695            pane.pin_tab_at(ix, window, cx);
4696        });
4697        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4698
4699        pane.update_in(cx, |pane, window, cx| {
4700            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4701        });
4702
4703        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4704
4705        // Pin all tabs
4706        pane.update_in(cx, |pane, window, cx| {
4707            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4708            pane.pin_tab_at(ix, window, cx);
4709
4710            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4711            pane.pin_tab_at(ix, window, cx);
4712
4713            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4714            pane.pin_tab_at(ix, window, cx);
4715        });
4716        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4717
4718        // Activate middle tab
4719        pane.update_in(cx, |pane, window, cx| {
4720            pane.activate_item(1, false, false, window, cx);
4721        });
4722        assert_item_labels(&pane, ["A!", "B*!", "C!"], cx);
4723
4724        pane.update_in(cx, |pane, window, cx| {
4725            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4726        });
4727
4728        // Order has not changed
4729        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4730    }
4731
4732    #[gpui::test]
4733    async fn test_pinning_active_tab_without_position_change_maintains_focus(
4734        cx: &mut TestAppContext,
4735    ) {
4736        init_test(cx);
4737        let fs = FakeFs::new(cx.executor());
4738
4739        let project = Project::test(fs, None, cx).await;
4740        let (workspace, cx) =
4741            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4742        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4743
4744        // Add A
4745        let item_a = add_labeled_item(&pane, "A", false, cx);
4746        assert_item_labels(&pane, ["A*"], cx);
4747
4748        // Add B
4749        add_labeled_item(&pane, "B", false, cx);
4750        assert_item_labels(&pane, ["A", "B*"], cx);
4751
4752        // Activate A again
4753        pane.update_in(cx, |pane, window, cx| {
4754            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4755            pane.activate_item(ix, true, true, window, cx);
4756        });
4757        assert_item_labels(&pane, ["A*", "B"], cx);
4758
4759        // Pin A - remains active
4760        pane.update_in(cx, |pane, window, cx| {
4761            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4762            pane.pin_tab_at(ix, window, cx);
4763        });
4764        assert_item_labels(&pane, ["A*!", "B"], cx);
4765
4766        // Unpin A - remain active
4767        pane.update_in(cx, |pane, window, cx| {
4768            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4769            pane.unpin_tab_at(ix, window, cx);
4770        });
4771        assert_item_labels(&pane, ["A*", "B"], cx);
4772    }
4773
4774    #[gpui::test]
4775    async fn test_pinning_active_tab_with_position_change_maintains_focus(cx: &mut TestAppContext) {
4776        init_test(cx);
4777        let fs = FakeFs::new(cx.executor());
4778
4779        let project = Project::test(fs, None, cx).await;
4780        let (workspace, cx) =
4781            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4782        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4783
4784        // Add A, B, C
4785        add_labeled_item(&pane, "A", false, cx);
4786        add_labeled_item(&pane, "B", false, cx);
4787        let item_c = add_labeled_item(&pane, "C", false, cx);
4788        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4789
4790        // Pin C - moves to pinned area, remains active
4791        pane.update_in(cx, |pane, window, cx| {
4792            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4793            pane.pin_tab_at(ix, window, cx);
4794        });
4795        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4796
4797        // Unpin C - moves after pinned area, remains active
4798        pane.update_in(cx, |pane, window, cx| {
4799            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4800            pane.unpin_tab_at(ix, window, cx);
4801        });
4802        assert_item_labels(&pane, ["C*", "A", "B"], cx);
4803    }
4804
4805    #[gpui::test]
4806    async fn test_pinning_inactive_tab_without_position_change_preserves_existing_focus(
4807        cx: &mut TestAppContext,
4808    ) {
4809        init_test(cx);
4810        let fs = FakeFs::new(cx.executor());
4811
4812        let project = Project::test(fs, None, cx).await;
4813        let (workspace, cx) =
4814            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4815        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4816
4817        // Add A, B
4818        let item_a = add_labeled_item(&pane, "A", false, cx);
4819        add_labeled_item(&pane, "B", false, cx);
4820        assert_item_labels(&pane, ["A", "B*"], cx);
4821
4822        // Pin A - already in pinned area, B remains active
4823        pane.update_in(cx, |pane, window, cx| {
4824            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4825            pane.pin_tab_at(ix, window, cx);
4826        });
4827        assert_item_labels(&pane, ["A!", "B*"], cx);
4828
4829        // Unpin A - stays in place, B remains active
4830        pane.update_in(cx, |pane, window, cx| {
4831            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4832            pane.unpin_tab_at(ix, window, cx);
4833        });
4834        assert_item_labels(&pane, ["A", "B*"], cx);
4835    }
4836
4837    #[gpui::test]
4838    async fn test_pinning_inactive_tab_with_position_change_preserves_existing_focus(
4839        cx: &mut TestAppContext,
4840    ) {
4841        init_test(cx);
4842        let fs = FakeFs::new(cx.executor());
4843
4844        let project = Project::test(fs, None, cx).await;
4845        let (workspace, cx) =
4846            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4847        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4848
4849        // Add A, B, C
4850        add_labeled_item(&pane, "A", false, cx);
4851        let item_b = add_labeled_item(&pane, "B", false, cx);
4852        let item_c = add_labeled_item(&pane, "C", false, cx);
4853        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4854
4855        // Activate B
4856        pane.update_in(cx, |pane, window, cx| {
4857            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4858            pane.activate_item(ix, true, true, window, cx);
4859        });
4860        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4861
4862        // Pin C - moves to pinned area, B remains active
4863        pane.update_in(cx, |pane, window, cx| {
4864            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4865            pane.pin_tab_at(ix, window, cx);
4866        });
4867        assert_item_labels(&pane, ["C!", "A", "B*"], cx);
4868
4869        // Unpin C - moves after pinned area, B remains active
4870        pane.update_in(cx, |pane, window, cx| {
4871            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4872            pane.unpin_tab_at(ix, window, cx);
4873        });
4874        assert_item_labels(&pane, ["C", "A", "B*"], cx);
4875    }
4876
4877    #[gpui::test]
4878    async fn test_drag_unpinned_tab_to_split_creates_pane_with_unpinned_tab(
4879        cx: &mut TestAppContext,
4880    ) {
4881        init_test(cx);
4882        let fs = FakeFs::new(cx.executor());
4883
4884        let project = Project::test(fs, None, cx).await;
4885        let (workspace, cx) =
4886            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4887        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4888
4889        // Add A, B. Pin B. Activate A
4890        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4891        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4892
4893        pane_a.update_in(cx, |pane, window, cx| {
4894            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4895            pane.pin_tab_at(ix, window, cx);
4896
4897            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4898            pane.activate_item(ix, true, true, window, cx);
4899        });
4900
4901        // Drag A to create new split
4902        pane_a.update_in(cx, |pane, window, cx| {
4903            pane.drag_split_direction = Some(SplitDirection::Right);
4904
4905            let dragged_tab = DraggedTab {
4906                pane: pane_a.clone(),
4907                item: item_a.boxed_clone(),
4908                ix: 0,
4909                detail: 0,
4910                is_active: true,
4911            };
4912            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4913        });
4914
4915        // A should be moved to new pane. B should remain pinned, A should not be pinned
4916        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
4917            let panes = workspace.panes();
4918            (panes[0].clone(), panes[1].clone())
4919        });
4920        assert_item_labels(&pane_a, ["B*!"], cx);
4921        assert_item_labels(&pane_b, ["A*"], cx);
4922    }
4923
4924    #[gpui::test]
4925    async fn test_drag_pinned_tab_to_split_creates_pane_with_pinned_tab(cx: &mut TestAppContext) {
4926        init_test(cx);
4927        let fs = FakeFs::new(cx.executor());
4928
4929        let project = Project::test(fs, None, cx).await;
4930        let (workspace, cx) =
4931            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4932        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4933
4934        // Add A, B. Pin both. Activate A
4935        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4936        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4937
4938        pane_a.update_in(cx, |pane, window, cx| {
4939            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4940            pane.pin_tab_at(ix, window, cx);
4941
4942            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4943            pane.pin_tab_at(ix, window, cx);
4944
4945            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4946            pane.activate_item(ix, true, true, window, cx);
4947        });
4948        assert_item_labels(&pane_a, ["A*!", "B!"], cx);
4949
4950        // Drag A to create new split
4951        pane_a.update_in(cx, |pane, window, cx| {
4952            pane.drag_split_direction = Some(SplitDirection::Right);
4953
4954            let dragged_tab = DraggedTab {
4955                pane: pane_a.clone(),
4956                item: item_a.boxed_clone(),
4957                ix: 0,
4958                detail: 0,
4959                is_active: true,
4960            };
4961            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4962        });
4963
4964        // A should be moved to new pane. Both A and B should still be pinned
4965        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
4966            let panes = workspace.panes();
4967            (panes[0].clone(), panes[1].clone())
4968        });
4969        assert_item_labels(&pane_a, ["B*!"], cx);
4970        assert_item_labels(&pane_b, ["A*!"], cx);
4971    }
4972
4973    #[gpui::test]
4974    async fn test_drag_pinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
4975        init_test(cx);
4976        let fs = FakeFs::new(cx.executor());
4977
4978        let project = Project::test(fs, None, cx).await;
4979        let (workspace, cx) =
4980            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4981        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4982
4983        // Add A to pane A and pin
4984        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4985        pane_a.update_in(cx, |pane, window, cx| {
4986            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4987            pane.pin_tab_at(ix, window, cx);
4988        });
4989        assert_item_labels(&pane_a, ["A*!"], cx);
4990
4991        // Add B to pane B and pin
4992        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4993            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4994        });
4995        let item_b = add_labeled_item(&pane_b, "B", false, cx);
4996        pane_b.update_in(cx, |pane, window, cx| {
4997            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4998            pane.pin_tab_at(ix, window, cx);
4999        });
5000        assert_item_labels(&pane_b, ["B*!"], cx);
5001
5002        // Move A from pane A to pane B's pinned region
5003        pane_b.update_in(cx, |pane, window, cx| {
5004            let dragged_tab = DraggedTab {
5005                pane: pane_a.clone(),
5006                item: item_a.boxed_clone(),
5007                ix: 0,
5008                detail: 0,
5009                is_active: true,
5010            };
5011            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5012        });
5013
5014        // A should stay pinned
5015        assert_item_labels(&pane_a, [], cx);
5016        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5017    }
5018
5019    #[gpui::test]
5020    async fn test_drag_pinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5021        init_test(cx);
5022        let fs = FakeFs::new(cx.executor());
5023
5024        let project = Project::test(fs, None, cx).await;
5025        let (workspace, cx) =
5026            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5027        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5028
5029        // Add A to pane A and pin
5030        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5031        pane_a.update_in(cx, |pane, window, cx| {
5032            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5033            pane.pin_tab_at(ix, window, cx);
5034        });
5035        assert_item_labels(&pane_a, ["A*!"], cx);
5036
5037        // Create pane B with pinned item B
5038        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5039            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5040        });
5041        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5042        assert_item_labels(&pane_b, ["B*"], cx);
5043
5044        pane_b.update_in(cx, |pane, window, cx| {
5045            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5046            pane.pin_tab_at(ix, window, cx);
5047        });
5048        assert_item_labels(&pane_b, ["B*!"], cx);
5049
5050        // Move A from pane A to pane B's unpinned region
5051        pane_b.update_in(cx, |pane, window, cx| {
5052            let dragged_tab = DraggedTab {
5053                pane: pane_a.clone(),
5054                item: item_a.boxed_clone(),
5055                ix: 0,
5056                detail: 0,
5057                is_active: true,
5058            };
5059            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5060        });
5061
5062        // A should become pinned
5063        assert_item_labels(&pane_a, [], cx);
5064        assert_item_labels(&pane_b, ["B!", "A*"], cx);
5065    }
5066
5067    #[gpui::test]
5068    async fn test_drag_pinned_tab_into_existing_panes_first_position_with_no_pinned_tabs(
5069        cx: &mut TestAppContext,
5070    ) {
5071        init_test(cx);
5072        let fs = FakeFs::new(cx.executor());
5073
5074        let project = Project::test(fs, None, cx).await;
5075        let (workspace, cx) =
5076            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5077        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5078
5079        // Add A to pane A and pin
5080        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5081        pane_a.update_in(cx, |pane, window, cx| {
5082            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5083            pane.pin_tab_at(ix, window, cx);
5084        });
5085        assert_item_labels(&pane_a, ["A*!"], cx);
5086
5087        // Add B to pane B
5088        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5089            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5090        });
5091        add_labeled_item(&pane_b, "B", false, cx);
5092        assert_item_labels(&pane_b, ["B*"], cx);
5093
5094        // Move A from pane A to position 0 in pane B, indicating it should stay pinned
5095        pane_b.update_in(cx, |pane, window, cx| {
5096            let dragged_tab = DraggedTab {
5097                pane: pane_a.clone(),
5098                item: item_a.boxed_clone(),
5099                ix: 0,
5100                detail: 0,
5101                is_active: true,
5102            };
5103            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5104        });
5105
5106        // A should stay pinned
5107        assert_item_labels(&pane_a, [], cx);
5108        assert_item_labels(&pane_b, ["A*!", "B"], cx);
5109    }
5110
5111    #[gpui::test]
5112    async fn test_drag_pinned_tab_into_existing_pane_at_max_capacity_closes_unpinned_tabs(
5113        cx: &mut TestAppContext,
5114    ) {
5115        init_test(cx);
5116        let fs = FakeFs::new(cx.executor());
5117
5118        let project = Project::test(fs, None, cx).await;
5119        let (workspace, cx) =
5120            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5121        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5122        set_max_tabs(cx, Some(2));
5123
5124        // Add A, B to pane A. Pin both
5125        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5126        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5127        pane_a.update_in(cx, |pane, window, cx| {
5128            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5129            pane.pin_tab_at(ix, window, cx);
5130
5131            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5132            pane.pin_tab_at(ix, window, cx);
5133        });
5134        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5135
5136        // Add C, D to pane B. Pin both
5137        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5138            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5139        });
5140        let item_c = add_labeled_item(&pane_b, "C", false, cx);
5141        let item_d = add_labeled_item(&pane_b, "D", false, cx);
5142        pane_b.update_in(cx, |pane, window, cx| {
5143            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5144            pane.pin_tab_at(ix, window, cx);
5145
5146            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
5147            pane.pin_tab_at(ix, window, cx);
5148        });
5149        assert_item_labels(&pane_b, ["C!", "D*!"], cx);
5150
5151        // Add a third unpinned item to pane B (exceeds max tabs), but is allowed,
5152        // as we allow 1 tab over max if the others are pinned or dirty
5153        add_labeled_item(&pane_b, "E", false, cx);
5154        assert_item_labels(&pane_b, ["C!", "D!", "E*"], cx);
5155
5156        // Drag pinned A from pane A to position 0 in pane B
5157        pane_b.update_in(cx, |pane, window, cx| {
5158            let dragged_tab = DraggedTab {
5159                pane: pane_a.clone(),
5160                item: item_a.boxed_clone(),
5161                ix: 0,
5162                detail: 0,
5163                is_active: true,
5164            };
5165            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5166        });
5167
5168        // E (unpinned) should be closed, leaving 3 pinned items
5169        assert_item_labels(&pane_a, ["B*!"], cx);
5170        assert_item_labels(&pane_b, ["A*!", "C!", "D!"], cx);
5171    }
5172
5173    #[gpui::test]
5174    async fn test_drag_last_pinned_tab_to_same_position_stays_pinned(cx: &mut TestAppContext) {
5175        init_test(cx);
5176        let fs = FakeFs::new(cx.executor());
5177
5178        let project = Project::test(fs, None, cx).await;
5179        let (workspace, cx) =
5180            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5181        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5182
5183        // Add A to pane A and pin it
5184        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5185        pane_a.update_in(cx, |pane, window, cx| {
5186            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5187            pane.pin_tab_at(ix, window, cx);
5188        });
5189        assert_item_labels(&pane_a, ["A*!"], cx);
5190
5191        // Drag pinned A to position 1 (directly to the right) in the same pane
5192        pane_a.update_in(cx, |pane, window, cx| {
5193            let dragged_tab = DraggedTab {
5194                pane: pane_a.clone(),
5195                item: item_a.boxed_clone(),
5196                ix: 0,
5197                detail: 0,
5198                is_active: true,
5199            };
5200            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5201        });
5202
5203        // A should still be pinned and active
5204        assert_item_labels(&pane_a, ["A*!"], cx);
5205    }
5206
5207    #[gpui::test]
5208    async fn test_drag_pinned_tab_beyond_last_pinned_tab_in_same_pane_stays_pinned(
5209        cx: &mut TestAppContext,
5210    ) {
5211        init_test(cx);
5212        let fs = FakeFs::new(cx.executor());
5213
5214        let project = Project::test(fs, None, cx).await;
5215        let (workspace, cx) =
5216            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5217        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5218
5219        // Add A, B to pane A and pin both
5220        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5221        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5222        pane_a.update_in(cx, |pane, window, cx| {
5223            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5224            pane.pin_tab_at(ix, window, cx);
5225
5226            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5227            pane.pin_tab_at(ix, window, cx);
5228        });
5229        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5230
5231        // Drag pinned A right of B in the same pane
5232        pane_a.update_in(cx, |pane, window, cx| {
5233            let dragged_tab = DraggedTab {
5234                pane: pane_a.clone(),
5235                item: item_a.boxed_clone(),
5236                ix: 0,
5237                detail: 0,
5238                is_active: true,
5239            };
5240            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5241        });
5242
5243        // A stays pinned
5244        assert_item_labels(&pane_a, ["B!", "A*!"], cx);
5245    }
5246
5247    #[gpui::test]
5248    async fn test_dragging_pinned_tab_onto_unpinned_tab_reduces_unpinned_tab_count(
5249        cx: &mut TestAppContext,
5250    ) {
5251        init_test(cx);
5252        let fs = FakeFs::new(cx.executor());
5253
5254        let project = Project::test(fs, None, cx).await;
5255        let (workspace, cx) =
5256            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5257        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5258
5259        // Add A, B to pane A and pin A
5260        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5261        add_labeled_item(&pane_a, "B", false, cx);
5262        pane_a.update_in(cx, |pane, window, cx| {
5263            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5264            pane.pin_tab_at(ix, window, cx);
5265        });
5266        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5267
5268        // Drag pinned A on top of B in the same pane, which changes tab order to B, A
5269        pane_a.update_in(cx, |pane, window, cx| {
5270            let dragged_tab = DraggedTab {
5271                pane: pane_a.clone(),
5272                item: item_a.boxed_clone(),
5273                ix: 0,
5274                detail: 0,
5275                is_active: true,
5276            };
5277            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5278        });
5279
5280        // Neither are pinned
5281        assert_item_labels(&pane_a, ["B", "A*"], cx);
5282    }
5283
5284    #[gpui::test]
5285    async fn test_drag_pinned_tab_beyond_unpinned_tab_in_same_pane_becomes_unpinned(
5286        cx: &mut TestAppContext,
5287    ) {
5288        init_test(cx);
5289        let fs = FakeFs::new(cx.executor());
5290
5291        let project = Project::test(fs, None, cx).await;
5292        let (workspace, cx) =
5293            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5294        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5295
5296        // Add A, B to pane A and pin A
5297        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5298        add_labeled_item(&pane_a, "B", false, cx);
5299        pane_a.update_in(cx, |pane, window, cx| {
5300            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5301            pane.pin_tab_at(ix, window, cx);
5302        });
5303        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5304
5305        // Drag pinned A right of B in the same pane
5306        pane_a.update_in(cx, |pane, window, cx| {
5307            let dragged_tab = DraggedTab {
5308                pane: pane_a.clone(),
5309                item: item_a.boxed_clone(),
5310                ix: 0,
5311                detail: 0,
5312                is_active: true,
5313            };
5314            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5315        });
5316
5317        // A becomes unpinned
5318        assert_item_labels(&pane_a, ["B", "A*"], cx);
5319    }
5320
5321    #[gpui::test]
5322    async fn test_drag_unpinned_tab_in_front_of_pinned_tab_in_same_pane_becomes_pinned(
5323        cx: &mut TestAppContext,
5324    ) {
5325        init_test(cx);
5326        let fs = FakeFs::new(cx.executor());
5327
5328        let project = Project::test(fs, None, cx).await;
5329        let (workspace, cx) =
5330            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5331        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5332
5333        // Add A, B to pane A and pin A
5334        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5335        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5336        pane_a.update_in(cx, |pane, window, cx| {
5337            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5338            pane.pin_tab_at(ix, window, cx);
5339        });
5340        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5341
5342        // Drag pinned B left of A in the same pane
5343        pane_a.update_in(cx, |pane, window, cx| {
5344            let dragged_tab = DraggedTab {
5345                pane: pane_a.clone(),
5346                item: item_b.boxed_clone(),
5347                ix: 1,
5348                detail: 0,
5349                is_active: true,
5350            };
5351            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5352        });
5353
5354        // A becomes unpinned
5355        assert_item_labels(&pane_a, ["B*!", "A!"], cx);
5356    }
5357
5358    #[gpui::test]
5359    async fn test_drag_unpinned_tab_to_the_pinned_region_stays_pinned(cx: &mut TestAppContext) {
5360        init_test(cx);
5361        let fs = FakeFs::new(cx.executor());
5362
5363        let project = Project::test(fs, None, cx).await;
5364        let (workspace, cx) =
5365            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5366        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5367
5368        // Add A, B, C to pane A and pin A
5369        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5370        add_labeled_item(&pane_a, "B", false, cx);
5371        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5372        pane_a.update_in(cx, |pane, window, cx| {
5373            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5374            pane.pin_tab_at(ix, window, cx);
5375        });
5376        assert_item_labels(&pane_a, ["A!", "B", "C*"], cx);
5377
5378        // Drag pinned C left of B in the same pane
5379        pane_a.update_in(cx, |pane, window, cx| {
5380            let dragged_tab = DraggedTab {
5381                pane: pane_a.clone(),
5382                item: item_c.boxed_clone(),
5383                ix: 2,
5384                detail: 0,
5385                is_active: true,
5386            };
5387            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5388        });
5389
5390        // A stays pinned, B and C remain unpinned
5391        assert_item_labels(&pane_a, ["A!", "C*", "B"], cx);
5392    }
5393
5394    #[gpui::test]
5395    async fn test_drag_unpinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5396        init_test(cx);
5397        let fs = FakeFs::new(cx.executor());
5398
5399        let project = Project::test(fs, None, cx).await;
5400        let (workspace, cx) =
5401            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5402        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5403
5404        // Add unpinned item A to pane A
5405        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5406        assert_item_labels(&pane_a, ["A*"], cx);
5407
5408        // Create pane B with pinned item B
5409        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5410            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5411        });
5412        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5413        pane_b.update_in(cx, |pane, window, cx| {
5414            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5415            pane.pin_tab_at(ix, window, cx);
5416        });
5417        assert_item_labels(&pane_b, ["B*!"], cx);
5418
5419        // Move A from pane A to pane B's pinned region
5420        pane_b.update_in(cx, |pane, window, cx| {
5421            let dragged_tab = DraggedTab {
5422                pane: pane_a.clone(),
5423                item: item_a.boxed_clone(),
5424                ix: 0,
5425                detail: 0,
5426                is_active: true,
5427            };
5428            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5429        });
5430
5431        // A should become pinned since it was dropped in the pinned region
5432        assert_item_labels(&pane_a, [], cx);
5433        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5434    }
5435
5436    #[gpui::test]
5437    async fn test_drag_unpinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5438        init_test(cx);
5439        let fs = FakeFs::new(cx.executor());
5440
5441        let project = Project::test(fs, None, cx).await;
5442        let (workspace, cx) =
5443            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5444        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5445
5446        // Add unpinned item A to pane A
5447        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5448        assert_item_labels(&pane_a, ["A*"], cx);
5449
5450        // Create pane B with one pinned item B
5451        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5452            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5453        });
5454        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5455        pane_b.update_in(cx, |pane, window, cx| {
5456            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5457            pane.pin_tab_at(ix, window, cx);
5458        });
5459        assert_item_labels(&pane_b, ["B*!"], cx);
5460
5461        // Move A from pane A to pane B's unpinned region
5462        pane_b.update_in(cx, |pane, window, cx| {
5463            let dragged_tab = DraggedTab {
5464                pane: pane_a.clone(),
5465                item: item_a.boxed_clone(),
5466                ix: 0,
5467                detail: 0,
5468                is_active: true,
5469            };
5470            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5471        });
5472
5473        // A should remain unpinned since it was dropped outside the pinned region
5474        assert_item_labels(&pane_a, [], cx);
5475        assert_item_labels(&pane_b, ["B!", "A*"], cx);
5476    }
5477
5478    #[gpui::test]
5479    async fn test_drag_pinned_tab_throughout_entire_range_of_pinned_tabs_both_directions(
5480        cx: &mut TestAppContext,
5481    ) {
5482        init_test(cx);
5483        let fs = FakeFs::new(cx.executor());
5484
5485        let project = Project::test(fs, None, cx).await;
5486        let (workspace, cx) =
5487            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5488        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5489
5490        // Add A, B, C and pin all
5491        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5492        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5493        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5494        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5495
5496        pane_a.update_in(cx, |pane, window, cx| {
5497            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5498            pane.pin_tab_at(ix, window, cx);
5499
5500            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5501            pane.pin_tab_at(ix, window, cx);
5502
5503            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5504            pane.pin_tab_at(ix, window, cx);
5505        });
5506        assert_item_labels(&pane_a, ["A!", "B!", "C*!"], cx);
5507
5508        // Move A to right of B
5509        pane_a.update_in(cx, |pane, window, cx| {
5510            let dragged_tab = DraggedTab {
5511                pane: pane_a.clone(),
5512                item: item_a.boxed_clone(),
5513                ix: 0,
5514                detail: 0,
5515                is_active: true,
5516            };
5517            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5518        });
5519
5520        // A should be after B and all are pinned
5521        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5522
5523        // Move A to right of C
5524        pane_a.update_in(cx, |pane, window, cx| {
5525            let dragged_tab = DraggedTab {
5526                pane: pane_a.clone(),
5527                item: item_a.boxed_clone(),
5528                ix: 1,
5529                detail: 0,
5530                is_active: true,
5531            };
5532            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5533        });
5534
5535        // A should be after C and all are pinned
5536        assert_item_labels(&pane_a, ["B!", "C!", "A*!"], cx);
5537
5538        // Move A to left of C
5539        pane_a.update_in(cx, |pane, window, cx| {
5540            let dragged_tab = DraggedTab {
5541                pane: pane_a.clone(),
5542                item: item_a.boxed_clone(),
5543                ix: 2,
5544                detail: 0,
5545                is_active: true,
5546            };
5547            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5548        });
5549
5550        // A should be before C and all are pinned
5551        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5552
5553        // Move A to left of B
5554        pane_a.update_in(cx, |pane, window, cx| {
5555            let dragged_tab = DraggedTab {
5556                pane: pane_a.clone(),
5557                item: item_a.boxed_clone(),
5558                ix: 1,
5559                detail: 0,
5560                is_active: true,
5561            };
5562            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5563        });
5564
5565        // A should be before B and all are pinned
5566        assert_item_labels(&pane_a, ["A*!", "B!", "C!"], cx);
5567    }
5568
5569    #[gpui::test]
5570    async fn test_drag_first_tab_to_last_position(cx: &mut TestAppContext) {
5571        init_test(cx);
5572        let fs = FakeFs::new(cx.executor());
5573
5574        let project = Project::test(fs, None, cx).await;
5575        let (workspace, cx) =
5576            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5577        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5578
5579        // Add A, B, C
5580        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5581        add_labeled_item(&pane_a, "B", false, cx);
5582        add_labeled_item(&pane_a, "C", false, cx);
5583        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5584
5585        // Move A to the end
5586        pane_a.update_in(cx, |pane, window, cx| {
5587            let dragged_tab = DraggedTab {
5588                pane: pane_a.clone(),
5589                item: item_a.boxed_clone(),
5590                ix: 0,
5591                detail: 0,
5592                is_active: true,
5593            };
5594            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5595        });
5596
5597        // A should be at the end
5598        assert_item_labels(&pane_a, ["B", "C", "A*"], cx);
5599    }
5600
5601    #[gpui::test]
5602    async fn test_drag_last_tab_to_first_position(cx: &mut TestAppContext) {
5603        init_test(cx);
5604        let fs = FakeFs::new(cx.executor());
5605
5606        let project = Project::test(fs, None, cx).await;
5607        let (workspace, cx) =
5608            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5609        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5610
5611        // Add A, B, C
5612        add_labeled_item(&pane_a, "A", false, cx);
5613        add_labeled_item(&pane_a, "B", false, cx);
5614        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5615        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5616
5617        // Move C to the beginning
5618        pane_a.update_in(cx, |pane, window, cx| {
5619            let dragged_tab = DraggedTab {
5620                pane: pane_a.clone(),
5621                item: item_c.boxed_clone(),
5622                ix: 2,
5623                detail: 0,
5624                is_active: true,
5625            };
5626            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5627        });
5628
5629        // C should be at the beginning
5630        assert_item_labels(&pane_a, ["C*", "A", "B"], cx);
5631    }
5632
5633    #[gpui::test]
5634    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
5635        init_test(cx);
5636        let fs = FakeFs::new(cx.executor());
5637
5638        let project = Project::test(fs, None, cx).await;
5639        let (workspace, cx) =
5640            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5641        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5642
5643        // 1. Add with a destination index
5644        //   a. Add before the active item
5645        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5646        pane.update_in(cx, |pane, window, cx| {
5647            pane.add_item(
5648                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5649                false,
5650                false,
5651                Some(0),
5652                window,
5653                cx,
5654            );
5655        });
5656        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5657
5658        //   b. Add after the active item
5659        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5660        pane.update_in(cx, |pane, window, cx| {
5661            pane.add_item(
5662                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5663                false,
5664                false,
5665                Some(2),
5666                window,
5667                cx,
5668            );
5669        });
5670        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5671
5672        //   c. Add at the end of the item list (including off the length)
5673        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5674        pane.update_in(cx, |pane, window, cx| {
5675            pane.add_item(
5676                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5677                false,
5678                false,
5679                Some(5),
5680                window,
5681                cx,
5682            );
5683        });
5684        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5685
5686        // 2. Add without a destination index
5687        //   a. Add with active item at the start of the item list
5688        set_labeled_items(&pane, ["A*", "B", "C"], cx);
5689        pane.update_in(cx, |pane, window, cx| {
5690            pane.add_item(
5691                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5692                false,
5693                false,
5694                None,
5695                window,
5696                cx,
5697            );
5698        });
5699        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
5700
5701        //   b. Add with active item at the end of the item list
5702        set_labeled_items(&pane, ["A", "B", "C*"], cx);
5703        pane.update_in(cx, |pane, window, cx| {
5704            pane.add_item(
5705                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5706                false,
5707                false,
5708                None,
5709                window,
5710                cx,
5711            );
5712        });
5713        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5714    }
5715
5716    #[gpui::test]
5717    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
5718        init_test(cx);
5719        let fs = FakeFs::new(cx.executor());
5720
5721        let project = Project::test(fs, None, cx).await;
5722        let (workspace, cx) =
5723            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5724        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5725
5726        // 1. Add with a destination index
5727        //   1a. Add before the active item
5728        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5729        pane.update_in(cx, |pane, window, cx| {
5730            pane.add_item(d, false, false, Some(0), window, cx);
5731        });
5732        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5733
5734        //   1b. Add after the active item
5735        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5736        pane.update_in(cx, |pane, window, cx| {
5737            pane.add_item(d, false, false, Some(2), window, cx);
5738        });
5739        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5740
5741        //   1c. Add at the end of the item list (including off the length)
5742        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5743        pane.update_in(cx, |pane, window, cx| {
5744            pane.add_item(a, false, false, Some(5), window, cx);
5745        });
5746        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5747
5748        //   1d. Add same item to active index
5749        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5750        pane.update_in(cx, |pane, window, cx| {
5751            pane.add_item(b, false, false, Some(1), window, cx);
5752        });
5753        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5754
5755        //   1e. Add item to index after same item in last position
5756        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5757        pane.update_in(cx, |pane, window, cx| {
5758            pane.add_item(c, false, false, Some(2), window, cx);
5759        });
5760        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5761
5762        // 2. Add without a destination index
5763        //   2a. Add with active item at the start of the item list
5764        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
5765        pane.update_in(cx, |pane, window, cx| {
5766            pane.add_item(d, false, false, None, window, cx);
5767        });
5768        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
5769
5770        //   2b. Add with active item at the end of the item list
5771        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
5772        pane.update_in(cx, |pane, window, cx| {
5773            pane.add_item(a, false, false, None, window, cx);
5774        });
5775        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5776
5777        //   2c. Add active item to active item at end of list
5778        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
5779        pane.update_in(cx, |pane, window, cx| {
5780            pane.add_item(c, false, false, None, window, cx);
5781        });
5782        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5783
5784        //   2d. Add active item to active item at start of list
5785        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
5786        pane.update_in(cx, |pane, window, cx| {
5787            pane.add_item(a, false, false, None, window, cx);
5788        });
5789        assert_item_labels(&pane, ["A*", "B", "C"], cx);
5790    }
5791
5792    #[gpui::test]
5793    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
5794        init_test(cx);
5795        let fs = FakeFs::new(cx.executor());
5796
5797        let project = Project::test(fs, None, cx).await;
5798        let (workspace, cx) =
5799            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5800        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5801
5802        // singleton view
5803        pane.update_in(cx, |pane, window, cx| {
5804            pane.add_item(
5805                Box::new(cx.new(|cx| {
5806                    TestItem::new(cx)
5807                        .with_buffer_kind(ItemBufferKind::Singleton)
5808                        .with_label("buffer 1")
5809                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
5810                })),
5811                false,
5812                false,
5813                None,
5814                window,
5815                cx,
5816            );
5817        });
5818        assert_item_labels(&pane, ["buffer 1*"], cx);
5819
5820        // new singleton view with the same project entry
5821        pane.update_in(cx, |pane, window, cx| {
5822            pane.add_item(
5823                Box::new(cx.new(|cx| {
5824                    TestItem::new(cx)
5825                        .with_buffer_kind(ItemBufferKind::Singleton)
5826                        .with_label("buffer 1")
5827                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5828                })),
5829                false,
5830                false,
5831                None,
5832                window,
5833                cx,
5834            );
5835        });
5836        assert_item_labels(&pane, ["buffer 1*"], cx);
5837
5838        // new singleton view with different project entry
5839        pane.update_in(cx, |pane, window, cx| {
5840            pane.add_item(
5841                Box::new(cx.new(|cx| {
5842                    TestItem::new(cx)
5843                        .with_buffer_kind(ItemBufferKind::Singleton)
5844                        .with_label("buffer 2")
5845                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
5846                })),
5847                false,
5848                false,
5849                None,
5850                window,
5851                cx,
5852            );
5853        });
5854        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
5855
5856        // new multibuffer view with the same project entry
5857        pane.update_in(cx, |pane, window, cx| {
5858            pane.add_item(
5859                Box::new(cx.new(|cx| {
5860                    TestItem::new(cx)
5861                        .with_buffer_kind(ItemBufferKind::Multibuffer)
5862                        .with_label("multibuffer 1")
5863                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5864                })),
5865                false,
5866                false,
5867                None,
5868                window,
5869                cx,
5870            );
5871        });
5872        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
5873
5874        // another multibuffer view with the same project entry
5875        pane.update_in(cx, |pane, window, cx| {
5876            pane.add_item(
5877                Box::new(cx.new(|cx| {
5878                    TestItem::new(cx)
5879                        .with_buffer_kind(ItemBufferKind::Multibuffer)
5880                        .with_label("multibuffer 1b")
5881                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5882                })),
5883                false,
5884                false,
5885                None,
5886                window,
5887                cx,
5888            );
5889        });
5890        assert_item_labels(
5891            &pane,
5892            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
5893            cx,
5894        );
5895    }
5896
5897    #[gpui::test]
5898    async fn test_remove_item_ordering_history(cx: &mut TestAppContext) {
5899        init_test(cx);
5900        let fs = FakeFs::new(cx.executor());
5901
5902        let project = Project::test(fs, None, cx).await;
5903        let (workspace, cx) =
5904            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5905        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5906
5907        add_labeled_item(&pane, "A", false, cx);
5908        add_labeled_item(&pane, "B", false, cx);
5909        add_labeled_item(&pane, "C", false, cx);
5910        add_labeled_item(&pane, "D", false, cx);
5911        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5912
5913        pane.update_in(cx, |pane, window, cx| {
5914            pane.activate_item(1, false, false, window, cx)
5915        });
5916        add_labeled_item(&pane, "1", false, cx);
5917        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5918
5919        pane.update_in(cx, |pane, window, cx| {
5920            pane.close_active_item(
5921                &CloseActiveItem {
5922                    save_intent: None,
5923                    close_pinned: false,
5924                },
5925                window,
5926                cx,
5927            )
5928        })
5929        .await
5930        .unwrap();
5931        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
5932
5933        pane.update_in(cx, |pane, window, cx| {
5934            pane.activate_item(3, false, false, window, cx)
5935        });
5936        assert_item_labels(&pane, ["A", "B", "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"], cx);
5951
5952        pane.update_in(cx, |pane, window, cx| {
5953            pane.close_active_item(
5954                &CloseActiveItem {
5955                    save_intent: None,
5956                    close_pinned: false,
5957                },
5958                window,
5959                cx,
5960            )
5961        })
5962        .await
5963        .unwrap();
5964        assert_item_labels(&pane, ["A", "C*"], cx);
5965
5966        pane.update_in(cx, |pane, window, cx| {
5967            pane.close_active_item(
5968                &CloseActiveItem {
5969                    save_intent: None,
5970                    close_pinned: false,
5971                },
5972                window,
5973                cx,
5974            )
5975        })
5976        .await
5977        .unwrap();
5978        assert_item_labels(&pane, ["A*"], cx);
5979    }
5980
5981    #[gpui::test]
5982    async fn test_remove_item_ordering_neighbour(cx: &mut TestAppContext) {
5983        init_test(cx);
5984        cx.update_global::<SettingsStore, ()>(|s, cx| {
5985            s.update_user_settings(cx, |s| {
5986                s.tabs.get_or_insert_default().activate_on_close = Some(ActivateOnClose::Neighbour);
5987            });
5988        });
5989        let fs = FakeFs::new(cx.executor());
5990
5991        let project = Project::test(fs, None, cx).await;
5992        let (workspace, cx) =
5993            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5994        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5995
5996        add_labeled_item(&pane, "A", false, cx);
5997        add_labeled_item(&pane, "B", false, cx);
5998        add_labeled_item(&pane, "C", false, cx);
5999        add_labeled_item(&pane, "D", false, cx);
6000        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6001
6002        pane.update_in(cx, |pane, window, cx| {
6003            pane.activate_item(1, false, false, window, cx)
6004        });
6005        add_labeled_item(&pane, "1", false, cx);
6006        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6007
6008        pane.update_in(cx, |pane, window, cx| {
6009            pane.close_active_item(
6010                &CloseActiveItem {
6011                    save_intent: None,
6012                    close_pinned: false,
6013                },
6014                window,
6015                cx,
6016            )
6017        })
6018        .await
6019        .unwrap();
6020        assert_item_labels(&pane, ["A", "B", "C*", "D"], cx);
6021
6022        pane.update_in(cx, |pane, window, cx| {
6023            pane.activate_item(3, false, false, window, cx)
6024        });
6025        assert_item_labels(&pane, ["A", "B", "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*"], cx);
6040
6041        pane.update_in(cx, |pane, window, cx| {
6042            pane.close_active_item(
6043                &CloseActiveItem {
6044                    save_intent: None,
6045                    close_pinned: false,
6046                },
6047                window,
6048                cx,
6049            )
6050        })
6051        .await
6052        .unwrap();
6053        assert_item_labels(&pane, ["A", "B*"], cx);
6054
6055        pane.update_in(cx, |pane, window, cx| {
6056            pane.close_active_item(
6057                &CloseActiveItem {
6058                    save_intent: None,
6059                    close_pinned: false,
6060                },
6061                window,
6062                cx,
6063            )
6064        })
6065        .await
6066        .unwrap();
6067        assert_item_labels(&pane, ["A*"], cx);
6068    }
6069
6070    #[gpui::test]
6071    async fn test_remove_item_ordering_left_neighbour(cx: &mut TestAppContext) {
6072        init_test(cx);
6073        cx.update_global::<SettingsStore, ()>(|s, cx| {
6074            s.update_user_settings(cx, |s| {
6075                s.tabs.get_or_insert_default().activate_on_close =
6076                    Some(ActivateOnClose::LeftNeighbour);
6077            });
6078        });
6079        let fs = FakeFs::new(cx.executor());
6080
6081        let project = Project::test(fs, None, cx).await;
6082        let (workspace, cx) =
6083            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6084        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6085
6086        add_labeled_item(&pane, "A", false, cx);
6087        add_labeled_item(&pane, "B", false, cx);
6088        add_labeled_item(&pane, "C", false, cx);
6089        add_labeled_item(&pane, "D", false, cx);
6090        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6091
6092        pane.update_in(cx, |pane, window, cx| {
6093            pane.activate_item(1, false, false, window, cx)
6094        });
6095        add_labeled_item(&pane, "1", false, cx);
6096        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6097
6098        pane.update_in(cx, |pane, window, cx| {
6099            pane.close_active_item(
6100                &CloseActiveItem {
6101                    save_intent: None,
6102                    close_pinned: false,
6103                },
6104                window,
6105                cx,
6106            )
6107        })
6108        .await
6109        .unwrap();
6110        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
6111
6112        pane.update_in(cx, |pane, window, cx| {
6113            pane.activate_item(3, false, false, window, cx)
6114        });
6115        assert_item_labels(&pane, ["A", "B", "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*"], cx);
6130
6131        pane.update_in(cx, |pane, window, cx| {
6132            pane.activate_item(0, false, false, window, cx)
6133        });
6134        assert_item_labels(&pane, ["A*", "B", "C"], 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, ["B*", "C"], cx);
6149
6150        pane.update_in(cx, |pane, window, cx| {
6151            pane.close_active_item(
6152                &CloseActiveItem {
6153                    save_intent: None,
6154                    close_pinned: false,
6155                },
6156                window,
6157                cx,
6158            )
6159        })
6160        .await
6161        .unwrap();
6162        assert_item_labels(&pane, ["C*"], cx);
6163    }
6164
6165    #[gpui::test]
6166    async fn test_close_inactive_items(cx: &mut TestAppContext) {
6167        init_test(cx);
6168        let fs = FakeFs::new(cx.executor());
6169
6170        let project = Project::test(fs, None, cx).await;
6171        let (workspace, cx) =
6172            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6173        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6174
6175        let item_a = add_labeled_item(&pane, "A", false, cx);
6176        pane.update_in(cx, |pane, window, cx| {
6177            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6178            pane.pin_tab_at(ix, window, cx);
6179        });
6180        assert_item_labels(&pane, ["A*!"], cx);
6181
6182        let item_b = add_labeled_item(&pane, "B", false, cx);
6183        pane.update_in(cx, |pane, window, cx| {
6184            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6185            pane.pin_tab_at(ix, window, cx);
6186        });
6187        assert_item_labels(&pane, ["A!", "B*!"], cx);
6188
6189        add_labeled_item(&pane, "C", false, cx);
6190        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
6191
6192        add_labeled_item(&pane, "D", false, cx);
6193        add_labeled_item(&pane, "E", false, cx);
6194        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
6195
6196        pane.update_in(cx, |pane, window, cx| {
6197            pane.close_other_items(
6198                &CloseOtherItems {
6199                    save_intent: None,
6200                    close_pinned: false,
6201                },
6202                None,
6203                window,
6204                cx,
6205            )
6206        })
6207        .await
6208        .unwrap();
6209        assert_item_labels(&pane, ["A!", "B!", "E*"], cx);
6210    }
6211
6212    #[gpui::test]
6213    async fn test_running_close_inactive_items_via_an_inactive_item(cx: &mut TestAppContext) {
6214        init_test(cx);
6215        let fs = FakeFs::new(cx.executor());
6216
6217        let project = Project::test(fs, None, cx).await;
6218        let (workspace, cx) =
6219            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6220        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6221
6222        add_labeled_item(&pane, "A", false, cx);
6223        assert_item_labels(&pane, ["A*"], cx);
6224
6225        let item_b = add_labeled_item(&pane, "B", false, cx);
6226        assert_item_labels(&pane, ["A", "B*"], cx);
6227
6228        add_labeled_item(&pane, "C", false, cx);
6229        add_labeled_item(&pane, "D", false, cx);
6230        add_labeled_item(&pane, "E", false, cx);
6231        assert_item_labels(&pane, ["A", "B", "C", "D", "E*"], cx);
6232
6233        pane.update_in(cx, |pane, window, cx| {
6234            pane.close_other_items(
6235                &CloseOtherItems {
6236                    save_intent: None,
6237                    close_pinned: false,
6238                },
6239                Some(item_b.item_id()),
6240                window,
6241                cx,
6242            )
6243        })
6244        .await
6245        .unwrap();
6246        assert_item_labels(&pane, ["B*"], cx);
6247    }
6248
6249    #[gpui::test]
6250    async fn test_close_clean_items(cx: &mut TestAppContext) {
6251        init_test(cx);
6252        let fs = FakeFs::new(cx.executor());
6253
6254        let project = Project::test(fs, None, cx).await;
6255        let (workspace, cx) =
6256            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6257        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6258
6259        add_labeled_item(&pane, "A", true, cx);
6260        add_labeled_item(&pane, "B", false, cx);
6261        add_labeled_item(&pane, "C", true, cx);
6262        add_labeled_item(&pane, "D", false, cx);
6263        add_labeled_item(&pane, "E", false, cx);
6264        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
6265
6266        pane.update_in(cx, |pane, window, cx| {
6267            pane.close_clean_items(
6268                &CloseCleanItems {
6269                    close_pinned: false,
6270                },
6271                window,
6272                cx,
6273            )
6274        })
6275        .await
6276        .unwrap();
6277        assert_item_labels(&pane, ["A^", "C*^"], cx);
6278    }
6279
6280    #[gpui::test]
6281    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
6282        init_test(cx);
6283        let fs = FakeFs::new(cx.executor());
6284
6285        let project = Project::test(fs, None, cx).await;
6286        let (workspace, cx) =
6287            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6288        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6289
6290        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6291
6292        pane.update_in(cx, |pane, window, cx| {
6293            pane.close_items_to_the_left_by_id(
6294                None,
6295                &CloseItemsToTheLeft {
6296                    close_pinned: false,
6297                },
6298                window,
6299                cx,
6300            )
6301        })
6302        .await
6303        .unwrap();
6304        assert_item_labels(&pane, ["C*", "D", "E"], cx);
6305    }
6306
6307    #[gpui::test]
6308    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
6309        init_test(cx);
6310        let fs = FakeFs::new(cx.executor());
6311
6312        let project = Project::test(fs, None, cx).await;
6313        let (workspace, cx) =
6314            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6315        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6316
6317        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6318
6319        pane.update_in(cx, |pane, window, cx| {
6320            pane.close_items_to_the_right_by_id(
6321                None,
6322                &CloseItemsToTheRight {
6323                    close_pinned: false,
6324                },
6325                window,
6326                cx,
6327            )
6328        })
6329        .await
6330        .unwrap();
6331        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6332    }
6333
6334    #[gpui::test]
6335    async fn test_close_all_items(cx: &mut TestAppContext) {
6336        init_test(cx);
6337        let fs = FakeFs::new(cx.executor());
6338
6339        let project = Project::test(fs, None, cx).await;
6340        let (workspace, cx) =
6341            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6342        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6343
6344        let item_a = add_labeled_item(&pane, "A", false, cx);
6345        add_labeled_item(&pane, "B", false, cx);
6346        add_labeled_item(&pane, "C", false, cx);
6347        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6348
6349        pane.update_in(cx, |pane, window, cx| {
6350            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6351            pane.pin_tab_at(ix, window, cx);
6352            pane.close_all_items(
6353                &CloseAllItems {
6354                    save_intent: None,
6355                    close_pinned: false,
6356                },
6357                window,
6358                cx,
6359            )
6360        })
6361        .await
6362        .unwrap();
6363        assert_item_labels(&pane, ["A*!"], cx);
6364
6365        pane.update_in(cx, |pane, window, cx| {
6366            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6367            pane.unpin_tab_at(ix, window, cx);
6368            pane.close_all_items(
6369                &CloseAllItems {
6370                    save_intent: None,
6371                    close_pinned: false,
6372                },
6373                window,
6374                cx,
6375            )
6376        })
6377        .await
6378        .unwrap();
6379
6380        assert_item_labels(&pane, [], cx);
6381
6382        add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6383            item.project_items
6384                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6385        });
6386        add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6387            item.project_items
6388                .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6389        });
6390        add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6391            item.project_items
6392                .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6393        });
6394        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6395
6396        let save = pane.update_in(cx, |pane, window, cx| {
6397            pane.close_all_items(
6398                &CloseAllItems {
6399                    save_intent: None,
6400                    close_pinned: false,
6401                },
6402                window,
6403                cx,
6404            )
6405        });
6406
6407        cx.executor().run_until_parked();
6408        cx.simulate_prompt_answer("Save all");
6409        save.await.unwrap();
6410        assert_item_labels(&pane, [], cx);
6411
6412        add_labeled_item(&pane, "A", true, cx);
6413        add_labeled_item(&pane, "B", true, cx);
6414        add_labeled_item(&pane, "C", true, cx);
6415        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6416        let save = pane.update_in(cx, |pane, window, cx| {
6417            pane.close_all_items(
6418                &CloseAllItems {
6419                    save_intent: None,
6420                    close_pinned: false,
6421                },
6422                window,
6423                cx,
6424            )
6425        });
6426
6427        cx.executor().run_until_parked();
6428        cx.simulate_prompt_answer("Discard all");
6429        save.await.unwrap();
6430        assert_item_labels(&pane, [], cx);
6431    }
6432
6433    #[gpui::test]
6434    async fn test_close_multibuffer_items(cx: &mut TestAppContext) {
6435        init_test(cx);
6436        let fs = FakeFs::new(cx.executor());
6437
6438        let project = Project::test(fs, None, cx).await;
6439        let (workspace, cx) =
6440            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6441        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6442
6443        let add_labeled_item = |pane: &Entity<Pane>,
6444                                label,
6445                                is_dirty,
6446                                kind: ItemBufferKind,
6447                                cx: &mut VisualTestContext| {
6448            pane.update_in(cx, |pane, window, cx| {
6449                let labeled_item = Box::new(cx.new(|cx| {
6450                    TestItem::new(cx)
6451                        .with_label(label)
6452                        .with_dirty(is_dirty)
6453                        .with_buffer_kind(kind)
6454                }));
6455                pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6456                labeled_item
6457            })
6458        };
6459
6460        let item_a = add_labeled_item(&pane, "A", false, ItemBufferKind::Multibuffer, cx);
6461        add_labeled_item(&pane, "B", false, ItemBufferKind::Multibuffer, cx);
6462        add_labeled_item(&pane, "C", false, ItemBufferKind::Singleton, cx);
6463        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6464
6465        pane.update_in(cx, |pane, window, cx| {
6466            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6467            pane.pin_tab_at(ix, window, cx);
6468            pane.close_multibuffer_items(
6469                &CloseMultibufferItems {
6470                    save_intent: None,
6471                    close_pinned: false,
6472                },
6473                window,
6474                cx,
6475            )
6476        })
6477        .await
6478        .unwrap();
6479        assert_item_labels(&pane, ["A!", "C*"], cx);
6480
6481        pane.update_in(cx, |pane, window, cx| {
6482            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6483            pane.unpin_tab_at(ix, window, cx);
6484            pane.close_multibuffer_items(
6485                &CloseMultibufferItems {
6486                    save_intent: None,
6487                    close_pinned: false,
6488                },
6489                window,
6490                cx,
6491            )
6492        })
6493        .await
6494        .unwrap();
6495
6496        assert_item_labels(&pane, ["C*"], cx);
6497
6498        add_labeled_item(&pane, "A", true, ItemBufferKind::Singleton, cx).update(cx, |item, cx| {
6499            item.project_items
6500                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6501        });
6502        add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
6503            cx,
6504            |item, cx| {
6505                item.project_items
6506                    .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6507            },
6508        );
6509        add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
6510            cx,
6511            |item, cx| {
6512                item.project_items
6513                    .push(TestProjectItem::new_dirty(3, "D.txt", cx))
6514            },
6515        );
6516        assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
6517
6518        let save = pane.update_in(cx, |pane, window, cx| {
6519            pane.close_multibuffer_items(
6520                &CloseMultibufferItems {
6521                    save_intent: None,
6522                    close_pinned: false,
6523                },
6524                window,
6525                cx,
6526            )
6527        });
6528
6529        cx.executor().run_until_parked();
6530        cx.simulate_prompt_answer("Save all");
6531        save.await.unwrap();
6532        assert_item_labels(&pane, ["C", "A*^"], cx);
6533
6534        add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
6535            cx,
6536            |item, cx| {
6537                item.project_items
6538                    .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6539            },
6540        );
6541        add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
6542            cx,
6543            |item, cx| {
6544                item.project_items
6545                    .push(TestProjectItem::new_dirty(3, "D.txt", cx))
6546            },
6547        );
6548        assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
6549        let save = pane.update_in(cx, |pane, window, cx| {
6550            pane.close_multibuffer_items(
6551                &CloseMultibufferItems {
6552                    save_intent: None,
6553                    close_pinned: false,
6554                },
6555                window,
6556                cx,
6557            )
6558        });
6559
6560        cx.executor().run_until_parked();
6561        cx.simulate_prompt_answer("Discard all");
6562        save.await.unwrap();
6563        assert_item_labels(&pane, ["C", "A*^"], cx);
6564    }
6565
6566    #[gpui::test]
6567    async fn test_close_with_save_intent(cx: &mut TestAppContext) {
6568        init_test(cx);
6569        let fs = FakeFs::new(cx.executor());
6570
6571        let project = Project::test(fs, None, cx).await;
6572        let (workspace, cx) =
6573            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6574        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6575
6576        let a = cx.update(|_, cx| TestProjectItem::new_dirty(1, "A.txt", cx));
6577        let b = cx.update(|_, cx| TestProjectItem::new_dirty(1, "B.txt", cx));
6578        let c = cx.update(|_, cx| TestProjectItem::new_dirty(1, "C.txt", cx));
6579
6580        add_labeled_item(&pane, "AB", true, cx).update(cx, |item, _| {
6581            item.project_items.push(a.clone());
6582            item.project_items.push(b.clone());
6583        });
6584        add_labeled_item(&pane, "C", true, cx)
6585            .update(cx, |item, _| item.project_items.push(c.clone()));
6586        assert_item_labels(&pane, ["AB^", "C*^"], cx);
6587
6588        pane.update_in(cx, |pane, window, cx| {
6589            pane.close_all_items(
6590                &CloseAllItems {
6591                    save_intent: Some(SaveIntent::Save),
6592                    close_pinned: false,
6593                },
6594                window,
6595                cx,
6596            )
6597        })
6598        .await
6599        .unwrap();
6600
6601        assert_item_labels(&pane, [], cx);
6602        cx.update(|_, cx| {
6603            assert!(!a.read(cx).is_dirty);
6604            assert!(!b.read(cx).is_dirty);
6605            assert!(!c.read(cx).is_dirty);
6606        });
6607    }
6608
6609    #[gpui::test]
6610    async fn test_new_tab_scrolls_into_view_completely(cx: &mut TestAppContext) {
6611        // Arrange
6612        init_test(cx);
6613        let fs = FakeFs::new(cx.executor());
6614
6615        let project = Project::test(fs, None, cx).await;
6616        let (workspace, cx) =
6617            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6618        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6619
6620        cx.simulate_resize(size(px(300.), px(300.)));
6621
6622        add_labeled_item(&pane, "untitled", false, cx);
6623        add_labeled_item(&pane, "untitled", false, cx);
6624        add_labeled_item(&pane, "untitled", false, cx);
6625        add_labeled_item(&pane, "untitled", false, cx);
6626        // Act: this should trigger a scroll
6627        add_labeled_item(&pane, "untitled", false, cx);
6628        // Assert
6629        let tab_bar_scroll_handle =
6630            pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
6631        assert_eq!(tab_bar_scroll_handle.children_count(), 6);
6632        let tab_bounds = cx.debug_bounds("TAB-3").unwrap();
6633        let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
6634        let scroll_bounds = tab_bar_scroll_handle.bounds();
6635        let scroll_offset = tab_bar_scroll_handle.offset();
6636        assert!(tab_bounds.right() <= scroll_bounds.right() + scroll_offset.x);
6637        // -39.5 is the magic number for this setup
6638        assert_eq!(scroll_offset.x, px(-39.5));
6639        assert!(
6640            !tab_bounds.intersects(&new_tab_button_bounds),
6641            "Tab should not overlap with the new tab button, if this is failing check if there's been a redesign!"
6642        );
6643    }
6644
6645    #[gpui::test]
6646    async fn test_close_all_items_including_pinned(cx: &mut TestAppContext) {
6647        init_test(cx);
6648        let fs = FakeFs::new(cx.executor());
6649
6650        let project = Project::test(fs, None, cx).await;
6651        let (workspace, cx) =
6652            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6653        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6654
6655        let item_a = add_labeled_item(&pane, "A", false, cx);
6656        add_labeled_item(&pane, "B", false, cx);
6657        add_labeled_item(&pane, "C", false, cx);
6658        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6659
6660        pane.update_in(cx, |pane, window, cx| {
6661            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6662            pane.pin_tab_at(ix, window, cx);
6663            pane.close_all_items(
6664                &CloseAllItems {
6665                    save_intent: None,
6666                    close_pinned: true,
6667                },
6668                window,
6669                cx,
6670            )
6671        })
6672        .await
6673        .unwrap();
6674        assert_item_labels(&pane, [], cx);
6675    }
6676
6677    #[gpui::test]
6678    async fn test_close_pinned_tab_with_non_pinned_in_same_pane(cx: &mut TestAppContext) {
6679        init_test(cx);
6680        let fs = FakeFs::new(cx.executor());
6681        let project = Project::test(fs, None, cx).await;
6682        let (workspace, cx) =
6683            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6684
6685        // Non-pinned tabs in same pane
6686        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6687        add_labeled_item(&pane, "A", false, cx);
6688        add_labeled_item(&pane, "B", false, cx);
6689        add_labeled_item(&pane, "C", false, cx);
6690        pane.update_in(cx, |pane, window, cx| {
6691            pane.pin_tab_at(0, window, cx);
6692        });
6693        set_labeled_items(&pane, ["A*", "B", "C"], cx);
6694        pane.update_in(cx, |pane, window, cx| {
6695            pane.close_active_item(
6696                &CloseActiveItem {
6697                    save_intent: None,
6698                    close_pinned: false,
6699                },
6700                window,
6701                cx,
6702            )
6703            .unwrap();
6704        });
6705        // Non-pinned tab should be active
6706        assert_item_labels(&pane, ["A!", "B*", "C"], cx);
6707    }
6708
6709    #[gpui::test]
6710    async fn test_close_pinned_tab_with_non_pinned_in_different_pane(cx: &mut TestAppContext) {
6711        init_test(cx);
6712        let fs = FakeFs::new(cx.executor());
6713        let project = Project::test(fs, None, cx).await;
6714        let (workspace, cx) =
6715            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6716
6717        // No non-pinned tabs in same pane, non-pinned tabs in another pane
6718        let pane1 = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6719        let pane2 = workspace.update_in(cx, |workspace, window, cx| {
6720            workspace.split_pane(pane1.clone(), SplitDirection::Right, window, cx)
6721        });
6722        add_labeled_item(&pane1, "A", false, cx);
6723        pane1.update_in(cx, |pane, window, cx| {
6724            pane.pin_tab_at(0, window, cx);
6725        });
6726        set_labeled_items(&pane1, ["A*"], cx);
6727        add_labeled_item(&pane2, "B", false, cx);
6728        set_labeled_items(&pane2, ["B"], cx);
6729        pane1.update_in(cx, |pane, window, cx| {
6730            pane.close_active_item(
6731                &CloseActiveItem {
6732                    save_intent: None,
6733                    close_pinned: false,
6734                },
6735                window,
6736                cx,
6737            )
6738            .unwrap();
6739        });
6740        //  Non-pinned tab of other pane should be active
6741        assert_item_labels(&pane2, ["B*"], cx);
6742    }
6743
6744    #[gpui::test]
6745    async fn ensure_item_closing_actions_do_not_panic_when_no_items_exist(cx: &mut TestAppContext) {
6746        init_test(cx);
6747        let fs = FakeFs::new(cx.executor());
6748        let project = Project::test(fs, None, cx).await;
6749        let (workspace, cx) =
6750            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6751
6752        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6753        assert_item_labels(&pane, [], cx);
6754
6755        pane.update_in(cx, |pane, window, cx| {
6756            pane.close_active_item(
6757                &CloseActiveItem {
6758                    save_intent: None,
6759                    close_pinned: false,
6760                },
6761                window,
6762                cx,
6763            )
6764        })
6765        .await
6766        .unwrap();
6767
6768        pane.update_in(cx, |pane, window, cx| {
6769            pane.close_other_items(
6770                &CloseOtherItems {
6771                    save_intent: None,
6772                    close_pinned: false,
6773                },
6774                None,
6775                window,
6776                cx,
6777            )
6778        })
6779        .await
6780        .unwrap();
6781
6782        pane.update_in(cx, |pane, window, cx| {
6783            pane.close_all_items(
6784                &CloseAllItems {
6785                    save_intent: None,
6786                    close_pinned: false,
6787                },
6788                window,
6789                cx,
6790            )
6791        })
6792        .await
6793        .unwrap();
6794
6795        pane.update_in(cx, |pane, window, cx| {
6796            pane.close_clean_items(
6797                &CloseCleanItems {
6798                    close_pinned: false,
6799                },
6800                window,
6801                cx,
6802            )
6803        })
6804        .await
6805        .unwrap();
6806
6807        pane.update_in(cx, |pane, window, cx| {
6808            pane.close_items_to_the_right_by_id(
6809                None,
6810                &CloseItemsToTheRight {
6811                    close_pinned: false,
6812                },
6813                window,
6814                cx,
6815            )
6816        })
6817        .await
6818        .unwrap();
6819
6820        pane.update_in(cx, |pane, window, cx| {
6821            pane.close_items_to_the_left_by_id(
6822                None,
6823                &CloseItemsToTheLeft {
6824                    close_pinned: false,
6825                },
6826                window,
6827                cx,
6828            )
6829        })
6830        .await
6831        .unwrap();
6832    }
6833
6834    #[gpui::test]
6835    async fn test_item_swapping_actions(cx: &mut TestAppContext) {
6836        init_test(cx);
6837        let fs = FakeFs::new(cx.executor());
6838        let project = Project::test(fs, None, cx).await;
6839        let (workspace, cx) =
6840            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6841
6842        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6843        assert_item_labels(&pane, [], cx);
6844
6845        // Test that these actions do not panic
6846        pane.update_in(cx, |pane, window, cx| {
6847            pane.swap_item_right(&Default::default(), window, cx);
6848        });
6849
6850        pane.update_in(cx, |pane, window, cx| {
6851            pane.swap_item_left(&Default::default(), window, cx);
6852        });
6853
6854        add_labeled_item(&pane, "A", false, cx);
6855        add_labeled_item(&pane, "B", false, cx);
6856        add_labeled_item(&pane, "C", false, cx);
6857        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6858
6859        pane.update_in(cx, |pane, window, cx| {
6860            pane.swap_item_right(&Default::default(), window, cx);
6861        });
6862        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6863
6864        pane.update_in(cx, |pane, window, cx| {
6865            pane.swap_item_left(&Default::default(), window, cx);
6866        });
6867        assert_item_labels(&pane, ["A", "C*", "B"], cx);
6868
6869        pane.update_in(cx, |pane, window, cx| {
6870            pane.swap_item_left(&Default::default(), window, cx);
6871        });
6872        assert_item_labels(&pane, ["C*", "A", "B"], cx);
6873
6874        pane.update_in(cx, |pane, window, cx| {
6875            pane.swap_item_left(&Default::default(), window, cx);
6876        });
6877        assert_item_labels(&pane, ["C*", "A", "B"], cx);
6878
6879        pane.update_in(cx, |pane, window, cx| {
6880            pane.swap_item_right(&Default::default(), window, cx);
6881        });
6882        assert_item_labels(&pane, ["A", "C*", "B"], cx);
6883    }
6884
6885    fn init_test(cx: &mut TestAppContext) {
6886        cx.update(|cx| {
6887            let settings_store = SettingsStore::test(cx);
6888            cx.set_global(settings_store);
6889            theme::init(LoadThemes::JustBase, cx);
6890        });
6891    }
6892
6893    fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
6894        cx.update_global(|store: &mut SettingsStore, cx| {
6895            store.update_user_settings(cx, |settings| {
6896                settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
6897            });
6898        });
6899    }
6900
6901    fn add_labeled_item(
6902        pane: &Entity<Pane>,
6903        label: &str,
6904        is_dirty: bool,
6905        cx: &mut VisualTestContext,
6906    ) -> Box<Entity<TestItem>> {
6907        pane.update_in(cx, |pane, window, cx| {
6908            let labeled_item =
6909                Box::new(cx.new(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)));
6910            pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6911            labeled_item
6912        })
6913    }
6914
6915    fn set_labeled_items<const COUNT: usize>(
6916        pane: &Entity<Pane>,
6917        labels: [&str; COUNT],
6918        cx: &mut VisualTestContext,
6919    ) -> [Box<Entity<TestItem>>; COUNT] {
6920        pane.update_in(cx, |pane, window, cx| {
6921            pane.items.clear();
6922            let mut active_item_index = 0;
6923
6924            let mut index = 0;
6925            let items = labels.map(|mut label| {
6926                if label.ends_with('*') {
6927                    label = label.trim_end_matches('*');
6928                    active_item_index = index;
6929                }
6930
6931                let labeled_item = Box::new(cx.new(|cx| TestItem::new(cx).with_label(label)));
6932                pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6933                index += 1;
6934                labeled_item
6935            });
6936
6937            pane.activate_item(active_item_index, false, false, window, cx);
6938
6939            items
6940        })
6941    }
6942
6943    // Assert the item label, with the active item label suffixed with a '*'
6944    #[track_caller]
6945    fn assert_item_labels<const COUNT: usize>(
6946        pane: &Entity<Pane>,
6947        expected_states: [&str; COUNT],
6948        cx: &mut VisualTestContext,
6949    ) {
6950        let actual_states = pane.update(cx, |pane, cx| {
6951            pane.items
6952                .iter()
6953                .enumerate()
6954                .map(|(ix, item)| {
6955                    let mut state = item
6956                        .to_any()
6957                        .downcast::<TestItem>()
6958                        .unwrap()
6959                        .read(cx)
6960                        .label
6961                        .clone();
6962                    if ix == pane.active_item_index {
6963                        state.push('*');
6964                    }
6965                    if item.is_dirty(cx) {
6966                        state.push('^');
6967                    }
6968                    if pane.is_tab_pinned(ix) {
6969                        state.push('!');
6970                    }
6971                    state
6972                })
6973                .collect::<Vec<_>>()
6974        });
6975        assert_eq!(
6976            actual_states, expected_states,
6977            "pane items do not match expectation"
6978        );
6979    }
6980}