pane.rs

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