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        self.nav_history.set_mode(mode);
1833
1834        if self.is_active_preview_item(item.item_id()) {
1835            self.set_preview_item_id(None, cx);
1836        }
1837
1838        if let Some(path) = item.project_path(cx) {
1839            let abs_path = self
1840                .nav_history
1841                .0
1842                .lock()
1843                .paths_by_item
1844                .get(&item.item_id())
1845                .and_then(|(_, abs_path)| abs_path.clone());
1846
1847            self.nav_history
1848                .0
1849                .lock()
1850                .paths_by_item
1851                .insert(item.item_id(), (path, abs_path));
1852        } else {
1853            self.nav_history
1854                .0
1855                .lock()
1856                .paths_by_item
1857                .remove(&item.item_id());
1858        }
1859
1860        if self.zoom_out_on_close && self.items.is_empty() && close_pane_if_empty && self.zoomed {
1861            cx.emit(Event::ZoomOut);
1862        }
1863
1864        cx.notify();
1865    }
1866
1867    pub async fn save_item(
1868        project: Entity<Project>,
1869        pane: &WeakEntity<Pane>,
1870        item: &dyn ItemHandle,
1871        save_intent: SaveIntent,
1872        cx: &mut AsyncWindowContext,
1873    ) -> Result<bool> {
1874        const CONFLICT_MESSAGE: &str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1875
1876        const DELETED_MESSAGE: &str = "This file has been deleted on disk since you started editing it. Do you want to recreate it?";
1877
1878        if save_intent == SaveIntent::Skip {
1879            return Ok(true);
1880        }
1881        let Some(item_ix) = pane
1882            .read_with(cx, |pane, _| pane.index_for_item(item))
1883            .ok()
1884            .flatten()
1885        else {
1886            return Ok(true);
1887        };
1888
1889        let (
1890            mut has_conflict,
1891            mut is_dirty,
1892            mut can_save,
1893            can_save_as,
1894            is_singleton,
1895            has_deleted_file,
1896        ) = cx.update(|_window, cx| {
1897            (
1898                item.has_conflict(cx),
1899                item.is_dirty(cx),
1900                item.can_save(cx),
1901                item.can_save_as(cx),
1902                item.is_singleton(cx),
1903                item.has_deleted_file(cx),
1904            )
1905        })?;
1906
1907        // when saving a single buffer, we ignore whether or not it's dirty.
1908        if save_intent == SaveIntent::Save || save_intent == SaveIntent::SaveWithoutFormat {
1909            is_dirty = true;
1910        }
1911
1912        if save_intent == SaveIntent::SaveAs {
1913            is_dirty = true;
1914            has_conflict = false;
1915            can_save = false;
1916        }
1917
1918        if save_intent == SaveIntent::Overwrite {
1919            has_conflict = false;
1920        }
1921
1922        let should_format = save_intent != SaveIntent::SaveWithoutFormat;
1923
1924        if has_conflict && can_save {
1925            if has_deleted_file && is_singleton {
1926                let answer = pane.update_in(cx, |pane, window, cx| {
1927                    pane.activate_item(item_ix, true, true, window, cx);
1928                    window.prompt(
1929                        PromptLevel::Warning,
1930                        DELETED_MESSAGE,
1931                        None,
1932                        &["Save", "Close", "Cancel"],
1933                        cx,
1934                    )
1935                })?;
1936                match answer.await {
1937                    Ok(0) => {
1938                        pane.update_in(cx, |_, window, cx| {
1939                            item.save(
1940                                SaveOptions {
1941                                    format: should_format,
1942                                    autosave: false,
1943                                },
1944                                project,
1945                                window,
1946                                cx,
1947                            )
1948                        })?
1949                        .await?
1950                    }
1951                    Ok(1) => {
1952                        pane.update_in(cx, |pane, window, cx| {
1953                            pane.remove_item(item.item_id(), false, true, window, cx)
1954                        })?;
1955                    }
1956                    _ => return Ok(false),
1957                }
1958                return Ok(true);
1959            } else {
1960                let answer = pane.update_in(cx, |pane, window, cx| {
1961                    pane.activate_item(item_ix, true, true, window, cx);
1962                    window.prompt(
1963                        PromptLevel::Warning,
1964                        CONFLICT_MESSAGE,
1965                        None,
1966                        &["Overwrite", "Discard", "Cancel"],
1967                        cx,
1968                    )
1969                })?;
1970                match answer.await {
1971                    Ok(0) => {
1972                        pane.update_in(cx, |_, window, cx| {
1973                            item.save(
1974                                SaveOptions {
1975                                    format: should_format,
1976                                    autosave: false,
1977                                },
1978                                project,
1979                                window,
1980                                cx,
1981                            )
1982                        })?
1983                        .await?
1984                    }
1985                    Ok(1) => {
1986                        pane.update_in(cx, |_, window, cx| item.reload(project, window, cx))?
1987                            .await?
1988                    }
1989                    _ => return Ok(false),
1990                }
1991            }
1992        } else if is_dirty && (can_save || can_save_as) {
1993            if save_intent == SaveIntent::Close {
1994                let will_autosave = cx.update(|_window, cx| {
1995                    matches!(
1996                        item.workspace_settings(cx).autosave,
1997                        AutosaveSetting::OnFocusChange | AutosaveSetting::OnWindowChange
1998                    ) && item.can_autosave(cx)
1999                })?;
2000                if !will_autosave {
2001                    let item_id = item.item_id();
2002                    let answer_task = pane.update_in(cx, |pane, window, cx| {
2003                        if pane.save_modals_spawned.insert(item_id) {
2004                            pane.activate_item(item_ix, true, true, window, cx);
2005                            let prompt = dirty_message_for(item.project_path(cx));
2006                            Some(window.prompt(
2007                                PromptLevel::Warning,
2008                                &prompt,
2009                                None,
2010                                &["Save", "Don't Save", "Cancel"],
2011                                cx,
2012                            ))
2013                        } else {
2014                            None
2015                        }
2016                    })?;
2017                    if let Some(answer_task) = answer_task {
2018                        let answer = answer_task.await;
2019                        pane.update(cx, |pane, _| {
2020                            if !pane.save_modals_spawned.remove(&item_id) {
2021                                debug_panic!(
2022                                    "save modal was not present in spawned modals after awaiting for its answer"
2023                                )
2024                            }
2025                        })?;
2026                        match answer {
2027                            Ok(0) => {}
2028                            Ok(1) => {
2029                                // Don't save this file
2030                                pane.update_in(cx, |pane, window, cx| {
2031                                    if pane.is_tab_pinned(item_ix) && !item.can_save(cx) {
2032                                        pane.pinned_tab_count -= 1;
2033                                    }
2034                                    item.discarded(project, window, cx)
2035                                })
2036                                .log_err();
2037                                return Ok(true);
2038                            }
2039                            _ => return Ok(false), // Cancel
2040                        }
2041                    } else {
2042                        return Ok(false);
2043                    }
2044                }
2045            }
2046
2047            if can_save {
2048                pane.update_in(cx, |pane, window, cx| {
2049                    if pane.is_active_preview_item(item.item_id()) {
2050                        pane.set_preview_item_id(None, cx);
2051                    }
2052                    item.save(
2053                        SaveOptions {
2054                            format: should_format,
2055                            autosave: false,
2056                        },
2057                        project,
2058                        window,
2059                        cx,
2060                    )
2061                })?
2062                .await?;
2063            } else if can_save_as && is_singleton {
2064                let new_path = pane.update_in(cx, |pane, window, cx| {
2065                    pane.activate_item(item_ix, true, true, window, cx);
2066                    pane.workspace.update(cx, |workspace, cx| {
2067                        let lister = if workspace.project().read(cx).is_local() {
2068                            DirectoryLister::Local(
2069                                workspace.project().clone(),
2070                                workspace.app_state().fs.clone(),
2071                            )
2072                        } else {
2073                            DirectoryLister::Project(workspace.project().clone())
2074                        };
2075                        workspace.prompt_for_new_path(lister, window, cx)
2076                    })
2077                })??;
2078                let Some(new_path) = new_path.await.ok().flatten().into_iter().flatten().next()
2079                else {
2080                    return Ok(false);
2081                };
2082
2083                let project_path = pane
2084                    .update(cx, |pane, cx| {
2085                        pane.project
2086                            .update(cx, |project, cx| {
2087                                project.find_or_create_worktree(new_path, true, cx)
2088                            })
2089                            .ok()
2090                    })
2091                    .ok()
2092                    .flatten();
2093                let save_task = if let Some(project_path) = project_path {
2094                    let (worktree, path) = project_path.await?;
2095                    let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id())?;
2096                    let new_path = ProjectPath {
2097                        worktree_id,
2098                        path: path.into(),
2099                    };
2100
2101                    pane.update_in(cx, |pane, window, cx| {
2102                        if let Some(item) = pane.item_for_path(new_path.clone(), cx) {
2103                            pane.remove_item(item.item_id(), false, false, window, cx);
2104                        }
2105
2106                        item.save_as(project, new_path, window, cx)
2107                    })?
2108                } else {
2109                    return Ok(false);
2110                };
2111
2112                save_task.await?;
2113                return Ok(true);
2114            }
2115        }
2116
2117        pane.update(cx, |_, cx| {
2118            cx.emit(Event::UserSavedItem {
2119                item: item.downgrade_item(),
2120                save_intent,
2121            });
2122            true
2123        })
2124    }
2125
2126    pub fn autosave_item(
2127        item: &dyn ItemHandle,
2128        project: Entity<Project>,
2129        window: &mut Window,
2130        cx: &mut App,
2131    ) -> Task<Result<()>> {
2132        let format = !matches!(
2133            item.workspace_settings(cx).autosave,
2134            AutosaveSetting::AfterDelay { .. }
2135        );
2136        if item.can_autosave(cx) {
2137            item.save(
2138                SaveOptions {
2139                    format,
2140                    autosave: true,
2141                },
2142                project,
2143                window,
2144                cx,
2145            )
2146        } else {
2147            Task::ready(Ok(()))
2148        }
2149    }
2150
2151    pub fn focus_active_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2152        if let Some(active_item) = self.active_item() {
2153            let focus_handle = active_item.item_focus_handle(cx);
2154            window.focus(&focus_handle);
2155        }
2156    }
2157
2158    pub fn split(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
2159        cx.emit(Event::Split(direction));
2160    }
2161
2162    pub fn toolbar(&self) -> &Entity<Toolbar> {
2163        &self.toolbar
2164    }
2165
2166    pub fn handle_deleted_project_item(
2167        &mut self,
2168        entry_id: ProjectEntryId,
2169        window: &mut Window,
2170        cx: &mut Context<Pane>,
2171    ) -> Option<()> {
2172        let item_id = self.items().find_map(|item| {
2173            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
2174                Some(item.item_id())
2175            } else {
2176                None
2177            }
2178        })?;
2179
2180        self.remove_item(item_id, false, true, window, cx);
2181        self.nav_history.remove_item(item_id);
2182
2183        Some(())
2184    }
2185
2186    fn update_toolbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2187        let active_item = self
2188            .items
2189            .get(self.active_item_index)
2190            .map(|item| item.as_ref());
2191        self.toolbar.update(cx, |toolbar, cx| {
2192            toolbar.set_active_item(active_item, window, cx);
2193        });
2194    }
2195
2196    fn update_status_bar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2197        let workspace = self.workspace.clone();
2198        let pane = cx.entity().clone();
2199
2200        window.defer(cx, move |window, cx| {
2201            let Ok(status_bar) =
2202                workspace.read_with(cx, |workspace, _| workspace.status_bar.clone())
2203            else {
2204                return;
2205            };
2206
2207            status_bar.update(cx, move |status_bar, cx| {
2208                status_bar.set_active_pane(&pane, window, cx);
2209            });
2210        });
2211    }
2212
2213    fn entry_abs_path(&self, entry: ProjectEntryId, cx: &App) -> Option<PathBuf> {
2214        let worktree = self
2215            .workspace
2216            .upgrade()?
2217            .read(cx)
2218            .project()
2219            .read(cx)
2220            .worktree_for_entry(entry, cx)?
2221            .read(cx);
2222        let entry = worktree.entry_for_id(entry)?;
2223        match &entry.canonical_path {
2224            Some(canonical_path) => Some(canonical_path.to_path_buf()),
2225            None => worktree.absolutize(&entry.path).ok(),
2226        }
2227    }
2228
2229    pub fn icon_color(selected: bool) -> Color {
2230        if selected {
2231            Color::Default
2232        } else {
2233            Color::Muted
2234        }
2235    }
2236
2237    fn toggle_pin_tab(&mut self, _: &TogglePinTab, window: &mut Window, cx: &mut Context<Self>) {
2238        if self.items.is_empty() {
2239            return;
2240        }
2241        let active_tab_ix = self.active_item_index();
2242        if self.is_tab_pinned(active_tab_ix) {
2243            self.unpin_tab_at(active_tab_ix, window, cx);
2244        } else {
2245            self.pin_tab_at(active_tab_ix, window, cx);
2246        }
2247    }
2248
2249    fn unpin_all_tabs(&mut self, _: &UnpinAllTabs, window: &mut Window, cx: &mut Context<Self>) {
2250        if self.items.is_empty() {
2251            return;
2252        }
2253
2254        let pinned_item_ids = self.pinned_item_ids().into_iter().rev();
2255
2256        for pinned_item_id in pinned_item_ids {
2257            if let Some(ix) = self.index_for_item_id(pinned_item_id) {
2258                self.unpin_tab_at(ix, window, cx);
2259            }
2260        }
2261    }
2262
2263    fn pin_tab_at(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
2264        self.change_tab_pin_state(ix, PinOperation::Pin, window, cx);
2265    }
2266
2267    fn unpin_tab_at(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
2268        self.change_tab_pin_state(ix, PinOperation::Unpin, window, cx);
2269    }
2270
2271    fn change_tab_pin_state(
2272        &mut self,
2273        ix: usize,
2274        operation: PinOperation,
2275        window: &mut Window,
2276        cx: &mut Context<Self>,
2277    ) {
2278        maybe!({
2279            let pane = cx.entity().clone();
2280
2281            let destination_index = match operation {
2282                PinOperation::Pin => self.pinned_tab_count.min(ix),
2283                PinOperation::Unpin => self.pinned_tab_count.checked_sub(1)?,
2284            };
2285
2286            let id = self.item_for_index(ix)?.item_id();
2287            let should_activate = ix == self.active_item_index;
2288
2289            if matches!(operation, PinOperation::Pin) && self.is_active_preview_item(id) {
2290                self.set_preview_item_id(None, cx);
2291            }
2292
2293            match operation {
2294                PinOperation::Pin => self.pinned_tab_count += 1,
2295                PinOperation::Unpin => self.pinned_tab_count -= 1,
2296            }
2297
2298            if ix == destination_index {
2299                cx.notify();
2300            } else {
2301                self.workspace
2302                    .update(cx, |_, cx| {
2303                        cx.defer_in(window, move |_, window, cx| {
2304                            move_item(
2305                                &pane,
2306                                &pane,
2307                                id,
2308                                destination_index,
2309                                should_activate,
2310                                window,
2311                                cx,
2312                            );
2313                        });
2314                    })
2315                    .ok()?;
2316            }
2317
2318            let event = match operation {
2319                PinOperation::Pin => Event::ItemPinned,
2320                PinOperation::Unpin => Event::ItemUnpinned,
2321            };
2322
2323            cx.emit(event);
2324
2325            Some(())
2326        });
2327    }
2328
2329    fn is_tab_pinned(&self, ix: usize) -> bool {
2330        self.pinned_tab_count > ix
2331    }
2332
2333    fn has_unpinned_tabs(&self) -> bool {
2334        self.pinned_tab_count < self.items.len()
2335    }
2336
2337    fn activate_unpinned_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2338        if self.items.is_empty() {
2339            return;
2340        }
2341        let Some(index) = self
2342            .items()
2343            .enumerate()
2344            .find_map(|(index, _item)| (!self.is_tab_pinned(index)).then_some(index))
2345        else {
2346            return;
2347        };
2348        self.activate_item(index, true, true, window, cx);
2349    }
2350
2351    fn render_tab(
2352        &self,
2353        ix: usize,
2354        item: &dyn ItemHandle,
2355        detail: usize,
2356        focus_handle: &FocusHandle,
2357        window: &mut Window,
2358        cx: &mut Context<Pane>,
2359    ) -> impl IntoElement + use<> {
2360        let is_active = ix == self.active_item_index;
2361        let is_preview = self
2362            .preview_item_id
2363            .map(|id| id == item.item_id())
2364            .unwrap_or(false);
2365
2366        let label = item.tab_content(
2367            TabContentParams {
2368                detail: Some(detail),
2369                selected: is_active,
2370                preview: is_preview,
2371                deemphasized: !self.has_focus(window, cx),
2372            },
2373            window,
2374            cx,
2375        );
2376
2377        let item_diagnostic = item
2378            .project_path(cx)
2379            .map_or(None, |project_path| self.diagnostics.get(&project_path));
2380
2381        let decorated_icon = item_diagnostic.map_or(None, |diagnostic| {
2382            let icon = match item.tab_icon(window, cx) {
2383                Some(icon) => icon,
2384                None => return None,
2385            };
2386
2387            let knockout_item_color = if is_active {
2388                cx.theme().colors().tab_active_background
2389            } else {
2390                cx.theme().colors().tab_bar_background
2391            };
2392
2393            let (icon_decoration, icon_color) = if matches!(diagnostic, &DiagnosticSeverity::ERROR)
2394            {
2395                (IconDecorationKind::X, Color::Error)
2396            } else {
2397                (IconDecorationKind::Triangle, Color::Warning)
2398            };
2399
2400            Some(DecoratedIcon::new(
2401                icon.size(IconSize::Small).color(Color::Muted),
2402                Some(
2403                    IconDecoration::new(icon_decoration, knockout_item_color, cx)
2404                        .color(icon_color.color(cx))
2405                        .position(Point {
2406                            x: px(-2.),
2407                            y: px(-2.),
2408                        }),
2409                ),
2410            ))
2411        });
2412
2413        let icon = if decorated_icon.is_none() {
2414            match item_diagnostic {
2415                Some(&DiagnosticSeverity::ERROR) => None,
2416                Some(&DiagnosticSeverity::WARNING) => None,
2417                _ => item
2418                    .tab_icon(window, cx)
2419                    .map(|icon| icon.color(Color::Muted)),
2420            }
2421            .map(|icon| icon.size(IconSize::Small))
2422        } else {
2423            None
2424        };
2425
2426        let settings = ItemSettings::get_global(cx);
2427        let close_side = &settings.close_position;
2428        let show_close_button = &settings.show_close_button;
2429        let indicator = render_item_indicator(item.boxed_clone(), cx);
2430        let item_id = item.item_id();
2431        let is_first_item = ix == 0;
2432        let is_last_item = ix == self.items.len() - 1;
2433        let is_pinned = self.is_tab_pinned(ix);
2434        let position_relative_to_active_item = ix.cmp(&self.active_item_index);
2435
2436        let tab = Tab::new(ix)
2437            .position(if is_first_item {
2438                TabPosition::First
2439            } else if is_last_item {
2440                TabPosition::Last
2441            } else {
2442                TabPosition::Middle(position_relative_to_active_item)
2443            })
2444            .close_side(match close_side {
2445                ClosePosition::Left => ui::TabCloseSide::Start,
2446                ClosePosition::Right => ui::TabCloseSide::End,
2447            })
2448            .toggle_state(is_active)
2449            .on_click(cx.listener(move |pane: &mut Self, _, window, cx| {
2450                pane.activate_item(ix, true, true, window, cx)
2451            }))
2452            // TODO: This should be a click listener with the middle mouse button instead of a mouse down listener.
2453            .on_mouse_down(
2454                MouseButton::Middle,
2455                cx.listener(move |pane, _event, window, cx| {
2456                    pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2457                        .detach_and_log_err(cx);
2458                }),
2459            )
2460            .on_mouse_down(
2461                MouseButton::Left,
2462                cx.listener(move |pane, event: &MouseDownEvent, _, cx| {
2463                    if let Some(id) = pane.preview_item_id {
2464                        if id == item_id && event.click_count > 1 {
2465                            pane.set_preview_item_id(None, cx);
2466                        }
2467                    }
2468                }),
2469            )
2470            .on_drag(
2471                DraggedTab {
2472                    item: item.boxed_clone(),
2473                    pane: cx.entity().clone(),
2474                    detail,
2475                    is_active,
2476                    ix,
2477                },
2478                |tab, _, _, cx| cx.new(|_| tab.clone()),
2479            )
2480            .drag_over::<DraggedTab>(|tab, _, _, cx| {
2481                tab.bg(cx.theme().colors().drop_target_background)
2482            })
2483            .drag_over::<DraggedSelection>(|tab, _, _, cx| {
2484                tab.bg(cx.theme().colors().drop_target_background)
2485            })
2486            .when_some(self.can_drop_predicate.clone(), |this, p| {
2487                this.can_drop(move |a, window, cx| p(a, window, cx))
2488            })
2489            .on_drop(
2490                cx.listener(move |this, dragged_tab: &DraggedTab, window, cx| {
2491                    this.drag_split_direction = None;
2492                    this.handle_tab_drop(dragged_tab, ix, window, cx)
2493                }),
2494            )
2495            .on_drop(
2496                cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2497                    this.drag_split_direction = None;
2498                    this.handle_dragged_selection_drop(selection, Some(ix), window, cx)
2499                }),
2500            )
2501            .on_drop(cx.listener(move |this, paths, window, cx| {
2502                this.drag_split_direction = None;
2503                this.handle_external_paths_drop(paths, window, cx)
2504            }))
2505            .when_some(item.tab_tooltip_content(cx), |tab, content| match content {
2506                TabTooltipContent::Text(text) => tab.tooltip(Tooltip::text(text.clone())),
2507                TabTooltipContent::Custom(element_fn) => {
2508                    tab.tooltip(move |window, cx| element_fn(window, cx))
2509                }
2510            })
2511            .start_slot::<Indicator>(indicator)
2512            .map(|this| {
2513                let end_slot_action: &'static dyn Action;
2514                let end_slot_tooltip_text: &'static str;
2515                let end_slot = if is_pinned {
2516                    end_slot_action = &TogglePinTab;
2517                    end_slot_tooltip_text = "Unpin Tab";
2518                    IconButton::new("unpin tab", IconName::Pin)
2519                        .shape(IconButtonShape::Square)
2520                        .icon_color(Color::Muted)
2521                        .size(ButtonSize::None)
2522                        .icon_size(IconSize::XSmall)
2523                        .on_click(cx.listener(move |pane, _, window, cx| {
2524                            pane.unpin_tab_at(ix, window, cx);
2525                        }))
2526                } else {
2527                    end_slot_action = &CloseActiveItem {
2528                        save_intent: None,
2529                        close_pinned: false,
2530                    };
2531                    end_slot_tooltip_text = "Close Tab";
2532                    match show_close_button {
2533                        ShowCloseButton::Always => IconButton::new("close tab", IconName::Close),
2534                        ShowCloseButton::Hover => {
2535                            IconButton::new("close tab", IconName::Close).visible_on_hover("")
2536                        }
2537                        ShowCloseButton::Hidden => return this,
2538                    }
2539                    .shape(IconButtonShape::Square)
2540                    .icon_color(Color::Muted)
2541                    .size(ButtonSize::None)
2542                    .icon_size(IconSize::XSmall)
2543                    .on_click(cx.listener(move |pane, _, window, cx| {
2544                        pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2545                            .detach_and_log_err(cx);
2546                    }))
2547                }
2548                .map(|this| {
2549                    if is_active {
2550                        let focus_handle = focus_handle.clone();
2551                        this.tooltip(move |window, cx| {
2552                            Tooltip::for_action_in(
2553                                end_slot_tooltip_text,
2554                                end_slot_action,
2555                                &focus_handle,
2556                                window,
2557                                cx,
2558                            )
2559                        })
2560                    } else {
2561                        this.tooltip(Tooltip::text(end_slot_tooltip_text))
2562                    }
2563                });
2564                this.end_slot(end_slot)
2565            })
2566            .child(
2567                h_flex()
2568                    .gap_1()
2569                    .items_center()
2570                    .children(
2571                        std::iter::once(if let Some(decorated_icon) = decorated_icon {
2572                            Some(div().child(decorated_icon.into_any_element()))
2573                        } else if let Some(icon) = icon {
2574                            Some(div().child(icon.into_any_element()))
2575                        } else {
2576                            None
2577                        })
2578                        .flatten(),
2579                    )
2580                    .child(label),
2581            );
2582
2583        let single_entry_to_resolve = self.items[ix]
2584            .is_singleton(cx)
2585            .then(|| self.items[ix].project_entry_ids(cx).get(0).copied())
2586            .flatten();
2587
2588        let total_items = self.items.len();
2589        let has_items_to_left = ix > 0;
2590        let has_items_to_right = ix < total_items - 1;
2591        let has_clean_items = self.items.iter().any(|item| !item.is_dirty(cx));
2592        let is_pinned = self.is_tab_pinned(ix);
2593        let pane = cx.entity().downgrade();
2594        let menu_context = item.item_focus_handle(cx);
2595        right_click_menu(ix)
2596            .trigger(|_, _, _| tab)
2597            .menu(move |window, cx| {
2598                let pane = pane.clone();
2599                let menu_context = menu_context.clone();
2600                ContextMenu::build(window, cx, move |mut menu, window, cx| {
2601                    let close_active_item_action = CloseActiveItem {
2602                        save_intent: None,
2603                        close_pinned: true,
2604                    };
2605                    let close_inactive_items_action = CloseOtherItems {
2606                        save_intent: None,
2607                        close_pinned: false,
2608                    };
2609                    let close_items_to_the_left_action = CloseItemsToTheLeft {
2610                        close_pinned: false,
2611                    };
2612                    let close_items_to_the_right_action = CloseItemsToTheRight {
2613                        close_pinned: false,
2614                    };
2615                    let close_clean_items_action = CloseCleanItems {
2616                        close_pinned: false,
2617                    };
2618                    let close_all_items_action = CloseAllItems {
2619                        save_intent: None,
2620                        close_pinned: false,
2621                    };
2622                    if let Some(pane) = pane.upgrade() {
2623                        menu = menu
2624                            .entry(
2625                                "Close",
2626                                Some(Box::new(close_active_item_action)),
2627                                window.handler_for(&pane, move |pane, window, cx| {
2628                                    pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2629                                        .detach_and_log_err(cx);
2630                                }),
2631                            )
2632                            .item(ContextMenuItem::Entry(
2633                                ContextMenuEntry::new("Close Others")
2634                                    .action(Box::new(close_inactive_items_action.clone()))
2635                                    .disabled(total_items == 1)
2636                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2637                                        pane.close_other_items(
2638                                            &close_inactive_items_action,
2639                                            Some(item_id),
2640                                            window,
2641                                            cx,
2642                                        )
2643                                        .detach_and_log_err(cx);
2644                                    })),
2645                            ))
2646                            .separator()
2647                            .item(ContextMenuItem::Entry(
2648                                ContextMenuEntry::new("Close Left")
2649                                    .action(Box::new(close_items_to_the_left_action.clone()))
2650                                    .disabled(!has_items_to_left)
2651                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2652                                        pane.close_items_to_the_left_by_id(
2653                                            Some(item_id),
2654                                            &close_items_to_the_left_action,
2655                                            window,
2656                                            cx,
2657                                        )
2658                                        .detach_and_log_err(cx);
2659                                    })),
2660                            ))
2661                            .item(ContextMenuItem::Entry(
2662                                ContextMenuEntry::new("Close Right")
2663                                    .action(Box::new(close_items_to_the_right_action.clone()))
2664                                    .disabled(!has_items_to_right)
2665                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2666                                        pane.close_items_to_the_right_by_id(
2667                                            Some(item_id),
2668                                            &close_items_to_the_right_action,
2669                                            window,
2670                                            cx,
2671                                        )
2672                                        .detach_and_log_err(cx);
2673                                    })),
2674                            ))
2675                            .separator()
2676                            .item(ContextMenuItem::Entry(
2677                                ContextMenuEntry::new("Close Clean")
2678                                    .action(Box::new(close_clean_items_action.clone()))
2679                                    .disabled(!has_clean_items)
2680                                    .handler(window.handler_for(&pane, move |pane, window, cx| {
2681                                        pane.close_clean_items(
2682                                            &close_clean_items_action,
2683                                            window,
2684                                            cx,
2685                                        )
2686                                        .detach_and_log_err(cx)
2687                                    })),
2688                            ))
2689                            .entry(
2690                                "Close All",
2691                                Some(Box::new(close_all_items_action.clone())),
2692                                window.handler_for(&pane, move |pane, window, cx| {
2693                                    pane.close_all_items(&close_all_items_action, window, cx)
2694                                        .detach_and_log_err(cx)
2695                                }),
2696                            );
2697
2698                        let pin_tab_entries = |menu: ContextMenu| {
2699                            menu.separator().map(|this| {
2700                                if is_pinned {
2701                                    this.entry(
2702                                        "Unpin Tab",
2703                                        Some(TogglePinTab.boxed_clone()),
2704                                        window.handler_for(&pane, move |pane, window, cx| {
2705                                            pane.unpin_tab_at(ix, window, cx);
2706                                        }),
2707                                    )
2708                                } else {
2709                                    this.entry(
2710                                        "Pin Tab",
2711                                        Some(TogglePinTab.boxed_clone()),
2712                                        window.handler_for(&pane, move |pane, window, cx| {
2713                                            pane.pin_tab_at(ix, window, cx);
2714                                        }),
2715                                    )
2716                                }
2717                            })
2718                        };
2719                        if let Some(entry) = single_entry_to_resolve {
2720                            let project_path = pane
2721                                .read(cx)
2722                                .item_for_entry(entry, cx)
2723                                .and_then(|item| item.project_path(cx));
2724                            let worktree = project_path.as_ref().and_then(|project_path| {
2725                                pane.read(cx)
2726                                    .project
2727                                    .upgrade()?
2728                                    .read(cx)
2729                                    .worktree_for_id(project_path.worktree_id, cx)
2730                            });
2731                            let has_relative_path = worktree.as_ref().is_some_and(|worktree| {
2732                                worktree
2733                                    .read(cx)
2734                                    .root_entry()
2735                                    .map_or(false, |entry| entry.is_dir())
2736                            });
2737
2738                            let entry_abs_path = pane.read(cx).entry_abs_path(entry, cx);
2739                            let parent_abs_path = entry_abs_path
2740                                .as_deref()
2741                                .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
2742                            let relative_path = project_path
2743                                .map(|project_path| project_path.path)
2744                                .filter(|_| has_relative_path);
2745
2746                            let visible_in_project_panel = relative_path.is_some()
2747                                && worktree.is_some_and(|worktree| worktree.read(cx).is_visible());
2748
2749                            let entry_id = entry.to_proto();
2750                            menu = menu
2751                                .separator()
2752                                .when_some(entry_abs_path, |menu, abs_path| {
2753                                    menu.entry(
2754                                        "Copy Path",
2755                                        Some(Box::new(zed_actions::workspace::CopyPath)),
2756                                        window.handler_for(&pane, move |_, _, cx| {
2757                                            cx.write_to_clipboard(ClipboardItem::new_string(
2758                                                abs_path.to_string_lossy().to_string(),
2759                                            ));
2760                                        }),
2761                                    )
2762                                })
2763                                .when_some(relative_path, |menu, relative_path| {
2764                                    menu.entry(
2765                                        "Copy Relative Path",
2766                                        Some(Box::new(zed_actions::workspace::CopyRelativePath)),
2767                                        window.handler_for(&pane, move |_, _, cx| {
2768                                            cx.write_to_clipboard(ClipboardItem::new_string(
2769                                                relative_path.to_string_lossy().to_string(),
2770                                            ));
2771                                        }),
2772                                    )
2773                                })
2774                                .map(pin_tab_entries)
2775                                .separator()
2776                                .when(visible_in_project_panel, |menu| {
2777                                    menu.entry(
2778                                        "Reveal In Project Panel",
2779                                        Some(Box::new(RevealInProjectPanel::default())),
2780                                        window.handler_for(&pane, move |pane, _, cx| {
2781                                            pane.project
2782                                                .update(cx, |_, cx| {
2783                                                    cx.emit(project::Event::RevealInProjectPanel(
2784                                                        ProjectEntryId::from_proto(entry_id),
2785                                                    ))
2786                                                })
2787                                                .ok();
2788                                        }),
2789                                    )
2790                                })
2791                                .when_some(parent_abs_path, |menu, parent_abs_path| {
2792                                    menu.entry(
2793                                        "Open in Terminal",
2794                                        Some(Box::new(OpenInTerminal)),
2795                                        window.handler_for(&pane, move |_, window, cx| {
2796                                            window.dispatch_action(
2797                                                OpenTerminal {
2798                                                    working_directory: parent_abs_path.clone(),
2799                                                }
2800                                                .boxed_clone(),
2801                                                cx,
2802                                            );
2803                                        }),
2804                                    )
2805                                });
2806                        } else {
2807                            menu = menu.map(pin_tab_entries);
2808                        }
2809                    }
2810
2811                    menu.context(menu_context)
2812                })
2813            })
2814    }
2815
2816    fn render_tab_bar(&mut self, window: &mut Window, cx: &mut Context<Pane>) -> AnyElement {
2817        let focus_handle = self.focus_handle.clone();
2818        let navigate_backward = IconButton::new("navigate_backward", IconName::ArrowLeft)
2819            .icon_size(IconSize::Small)
2820            .on_click({
2821                let entity = cx.entity().clone();
2822                move |_, window, cx| {
2823                    entity.update(cx, |pane, cx| pane.navigate_backward(window, cx))
2824                }
2825            })
2826            .disabled(!self.can_navigate_backward())
2827            .tooltip({
2828                let focus_handle = focus_handle.clone();
2829                move |window, cx| {
2830                    Tooltip::for_action_in("Go Back", &GoBack, &focus_handle, window, cx)
2831                }
2832            });
2833
2834        let navigate_forward = IconButton::new("navigate_forward", IconName::ArrowRight)
2835            .icon_size(IconSize::Small)
2836            .on_click({
2837                let entity = cx.entity().clone();
2838                move |_, window, cx| entity.update(cx, |pane, cx| pane.navigate_forward(window, cx))
2839            })
2840            .disabled(!self.can_navigate_forward())
2841            .tooltip({
2842                let focus_handle = focus_handle.clone();
2843                move |window, cx| {
2844                    Tooltip::for_action_in("Go Forward", &GoForward, &focus_handle, window, cx)
2845                }
2846            });
2847
2848        let mut tab_items = self
2849            .items
2850            .iter()
2851            .enumerate()
2852            .zip(tab_details(&self.items, window, cx))
2853            .map(|((ix, item), detail)| {
2854                self.render_tab(ix, &**item, detail, &focus_handle, window, cx)
2855            })
2856            .collect::<Vec<_>>();
2857        let tab_count = tab_items.len();
2858        if self.is_tab_pinned(tab_count) {
2859            log::warn!(
2860                "Pinned tab count ({}) exceeds actual tab count ({}). \
2861                This should not happen. If possible, add reproduction steps, \
2862                in a comment, to https://github.com/zed-industries/zed/issues/33342",
2863                self.pinned_tab_count,
2864                tab_count
2865            );
2866            self.pinned_tab_count = tab_count;
2867        }
2868        let unpinned_tabs = tab_items.split_off(self.pinned_tab_count);
2869        let pinned_tabs = tab_items;
2870        TabBar::new("tab_bar")
2871            .when(
2872                self.display_nav_history_buttons.unwrap_or_default(),
2873                |tab_bar| {
2874                    tab_bar
2875                        .start_child(navigate_backward)
2876                        .start_child(navigate_forward)
2877                },
2878            )
2879            .map(|tab_bar| {
2880                if self.show_tab_bar_buttons {
2881                    let render_tab_buttons = self.render_tab_bar_buttons.clone();
2882                    let (left_children, right_children) = render_tab_buttons(self, window, cx);
2883                    tab_bar
2884                        .start_children(left_children)
2885                        .end_children(right_children)
2886                } else {
2887                    tab_bar
2888                }
2889            })
2890            .children(pinned_tabs.len().ne(&0).then(|| {
2891                let max_scroll = self.tab_bar_scroll_handle.max_offset().width;
2892                // We need to check both because offset returns delta values even when the scroll handle is not scrollable
2893                let is_scrollable = !max_scroll.is_zero();
2894                let is_scrolled = self.tab_bar_scroll_handle.offset().x < px(0.);
2895                let has_active_unpinned_tab = self.active_item_index >= self.pinned_tab_count;
2896                h_flex()
2897                    .children(pinned_tabs)
2898                    .when(is_scrollable && is_scrolled, |this| {
2899                        this.when(has_active_unpinned_tab, |this| this.border_r_2())
2900                            .when(!has_active_unpinned_tab, |this| this.border_r_1())
2901                            .border_color(cx.theme().colors().border)
2902                    })
2903            }))
2904            .child(
2905                h_flex()
2906                    .id("unpinned tabs")
2907                    .overflow_x_scroll()
2908                    .w_full()
2909                    .track_scroll(&self.tab_bar_scroll_handle)
2910                    .children(unpinned_tabs)
2911                    .child(
2912                        div()
2913                            .id("tab_bar_drop_target")
2914                            .min_w_6()
2915                            // HACK: This empty child is currently necessary to force the drop target to appear
2916                            // despite us setting a min width above.
2917                            .child("")
2918                            .h_full()
2919                            .flex_grow()
2920                            .drag_over::<DraggedTab>(|bar, _, _, cx| {
2921                                bar.bg(cx.theme().colors().drop_target_background)
2922                            })
2923                            .drag_over::<DraggedSelection>(|bar, _, _, cx| {
2924                                bar.bg(cx.theme().colors().drop_target_background)
2925                            })
2926                            .on_drop(cx.listener(
2927                                move |this, dragged_tab: &DraggedTab, window, cx| {
2928                                    this.drag_split_direction = None;
2929                                    this.handle_tab_drop(dragged_tab, this.items.len(), window, cx)
2930                                },
2931                            ))
2932                            .on_drop(cx.listener(
2933                                move |this, selection: &DraggedSelection, window, cx| {
2934                                    this.drag_split_direction = None;
2935                                    this.handle_project_entry_drop(
2936                                        &selection.active_selection.entry_id,
2937                                        Some(tab_count),
2938                                        window,
2939                                        cx,
2940                                    )
2941                                },
2942                            ))
2943                            .on_drop(cx.listener(move |this, paths, window, cx| {
2944                                this.drag_split_direction = None;
2945                                this.handle_external_paths_drop(paths, window, cx)
2946                            }))
2947                            .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
2948                                if event.click_count() == 2 {
2949                                    window.dispatch_action(
2950                                        this.double_click_dispatch_action.boxed_clone(),
2951                                        cx,
2952                                    );
2953                                }
2954                            })),
2955                    ),
2956            )
2957            .into_any_element()
2958    }
2959
2960    pub fn render_menu_overlay(menu: &Entity<ContextMenu>) -> Div {
2961        div().absolute().bottom_0().right_0().size_0().child(
2962            deferred(anchored().anchor(Corner::TopRight).child(menu.clone())).with_priority(1),
2963        )
2964    }
2965
2966    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut Context<Self>) {
2967        self.zoomed = zoomed;
2968        cx.notify();
2969    }
2970
2971    pub fn is_zoomed(&self) -> bool {
2972        self.zoomed
2973    }
2974
2975    fn handle_drag_move<T: 'static>(
2976        &mut self,
2977        event: &DragMoveEvent<T>,
2978        window: &mut Window,
2979        cx: &mut Context<Self>,
2980    ) {
2981        let can_split_predicate = self.can_split_predicate.take();
2982        let can_split = match &can_split_predicate {
2983            Some(can_split_predicate) => {
2984                can_split_predicate(self, event.dragged_item(), window, cx)
2985            }
2986            None => false,
2987        };
2988        self.can_split_predicate = can_split_predicate;
2989        if !can_split {
2990            return;
2991        }
2992
2993        let rect = event.bounds.size;
2994
2995        let size = event.bounds.size.width.min(event.bounds.size.height)
2996            * WorkspaceSettings::get_global(cx).drop_target_size;
2997
2998        let relative_cursor = Point::new(
2999            event.event.position.x - event.bounds.left(),
3000            event.event.position.y - event.bounds.top(),
3001        );
3002
3003        let direction = if relative_cursor.x < size
3004            || relative_cursor.x > rect.width - size
3005            || relative_cursor.y < size
3006            || relative_cursor.y > rect.height - size
3007        {
3008            [
3009                SplitDirection::Up,
3010                SplitDirection::Right,
3011                SplitDirection::Down,
3012                SplitDirection::Left,
3013            ]
3014            .iter()
3015            .min_by_key(|side| match side {
3016                SplitDirection::Up => relative_cursor.y,
3017                SplitDirection::Right => rect.width - relative_cursor.x,
3018                SplitDirection::Down => rect.height - relative_cursor.y,
3019                SplitDirection::Left => relative_cursor.x,
3020            })
3021            .cloned()
3022        } else {
3023            None
3024        };
3025
3026        if direction != self.drag_split_direction {
3027            self.drag_split_direction = direction;
3028        }
3029    }
3030
3031    pub fn handle_tab_drop(
3032        &mut self,
3033        dragged_tab: &DraggedTab,
3034        ix: usize,
3035        window: &mut Window,
3036        cx: &mut Context<Self>,
3037    ) {
3038        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
3039            if let ControlFlow::Break(()) = custom_drop_handle(self, dragged_tab, window, cx) {
3040                return;
3041            }
3042        }
3043        let mut to_pane = cx.entity().clone();
3044        let split_direction = self.drag_split_direction;
3045        let item_id = dragged_tab.item.item_id();
3046        if let Some(preview_item_id) = self.preview_item_id {
3047            if item_id == preview_item_id {
3048                self.set_preview_item_id(None, cx);
3049            }
3050        }
3051
3052        let is_clone = cfg!(target_os = "macos") && window.modifiers().alt
3053            || cfg!(not(target_os = "macos")) && window.modifiers().control;
3054
3055        let from_pane = dragged_tab.pane.clone();
3056
3057        self.workspace
3058            .update(cx, |_, cx| {
3059                cx.defer_in(window, move |workspace, window, cx| {
3060                    if let Some(split_direction) = split_direction {
3061                        to_pane = workspace.split_pane(to_pane, split_direction, window, cx);
3062                    }
3063                    let database_id = workspace.database_id();
3064                    let was_pinned_in_from_pane = from_pane.read_with(cx, |pane, _| {
3065                        pane.index_for_item_id(item_id)
3066                            .is_some_and(|ix| pane.is_tab_pinned(ix))
3067                    });
3068                    let to_pane_old_length = to_pane.read(cx).items.len();
3069                    if is_clone {
3070                        let Some(item) = from_pane
3071                            .read(cx)
3072                            .items()
3073                            .find(|item| item.item_id() == item_id)
3074                            .map(|item| item.clone())
3075                        else {
3076                            return;
3077                        };
3078                        if let Some(item) = item.clone_on_split(database_id, window, cx) {
3079                            to_pane.update(cx, |pane, cx| {
3080                                pane.add_item(item, true, true, None, window, cx);
3081                            })
3082                        }
3083                    } else {
3084                        move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3085                    }
3086                    to_pane.update(cx, |this, _| {
3087                        if to_pane == from_pane {
3088                            let actual_ix = this
3089                                .items
3090                                .iter()
3091                                .position(|item| item.item_id() == item_id)
3092                                .unwrap_or(0);
3093
3094                            let is_pinned_in_to_pane = this.is_tab_pinned(actual_ix);
3095
3096                            if !was_pinned_in_from_pane && is_pinned_in_to_pane {
3097                                this.pinned_tab_count += 1;
3098                            } else if was_pinned_in_from_pane && !is_pinned_in_to_pane {
3099                                this.pinned_tab_count -= 1;
3100                            }
3101                        } else if this.items.len() >= to_pane_old_length {
3102                            let is_pinned_in_to_pane = this.is_tab_pinned(ix);
3103                            let item_created_pane = to_pane_old_length == 0;
3104                            let is_first_position = ix == 0;
3105                            let was_dropped_at_beginning = item_created_pane || is_first_position;
3106                            let should_remain_pinned = is_pinned_in_to_pane
3107                                || (was_pinned_in_from_pane && was_dropped_at_beginning);
3108
3109                            if should_remain_pinned {
3110                                this.pinned_tab_count += 1;
3111                            }
3112                        }
3113                    });
3114                });
3115            })
3116            .log_err();
3117    }
3118
3119    fn handle_dragged_selection_drop(
3120        &mut self,
3121        dragged_selection: &DraggedSelection,
3122        dragged_onto: Option<usize>,
3123        window: &mut Window,
3124        cx: &mut Context<Self>,
3125    ) {
3126        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
3127            if let ControlFlow::Break(()) = custom_drop_handle(self, dragged_selection, window, cx)
3128            {
3129                return;
3130            }
3131        }
3132        self.handle_project_entry_drop(
3133            &dragged_selection.active_selection.entry_id,
3134            dragged_onto,
3135            window,
3136            cx,
3137        );
3138    }
3139
3140    fn handle_project_entry_drop(
3141        &mut self,
3142        project_entry_id: &ProjectEntryId,
3143        target: Option<usize>,
3144        window: &mut Window,
3145        cx: &mut Context<Self>,
3146    ) {
3147        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
3148            if let ControlFlow::Break(()) = custom_drop_handle(self, project_entry_id, window, cx) {
3149                return;
3150            }
3151        }
3152        let mut to_pane = cx.entity().clone();
3153        let split_direction = self.drag_split_direction;
3154        let project_entry_id = *project_entry_id;
3155        self.workspace
3156            .update(cx, |_, cx| {
3157                cx.defer_in(window, move |workspace, window, cx| {
3158                    if let Some(project_path) = workspace
3159                        .project()
3160                        .read(cx)
3161                        .path_for_entry(project_entry_id, cx)
3162                    {
3163                        let load_path_task = workspace.load_path(project_path.clone(), window, cx);
3164                        cx.spawn_in(window, async move |workspace, cx| {
3165                            if let Some((project_entry_id, build_item)) =
3166                                load_path_task.await.notify_async_err(cx)
3167                            {
3168                                let (to_pane, new_item_handle) = workspace
3169                                    .update_in(cx, |workspace, window, cx| {
3170                                        if let Some(split_direction) = split_direction {
3171                                            to_pane = workspace.split_pane(
3172                                                to_pane,
3173                                                split_direction,
3174                                                window,
3175                                                cx,
3176                                            );
3177                                        }
3178                                        let new_item_handle = to_pane.update(cx, |pane, cx| {
3179                                            pane.open_item(
3180                                                project_entry_id,
3181                                                project_path,
3182                                                true,
3183                                                false,
3184                                                true,
3185                                                target,
3186                                                window,
3187                                                cx,
3188                                                build_item,
3189                                            )
3190                                        });
3191                                        (to_pane, new_item_handle)
3192                                    })
3193                                    .log_err()?;
3194                                to_pane
3195                                    .update_in(cx, |this, window, cx| {
3196                                        let Some(index) = this.index_for_item(&*new_item_handle)
3197                                        else {
3198                                            return;
3199                                        };
3200
3201                                        if target.map_or(false, |target| this.is_tab_pinned(target))
3202                                        {
3203                                            this.pin_tab_at(index, window, cx);
3204                                        }
3205                                    })
3206                                    .ok()?
3207                            }
3208                            Some(())
3209                        })
3210                        .detach();
3211                    };
3212                });
3213            })
3214            .log_err();
3215    }
3216
3217    fn handle_external_paths_drop(
3218        &mut self,
3219        paths: &ExternalPaths,
3220        window: &mut Window,
3221        cx: &mut Context<Self>,
3222    ) {
3223        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
3224            if let ControlFlow::Break(()) = custom_drop_handle(self, paths, window, cx) {
3225                return;
3226            }
3227        }
3228        let mut to_pane = cx.entity().clone();
3229        let mut split_direction = self.drag_split_direction;
3230        let paths = paths.paths().to_vec();
3231        let is_remote = self
3232            .workspace
3233            .update(cx, |workspace, cx| {
3234                if workspace.project().read(cx).is_via_collab() {
3235                    workspace.show_error(
3236                        &anyhow::anyhow!("Cannot drop files on a remote project"),
3237                        cx,
3238                    );
3239                    true
3240                } else {
3241                    false
3242                }
3243            })
3244            .unwrap_or(true);
3245        if is_remote {
3246            return;
3247        }
3248
3249        self.workspace
3250            .update(cx, |workspace, cx| {
3251                let fs = Arc::clone(workspace.project().read(cx).fs());
3252                cx.spawn_in(window, async move |workspace, cx| {
3253                    let mut is_file_checks = FuturesUnordered::new();
3254                    for path in &paths {
3255                        is_file_checks.push(fs.is_file(path))
3256                    }
3257                    let mut has_files_to_open = false;
3258                    while let Some(is_file) = is_file_checks.next().await {
3259                        if is_file {
3260                            has_files_to_open = true;
3261                            break;
3262                        }
3263                    }
3264                    drop(is_file_checks);
3265                    if !has_files_to_open {
3266                        split_direction = None;
3267                    }
3268
3269                    if let Ok((open_task, to_pane)) =
3270                        workspace.update_in(cx, |workspace, window, cx| {
3271                            if let Some(split_direction) = split_direction {
3272                                to_pane =
3273                                    workspace.split_pane(to_pane, split_direction, window, cx);
3274                            }
3275                            (
3276                                workspace.open_paths(
3277                                    paths,
3278                                    OpenOptions {
3279                                        visible: Some(OpenVisible::OnlyDirectories),
3280                                        ..Default::default()
3281                                    },
3282                                    Some(to_pane.downgrade()),
3283                                    window,
3284                                    cx,
3285                                ),
3286                                to_pane,
3287                            )
3288                        })
3289                    {
3290                        let opened_items: Vec<_> = open_task.await;
3291                        _ = workspace.update_in(cx, |workspace, window, cx| {
3292                            for item in opened_items.into_iter().flatten() {
3293                                if let Err(e) = item {
3294                                    workspace.show_error(&e, cx);
3295                                }
3296                            }
3297                            if to_pane.read(cx).items_len() == 0 {
3298                                workspace.remove_pane(to_pane, None, window, cx);
3299                            }
3300                        });
3301                    }
3302                })
3303                .detach();
3304            })
3305            .log_err();
3306    }
3307
3308    pub fn display_nav_history_buttons(&mut self, display: Option<bool>) {
3309        self.display_nav_history_buttons = display;
3310    }
3311
3312    fn pinned_item_ids(&self) -> Vec<EntityId> {
3313        self.items
3314            .iter()
3315            .enumerate()
3316            .filter_map(|(index, item)| {
3317                if self.is_tab_pinned(index) {
3318                    return Some(item.item_id());
3319                }
3320
3321                None
3322            })
3323            .collect()
3324    }
3325
3326    fn clean_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3327        self.items()
3328            .filter_map(|item| {
3329                if !item.is_dirty(cx) {
3330                    return Some(item.item_id());
3331                }
3332
3333                None
3334            })
3335            .collect()
3336    }
3337
3338    fn to_the_side_item_ids(&self, item_id: EntityId, side: Side) -> Vec<EntityId> {
3339        match side {
3340            Side::Left => self
3341                .items()
3342                .take_while(|item| item.item_id() != item_id)
3343                .map(|item| item.item_id())
3344                .collect(),
3345            Side::Right => self
3346                .items()
3347                .rev()
3348                .take_while(|item| item.item_id() != item_id)
3349                .map(|item| item.item_id())
3350                .collect(),
3351        }
3352    }
3353
3354    pub fn drag_split_direction(&self) -> Option<SplitDirection> {
3355        self.drag_split_direction
3356    }
3357
3358    pub fn set_zoom_out_on_close(&mut self, zoom_out_on_close: bool) {
3359        self.zoom_out_on_close = zoom_out_on_close;
3360    }
3361}
3362
3363fn default_render_tab_bar_buttons(
3364    pane: &mut Pane,
3365    window: &mut Window,
3366    cx: &mut Context<Pane>,
3367) -> (Option<AnyElement>, Option<AnyElement>) {
3368    if !pane.has_focus(window, cx) && !pane.context_menu_focused(window, cx) {
3369        return (None, None);
3370    }
3371    // Ideally we would return a vec of elements here to pass directly to the [TabBar]'s
3372    // `end_slot`, but due to needing a view here that isn't possible.
3373    let right_children = h_flex()
3374        // Instead we need to replicate the spacing from the [TabBar]'s `end_slot` here.
3375        .gap(DynamicSpacing::Base04.rems(cx))
3376        .child(
3377            PopoverMenu::new("pane-tab-bar-popover-menu")
3378                .trigger_with_tooltip(
3379                    IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
3380                    Tooltip::text("New..."),
3381                )
3382                .anchor(Corner::TopRight)
3383                .with_handle(pane.new_item_context_menu_handle.clone())
3384                .menu(move |window, cx| {
3385                    Some(ContextMenu::build(window, cx, |menu, _, _| {
3386                        menu.action("New File", NewFile.boxed_clone())
3387                            .action("Open File", ToggleFileFinder::default().boxed_clone())
3388                            .separator()
3389                            .action(
3390                                "Search Project",
3391                                DeploySearch {
3392                                    replace_enabled: false,
3393                                    included_files: None,
3394                                    excluded_files: None,
3395                                }
3396                                .boxed_clone(),
3397                            )
3398                            .action("Search Symbols", ToggleProjectSymbols.boxed_clone())
3399                            .separator()
3400                            .action("New Terminal", NewTerminal.boxed_clone())
3401                    }))
3402                }),
3403        )
3404        .child(
3405            PopoverMenu::new("pane-tab-bar-split")
3406                .trigger_with_tooltip(
3407                    IconButton::new("split", IconName::Split).icon_size(IconSize::Small),
3408                    Tooltip::text("Split Pane"),
3409                )
3410                .anchor(Corner::TopRight)
3411                .with_handle(pane.split_item_context_menu_handle.clone())
3412                .menu(move |window, cx| {
3413                    ContextMenu::build(window, cx, |menu, _, _| {
3414                        menu.action("Split Right", SplitRight.boxed_clone())
3415                            .action("Split Left", SplitLeft.boxed_clone())
3416                            .action("Split Up", SplitUp.boxed_clone())
3417                            .action("Split Down", SplitDown.boxed_clone())
3418                    })
3419                    .into()
3420                }),
3421        )
3422        .child({
3423            let zoomed = pane.is_zoomed();
3424            IconButton::new("toggle_zoom", IconName::Maximize)
3425                .icon_size(IconSize::Small)
3426                .toggle_state(zoomed)
3427                .selected_icon(IconName::Minimize)
3428                .on_click(cx.listener(|pane, _, window, cx| {
3429                    pane.toggle_zoom(&crate::ToggleZoom, window, cx);
3430                }))
3431                .tooltip(move |window, cx| {
3432                    Tooltip::for_action(
3433                        if zoomed { "Zoom Out" } else { "Zoom In" },
3434                        &ToggleZoom,
3435                        window,
3436                        cx,
3437                    )
3438                })
3439        })
3440        .into_any_element()
3441        .into();
3442    (None, right_children)
3443}
3444
3445impl Focusable for Pane {
3446    fn focus_handle(&self, _cx: &App) -> FocusHandle {
3447        self.focus_handle.clone()
3448    }
3449}
3450
3451impl Render for Pane {
3452    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3453        let mut key_context = KeyContext::new_with_defaults();
3454        key_context.add("Pane");
3455        if self.active_item().is_none() {
3456            key_context.add("EmptyPane");
3457        }
3458
3459        let should_display_tab_bar = self.should_display_tab_bar.clone();
3460        let display_tab_bar = should_display_tab_bar(window, cx);
3461        let Some(project) = self.project.upgrade() else {
3462            return div().track_focus(&self.focus_handle(cx));
3463        };
3464        let is_local = project.read(cx).is_local();
3465
3466        v_flex()
3467            .key_context(key_context)
3468            .track_focus(&self.focus_handle(cx))
3469            .size_full()
3470            .flex_none()
3471            .overflow_hidden()
3472            .on_action(cx.listener(|pane, _: &AlternateFile, window, cx| {
3473                pane.alternate_file(window, cx);
3474            }))
3475            .on_action(
3476                cx.listener(|pane, _: &SplitLeft, _, cx| pane.split(SplitDirection::Left, cx)),
3477            )
3478            .on_action(cx.listener(|pane, _: &SplitUp, _, cx| pane.split(SplitDirection::Up, cx)))
3479            .on_action(cx.listener(|pane, _: &SplitHorizontal, _, cx| {
3480                pane.split(SplitDirection::horizontal(cx), cx)
3481            }))
3482            .on_action(cx.listener(|pane, _: &SplitVertical, _, cx| {
3483                pane.split(SplitDirection::vertical(cx), cx)
3484            }))
3485            .on_action(
3486                cx.listener(|pane, _: &SplitRight, _, cx| pane.split(SplitDirection::Right, cx)),
3487            )
3488            .on_action(
3489                cx.listener(|pane, _: &SplitDown, _, cx| pane.split(SplitDirection::Down, cx)),
3490            )
3491            .on_action(
3492                cx.listener(|pane, _: &GoBack, window, cx| pane.navigate_backward(window, cx)),
3493            )
3494            .on_action(
3495                cx.listener(|pane, _: &GoForward, window, cx| pane.navigate_forward(window, cx)),
3496            )
3497            .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
3498                cx.emit(Event::JoinIntoNext);
3499            }))
3500            .on_action(cx.listener(|_, _: &JoinAll, _, cx| {
3501                cx.emit(Event::JoinAll);
3502            }))
3503            .on_action(cx.listener(Pane::toggle_zoom))
3504            .on_action(
3505                cx.listener(|pane: &mut Pane, action: &ActivateItem, window, cx| {
3506                    pane.activate_item(
3507                        action.0.min(pane.items.len().saturating_sub(1)),
3508                        true,
3509                        true,
3510                        window,
3511                        cx,
3512                    );
3513                }),
3514            )
3515            .on_action(
3516                cx.listener(|pane: &mut Pane, _: &ActivateLastItem, window, cx| {
3517                    pane.activate_item(pane.items.len().saturating_sub(1), true, true, window, cx);
3518                }),
3519            )
3520            .on_action(
3521                cx.listener(|pane: &mut Pane, _: &ActivatePreviousItem, window, cx| {
3522                    pane.activate_prev_item(true, window, cx);
3523                }),
3524            )
3525            .on_action(
3526                cx.listener(|pane: &mut Pane, _: &ActivateNextItem, window, cx| {
3527                    pane.activate_next_item(true, window, cx);
3528                }),
3529            )
3530            .on_action(
3531                cx.listener(|pane, _: &SwapItemLeft, window, cx| pane.swap_item_left(window, cx)),
3532            )
3533            .on_action(
3534                cx.listener(|pane, _: &SwapItemRight, window, cx| pane.swap_item_right(window, cx)),
3535            )
3536            .on_action(cx.listener(|pane, action, window, cx| {
3537                pane.toggle_pin_tab(action, window, cx);
3538            }))
3539            .on_action(cx.listener(|pane, action, window, cx| {
3540                pane.unpin_all_tabs(action, window, cx);
3541            }))
3542            .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
3543                this.on_action(cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, _, cx| {
3544                    if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
3545                        if pane.is_active_preview_item(active_item_id) {
3546                            pane.set_preview_item_id(None, cx);
3547                        } else {
3548                            pane.set_preview_item_id(Some(active_item_id), cx);
3549                        }
3550                    }
3551                }))
3552            })
3553            .on_action(
3554                cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
3555                    pane.close_active_item(action, window, cx)
3556                        .detach_and_log_err(cx)
3557                }),
3558            )
3559            .on_action(
3560                cx.listener(|pane: &mut Self, action: &CloseOtherItems, window, cx| {
3561                    pane.close_other_items(action, None, window, cx)
3562                        .detach_and_log_err(cx);
3563                }),
3564            )
3565            .on_action(
3566                cx.listener(|pane: &mut Self, action: &CloseCleanItems, window, cx| {
3567                    pane.close_clean_items(action, window, cx)
3568                        .detach_and_log_err(cx)
3569                }),
3570            )
3571            .on_action(cx.listener(
3572                |pane: &mut Self, action: &CloseItemsToTheLeft, window, cx| {
3573                    pane.close_items_to_the_left_by_id(None, action, window, cx)
3574                        .detach_and_log_err(cx)
3575                },
3576            ))
3577            .on_action(cx.listener(
3578                |pane: &mut Self, action: &CloseItemsToTheRight, window, cx| {
3579                    pane.close_items_to_the_right_by_id(None, action, window, cx)
3580                        .detach_and_log_err(cx)
3581                },
3582            ))
3583            .on_action(
3584                cx.listener(|pane: &mut Self, action: &CloseAllItems, window, cx| {
3585                    pane.close_all_items(action, window, cx)
3586                        .detach_and_log_err(cx)
3587                }),
3588            )
3589            .on_action(
3590                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, _, cx| {
3591                    let entry_id = action
3592                        .entry_id
3593                        .map(ProjectEntryId::from_proto)
3594                        .or_else(|| pane.active_item()?.project_entry_ids(cx).first().copied());
3595                    if let Some(entry_id) = entry_id {
3596                        pane.project
3597                            .update(cx, |_, cx| {
3598                                cx.emit(project::Event::RevealInProjectPanel(entry_id))
3599                            })
3600                            .ok();
3601                    }
3602                }),
3603            )
3604            .on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
3605                if cx.stop_active_drag(window) {
3606                    return;
3607                } else {
3608                    cx.propagate();
3609                }
3610            }))
3611            .when(self.active_item().is_some() && display_tab_bar, |pane| {
3612                pane.child((self.render_tab_bar.clone())(self, window, cx))
3613            })
3614            .child({
3615                let has_worktrees = project.read(cx).visible_worktrees(cx).next().is_some();
3616                // main content
3617                div()
3618                    .flex_1()
3619                    .relative()
3620                    .group("")
3621                    .overflow_hidden()
3622                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
3623                    .on_drag_move::<DraggedSelection>(cx.listener(Self::handle_drag_move))
3624                    .when(is_local, |div| {
3625                        div.on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
3626                    })
3627                    .map(|div| {
3628                        if let Some(item) = self.active_item() {
3629                            div.id("pane_placeholder")
3630                                .v_flex()
3631                                .size_full()
3632                                .overflow_hidden()
3633                                .child(self.toolbar.clone())
3634                                .child(item.to_any())
3635                        } else {
3636                            let placeholder = div
3637                                .id("pane_placeholder")
3638                                .h_flex()
3639                                .size_full()
3640                                .justify_center()
3641                                .on_click(cx.listener(
3642                                    move |this, event: &ClickEvent, window, cx| {
3643                                        if event.click_count() == 2 {
3644                                            window.dispatch_action(
3645                                                this.double_click_dispatch_action.boxed_clone(),
3646                                                cx,
3647                                            );
3648                                        }
3649                                    },
3650                                ));
3651                            if has_worktrees {
3652                                placeholder
3653                            } else {
3654                                placeholder.child(
3655                                    Label::new("Open a file or project to get started.")
3656                                        .color(Color::Muted),
3657                                )
3658                            }
3659                        }
3660                    })
3661                    .child(
3662                        // drag target
3663                        div()
3664                            .invisible()
3665                            .absolute()
3666                            .bg(cx.theme().colors().drop_target_background)
3667                            .group_drag_over::<DraggedTab>("", |style| style.visible())
3668                            .group_drag_over::<DraggedSelection>("", |style| style.visible())
3669                            .when(is_local, |div| {
3670                                div.group_drag_over::<ExternalPaths>("", |style| style.visible())
3671                            })
3672                            .when_some(self.can_drop_predicate.clone(), |this, p| {
3673                                this.can_drop(move |a, window, cx| p(a, window, cx))
3674                            })
3675                            .on_drop(cx.listener(move |this, dragged_tab, window, cx| {
3676                                this.handle_tab_drop(
3677                                    dragged_tab,
3678                                    this.active_item_index(),
3679                                    window,
3680                                    cx,
3681                                )
3682                            }))
3683                            .on_drop(cx.listener(
3684                                move |this, selection: &DraggedSelection, window, cx| {
3685                                    this.handle_dragged_selection_drop(selection, None, window, cx)
3686                                },
3687                            ))
3688                            .on_drop(cx.listener(move |this, paths, window, cx| {
3689                                this.handle_external_paths_drop(paths, window, cx)
3690                            }))
3691                            .map(|div| {
3692                                let size = DefiniteLength::Fraction(0.5);
3693                                match self.drag_split_direction {
3694                                    None => div.top_0().right_0().bottom_0().left_0(),
3695                                    Some(SplitDirection::Up) => {
3696                                        div.top_0().left_0().right_0().h(size)
3697                                    }
3698                                    Some(SplitDirection::Down) => {
3699                                        div.left_0().bottom_0().right_0().h(size)
3700                                    }
3701                                    Some(SplitDirection::Left) => {
3702                                        div.top_0().left_0().bottom_0().w(size)
3703                                    }
3704                                    Some(SplitDirection::Right) => {
3705                                        div.top_0().bottom_0().right_0().w(size)
3706                                    }
3707                                }
3708                            }),
3709                    )
3710            })
3711            .on_mouse_down(
3712                MouseButton::Navigate(NavigationDirection::Back),
3713                cx.listener(|pane, _, window, cx| {
3714                    if let Some(workspace) = pane.workspace.upgrade() {
3715                        let pane = cx.entity().downgrade();
3716                        window.defer(cx, move |window, cx| {
3717                            workspace.update(cx, |workspace, cx| {
3718                                workspace.go_back(pane, window, cx).detach_and_log_err(cx)
3719                            })
3720                        })
3721                    }
3722                }),
3723            )
3724            .on_mouse_down(
3725                MouseButton::Navigate(NavigationDirection::Forward),
3726                cx.listener(|pane, _, window, cx| {
3727                    if let Some(workspace) = pane.workspace.upgrade() {
3728                        let pane = cx.entity().downgrade();
3729                        window.defer(cx, move |window, cx| {
3730                            workspace.update(cx, |workspace, cx| {
3731                                workspace
3732                                    .go_forward(pane, window, cx)
3733                                    .detach_and_log_err(cx)
3734                            })
3735                        })
3736                    }
3737                }),
3738            )
3739    }
3740}
3741
3742impl ItemNavHistory {
3743    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut App) {
3744        if self
3745            .item
3746            .upgrade()
3747            .is_some_and(|item| item.include_in_nav_history())
3748        {
3749            self.history
3750                .push(data, self.item.clone(), self.is_preview, cx);
3751        }
3752    }
3753
3754    pub fn pop_backward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
3755        self.history.pop(NavigationMode::GoingBack, cx)
3756    }
3757
3758    pub fn pop_forward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
3759        self.history.pop(NavigationMode::GoingForward, cx)
3760    }
3761}
3762
3763impl NavHistory {
3764    pub fn for_each_entry(
3765        &self,
3766        cx: &App,
3767        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
3768    ) {
3769        let borrowed_history = self.0.lock();
3770        borrowed_history
3771            .forward_stack
3772            .iter()
3773            .chain(borrowed_history.backward_stack.iter())
3774            .chain(borrowed_history.closed_stack.iter())
3775            .for_each(|entry| {
3776                if let Some(project_and_abs_path) =
3777                    borrowed_history.paths_by_item.get(&entry.item.id())
3778                {
3779                    f(entry, project_and_abs_path.clone());
3780                } else if let Some(item) = entry.item.upgrade() {
3781                    if let Some(path) = item.project_path(cx) {
3782                        f(entry, (path, None));
3783                    }
3784                }
3785            })
3786    }
3787
3788    pub fn set_mode(&mut self, mode: NavigationMode) {
3789        self.0.lock().mode = mode;
3790    }
3791
3792    pub fn mode(&self) -> NavigationMode {
3793        self.0.lock().mode
3794    }
3795
3796    pub fn disable(&mut self) {
3797        self.0.lock().mode = NavigationMode::Disabled;
3798    }
3799
3800    pub fn enable(&mut self) {
3801        self.0.lock().mode = NavigationMode::Normal;
3802    }
3803
3804    pub fn pop(&mut self, mode: NavigationMode, cx: &mut App) -> Option<NavigationEntry> {
3805        let mut state = self.0.lock();
3806        let entry = match mode {
3807            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
3808                return None;
3809            }
3810            NavigationMode::GoingBack => &mut state.backward_stack,
3811            NavigationMode::GoingForward => &mut state.forward_stack,
3812            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
3813        }
3814        .pop_back();
3815        if entry.is_some() {
3816            state.did_update(cx);
3817        }
3818        entry
3819    }
3820
3821    pub fn push<D: 'static + Send + Any>(
3822        &mut self,
3823        data: Option<D>,
3824        item: Arc<dyn WeakItemHandle>,
3825        is_preview: bool,
3826        cx: &mut App,
3827    ) {
3828        let state = &mut *self.0.lock();
3829        match state.mode {
3830            NavigationMode::Disabled => {}
3831            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
3832                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3833                    state.backward_stack.pop_front();
3834                }
3835                state.backward_stack.push_back(NavigationEntry {
3836                    item,
3837                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3838                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3839                    is_preview,
3840                });
3841                state.forward_stack.clear();
3842            }
3843            NavigationMode::GoingBack => {
3844                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3845                    state.forward_stack.pop_front();
3846                }
3847                state.forward_stack.push_back(NavigationEntry {
3848                    item,
3849                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3850                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3851                    is_preview,
3852                });
3853            }
3854            NavigationMode::GoingForward => {
3855                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3856                    state.backward_stack.pop_front();
3857                }
3858                state.backward_stack.push_back(NavigationEntry {
3859                    item,
3860                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3861                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3862                    is_preview,
3863                });
3864            }
3865            NavigationMode::ClosingItem => {
3866                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
3867                    state.closed_stack.pop_front();
3868                }
3869                state.closed_stack.push_back(NavigationEntry {
3870                    item,
3871                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
3872                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
3873                    is_preview,
3874                });
3875            }
3876        }
3877        state.did_update(cx);
3878    }
3879
3880    pub fn remove_item(&mut self, item_id: EntityId) {
3881        let mut state = self.0.lock();
3882        state.paths_by_item.remove(&item_id);
3883        state
3884            .backward_stack
3885            .retain(|entry| entry.item.id() != item_id);
3886        state
3887            .forward_stack
3888            .retain(|entry| entry.item.id() != item_id);
3889        state
3890            .closed_stack
3891            .retain(|entry| entry.item.id() != item_id);
3892    }
3893
3894    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
3895        self.0.lock().paths_by_item.get(&item_id).cloned()
3896    }
3897}
3898
3899impl NavHistoryState {
3900    pub fn did_update(&self, cx: &mut App) {
3901        if let Some(pane) = self.pane.upgrade() {
3902            cx.defer(move |cx| {
3903                pane.update(cx, |pane, cx| pane.history_updated(cx));
3904            });
3905        }
3906    }
3907}
3908
3909fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
3910    let path = buffer_path
3911        .as_ref()
3912        .and_then(|p| {
3913            p.path
3914                .to_str()
3915                .and_then(|s| if s.is_empty() { None } else { Some(s) })
3916        })
3917        .unwrap_or("This buffer");
3918    let path = truncate_and_remove_front(path, 80);
3919    format!("{path} contains unsaved edits. Do you want to save it?")
3920}
3921
3922pub fn tab_details(items: &[Box<dyn ItemHandle>], _window: &Window, cx: &App) -> Vec<usize> {
3923    let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
3924    let mut tab_descriptions = HashMap::default();
3925    let mut done = false;
3926    while !done {
3927        done = true;
3928
3929        // Store item indices by their tab description.
3930        for (ix, (item, detail)) in items.iter().zip(&tab_details).enumerate() {
3931            let description = item.tab_content_text(*detail, cx);
3932            if *detail == 0 || description != item.tab_content_text(detail - 1, cx) {
3933                tab_descriptions
3934                    .entry(description)
3935                    .or_insert(Vec::new())
3936                    .push(ix);
3937            }
3938        }
3939
3940        // If two or more items have the same tab description, increase their level
3941        // of detail and try again.
3942        for (_, item_ixs) in tab_descriptions.drain() {
3943            if item_ixs.len() > 1 {
3944                done = false;
3945                for ix in item_ixs {
3946                    tab_details[ix] += 1;
3947                }
3948            }
3949        }
3950    }
3951
3952    tab_details
3953}
3954
3955pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &App) -> Option<Indicator> {
3956    maybe!({
3957        let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
3958            (true, _) => Color::Warning,
3959            (_, true) => Color::Accent,
3960            (false, false) => return None,
3961        };
3962
3963        Some(Indicator::dot().color(indicator_color))
3964    })
3965}
3966
3967impl Render for DraggedTab {
3968    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3969        let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
3970        let label = self.item.tab_content(
3971            TabContentParams {
3972                detail: Some(self.detail),
3973                selected: false,
3974                preview: false,
3975                deemphasized: false,
3976            },
3977            window,
3978            cx,
3979        );
3980        Tab::new("")
3981            .toggle_state(self.is_active)
3982            .child(label)
3983            .render(window, cx)
3984            .font(ui_font)
3985    }
3986}
3987
3988#[cfg(test)]
3989mod tests {
3990    use std::num::NonZero;
3991
3992    use super::*;
3993    use crate::item::test::{TestItem, TestProjectItem};
3994    use gpui::{TestAppContext, VisualTestContext};
3995    use project::FakeFs;
3996    use settings::SettingsStore;
3997    use theme::LoadThemes;
3998    use util::TryFutureExt;
3999
4000    #[gpui::test]
4001    async fn test_add_item_capped_to_max_tabs(cx: &mut TestAppContext) {
4002        init_test(cx);
4003        let fs = FakeFs::new(cx.executor());
4004
4005        let project = Project::test(fs, None, cx).await;
4006        let (workspace, cx) =
4007            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4008        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4009
4010        for i in 0..7 {
4011            add_labeled_item(&pane, format!("{}", i).as_str(), false, cx);
4012        }
4013
4014        set_max_tabs(cx, Some(5));
4015        add_labeled_item(&pane, "7", false, cx);
4016        // Remove items to respect the max tab cap.
4017        assert_item_labels(&pane, ["3", "4", "5", "6", "7*"], cx);
4018        pane.update_in(cx, |pane, window, cx| {
4019            pane.activate_item(0, false, false, window, cx);
4020        });
4021        add_labeled_item(&pane, "X", false, cx);
4022        // Respect activation order.
4023        assert_item_labels(&pane, ["3", "X*", "5", "6", "7"], cx);
4024
4025        for i in 0..7 {
4026            add_labeled_item(&pane, format!("D{}", i).as_str(), true, cx);
4027        }
4028        // Keeps dirty items, even over max tab cap.
4029        assert_item_labels(
4030            &pane,
4031            ["D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6*^"],
4032            cx,
4033        );
4034
4035        set_max_tabs(cx, None);
4036        for i in 0..7 {
4037            add_labeled_item(&pane, format!("N{}", i).as_str(), false, cx);
4038        }
4039        // No cap when max tabs is None.
4040        assert_item_labels(
4041            &pane,
4042            [
4043                "D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6^", "N0", "N1", "N2", "N3", "N4",
4044                "N5", "N6*",
4045            ],
4046            cx,
4047        );
4048    }
4049
4050    #[gpui::test]
4051    async fn test_reduce_max_tabs_closes_existing_items(cx: &mut TestAppContext) {
4052        init_test(cx);
4053        let fs = FakeFs::new(cx.executor());
4054
4055        let project = Project::test(fs, None, cx).await;
4056        let (workspace, cx) =
4057            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4058        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4059
4060        add_labeled_item(&pane, "A", false, cx);
4061        add_labeled_item(&pane, "B", false, cx);
4062        let item_c = add_labeled_item(&pane, "C", false, cx);
4063        let item_d = add_labeled_item(&pane, "D", false, cx);
4064        add_labeled_item(&pane, "E", false, cx);
4065        add_labeled_item(&pane, "Settings", false, cx);
4066        assert_item_labels(&pane, ["A", "B", "C", "D", "E", "Settings*"], cx);
4067
4068        set_max_tabs(cx, Some(5));
4069        assert_item_labels(&pane, ["B", "C", "D", "E", "Settings*"], cx);
4070
4071        set_max_tabs(cx, Some(4));
4072        assert_item_labels(&pane, ["C", "D", "E", "Settings*"], cx);
4073
4074        pane.update_in(cx, |pane, window, cx| {
4075            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4076            pane.pin_tab_at(ix, window, cx);
4077
4078            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4079            pane.pin_tab_at(ix, window, cx);
4080        });
4081        assert_item_labels(&pane, ["C!", "D!", "E", "Settings*"], cx);
4082
4083        set_max_tabs(cx, Some(2));
4084        assert_item_labels(&pane, ["C!", "D!", "Settings*"], cx);
4085    }
4086
4087    #[gpui::test]
4088    async fn test_allow_pinning_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4089        init_test(cx);
4090        let fs = FakeFs::new(cx.executor());
4091
4092        let project = Project::test(fs, None, cx).await;
4093        let (workspace, cx) =
4094            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4095        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4096
4097        set_max_tabs(cx, Some(1));
4098        let item_a = add_labeled_item(&pane, "A", true, cx);
4099
4100        pane.update_in(cx, |pane, window, cx| {
4101            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4102            pane.pin_tab_at(ix, window, cx);
4103        });
4104        assert_item_labels(&pane, ["A*^!"], cx);
4105    }
4106
4107    #[gpui::test]
4108    async fn test_allow_pinning_non_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4109        init_test(cx);
4110        let fs = FakeFs::new(cx.executor());
4111
4112        let project = Project::test(fs, None, cx).await;
4113        let (workspace, cx) =
4114            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4115        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4116
4117        set_max_tabs(cx, Some(1));
4118        let item_a = add_labeled_item(&pane, "A", false, cx);
4119
4120        pane.update_in(cx, |pane, window, cx| {
4121            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4122            pane.pin_tab_at(ix, window, cx);
4123        });
4124        assert_item_labels(&pane, ["A*!"], cx);
4125    }
4126
4127    #[gpui::test]
4128    async fn test_pin_tabs_incrementally_at_max_capacity(cx: &mut TestAppContext) {
4129        init_test(cx);
4130        let fs = FakeFs::new(cx.executor());
4131
4132        let project = Project::test(fs, None, cx).await;
4133        let (workspace, cx) =
4134            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4135        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4136
4137        set_max_tabs(cx, Some(3));
4138
4139        let item_a = add_labeled_item(&pane, "A", false, cx);
4140        assert_item_labels(&pane, ["A*"], cx);
4141
4142        pane.update_in(cx, |pane, window, cx| {
4143            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4144            pane.pin_tab_at(ix, window, cx);
4145        });
4146        assert_item_labels(&pane, ["A*!"], cx);
4147
4148        let item_b = add_labeled_item(&pane, "B", false, cx);
4149        assert_item_labels(&pane, ["A!", "B*"], cx);
4150
4151        pane.update_in(cx, |pane, window, cx| {
4152            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4153            pane.pin_tab_at(ix, window, cx);
4154        });
4155        assert_item_labels(&pane, ["A!", "B*!"], cx);
4156
4157        let item_c = add_labeled_item(&pane, "C", false, cx);
4158        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4159
4160        pane.update_in(cx, |pane, window, cx| {
4161            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4162            pane.pin_tab_at(ix, window, cx);
4163        });
4164        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4165    }
4166
4167    #[gpui::test]
4168    async fn test_pin_tabs_left_to_right_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4169        init_test(cx);
4170        let fs = FakeFs::new(cx.executor());
4171
4172        let project = Project::test(fs, None, cx).await;
4173        let (workspace, cx) =
4174            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4175        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4176
4177        set_max_tabs(cx, Some(3));
4178
4179        let item_a = add_labeled_item(&pane, "A", false, cx);
4180        assert_item_labels(&pane, ["A*"], cx);
4181
4182        let item_b = add_labeled_item(&pane, "B", false, cx);
4183        assert_item_labels(&pane, ["A", "B*"], cx);
4184
4185        let item_c = add_labeled_item(&pane, "C", false, cx);
4186        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4187
4188        pane.update_in(cx, |pane, window, cx| {
4189            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4190            pane.pin_tab_at(ix, window, cx);
4191        });
4192        assert_item_labels(&pane, ["A!", "B", "C*"], cx);
4193
4194        pane.update_in(cx, |pane, window, cx| {
4195            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4196            pane.pin_tab_at(ix, window, cx);
4197        });
4198        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4199
4200        pane.update_in(cx, |pane, window, cx| {
4201            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4202            pane.pin_tab_at(ix, window, cx);
4203        });
4204        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4205    }
4206
4207    #[gpui::test]
4208    async fn test_pin_tabs_right_to_left_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4209        init_test(cx);
4210        let fs = FakeFs::new(cx.executor());
4211
4212        let project = Project::test(fs, None, cx).await;
4213        let (workspace, cx) =
4214            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4215        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4216
4217        set_max_tabs(cx, Some(3));
4218
4219        let item_a = add_labeled_item(&pane, "A", false, cx);
4220        assert_item_labels(&pane, ["A*"], cx);
4221
4222        let item_b = add_labeled_item(&pane, "B", false, cx);
4223        assert_item_labels(&pane, ["A", "B*"], cx);
4224
4225        let item_c = add_labeled_item(&pane, "C", false, cx);
4226        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4227
4228        pane.update_in(cx, |pane, window, cx| {
4229            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4230            pane.pin_tab_at(ix, window, cx);
4231        });
4232        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4233
4234        pane.update_in(cx, |pane, window, cx| {
4235            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4236            pane.pin_tab_at(ix, window, cx);
4237        });
4238        assert_item_labels(&pane, ["C*!", "B!", "A"], cx);
4239
4240        pane.update_in(cx, |pane, window, cx| {
4241            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4242            pane.pin_tab_at(ix, window, cx);
4243        });
4244        assert_item_labels(&pane, ["C*!", "B!", "A!"], cx);
4245    }
4246
4247    #[gpui::test]
4248    async fn test_pinned_tabs_never_closed_at_max_tabs(cx: &mut TestAppContext) {
4249        init_test(cx);
4250        let fs = FakeFs::new(cx.executor());
4251
4252        let project = Project::test(fs, None, cx).await;
4253        let (workspace, cx) =
4254            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4255        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4256
4257        let item_a = add_labeled_item(&pane, "A", false, cx);
4258        pane.update_in(cx, |pane, window, cx| {
4259            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4260            pane.pin_tab_at(ix, window, cx);
4261        });
4262
4263        let item_b = add_labeled_item(&pane, "B", false, cx);
4264        pane.update_in(cx, |pane, window, cx| {
4265            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4266            pane.pin_tab_at(ix, window, cx);
4267        });
4268
4269        add_labeled_item(&pane, "C", false, cx);
4270        add_labeled_item(&pane, "D", false, cx);
4271        add_labeled_item(&pane, "E", false, cx);
4272        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
4273
4274        set_max_tabs(cx, Some(3));
4275        add_labeled_item(&pane, "F", false, cx);
4276        assert_item_labels(&pane, ["A!", "B!", "F*"], cx);
4277
4278        add_labeled_item(&pane, "G", false, cx);
4279        assert_item_labels(&pane, ["A!", "B!", "G*"], cx);
4280
4281        add_labeled_item(&pane, "H", false, cx);
4282        assert_item_labels(&pane, ["A!", "B!", "H*"], cx);
4283    }
4284
4285    #[gpui::test]
4286    async fn test_always_allows_one_unpinned_item_over_max_tabs_regardless_of_pinned_count(
4287        cx: &mut TestAppContext,
4288    ) {
4289        init_test(cx);
4290        let fs = FakeFs::new(cx.executor());
4291
4292        let project = Project::test(fs, None, cx).await;
4293        let (workspace, cx) =
4294            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4295        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4296
4297        set_max_tabs(cx, Some(3));
4298
4299        let item_a = add_labeled_item(&pane, "A", false, cx);
4300        pane.update_in(cx, |pane, window, cx| {
4301            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4302            pane.pin_tab_at(ix, window, cx);
4303        });
4304
4305        let item_b = add_labeled_item(&pane, "B", false, cx);
4306        pane.update_in(cx, |pane, window, cx| {
4307            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4308            pane.pin_tab_at(ix, window, cx);
4309        });
4310
4311        let item_c = add_labeled_item(&pane, "C", false, cx);
4312        pane.update_in(cx, |pane, window, cx| {
4313            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4314            pane.pin_tab_at(ix, window, cx);
4315        });
4316
4317        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4318
4319        let item_d = add_labeled_item(&pane, "D", false, cx);
4320        assert_item_labels(&pane, ["A!", "B!", "C!", "D*"], cx);
4321
4322        pane.update_in(cx, |pane, window, cx| {
4323            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4324            pane.pin_tab_at(ix, window, cx);
4325        });
4326        assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
4327
4328        add_labeled_item(&pane, "E", false, cx);
4329        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "E*"], cx);
4330
4331        add_labeled_item(&pane, "F", false, cx);
4332        assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "F*"], cx);
4333    }
4334
4335    #[gpui::test]
4336    async fn test_can_open_one_item_when_all_tabs_are_dirty_at_max(cx: &mut TestAppContext) {
4337        init_test(cx);
4338        let fs = FakeFs::new(cx.executor());
4339
4340        let project = Project::test(fs, None, cx).await;
4341        let (workspace, cx) =
4342            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4343        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4344
4345        set_max_tabs(cx, Some(3));
4346
4347        add_labeled_item(&pane, "A", true, cx);
4348        assert_item_labels(&pane, ["A*^"], cx);
4349
4350        add_labeled_item(&pane, "B", true, cx);
4351        assert_item_labels(&pane, ["A^", "B*^"], cx);
4352
4353        add_labeled_item(&pane, "C", true, cx);
4354        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
4355
4356        add_labeled_item(&pane, "D", false, cx);
4357        assert_item_labels(&pane, ["A^", "B^", "C^", "D*"], cx);
4358
4359        add_labeled_item(&pane, "E", false, cx);
4360        assert_item_labels(&pane, ["A^", "B^", "C^", "E*"], cx);
4361
4362        add_labeled_item(&pane, "F", false, cx);
4363        assert_item_labels(&pane, ["A^", "B^", "C^", "F*"], cx);
4364
4365        add_labeled_item(&pane, "G", true, cx);
4366        assert_item_labels(&pane, ["A^", "B^", "C^", "G*^"], cx);
4367    }
4368
4369    #[gpui::test]
4370    async fn test_toggle_pin_tab(cx: &mut TestAppContext) {
4371        init_test(cx);
4372        let fs = FakeFs::new(cx.executor());
4373
4374        let project = Project::test(fs, None, cx).await;
4375        let (workspace, cx) =
4376            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4377        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4378
4379        set_labeled_items(&pane, ["A", "B*", "C"], cx);
4380        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4381
4382        pane.update_in(cx, |pane, window, cx| {
4383            pane.toggle_pin_tab(&TogglePinTab, window, cx);
4384        });
4385        assert_item_labels(&pane, ["B*!", "A", "C"], cx);
4386
4387        pane.update_in(cx, |pane, window, cx| {
4388            pane.toggle_pin_tab(&TogglePinTab, window, cx);
4389        });
4390        assert_item_labels(&pane, ["B*", "A", "C"], cx);
4391    }
4392
4393    #[gpui::test]
4394    async fn test_unpin_all_tabs(cx: &mut TestAppContext) {
4395        init_test(cx);
4396        let fs = FakeFs::new(cx.executor());
4397
4398        let project = Project::test(fs, None, cx).await;
4399        let (workspace, cx) =
4400            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4401        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4402
4403        // Unpin all, in an empty pane
4404        pane.update_in(cx, |pane, window, cx| {
4405            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4406        });
4407
4408        assert_item_labels(&pane, [], cx);
4409
4410        let item_a = add_labeled_item(&pane, "A", false, cx);
4411        let item_b = add_labeled_item(&pane, "B", false, cx);
4412        let item_c = add_labeled_item(&pane, "C", false, cx);
4413        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4414
4415        // Unpin all, when no tabs are pinned
4416        pane.update_in(cx, |pane, window, cx| {
4417            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4418        });
4419
4420        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4421
4422        // Pin inactive tabs only
4423        pane.update_in(cx, |pane, window, cx| {
4424            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4425            pane.pin_tab_at(ix, window, cx);
4426
4427            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4428            pane.pin_tab_at(ix, window, cx);
4429        });
4430        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4431
4432        pane.update_in(cx, |pane, window, cx| {
4433            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4434        });
4435
4436        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4437
4438        // Pin all tabs
4439        pane.update_in(cx, |pane, window, cx| {
4440            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4441            pane.pin_tab_at(ix, window, cx);
4442
4443            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4444            pane.pin_tab_at(ix, window, cx);
4445
4446            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4447            pane.pin_tab_at(ix, window, cx);
4448        });
4449        assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4450
4451        // Activate middle tab
4452        pane.update_in(cx, |pane, window, cx| {
4453            pane.activate_item(1, false, false, window, cx);
4454        });
4455        assert_item_labels(&pane, ["A!", "B*!", "C!"], cx);
4456
4457        pane.update_in(cx, |pane, window, cx| {
4458            pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4459        });
4460
4461        // Order has not changed
4462        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4463    }
4464
4465    #[gpui::test]
4466    async fn test_pinning_active_tab_without_position_change_maintains_focus(
4467        cx: &mut TestAppContext,
4468    ) {
4469        init_test(cx);
4470        let fs = FakeFs::new(cx.executor());
4471
4472        let project = Project::test(fs, None, cx).await;
4473        let (workspace, cx) =
4474            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4475        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4476
4477        // Add A
4478        let item_a = add_labeled_item(&pane, "A", false, cx);
4479        assert_item_labels(&pane, ["A*"], cx);
4480
4481        // Add B
4482        add_labeled_item(&pane, "B", false, cx);
4483        assert_item_labels(&pane, ["A", "B*"], cx);
4484
4485        // Activate A again
4486        pane.update_in(cx, |pane, window, cx| {
4487            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4488            pane.activate_item(ix, true, true, window, cx);
4489        });
4490        assert_item_labels(&pane, ["A*", "B"], cx);
4491
4492        // Pin A - remains active
4493        pane.update_in(cx, |pane, window, cx| {
4494            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4495            pane.pin_tab_at(ix, window, cx);
4496        });
4497        assert_item_labels(&pane, ["A*!", "B"], cx);
4498
4499        // Unpin A - remain active
4500        pane.update_in(cx, |pane, window, cx| {
4501            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4502            pane.unpin_tab_at(ix, window, cx);
4503        });
4504        assert_item_labels(&pane, ["A*", "B"], cx);
4505    }
4506
4507    #[gpui::test]
4508    async fn test_pinning_active_tab_with_position_change_maintains_focus(cx: &mut TestAppContext) {
4509        init_test(cx);
4510        let fs = FakeFs::new(cx.executor());
4511
4512        let project = Project::test(fs, None, cx).await;
4513        let (workspace, cx) =
4514            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4515        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4516
4517        // Add A, B, C
4518        add_labeled_item(&pane, "A", false, cx);
4519        add_labeled_item(&pane, "B", false, cx);
4520        let item_c = add_labeled_item(&pane, "C", false, cx);
4521        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4522
4523        // Pin C - moves to pinned area, remains active
4524        pane.update_in(cx, |pane, window, cx| {
4525            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4526            pane.pin_tab_at(ix, window, cx);
4527        });
4528        assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4529
4530        // Unpin C - moves after pinned area, remains active
4531        pane.update_in(cx, |pane, window, cx| {
4532            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4533            pane.unpin_tab_at(ix, window, cx);
4534        });
4535        assert_item_labels(&pane, ["C*", "A", "B"], cx);
4536    }
4537
4538    #[gpui::test]
4539    async fn test_pinning_inactive_tab_without_position_change_preserves_existing_focus(
4540        cx: &mut TestAppContext,
4541    ) {
4542        init_test(cx);
4543        let fs = FakeFs::new(cx.executor());
4544
4545        let project = Project::test(fs, None, cx).await;
4546        let (workspace, cx) =
4547            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4548        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4549
4550        // Add A, B
4551        let item_a = add_labeled_item(&pane, "A", false, cx);
4552        add_labeled_item(&pane, "B", false, cx);
4553        assert_item_labels(&pane, ["A", "B*"], cx);
4554
4555        // Pin A - already in pinned area, B remains active
4556        pane.update_in(cx, |pane, window, cx| {
4557            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4558            pane.pin_tab_at(ix, window, cx);
4559        });
4560        assert_item_labels(&pane, ["A!", "B*"], cx);
4561
4562        // Unpin A - stays in place, B remains active
4563        pane.update_in(cx, |pane, window, cx| {
4564            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4565            pane.unpin_tab_at(ix, window, cx);
4566        });
4567        assert_item_labels(&pane, ["A", "B*"], cx);
4568    }
4569
4570    #[gpui::test]
4571    async fn test_pinning_inactive_tab_with_position_change_preserves_existing_focus(
4572        cx: &mut TestAppContext,
4573    ) {
4574        init_test(cx);
4575        let fs = FakeFs::new(cx.executor());
4576
4577        let project = Project::test(fs, None, cx).await;
4578        let (workspace, cx) =
4579            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4580        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4581
4582        // Add A, B, C
4583        add_labeled_item(&pane, "A", false, cx);
4584        let item_b = add_labeled_item(&pane, "B", false, cx);
4585        let item_c = add_labeled_item(&pane, "C", false, cx);
4586        assert_item_labels(&pane, ["A", "B", "C*"], cx);
4587
4588        // Activate B
4589        pane.update_in(cx, |pane, window, cx| {
4590            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4591            pane.activate_item(ix, true, true, window, cx);
4592        });
4593        assert_item_labels(&pane, ["A", "B*", "C"], cx);
4594
4595        // Pin C - moves to pinned area, B remains active
4596        pane.update_in(cx, |pane, window, cx| {
4597            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4598            pane.pin_tab_at(ix, window, cx);
4599        });
4600        assert_item_labels(&pane, ["C!", "A", "B*"], cx);
4601
4602        // Unpin C - moves after pinned area, B remains active
4603        pane.update_in(cx, |pane, window, cx| {
4604            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4605            pane.unpin_tab_at(ix, window, cx);
4606        });
4607        assert_item_labels(&pane, ["C", "A", "B*"], cx);
4608    }
4609
4610    #[gpui::test]
4611    async fn test_drag_unpinned_tab_to_split_creates_pane_with_unpinned_tab(
4612        cx: &mut TestAppContext,
4613    ) {
4614        init_test(cx);
4615        let fs = FakeFs::new(cx.executor());
4616
4617        let project = Project::test(fs, None, cx).await;
4618        let (workspace, cx) =
4619            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4620        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4621
4622        // Add A, B. Pin B. Activate A
4623        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4624        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4625
4626        pane_a.update_in(cx, |pane, window, cx| {
4627            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4628            pane.pin_tab_at(ix, window, cx);
4629
4630            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4631            pane.activate_item(ix, true, true, window, cx);
4632        });
4633
4634        // Drag A to create new split
4635        pane_a.update_in(cx, |pane, window, cx| {
4636            pane.drag_split_direction = Some(SplitDirection::Right);
4637
4638            let dragged_tab = DraggedTab {
4639                pane: pane_a.clone(),
4640                item: item_a.boxed_clone(),
4641                ix: 0,
4642                detail: 0,
4643                is_active: true,
4644            };
4645            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4646        });
4647
4648        // A should be moved to new pane. B should remain pinned, A should not be pinned
4649        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
4650            let panes = workspace.panes();
4651            (panes[0].clone(), panes[1].clone())
4652        });
4653        assert_item_labels(&pane_a, ["B*!"], cx);
4654        assert_item_labels(&pane_b, ["A*"], cx);
4655    }
4656
4657    #[gpui::test]
4658    async fn test_drag_pinned_tab_to_split_creates_pane_with_pinned_tab(cx: &mut TestAppContext) {
4659        init_test(cx);
4660        let fs = FakeFs::new(cx.executor());
4661
4662        let project = Project::test(fs, None, cx).await;
4663        let (workspace, cx) =
4664            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4665        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4666
4667        // Add A, B. Pin both. Activate A
4668        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4669        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4670
4671        pane_a.update_in(cx, |pane, window, cx| {
4672            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4673            pane.pin_tab_at(ix, window, cx);
4674
4675            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4676            pane.pin_tab_at(ix, window, cx);
4677
4678            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4679            pane.activate_item(ix, true, true, window, cx);
4680        });
4681        assert_item_labels(&pane_a, ["A*!", "B!"], cx);
4682
4683        // Drag A to create new split
4684        pane_a.update_in(cx, |pane, window, cx| {
4685            pane.drag_split_direction = Some(SplitDirection::Right);
4686
4687            let dragged_tab = DraggedTab {
4688                pane: pane_a.clone(),
4689                item: item_a.boxed_clone(),
4690                ix: 0,
4691                detail: 0,
4692                is_active: true,
4693            };
4694            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4695        });
4696
4697        // A should be moved to new pane. Both A and B should still be pinned
4698        let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
4699            let panes = workspace.panes();
4700            (panes[0].clone(), panes[1].clone())
4701        });
4702        assert_item_labels(&pane_a, ["B*!"], cx);
4703        assert_item_labels(&pane_b, ["A*!"], cx);
4704    }
4705
4706    #[gpui::test]
4707    async fn test_drag_pinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
4708        init_test(cx);
4709        let fs = FakeFs::new(cx.executor());
4710
4711        let project = Project::test(fs, None, cx).await;
4712        let (workspace, cx) =
4713            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4714        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4715
4716        // Add A to pane A and pin
4717        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4718        pane_a.update_in(cx, |pane, window, cx| {
4719            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4720            pane.pin_tab_at(ix, window, cx);
4721        });
4722        assert_item_labels(&pane_a, ["A*!"], cx);
4723
4724        // Add B to pane B and pin
4725        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4726            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4727        });
4728        let item_b = add_labeled_item(&pane_b, "B", false, cx);
4729        pane_b.update_in(cx, |pane, window, cx| {
4730            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4731            pane.pin_tab_at(ix, window, cx);
4732        });
4733        assert_item_labels(&pane_b, ["B*!"], cx);
4734
4735        // Move A from pane A to pane B's pinned region
4736        pane_b.update_in(cx, |pane, window, cx| {
4737            let dragged_tab = DraggedTab {
4738                pane: pane_a.clone(),
4739                item: item_a.boxed_clone(),
4740                ix: 0,
4741                detail: 0,
4742                is_active: true,
4743            };
4744            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4745        });
4746
4747        // A should stay pinned
4748        assert_item_labels(&pane_a, [], cx);
4749        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
4750    }
4751
4752    #[gpui::test]
4753    async fn test_drag_pinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
4754        init_test(cx);
4755        let fs = FakeFs::new(cx.executor());
4756
4757        let project = Project::test(fs, None, cx).await;
4758        let (workspace, cx) =
4759            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4760        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4761
4762        // Add A to pane A and pin
4763        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4764        pane_a.update_in(cx, |pane, window, cx| {
4765            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4766            pane.pin_tab_at(ix, window, cx);
4767        });
4768        assert_item_labels(&pane_a, ["A*!"], cx);
4769
4770        // Create pane B with pinned item B
4771        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4772            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4773        });
4774        let item_b = add_labeled_item(&pane_b, "B", false, cx);
4775        assert_item_labels(&pane_b, ["B*"], cx);
4776
4777        pane_b.update_in(cx, |pane, window, cx| {
4778            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4779            pane.pin_tab_at(ix, window, cx);
4780        });
4781        assert_item_labels(&pane_b, ["B*!"], cx);
4782
4783        // Move A from pane A to pane B's unpinned region
4784        pane_b.update_in(cx, |pane, window, cx| {
4785            let dragged_tab = DraggedTab {
4786                pane: pane_a.clone(),
4787                item: item_a.boxed_clone(),
4788                ix: 0,
4789                detail: 0,
4790                is_active: true,
4791            };
4792            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
4793        });
4794
4795        // A should become pinned
4796        assert_item_labels(&pane_a, [], cx);
4797        assert_item_labels(&pane_b, ["B!", "A*"], cx);
4798    }
4799
4800    #[gpui::test]
4801    async fn test_drag_pinned_tab_into_existing_panes_first_position_with_no_pinned_tabs(
4802        cx: &mut TestAppContext,
4803    ) {
4804        init_test(cx);
4805        let fs = FakeFs::new(cx.executor());
4806
4807        let project = Project::test(fs, None, cx).await;
4808        let (workspace, cx) =
4809            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4810        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4811
4812        // Add A to pane A and pin
4813        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4814        pane_a.update_in(cx, |pane, window, cx| {
4815            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4816            pane.pin_tab_at(ix, window, cx);
4817        });
4818        assert_item_labels(&pane_a, ["A*!"], cx);
4819
4820        // Add B to pane B
4821        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4822            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4823        });
4824        add_labeled_item(&pane_b, "B", false, cx);
4825        assert_item_labels(&pane_b, ["B*"], cx);
4826
4827        // Move A from pane A to position 0 in pane B, indicating it should stay pinned
4828        pane_b.update_in(cx, |pane, window, cx| {
4829            let dragged_tab = DraggedTab {
4830                pane: pane_a.clone(),
4831                item: item_a.boxed_clone(),
4832                ix: 0,
4833                detail: 0,
4834                is_active: true,
4835            };
4836            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4837        });
4838
4839        // A should stay pinned
4840        assert_item_labels(&pane_a, [], cx);
4841        assert_item_labels(&pane_b, ["A*!", "B"], cx);
4842    }
4843
4844    #[gpui::test]
4845    async fn test_drag_pinned_tab_into_existing_pane_at_max_capacity_closes_unpinned_tabs(
4846        cx: &mut TestAppContext,
4847    ) {
4848        init_test(cx);
4849        let fs = FakeFs::new(cx.executor());
4850
4851        let project = Project::test(fs, None, cx).await;
4852        let (workspace, cx) =
4853            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4854        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4855        set_max_tabs(cx, Some(2));
4856
4857        // Add A, B to pane A. Pin both
4858        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4859        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4860        pane_a.update_in(cx, |pane, window, cx| {
4861            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4862            pane.pin_tab_at(ix, window, cx);
4863
4864            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4865            pane.pin_tab_at(ix, window, cx);
4866        });
4867        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
4868
4869        // Add C, D to pane B. Pin both
4870        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4871            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4872        });
4873        let item_c = add_labeled_item(&pane_b, "C", false, cx);
4874        let item_d = add_labeled_item(&pane_b, "D", false, cx);
4875        pane_b.update_in(cx, |pane, window, cx| {
4876            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4877            pane.pin_tab_at(ix, window, cx);
4878
4879            let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4880            pane.pin_tab_at(ix, window, cx);
4881        });
4882        assert_item_labels(&pane_b, ["C!", "D*!"], cx);
4883
4884        // Add a third unpinned item to pane B (exceeds max tabs), but is allowed,
4885        // as we allow 1 tab over max if the others are pinned or dirty
4886        add_labeled_item(&pane_b, "E", false, cx);
4887        assert_item_labels(&pane_b, ["C!", "D!", "E*"], cx);
4888
4889        // Drag pinned A from pane A to position 0 in pane B
4890        pane_b.update_in(cx, |pane, window, cx| {
4891            let dragged_tab = DraggedTab {
4892                pane: pane_a.clone(),
4893                item: item_a.boxed_clone(),
4894                ix: 0,
4895                detail: 0,
4896                is_active: true,
4897            };
4898            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4899        });
4900
4901        // E (unpinned) should be closed, leaving 3 pinned items
4902        assert_item_labels(&pane_a, ["B*!"], cx);
4903        assert_item_labels(&pane_b, ["A*!", "C!", "D!"], cx);
4904    }
4905
4906    #[gpui::test]
4907    async fn test_drag_last_pinned_tab_to_same_position_stays_pinned(cx: &mut TestAppContext) {
4908        init_test(cx);
4909        let fs = FakeFs::new(cx.executor());
4910
4911        let project = Project::test(fs, None, cx).await;
4912        let (workspace, cx) =
4913            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4914        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4915
4916        // Add A to pane A and pin it
4917        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4918        pane_a.update_in(cx, |pane, window, cx| {
4919            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4920            pane.pin_tab_at(ix, window, cx);
4921        });
4922        assert_item_labels(&pane_a, ["A*!"], cx);
4923
4924        // Drag pinned A to position 1 (directly to the right) in the same pane
4925        pane_a.update_in(cx, |pane, window, cx| {
4926            let dragged_tab = DraggedTab {
4927                pane: pane_a.clone(),
4928                item: item_a.boxed_clone(),
4929                ix: 0,
4930                detail: 0,
4931                is_active: true,
4932            };
4933            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
4934        });
4935
4936        // A should still be pinned and active
4937        assert_item_labels(&pane_a, ["A*!"], cx);
4938    }
4939
4940    #[gpui::test]
4941    async fn test_drag_pinned_tab_beyond_last_pinned_tab_in_same_pane_stays_pinned(
4942        cx: &mut TestAppContext,
4943    ) {
4944        init_test(cx);
4945        let fs = FakeFs::new(cx.executor());
4946
4947        let project = Project::test(fs, None, cx).await;
4948        let (workspace, cx) =
4949            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4950        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4951
4952        // Add A, B to pane A and pin both
4953        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4954        let item_b = add_labeled_item(&pane_a, "B", false, cx);
4955        pane_a.update_in(cx, |pane, window, cx| {
4956            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4957            pane.pin_tab_at(ix, window, cx);
4958
4959            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4960            pane.pin_tab_at(ix, window, cx);
4961        });
4962        assert_item_labels(&pane_a, ["A!", "B*!"], cx);
4963
4964        // Drag pinned A right of B in the same pane
4965        pane_a.update_in(cx, |pane, window, cx| {
4966            let dragged_tab = DraggedTab {
4967                pane: pane_a.clone(),
4968                item: item_a.boxed_clone(),
4969                ix: 0,
4970                detail: 0,
4971                is_active: true,
4972            };
4973            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
4974        });
4975
4976        // A stays pinned
4977        assert_item_labels(&pane_a, ["B!", "A*!"], cx);
4978    }
4979
4980    #[gpui::test]
4981    async fn test_dragging_pinned_tab_onto_unpinned_tab_reduces_unpinned_tab_count(
4982        cx: &mut TestAppContext,
4983    ) {
4984        init_test(cx);
4985        let fs = FakeFs::new(cx.executor());
4986
4987        let project = Project::test(fs, None, cx).await;
4988        let (workspace, cx) =
4989            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4990        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4991
4992        // Add A, B to pane A and pin A
4993        let item_a = add_labeled_item(&pane_a, "A", false, cx);
4994        add_labeled_item(&pane_a, "B", false, cx);
4995        pane_a.update_in(cx, |pane, window, cx| {
4996            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4997            pane.pin_tab_at(ix, window, cx);
4998        });
4999        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5000
5001        // Drag pinned A on top of B in the same pane, which changes tab order to B, A
5002        pane_a.update_in(cx, |pane, window, cx| {
5003            let dragged_tab = DraggedTab {
5004                pane: pane_a.clone(),
5005                item: item_a.boxed_clone(),
5006                ix: 0,
5007                detail: 0,
5008                is_active: true,
5009            };
5010            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5011        });
5012
5013        // Neither are pinned
5014        assert_item_labels(&pane_a, ["B", "A*"], cx);
5015    }
5016
5017    #[gpui::test]
5018    async fn test_drag_pinned_tab_beyond_unpinned_tab_in_same_pane_becomes_unpinned(
5019        cx: &mut TestAppContext,
5020    ) {
5021        init_test(cx);
5022        let fs = FakeFs::new(cx.executor());
5023
5024        let project = Project::test(fs, None, cx).await;
5025        let (workspace, cx) =
5026            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5027        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5028
5029        // Add A, B to pane A and pin A
5030        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5031        add_labeled_item(&pane_a, "B", false, cx);
5032        pane_a.update_in(cx, |pane, window, cx| {
5033            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5034            pane.pin_tab_at(ix, window, cx);
5035        });
5036        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5037
5038        // Drag pinned A right of B in the same pane
5039        pane_a.update_in(cx, |pane, window, cx| {
5040            let dragged_tab = DraggedTab {
5041                pane: pane_a.clone(),
5042                item: item_a.boxed_clone(),
5043                ix: 0,
5044                detail: 0,
5045                is_active: true,
5046            };
5047            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5048        });
5049
5050        // A becomes unpinned
5051        assert_item_labels(&pane_a, ["B", "A*"], cx);
5052    }
5053
5054    #[gpui::test]
5055    async fn test_drag_unpinned_tab_in_front_of_pinned_tab_in_same_pane_becomes_pinned(
5056        cx: &mut TestAppContext,
5057    ) {
5058        init_test(cx);
5059        let fs = FakeFs::new(cx.executor());
5060
5061        let project = Project::test(fs, None, cx).await;
5062        let (workspace, cx) =
5063            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5064        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5065
5066        // Add A, B to pane A and pin A
5067        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5068        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5069        pane_a.update_in(cx, |pane, window, cx| {
5070            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5071            pane.pin_tab_at(ix, window, cx);
5072        });
5073        assert_item_labels(&pane_a, ["A!", "B*"], cx);
5074
5075        // Drag pinned B left of A in the same pane
5076        pane_a.update_in(cx, |pane, window, cx| {
5077            let dragged_tab = DraggedTab {
5078                pane: pane_a.clone(),
5079                item: item_b.boxed_clone(),
5080                ix: 1,
5081                detail: 0,
5082                is_active: true,
5083            };
5084            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5085        });
5086
5087        // A becomes unpinned
5088        assert_item_labels(&pane_a, ["B*!", "A!"], cx);
5089    }
5090
5091    #[gpui::test]
5092    async fn test_drag_unpinned_tab_to_the_pinned_region_stays_pinned(cx: &mut TestAppContext) {
5093        init_test(cx);
5094        let fs = FakeFs::new(cx.executor());
5095
5096        let project = Project::test(fs, None, cx).await;
5097        let (workspace, cx) =
5098            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5099        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5100
5101        // Add A, B, C to pane A and pin A
5102        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5103        add_labeled_item(&pane_a, "B", false, cx);
5104        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5105        pane_a.update_in(cx, |pane, window, cx| {
5106            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5107            pane.pin_tab_at(ix, window, cx);
5108        });
5109        assert_item_labels(&pane_a, ["A!", "B", "C*"], cx);
5110
5111        // Drag pinned C left of B in the same pane
5112        pane_a.update_in(cx, |pane, window, cx| {
5113            let dragged_tab = DraggedTab {
5114                pane: pane_a.clone(),
5115                item: item_c.boxed_clone(),
5116                ix: 2,
5117                detail: 0,
5118                is_active: true,
5119            };
5120            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5121        });
5122
5123        // A stays pinned, B and C remain unpinned
5124        assert_item_labels(&pane_a, ["A!", "C*", "B"], cx);
5125    }
5126
5127    #[gpui::test]
5128    async fn test_drag_unpinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5129        init_test(cx);
5130        let fs = FakeFs::new(cx.executor());
5131
5132        let project = Project::test(fs, None, cx).await;
5133        let (workspace, cx) =
5134            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5135        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5136
5137        // Add unpinned item A to pane A
5138        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5139        assert_item_labels(&pane_a, ["A*"], cx);
5140
5141        // Create pane B with pinned item B
5142        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5143            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5144        });
5145        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5146        pane_b.update_in(cx, |pane, window, cx| {
5147            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5148            pane.pin_tab_at(ix, window, cx);
5149        });
5150        assert_item_labels(&pane_b, ["B*!"], cx);
5151
5152        // Move A from pane A to pane B's pinned region
5153        pane_b.update_in(cx, |pane, window, cx| {
5154            let dragged_tab = DraggedTab {
5155                pane: pane_a.clone(),
5156                item: item_a.boxed_clone(),
5157                ix: 0,
5158                detail: 0,
5159                is_active: true,
5160            };
5161            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5162        });
5163
5164        // A should become pinned since it was dropped in the pinned region
5165        assert_item_labels(&pane_a, [], cx);
5166        assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5167    }
5168
5169    #[gpui::test]
5170    async fn test_drag_unpinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5171        init_test(cx);
5172        let fs = FakeFs::new(cx.executor());
5173
5174        let project = Project::test(fs, None, cx).await;
5175        let (workspace, cx) =
5176            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5177        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5178
5179        // Add unpinned item A to pane A
5180        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5181        assert_item_labels(&pane_a, ["A*"], cx);
5182
5183        // Create pane B with one pinned item B
5184        let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5185            workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5186        });
5187        let item_b = add_labeled_item(&pane_b, "B", false, cx);
5188        pane_b.update_in(cx, |pane, window, cx| {
5189            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5190            pane.pin_tab_at(ix, window, cx);
5191        });
5192        assert_item_labels(&pane_b, ["B*!"], cx);
5193
5194        // Move A from pane A to pane B's unpinned region
5195        pane_b.update_in(cx, |pane, window, cx| {
5196            let dragged_tab = DraggedTab {
5197                pane: pane_a.clone(),
5198                item: item_a.boxed_clone(),
5199                ix: 0,
5200                detail: 0,
5201                is_active: true,
5202            };
5203            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5204        });
5205
5206        // A should remain unpinned since it was dropped outside the pinned region
5207        assert_item_labels(&pane_a, [], cx);
5208        assert_item_labels(&pane_b, ["B!", "A*"], cx);
5209    }
5210
5211    #[gpui::test]
5212    async fn test_drag_pinned_tab_throughout_entire_range_of_pinned_tabs_both_directions(
5213        cx: &mut TestAppContext,
5214    ) {
5215        init_test(cx);
5216        let fs = FakeFs::new(cx.executor());
5217
5218        let project = Project::test(fs, None, cx).await;
5219        let (workspace, cx) =
5220            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5221        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5222
5223        // Add A, B, C and pin all
5224        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5225        let item_b = add_labeled_item(&pane_a, "B", false, cx);
5226        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5227        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5228
5229        pane_a.update_in(cx, |pane, window, cx| {
5230            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5231            pane.pin_tab_at(ix, window, cx);
5232
5233            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5234            pane.pin_tab_at(ix, window, cx);
5235
5236            let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5237            pane.pin_tab_at(ix, window, cx);
5238        });
5239        assert_item_labels(&pane_a, ["A!", "B!", "C*!"], cx);
5240
5241        // Move A to right of B
5242        pane_a.update_in(cx, |pane, window, cx| {
5243            let dragged_tab = DraggedTab {
5244                pane: pane_a.clone(),
5245                item: item_a.boxed_clone(),
5246                ix: 0,
5247                detail: 0,
5248                is_active: true,
5249            };
5250            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5251        });
5252
5253        // A should be after B and all are pinned
5254        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5255
5256        // Move A to right of C
5257        pane_a.update_in(cx, |pane, window, cx| {
5258            let dragged_tab = DraggedTab {
5259                pane: pane_a.clone(),
5260                item: item_a.boxed_clone(),
5261                ix: 1,
5262                detail: 0,
5263                is_active: true,
5264            };
5265            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5266        });
5267
5268        // A should be after C and all are pinned
5269        assert_item_labels(&pane_a, ["B!", "C!", "A*!"], cx);
5270
5271        // Move A to left of C
5272        pane_a.update_in(cx, |pane, window, cx| {
5273            let dragged_tab = DraggedTab {
5274                pane: pane_a.clone(),
5275                item: item_a.boxed_clone(),
5276                ix: 2,
5277                detail: 0,
5278                is_active: true,
5279            };
5280            pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5281        });
5282
5283        // A should be before C and all are pinned
5284        assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5285
5286        // Move A to left of B
5287        pane_a.update_in(cx, |pane, window, cx| {
5288            let dragged_tab = DraggedTab {
5289                pane: pane_a.clone(),
5290                item: item_a.boxed_clone(),
5291                ix: 1,
5292                detail: 0,
5293                is_active: true,
5294            };
5295            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5296        });
5297
5298        // A should be before B and all are pinned
5299        assert_item_labels(&pane_a, ["A*!", "B!", "C!"], cx);
5300    }
5301
5302    #[gpui::test]
5303    async fn test_drag_first_tab_to_last_position(cx: &mut TestAppContext) {
5304        init_test(cx);
5305        let fs = FakeFs::new(cx.executor());
5306
5307        let project = Project::test(fs, None, cx).await;
5308        let (workspace, cx) =
5309            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5310        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5311
5312        // Add A, B, C
5313        let item_a = add_labeled_item(&pane_a, "A", false, cx);
5314        add_labeled_item(&pane_a, "B", false, cx);
5315        add_labeled_item(&pane_a, "C", false, cx);
5316        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5317
5318        // Move A to the end
5319        pane_a.update_in(cx, |pane, window, cx| {
5320            let dragged_tab = DraggedTab {
5321                pane: pane_a.clone(),
5322                item: item_a.boxed_clone(),
5323                ix: 0,
5324                detail: 0,
5325                is_active: true,
5326            };
5327            pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5328        });
5329
5330        // A should be at the end
5331        assert_item_labels(&pane_a, ["B", "C", "A*"], cx);
5332    }
5333
5334    #[gpui::test]
5335    async fn test_drag_last_tab_to_first_position(cx: &mut TestAppContext) {
5336        init_test(cx);
5337        let fs = FakeFs::new(cx.executor());
5338
5339        let project = Project::test(fs, None, cx).await;
5340        let (workspace, cx) =
5341            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5342        let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5343
5344        // Add A, B, C
5345        add_labeled_item(&pane_a, "A", false, cx);
5346        add_labeled_item(&pane_a, "B", false, cx);
5347        let item_c = add_labeled_item(&pane_a, "C", false, cx);
5348        assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5349
5350        // Move C to the beginning
5351        pane_a.update_in(cx, |pane, window, cx| {
5352            let dragged_tab = DraggedTab {
5353                pane: pane_a.clone(),
5354                item: item_c.boxed_clone(),
5355                ix: 2,
5356                detail: 0,
5357                is_active: true,
5358            };
5359            pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5360        });
5361
5362        // C should be at the beginning
5363        assert_item_labels(&pane_a, ["C*", "A", "B"], cx);
5364    }
5365
5366    #[gpui::test]
5367    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
5368        init_test(cx);
5369        let fs = FakeFs::new(cx.executor());
5370
5371        let project = Project::test(fs, None, cx).await;
5372        let (workspace, cx) =
5373            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5374        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5375
5376        // 1. Add with a destination index
5377        //   a. Add before the active item
5378        set_labeled_items(&pane, ["A", "B*", "C"], cx);
5379        pane.update_in(cx, |pane, window, cx| {
5380            pane.add_item(
5381                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5382                false,
5383                false,
5384                Some(0),
5385                window,
5386                cx,
5387            );
5388        });
5389        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5390
5391        //   b. Add after 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(2),
5399                window,
5400                cx,
5401            );
5402        });
5403        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5404
5405        //   c. Add at the end of the item list (including off the length)
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(5),
5413                window,
5414                cx,
5415            );
5416        });
5417        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5418
5419        // 2. Add without a destination index
5420        //   a. Add with active item at the start of the item list
5421        set_labeled_items(&pane, ["A*", "B", "C"], cx);
5422        pane.update_in(cx, |pane, window, cx| {
5423            pane.add_item(
5424                Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5425                false,
5426                false,
5427                None,
5428                window,
5429                cx,
5430            );
5431        });
5432        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
5433
5434        //   b. Add with active item at the end 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        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5447    }
5448
5449    #[gpui::test]
5450    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
5451        init_test(cx);
5452        let fs = FakeFs::new(cx.executor());
5453
5454        let project = Project::test(fs, None, cx).await;
5455        let (workspace, cx) =
5456            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5457        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5458
5459        // 1. Add with a destination index
5460        //   1a. Add before the active item
5461        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5462        pane.update_in(cx, |pane, window, cx| {
5463            pane.add_item(d, false, false, Some(0), window, cx);
5464        });
5465        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5466
5467        //   1b. Add after the active item
5468        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5469        pane.update_in(cx, |pane, window, cx| {
5470            pane.add_item(d, false, false, Some(2), window, cx);
5471        });
5472        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5473
5474        //   1c. Add at the end of the item list (including off the length)
5475        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5476        pane.update_in(cx, |pane, window, cx| {
5477            pane.add_item(a, false, false, Some(5), window, cx);
5478        });
5479        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5480
5481        //   1d. Add same item to active index
5482        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5483        pane.update_in(cx, |pane, window, cx| {
5484            pane.add_item(b, false, false, Some(1), window, cx);
5485        });
5486        assert_item_labels(&pane, ["A", "B*", "C"], cx);
5487
5488        //   1e. Add item to index after same item in last position
5489        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5490        pane.update_in(cx, |pane, window, cx| {
5491            pane.add_item(c, false, false, Some(2), window, cx);
5492        });
5493        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5494
5495        // 2. Add without a destination index
5496        //   2a. Add with active item at the start of the item list
5497        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
5498        pane.update_in(cx, |pane, window, cx| {
5499            pane.add_item(d, false, false, None, window, cx);
5500        });
5501        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
5502
5503        //   2b. Add with active item at the end of the item list
5504        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
5505        pane.update_in(cx, |pane, window, cx| {
5506            pane.add_item(a, false, false, None, window, cx);
5507        });
5508        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5509
5510        //   2c. Add active item to active item at end of list
5511        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
5512        pane.update_in(cx, |pane, window, cx| {
5513            pane.add_item(c, false, false, None, window, cx);
5514        });
5515        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5516
5517        //   2d. Add active item to active item at start of list
5518        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], 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, ["A*", "B", "C"], cx);
5523    }
5524
5525    #[gpui::test]
5526    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
5527        init_test(cx);
5528        let fs = FakeFs::new(cx.executor());
5529
5530        let project = Project::test(fs, None, cx).await;
5531        let (workspace, cx) =
5532            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5533        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5534
5535        // singleton view
5536        pane.update_in(cx, |pane, window, cx| {
5537            pane.add_item(
5538                Box::new(cx.new(|cx| {
5539                    TestItem::new(cx)
5540                        .with_singleton(true)
5541                        .with_label("buffer 1")
5542                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
5543                })),
5544                false,
5545                false,
5546                None,
5547                window,
5548                cx,
5549            );
5550        });
5551        assert_item_labels(&pane, ["buffer 1*"], cx);
5552
5553        // new singleton view with the same project entry
5554        pane.update_in(cx, |pane, window, cx| {
5555            pane.add_item(
5556                Box::new(cx.new(|cx| {
5557                    TestItem::new(cx)
5558                        .with_singleton(true)
5559                        .with_label("buffer 1")
5560                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5561                })),
5562                false,
5563                false,
5564                None,
5565                window,
5566                cx,
5567            );
5568        });
5569        assert_item_labels(&pane, ["buffer 1*"], cx);
5570
5571        // new singleton view with different project entry
5572        pane.update_in(cx, |pane, window, cx| {
5573            pane.add_item(
5574                Box::new(cx.new(|cx| {
5575                    TestItem::new(cx)
5576                        .with_singleton(true)
5577                        .with_label("buffer 2")
5578                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
5579                })),
5580                false,
5581                false,
5582                None,
5583                window,
5584                cx,
5585            );
5586        });
5587        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
5588
5589        // new multibuffer view with the same project entry
5590        pane.update_in(cx, |pane, window, cx| {
5591            pane.add_item(
5592                Box::new(cx.new(|cx| {
5593                    TestItem::new(cx)
5594                        .with_singleton(false)
5595                        .with_label("multibuffer 1")
5596                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5597                })),
5598                false,
5599                false,
5600                None,
5601                window,
5602                cx,
5603            );
5604        });
5605        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
5606
5607        // another multibuffer view with the same project entry
5608        pane.update_in(cx, |pane, window, cx| {
5609            pane.add_item(
5610                Box::new(cx.new(|cx| {
5611                    TestItem::new(cx)
5612                        .with_singleton(false)
5613                        .with_label("multibuffer 1b")
5614                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5615                })),
5616                false,
5617                false,
5618                None,
5619                window,
5620                cx,
5621            );
5622        });
5623        assert_item_labels(
5624            &pane,
5625            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
5626            cx,
5627        );
5628    }
5629
5630    #[gpui::test]
5631    async fn test_remove_item_ordering_history(cx: &mut TestAppContext) {
5632        init_test(cx);
5633        let fs = FakeFs::new(cx.executor());
5634
5635        let project = Project::test(fs, None, cx).await;
5636        let (workspace, cx) =
5637            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5638        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5639
5640        add_labeled_item(&pane, "A", false, cx);
5641        add_labeled_item(&pane, "B", false, cx);
5642        add_labeled_item(&pane, "C", false, cx);
5643        add_labeled_item(&pane, "D", false, cx);
5644        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5645
5646        pane.update_in(cx, |pane, window, cx| {
5647            pane.activate_item(1, false, false, window, cx)
5648        });
5649        add_labeled_item(&pane, "1", false, cx);
5650        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5651
5652        pane.update_in(cx, |pane, window, cx| {
5653            pane.close_active_item(
5654                &CloseActiveItem {
5655                    save_intent: None,
5656                    close_pinned: false,
5657                },
5658                window,
5659                cx,
5660            )
5661        })
5662        .await
5663        .unwrap();
5664        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
5665
5666        pane.update_in(cx, |pane, window, cx| {
5667            pane.activate_item(3, false, false, window, cx)
5668        });
5669        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5670
5671        pane.update_in(cx, |pane, window, cx| {
5672            pane.close_active_item(
5673                &CloseActiveItem {
5674                    save_intent: None,
5675                    close_pinned: false,
5676                },
5677                window,
5678                cx,
5679            )
5680        })
5681        .await
5682        .unwrap();
5683        assert_item_labels(&pane, ["A", "B*", "C"], 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", "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*"], cx);
5712    }
5713
5714    #[gpui::test]
5715    async fn test_remove_item_ordering_neighbour(cx: &mut TestAppContext) {
5716        init_test(cx);
5717        cx.update_global::<SettingsStore, ()>(|s, cx| {
5718            s.update_user_settings::<ItemSettings>(cx, |s| {
5719                s.activate_on_close = Some(ActivateOnClose::Neighbour);
5720            });
5721        });
5722        let fs = FakeFs::new(cx.executor());
5723
5724        let project = Project::test(fs, None, cx).await;
5725        let (workspace, cx) =
5726            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5727        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5728
5729        add_labeled_item(&pane, "A", false, cx);
5730        add_labeled_item(&pane, "B", false, cx);
5731        add_labeled_item(&pane, "C", false, cx);
5732        add_labeled_item(&pane, "D", false, cx);
5733        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5734
5735        pane.update_in(cx, |pane, window, cx| {
5736            pane.activate_item(1, false, false, window, cx)
5737        });
5738        add_labeled_item(&pane, "1", false, cx);
5739        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5740
5741        pane.update_in(cx, |pane, window, cx| {
5742            pane.close_active_item(
5743                &CloseActiveItem {
5744                    save_intent: None,
5745                    close_pinned: false,
5746                },
5747                window,
5748                cx,
5749            )
5750        })
5751        .await
5752        .unwrap();
5753        assert_item_labels(&pane, ["A", "B", "C*", "D"], cx);
5754
5755        pane.update_in(cx, |pane, window, cx| {
5756            pane.activate_item(3, false, false, window, cx)
5757        });
5758        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5759
5760        pane.update_in(cx, |pane, window, cx| {
5761            pane.close_active_item(
5762                &CloseActiveItem {
5763                    save_intent: None,
5764                    close_pinned: false,
5765                },
5766                window,
5767                cx,
5768            )
5769        })
5770        .await
5771        .unwrap();
5772        assert_item_labels(&pane, ["A", "B", "C*"], 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*"], 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*"], cx);
5801    }
5802
5803    #[gpui::test]
5804    async fn test_remove_item_ordering_left_neighbour(cx: &mut TestAppContext) {
5805        init_test(cx);
5806        cx.update_global::<SettingsStore, ()>(|s, cx| {
5807            s.update_user_settings::<ItemSettings>(cx, |s| {
5808                s.activate_on_close = Some(ActivateOnClose::LeftNeighbour);
5809            });
5810        });
5811        let fs = FakeFs::new(cx.executor());
5812
5813        let project = Project::test(fs, None, cx).await;
5814        let (workspace, cx) =
5815            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5816        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5817
5818        add_labeled_item(&pane, "A", false, cx);
5819        add_labeled_item(&pane, "B", false, cx);
5820        add_labeled_item(&pane, "C", false, cx);
5821        add_labeled_item(&pane, "D", false, cx);
5822        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5823
5824        pane.update_in(cx, |pane, window, cx| {
5825            pane.activate_item(1, false, false, window, cx)
5826        });
5827        add_labeled_item(&pane, "1", false, cx);
5828        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5829
5830        pane.update_in(cx, |pane, window, cx| {
5831            pane.close_active_item(
5832                &CloseActiveItem {
5833                    save_intent: None,
5834                    close_pinned: false,
5835                },
5836                window,
5837                cx,
5838            )
5839        })
5840        .await
5841        .unwrap();
5842        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
5843
5844        pane.update_in(cx, |pane, window, cx| {
5845            pane.activate_item(3, false, false, window, cx)
5846        });
5847        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5848
5849        pane.update_in(cx, |pane, window, cx| {
5850            pane.close_active_item(
5851                &CloseActiveItem {
5852                    save_intent: None,
5853                    close_pinned: false,
5854                },
5855                window,
5856                cx,
5857            )
5858        })
5859        .await
5860        .unwrap();
5861        assert_item_labels(&pane, ["A", "B", "C*"], cx);
5862
5863        pane.update_in(cx, |pane, window, cx| {
5864            pane.activate_item(0, false, false, window, cx)
5865        });
5866        assert_item_labels(&pane, ["A*", "B", "C"], cx);
5867
5868        pane.update_in(cx, |pane, window, cx| {
5869            pane.close_active_item(
5870                &CloseActiveItem {
5871                    save_intent: None,
5872                    close_pinned: false,
5873                },
5874                window,
5875                cx,
5876            )
5877        })
5878        .await
5879        .unwrap();
5880        assert_item_labels(&pane, ["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, ["C*"], cx);
5895    }
5896
5897    #[gpui::test]
5898    async fn test_close_inactive_items(cx: &mut TestAppContext) {
5899        init_test(cx);
5900        let fs = FakeFs::new(cx.executor());
5901
5902        let project = Project::test(fs, None, cx).await;
5903        let (workspace, cx) =
5904            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5905        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5906
5907        let item_a = add_labeled_item(&pane, "A", false, cx);
5908        pane.update_in(cx, |pane, window, cx| {
5909            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5910            pane.pin_tab_at(ix, window, cx);
5911        });
5912        assert_item_labels(&pane, ["A*!"], cx);
5913
5914        let item_b = add_labeled_item(&pane, "B", false, cx);
5915        pane.update_in(cx, |pane, window, cx| {
5916            let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5917            pane.pin_tab_at(ix, window, cx);
5918        });
5919        assert_item_labels(&pane, ["A!", "B*!"], cx);
5920
5921        add_labeled_item(&pane, "C", false, cx);
5922        assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
5923
5924        add_labeled_item(&pane, "D", false, cx);
5925        add_labeled_item(&pane, "E", false, cx);
5926        assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
5927
5928        pane.update_in(cx, |pane, window, cx| {
5929            pane.close_other_items(
5930                &CloseOtherItems {
5931                    save_intent: None,
5932                    close_pinned: false,
5933                },
5934                None,
5935                window,
5936                cx,
5937            )
5938        })
5939        .await
5940        .unwrap();
5941        assert_item_labels(&pane, ["A!", "B!", "E*"], cx);
5942    }
5943
5944    #[gpui::test]
5945    async fn test_running_close_inactive_items_via_an_inactive_item(cx: &mut TestAppContext) {
5946        init_test(cx);
5947        let fs = FakeFs::new(cx.executor());
5948
5949        let project = Project::test(fs, None, cx).await;
5950        let (workspace, cx) =
5951            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5952        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5953
5954        add_labeled_item(&pane, "A", false, cx);
5955        assert_item_labels(&pane, ["A*"], cx);
5956
5957        let item_b = add_labeled_item(&pane, "B", false, cx);
5958        assert_item_labels(&pane, ["A", "B*"], cx);
5959
5960        add_labeled_item(&pane, "C", false, cx);
5961        add_labeled_item(&pane, "D", false, cx);
5962        add_labeled_item(&pane, "E", false, cx);
5963        assert_item_labels(&pane, ["A", "B", "C", "D", "E*"], cx);
5964
5965        pane.update_in(cx, |pane, window, cx| {
5966            pane.close_other_items(
5967                &CloseOtherItems {
5968                    save_intent: None,
5969                    close_pinned: false,
5970                },
5971                Some(item_b.item_id()),
5972                window,
5973                cx,
5974            )
5975        })
5976        .await
5977        .unwrap();
5978        assert_item_labels(&pane, ["B*"], cx);
5979    }
5980
5981    #[gpui::test]
5982    async fn test_close_clean_items(cx: &mut TestAppContext) {
5983        init_test(cx);
5984        let fs = FakeFs::new(cx.executor());
5985
5986        let project = Project::test(fs, None, cx).await;
5987        let (workspace, cx) =
5988            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5989        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5990
5991        add_labeled_item(&pane, "A", true, cx);
5992        add_labeled_item(&pane, "B", false, cx);
5993        add_labeled_item(&pane, "C", true, cx);
5994        add_labeled_item(&pane, "D", false, cx);
5995        add_labeled_item(&pane, "E", false, cx);
5996        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
5997
5998        pane.update_in(cx, |pane, window, cx| {
5999            pane.close_clean_items(
6000                &CloseCleanItems {
6001                    close_pinned: false,
6002                },
6003                window,
6004                cx,
6005            )
6006        })
6007        .await
6008        .unwrap();
6009        assert_item_labels(&pane, ["A^", "C*^"], cx);
6010    }
6011
6012    #[gpui::test]
6013    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
6014        init_test(cx);
6015        let fs = FakeFs::new(cx.executor());
6016
6017        let project = Project::test(fs, None, cx).await;
6018        let (workspace, cx) =
6019            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6020        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6021
6022        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6023
6024        pane.update_in(cx, |pane, window, cx| {
6025            pane.close_items_to_the_left_by_id(
6026                None,
6027                &CloseItemsToTheLeft {
6028                    close_pinned: false,
6029                },
6030                window,
6031                cx,
6032            )
6033        })
6034        .await
6035        .unwrap();
6036        assert_item_labels(&pane, ["C*", "D", "E"], cx);
6037    }
6038
6039    #[gpui::test]
6040    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
6041        init_test(cx);
6042        let fs = FakeFs::new(cx.executor());
6043
6044        let project = Project::test(fs, None, cx).await;
6045        let (workspace, cx) =
6046            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6047        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6048
6049        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6050
6051        pane.update_in(cx, |pane, window, cx| {
6052            pane.close_items_to_the_right_by_id(
6053                None,
6054                &CloseItemsToTheRight {
6055                    close_pinned: false,
6056                },
6057                window,
6058                cx,
6059            )
6060        })
6061        .await
6062        .unwrap();
6063        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6064    }
6065
6066    #[gpui::test]
6067    async fn test_close_all_items(cx: &mut TestAppContext) {
6068        init_test(cx);
6069        let fs = FakeFs::new(cx.executor());
6070
6071        let project = Project::test(fs, None, cx).await;
6072        let (workspace, cx) =
6073            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6074        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6075
6076        let item_a = add_labeled_item(&pane, "A", false, cx);
6077        add_labeled_item(&pane, "B", false, cx);
6078        add_labeled_item(&pane, "C", false, cx);
6079        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6080
6081        pane.update_in(cx, |pane, window, cx| {
6082            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6083            pane.pin_tab_at(ix, window, cx);
6084            pane.close_all_items(
6085                &CloseAllItems {
6086                    save_intent: None,
6087                    close_pinned: false,
6088                },
6089                window,
6090                cx,
6091            )
6092        })
6093        .await
6094        .unwrap();
6095        assert_item_labels(&pane, ["A*!"], cx);
6096
6097        pane.update_in(cx, |pane, window, cx| {
6098            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6099            pane.unpin_tab_at(ix, window, cx);
6100            pane.close_all_items(
6101                &CloseAllItems {
6102                    save_intent: None,
6103                    close_pinned: false,
6104                },
6105                window,
6106                cx,
6107            )
6108        })
6109        .await
6110        .unwrap();
6111
6112        assert_item_labels(&pane, [], cx);
6113
6114        add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6115            item.project_items
6116                .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6117        });
6118        add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6119            item.project_items
6120                .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6121        });
6122        add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6123            item.project_items
6124                .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6125        });
6126        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6127
6128        let save = pane.update_in(cx, |pane, window, cx| {
6129            pane.close_all_items(
6130                &CloseAllItems {
6131                    save_intent: None,
6132                    close_pinned: false,
6133                },
6134                window,
6135                cx,
6136            )
6137        });
6138
6139        cx.executor().run_until_parked();
6140        cx.simulate_prompt_answer("Save all");
6141        save.await.unwrap();
6142        assert_item_labels(&pane, [], cx);
6143
6144        add_labeled_item(&pane, "A", true, cx);
6145        add_labeled_item(&pane, "B", true, cx);
6146        add_labeled_item(&pane, "C", true, cx);
6147        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6148        let save = pane.update_in(cx, |pane, window, cx| {
6149            pane.close_all_items(
6150                &CloseAllItems {
6151                    save_intent: None,
6152                    close_pinned: false,
6153                },
6154                window,
6155                cx,
6156            )
6157        });
6158
6159        cx.executor().run_until_parked();
6160        cx.simulate_prompt_answer("Discard all");
6161        save.await.unwrap();
6162        assert_item_labels(&pane, [], cx);
6163    }
6164
6165    #[gpui::test]
6166    async fn test_close_with_save_intent(cx: &mut TestAppContext) {
6167        init_test(cx);
6168        let fs = FakeFs::new(cx.executor());
6169
6170        let project = Project::test(fs, None, cx).await;
6171        let (workspace, cx) =
6172            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6173        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6174
6175        let a = cx.update(|_, cx| TestProjectItem::new_dirty(1, "A.txt", cx));
6176        let b = cx.update(|_, cx| TestProjectItem::new_dirty(1, "B.txt", cx));
6177        let c = cx.update(|_, cx| TestProjectItem::new_dirty(1, "C.txt", cx));
6178
6179        add_labeled_item(&pane, "AB", true, cx).update(cx, |item, _| {
6180            item.project_items.push(a.clone());
6181            item.project_items.push(b.clone());
6182        });
6183        add_labeled_item(&pane, "C", true, cx)
6184            .update(cx, |item, _| item.project_items.push(c.clone()));
6185        assert_item_labels(&pane, ["AB^", "C*^"], cx);
6186
6187        pane.update_in(cx, |pane, window, cx| {
6188            pane.close_all_items(
6189                &CloseAllItems {
6190                    save_intent: Some(SaveIntent::Save),
6191                    close_pinned: false,
6192                },
6193                window,
6194                cx,
6195            )
6196        })
6197        .await
6198        .unwrap();
6199
6200        assert_item_labels(&pane, [], cx);
6201        cx.update(|_, cx| {
6202            assert!(!a.read(cx).is_dirty);
6203            assert!(!b.read(cx).is_dirty);
6204            assert!(!c.read(cx).is_dirty);
6205        });
6206    }
6207
6208    #[gpui::test]
6209    async fn test_close_all_items_including_pinned(cx: &mut TestAppContext) {
6210        init_test(cx);
6211        let fs = FakeFs::new(cx.executor());
6212
6213        let project = Project::test(fs, None, cx).await;
6214        let (workspace, cx) =
6215            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6216        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6217
6218        let item_a = add_labeled_item(&pane, "A", false, cx);
6219        add_labeled_item(&pane, "B", false, cx);
6220        add_labeled_item(&pane, "C", false, cx);
6221        assert_item_labels(&pane, ["A", "B", "C*"], cx);
6222
6223        pane.update_in(cx, |pane, window, cx| {
6224            let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6225            pane.pin_tab_at(ix, window, cx);
6226            pane.close_all_items(
6227                &CloseAllItems {
6228                    save_intent: None,
6229                    close_pinned: true,
6230                },
6231                window,
6232                cx,
6233            )
6234        })
6235        .await
6236        .unwrap();
6237        assert_item_labels(&pane, [], cx);
6238    }
6239
6240    #[gpui::test]
6241    async fn test_close_pinned_tab_with_non_pinned_in_same_pane(cx: &mut TestAppContext) {
6242        init_test(cx);
6243        let fs = FakeFs::new(cx.executor());
6244        let project = Project::test(fs, None, cx).await;
6245        let (workspace, cx) =
6246            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6247
6248        // Non-pinned tabs in same pane
6249        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6250        add_labeled_item(&pane, "A", false, cx);
6251        add_labeled_item(&pane, "B", false, cx);
6252        add_labeled_item(&pane, "C", false, cx);
6253        pane.update_in(cx, |pane, window, cx| {
6254            pane.pin_tab_at(0, window, cx);
6255        });
6256        set_labeled_items(&pane, ["A*", "B", "C"], cx);
6257        pane.update_in(cx, |pane, window, cx| {
6258            pane.close_active_item(
6259                &CloseActiveItem {
6260                    save_intent: None,
6261                    close_pinned: false,
6262                },
6263                window,
6264                cx,
6265            )
6266            .unwrap();
6267        });
6268        // Non-pinned tab should be active
6269        assert_item_labels(&pane, ["A!", "B*", "C"], cx);
6270    }
6271
6272    #[gpui::test]
6273    async fn test_close_pinned_tab_with_non_pinned_in_different_pane(cx: &mut TestAppContext) {
6274        init_test(cx);
6275        let fs = FakeFs::new(cx.executor());
6276        let project = Project::test(fs, None, cx).await;
6277        let (workspace, cx) =
6278            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6279
6280        // No non-pinned tabs in same pane, non-pinned tabs in another pane
6281        let pane1 = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6282        let pane2 = workspace.update_in(cx, |workspace, window, cx| {
6283            workspace.split_pane(pane1.clone(), SplitDirection::Right, window, cx)
6284        });
6285        add_labeled_item(&pane1, "A", false, cx);
6286        pane1.update_in(cx, |pane, window, cx| {
6287            pane.pin_tab_at(0, window, cx);
6288        });
6289        set_labeled_items(&pane1, ["A*"], cx);
6290        add_labeled_item(&pane2, "B", false, cx);
6291        set_labeled_items(&pane2, ["B"], cx);
6292        pane1.update_in(cx, |pane, window, cx| {
6293            pane.close_active_item(
6294                &CloseActiveItem {
6295                    save_intent: None,
6296                    close_pinned: false,
6297                },
6298                window,
6299                cx,
6300            )
6301            .unwrap();
6302        });
6303        //  Non-pinned tab of other pane should be active
6304        assert_item_labels(&pane2, ["B*"], cx);
6305    }
6306
6307    #[gpui::test]
6308    async fn ensure_item_closing_actions_do_not_panic_when_no_items_exist(cx: &mut TestAppContext) {
6309        init_test(cx);
6310        let fs = FakeFs::new(cx.executor());
6311        let project = Project::test(fs, None, cx).await;
6312        let (workspace, cx) =
6313            cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6314
6315        let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6316        assert_item_labels(&pane, [], cx);
6317
6318        pane.update_in(cx, |pane, window, cx| {
6319            pane.close_active_item(
6320                &CloseActiveItem {
6321                    save_intent: None,
6322                    close_pinned: false,
6323                },
6324                window,
6325                cx,
6326            )
6327        })
6328        .await
6329        .unwrap();
6330
6331        pane.update_in(cx, |pane, window, cx| {
6332            pane.close_other_items(
6333                &CloseOtherItems {
6334                    save_intent: None,
6335                    close_pinned: false,
6336                },
6337                None,
6338                window,
6339                cx,
6340            )
6341        })
6342        .await
6343        .unwrap();
6344
6345        pane.update_in(cx, |pane, window, cx| {
6346            pane.close_all_items(
6347                &CloseAllItems {
6348                    save_intent: None,
6349                    close_pinned: false,
6350                },
6351                window,
6352                cx,
6353            )
6354        })
6355        .await
6356        .unwrap();
6357
6358        pane.update_in(cx, |pane, window, cx| {
6359            pane.close_clean_items(
6360                &CloseCleanItems {
6361                    close_pinned: false,
6362                },
6363                window,
6364                cx,
6365            )
6366        })
6367        .await
6368        .unwrap();
6369
6370        pane.update_in(cx, |pane, window, cx| {
6371            pane.close_items_to_the_right_by_id(
6372                None,
6373                &CloseItemsToTheRight {
6374                    close_pinned: false,
6375                },
6376                window,
6377                cx,
6378            )
6379        })
6380        .await
6381        .unwrap();
6382
6383        pane.update_in(cx, |pane, window, cx| {
6384            pane.close_items_to_the_left_by_id(
6385                None,
6386                &CloseItemsToTheLeft {
6387                    close_pinned: false,
6388                },
6389                window,
6390                cx,
6391            )
6392        })
6393        .await
6394        .unwrap();
6395    }
6396
6397    fn init_test(cx: &mut TestAppContext) {
6398        cx.update(|cx| {
6399            let settings_store = SettingsStore::test(cx);
6400            cx.set_global(settings_store);
6401            theme::init(LoadThemes::JustBase, cx);
6402            crate::init_settings(cx);
6403            Project::init_settings(cx);
6404        });
6405    }
6406
6407    fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
6408        cx.update_global(|store: &mut SettingsStore, cx| {
6409            store.update_user_settings::<WorkspaceSettings>(cx, |settings| {
6410                settings.max_tabs = value.map(|v| NonZero::new(v).unwrap())
6411            });
6412        });
6413    }
6414
6415    fn add_labeled_item(
6416        pane: &Entity<Pane>,
6417        label: &str,
6418        is_dirty: bool,
6419        cx: &mut VisualTestContext,
6420    ) -> Box<Entity<TestItem>> {
6421        pane.update_in(cx, |pane, window, cx| {
6422            let labeled_item =
6423                Box::new(cx.new(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)));
6424            pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6425            labeled_item
6426        })
6427    }
6428
6429    fn set_labeled_items<const COUNT: usize>(
6430        pane: &Entity<Pane>,
6431        labels: [&str; COUNT],
6432        cx: &mut VisualTestContext,
6433    ) -> [Box<Entity<TestItem>>; COUNT] {
6434        pane.update_in(cx, |pane, window, cx| {
6435            pane.items.clear();
6436            let mut active_item_index = 0;
6437
6438            let mut index = 0;
6439            let items = labels.map(|mut label| {
6440                if label.ends_with('*') {
6441                    label = label.trim_end_matches('*');
6442                    active_item_index = index;
6443                }
6444
6445                let labeled_item = Box::new(cx.new(|cx| TestItem::new(cx).with_label(label)));
6446                pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6447                index += 1;
6448                labeled_item
6449            });
6450
6451            pane.activate_item(active_item_index, false, false, window, cx);
6452
6453            items
6454        })
6455    }
6456
6457    // Assert the item label, with the active item label suffixed with a '*'
6458    #[track_caller]
6459    fn assert_item_labels<const COUNT: usize>(
6460        pane: &Entity<Pane>,
6461        expected_states: [&str; COUNT],
6462        cx: &mut VisualTestContext,
6463    ) {
6464        let actual_states = pane.update(cx, |pane, cx| {
6465            pane.items
6466                .iter()
6467                .enumerate()
6468                .map(|(ix, item)| {
6469                    let mut state = item
6470                        .to_any()
6471                        .downcast::<TestItem>()
6472                        .unwrap()
6473                        .read(cx)
6474                        .label
6475                        .clone();
6476                    if ix == pane.active_item_index {
6477                        state.push('*');
6478                    }
6479                    if item.is_dirty(cx) {
6480                        state.push('^');
6481                    }
6482                    if pane.is_tab_pinned(ix) {
6483                        state.push('!');
6484                    }
6485                    state
6486                })
6487                .collect::<Vec<_>>()
6488        });
6489        assert_eq!(
6490            actual_states, expected_states,
6491            "pane items do not match expectation"
6492        );
6493    }
6494}