pane.rs

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