pane.rs

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