pane.rs

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