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