pane.rs

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