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