pane.rs

   1use crate::{
   2    item::{
   3        ClosePosition, Item, ItemHandle, ItemSettings, PreviewTabsSettings, TabContentParams,
   4        WeakItemHandle,
   5    },
   6    toolbar::Toolbar,
   7    workspace_settings::{AutosaveSetting, TabBarSettings, WorkspaceSettings},
   8    CloseWindow, NewCenterTerminal, NewFile, NewSearch, OpenInTerminal, OpenTerminal, OpenVisible,
   9    SplitDirection, ToggleZoom, Workspace,
  10};
  11use anyhow::Result;
  12use collections::{HashMap, HashSet, VecDeque};
  13use futures::{stream::FuturesUnordered, StreamExt};
  14use gpui::{
  15    actions, anchored, deferred, impl_actions, prelude::*, Action, AnchorCorner, AnyElement,
  16    AppContext, AsyncWindowContext, ClickEvent, DismissEvent, Div, DragMoveEvent, EntityId,
  17    EventEmitter, ExternalPaths, FocusHandle, FocusableView, KeyContext, Model, MouseButton,
  18    MouseDownEvent, NavigationDirection, Pixels, Point, PromptLevel, Render, ScrollHandle,
  19    Subscription, Task, View, ViewContext, VisualContext, WeakFocusHandle, WeakView, WindowContext,
  20};
  21use parking_lot::Mutex;
  22use project::{Project, ProjectEntryId, ProjectPath};
  23use serde::Deserialize;
  24use settings::{Settings, SettingsStore};
  25use std::{
  26    any::Any,
  27    cmp, fmt, mem,
  28    ops::ControlFlow,
  29    path::{Path, PathBuf},
  30    rc::Rc,
  31    sync::{
  32        atomic::{AtomicUsize, Ordering},
  33        Arc,
  34    },
  35};
  36use theme::ThemeSettings;
  37
  38use ui::{
  39    prelude::*, right_click_menu, ButtonSize, Color, IconButton, IconButtonShape, IconName,
  40    IconSize, Indicator, Label, Tab, TabBar, TabPosition, Tooltip,
  41};
  42use ui::{v_flex, ContextMenu};
  43use util::{maybe, truncate_and_remove_front, ResultExt};
  44
  45#[derive(PartialEq, Clone, Copy, Deserialize, Debug)]
  46#[serde(rename_all = "camelCase")]
  47pub enum SaveIntent {
  48    /// write all files (even if unchanged)
  49    /// prompt before overwriting on-disk changes
  50    Save,
  51    /// same as Save, but without auto formatting
  52    SaveWithoutFormat,
  53    /// write any files that have local changes
  54    /// prompt before overwriting on-disk changes
  55    SaveAll,
  56    /// always prompt for a new path
  57    SaveAs,
  58    /// prompt "you have unsaved changes" before writing
  59    Close,
  60    /// write all dirty files, don't prompt on conflict
  61    Overwrite,
  62    /// skip all save-related behavior
  63    Skip,
  64}
  65
  66#[derive(Clone, Deserialize, PartialEq, Debug)]
  67pub struct ActivateItem(pub usize);
  68
  69#[derive(Clone, PartialEq, Debug, Deserialize, Default)]
  70#[serde(rename_all = "camelCase")]
  71pub struct CloseActiveItem {
  72    pub save_intent: Option<SaveIntent>,
  73}
  74
  75#[derive(Clone, PartialEq, Debug, Deserialize, Default)]
  76#[serde(rename_all = "camelCase")]
  77pub struct CloseInactiveItems {
  78    pub save_intent: Option<SaveIntent>,
  79}
  80
  81#[derive(Clone, PartialEq, Debug, Deserialize, Default)]
  82#[serde(rename_all = "camelCase")]
  83pub struct CloseAllItems {
  84    pub save_intent: Option<SaveIntent>,
  85}
  86
  87#[derive(Clone, PartialEq, Debug, Deserialize, Default)]
  88#[serde(rename_all = "camelCase")]
  89pub struct RevealInProjectPanel {
  90    pub entry_id: Option<u64>,
  91}
  92
  93#[derive(PartialEq, Clone, Deserialize)]
  94pub struct DeploySearch {
  95    #[serde(default)]
  96    pub replace_enabled: bool,
  97}
  98
  99impl_actions!(
 100    pane,
 101    [
 102        CloseAllItems,
 103        CloseActiveItem,
 104        CloseInactiveItems,
 105        ActivateItem,
 106        RevealInProjectPanel,
 107        DeploySearch,
 108    ]
 109);
 110
 111actions!(
 112    pane,
 113    [
 114        ActivatePrevItem,
 115        ActivateNextItem,
 116        ActivateLastItem,
 117        CloseCleanItems,
 118        CloseItemsToTheLeft,
 119        CloseItemsToTheRight,
 120        GoBack,
 121        GoForward,
 122        ReopenClosedItem,
 123        SplitLeft,
 124        SplitUp,
 125        SplitRight,
 126        SplitDown,
 127        TogglePreviewTab,
 128    ]
 129);
 130
 131impl DeploySearch {
 132    pub fn find() -> Self {
 133        Self {
 134            replace_enabled: false,
 135        }
 136    }
 137}
 138
 139const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
 140
 141pub enum Event {
 142    AddItem { item: Box<dyn ItemHandle> },
 143    ActivateItem { local: bool },
 144    Remove,
 145    RemoveItem { item_id: EntityId },
 146    Split(SplitDirection),
 147    ChangeItemTitle,
 148    Focus,
 149    ZoomIn,
 150    ZoomOut,
 151}
 152
 153impl fmt::Debug for Event {
 154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 155        match self {
 156            Event::AddItem { item } => f
 157                .debug_struct("AddItem")
 158                .field("item", &item.item_id())
 159                .finish(),
 160            Event::ActivateItem { local } => f
 161                .debug_struct("ActivateItem")
 162                .field("local", local)
 163                .finish(),
 164            Event::Remove => f.write_str("Remove"),
 165            Event::RemoveItem { item_id } => f
 166                .debug_struct("RemoveItem")
 167                .field("item_id", item_id)
 168                .finish(),
 169            Event::Split(direction) => f
 170                .debug_struct("Split")
 171                .field("direction", direction)
 172                .finish(),
 173            Event::ChangeItemTitle => f.write_str("ChangeItemTitle"),
 174            Event::Focus => f.write_str("Focus"),
 175            Event::ZoomIn => f.write_str("ZoomIn"),
 176            Event::ZoomOut => f.write_str("ZoomOut"),
 177        }
 178    }
 179}
 180
 181/// A container for 0 to many items that are open in the workspace.
 182/// Treats all items uniformly via the [`ItemHandle`] trait, whether it's an editor, search results multibuffer, terminal or something else,
 183/// responsible for managing item tabs, focus and zoom states and drag and drop features.
 184/// Can be split, see `PaneGroup` for more details.
 185pub struct Pane {
 186    focus_handle: FocusHandle,
 187    items: Vec<Box<dyn ItemHandle>>,
 188    activation_history: Vec<EntityId>,
 189    zoomed: bool,
 190    was_focused: bool,
 191    active_item_index: usize,
 192    preview_item_id: Option<EntityId>,
 193    last_focus_handle_by_item: HashMap<EntityId, WeakFocusHandle>,
 194    nav_history: NavHistory,
 195    toolbar: View<Toolbar>,
 196    pub new_item_menu: Option<View<ContextMenu>>,
 197    split_item_menu: Option<View<ContextMenu>>,
 198    //     tab_context_menu: View<ContextMenu>,
 199    pub(crate) workspace: WeakView<Workspace>,
 200    project: Model<Project>,
 201    drag_split_direction: Option<SplitDirection>,
 202    can_drop_predicate: Option<Arc<dyn Fn(&dyn Any, &mut WindowContext) -> bool>>,
 203    custom_drop_handle:
 204        Option<Arc<dyn Fn(&mut Pane, &dyn Any, &mut ViewContext<Pane>) -> ControlFlow<(), ()>>>,
 205    can_split: bool,
 206    render_tab_bar_buttons: Rc<dyn Fn(&mut Pane, &mut ViewContext<Pane>) -> AnyElement>,
 207    _subscriptions: Vec<Subscription>,
 208    tab_bar_scroll_handle: ScrollHandle,
 209    /// Is None if navigation buttons are permanently turned off (and should not react to setting changes).
 210    /// Otherwise, when `display_nav_history_buttons` is Some, it determines whether nav buttons should be displayed.
 211    display_nav_history_buttons: Option<bool>,
 212    double_click_dispatch_action: Box<dyn Action>,
 213}
 214
 215pub struct ItemNavHistory {
 216    history: NavHistory,
 217    item: Arc<dyn WeakItemHandle>,
 218    is_preview: bool,
 219}
 220
 221#[derive(Clone)]
 222pub struct NavHistory(Arc<Mutex<NavHistoryState>>);
 223
 224struct NavHistoryState {
 225    mode: NavigationMode,
 226    backward_stack: VecDeque<NavigationEntry>,
 227    forward_stack: VecDeque<NavigationEntry>,
 228    closed_stack: VecDeque<NavigationEntry>,
 229    paths_by_item: HashMap<EntityId, (ProjectPath, Option<PathBuf>)>,
 230    pane: WeakView<Pane>,
 231    next_timestamp: Arc<AtomicUsize>,
 232}
 233
 234#[derive(Debug, Copy, Clone)]
 235pub enum NavigationMode {
 236    Normal,
 237    GoingBack,
 238    GoingForward,
 239    ClosingItem,
 240    ReopeningClosedItem,
 241    Disabled,
 242}
 243
 244impl Default for NavigationMode {
 245    fn default() -> Self {
 246        Self::Normal
 247    }
 248}
 249
 250pub struct NavigationEntry {
 251    pub item: Arc<dyn WeakItemHandle>,
 252    pub data: Option<Box<dyn Any + Send>>,
 253    pub timestamp: usize,
 254    pub is_preview: bool,
 255}
 256
 257#[derive(Clone)]
 258pub struct DraggedTab {
 259    pub pane: View<Pane>,
 260    pub item: Box<dyn ItemHandle>,
 261    pub ix: usize,
 262    pub detail: usize,
 263    pub is_active: bool,
 264}
 265
 266impl EventEmitter<Event> for Pane {}
 267
 268impl Pane {
 269    pub fn new(
 270        workspace: WeakView<Workspace>,
 271        project: Model<Project>,
 272        next_timestamp: Arc<AtomicUsize>,
 273        can_drop_predicate: Option<Arc<dyn Fn(&dyn Any, &mut WindowContext) -> bool + 'static>>,
 274        double_click_dispatch_action: Box<dyn Action>,
 275        cx: &mut ViewContext<Self>,
 276    ) -> Self {
 277        let focus_handle = cx.focus_handle();
 278
 279        let subscriptions = vec![
 280            cx.on_focus(&focus_handle, Pane::focus_in),
 281            cx.on_focus_in(&focus_handle, Pane::focus_in),
 282            cx.on_focus_out(&focus_handle, Pane::focus_out),
 283            cx.observe_global::<SettingsStore>(Self::settings_changed),
 284        ];
 285
 286        let handle = cx.view().downgrade();
 287        Self {
 288            focus_handle,
 289            items: Vec::new(),
 290            activation_history: Vec::new(),
 291            was_focused: false,
 292            zoomed: false,
 293            active_item_index: 0,
 294            preview_item_id: None,
 295            last_focus_handle_by_item: Default::default(),
 296            nav_history: NavHistory(Arc::new(Mutex::new(NavHistoryState {
 297                mode: NavigationMode::Normal,
 298                backward_stack: Default::default(),
 299                forward_stack: Default::default(),
 300                closed_stack: Default::default(),
 301                paths_by_item: Default::default(),
 302                pane: handle.clone(),
 303                next_timestamp,
 304            }))),
 305            toolbar: cx.new_view(|_| Toolbar::new()),
 306            new_item_menu: None,
 307            split_item_menu: None,
 308            tab_bar_scroll_handle: ScrollHandle::new(),
 309            drag_split_direction: None,
 310            workspace,
 311            project,
 312            can_drop_predicate,
 313            custom_drop_handle: None,
 314            can_split: true,
 315            render_tab_bar_buttons: Rc::new(move |pane, cx| {
 316                h_flex()
 317                    .gap_2()
 318                    .child(
 319                        IconButton::new("plus", IconName::Plus)
 320                            .icon_size(IconSize::Small)
 321                            .icon_color(Color::Muted)
 322                            .on_click(cx.listener(|pane, _, cx| {
 323                                let menu = ContextMenu::build(cx, |menu, _| {
 324                                    menu.action("New File", NewFile.boxed_clone())
 325                                        .action("New Terminal", NewCenterTerminal.boxed_clone())
 326                                        .action("New Search", NewSearch.boxed_clone())
 327                                });
 328                                cx.subscribe(&menu, |pane, _, _: &DismissEvent, cx| {
 329                                    pane.focus(cx);
 330                                    pane.new_item_menu = None;
 331                                })
 332                                .detach();
 333                                pane.new_item_menu = Some(menu);
 334                            }))
 335                            .tooltip(|cx| Tooltip::text("New...", cx)),
 336                    )
 337                    .when_some(pane.new_item_menu.as_ref(), |el, new_item_menu| {
 338                        el.child(Self::render_menu_overlay(new_item_menu))
 339                    })
 340                    .child(
 341                        IconButton::new("split", IconName::Split)
 342                            .icon_size(IconSize::Small)
 343                            .icon_color(Color::Muted)
 344                            .on_click(cx.listener(|pane, _, cx| {
 345                                let menu = ContextMenu::build(cx, |menu, _| {
 346                                    menu.action("Split Right", SplitRight.boxed_clone())
 347                                        .action("Split Left", SplitLeft.boxed_clone())
 348                                        .action("Split Up", SplitUp.boxed_clone())
 349                                        .action("Split Down", SplitDown.boxed_clone())
 350                                });
 351                                cx.subscribe(&menu, |pane, _, _: &DismissEvent, cx| {
 352                                    pane.focus(cx);
 353                                    pane.split_item_menu = None;
 354                                })
 355                                .detach();
 356                                pane.split_item_menu = Some(menu);
 357                            }))
 358                            .tooltip(|cx| Tooltip::text("Split Pane", cx)),
 359                    )
 360                    .child({
 361                        let zoomed = pane.is_zoomed();
 362                        IconButton::new("toggle_zoom", IconName::Maximize)
 363                            .icon_size(IconSize::Small)
 364                            .icon_color(Color::Muted)
 365                            .selected(zoomed)
 366                            .selected_icon(IconName::Minimize)
 367                            .on_click(cx.listener(|pane, _, cx| {
 368                                pane.toggle_zoom(&crate::ToggleZoom, cx);
 369                            }))
 370                            .tooltip(move |cx| {
 371                                Tooltip::for_action(
 372                                    if zoomed { "Zoom Out" } else { "Zoom In" },
 373                                    &ToggleZoom,
 374                                    cx,
 375                                )
 376                            })
 377                    })
 378                    .when_some(pane.split_item_menu.as_ref(), |el, split_item_menu| {
 379                        el.child(Self::render_menu_overlay(split_item_menu))
 380                    })
 381                    .into_any_element()
 382            }),
 383            display_nav_history_buttons: Some(
 384                TabBarSettings::get_global(cx).show_nav_history_buttons,
 385            ),
 386            _subscriptions: subscriptions,
 387            double_click_dispatch_action,
 388        }
 389    }
 390
 391    pub fn has_focus(&self, cx: &WindowContext) -> bool {
 392        // We not only check whether our focus handle contains focus, but also
 393        // whether the active_item might have focus, because we might have just activated an item
 394        // but that hasn't rendered yet.
 395        // So before the next render, we might have transferred focus
 396        // to the item and `focus_handle.contains_focus` returns false because the `active_item`
 397        // is not hooked up to us in the dispatch tree.
 398        self.focus_handle.contains_focused(cx)
 399            || self
 400                .active_item()
 401                .map_or(false, |item| item.focus_handle(cx).contains_focused(cx))
 402    }
 403
 404    fn focus_in(&mut self, cx: &mut ViewContext<Self>) {
 405        if !self.was_focused {
 406            self.was_focused = true;
 407            cx.emit(Event::Focus);
 408            cx.notify();
 409        }
 410
 411        self.toolbar.update(cx, |toolbar, cx| {
 412            toolbar.focus_changed(true, cx);
 413        });
 414
 415        if let Some(active_item) = self.active_item() {
 416            if self.focus_handle.is_focused(cx) {
 417                // Pane was focused directly. We need to either focus a view inside the active item,
 418                // or focus the active item itself
 419                if let Some(weak_last_focus_handle) =
 420                    self.last_focus_handle_by_item.get(&active_item.item_id())
 421                {
 422                    if let Some(focus_handle) = weak_last_focus_handle.upgrade() {
 423                        focus_handle.focus(cx);
 424                        return;
 425                    }
 426                }
 427
 428                active_item.focus_handle(cx).focus(cx);
 429            } else if let Some(focused) = cx.focused() {
 430                if !self.context_menu_focused(cx) {
 431                    self.last_focus_handle_by_item
 432                        .insert(active_item.item_id(), focused.downgrade());
 433                }
 434            }
 435        }
 436    }
 437
 438    fn context_menu_focused(&self, cx: &mut ViewContext<Self>) -> bool {
 439        self.new_item_menu
 440            .as_ref()
 441            .or(self.split_item_menu.as_ref())
 442            .map_or(false, |menu| menu.focus_handle(cx).is_focused(cx))
 443    }
 444
 445    fn focus_out(&mut self, cx: &mut ViewContext<Self>) {
 446        self.was_focused = false;
 447        self.toolbar.update(cx, |toolbar, cx| {
 448            toolbar.focus_changed(false, cx);
 449        });
 450        cx.notify();
 451    }
 452
 453    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
 454        if let Some(display_nav_history_buttons) = self.display_nav_history_buttons.as_mut() {
 455            *display_nav_history_buttons = TabBarSettings::get_global(cx).show_nav_history_buttons;
 456        }
 457        if !PreviewTabsSettings::get_global(cx).enabled {
 458            self.preview_item_id = None;
 459        }
 460        cx.notify();
 461    }
 462
 463    pub fn active_item_index(&self) -> usize {
 464        self.active_item_index
 465    }
 466
 467    pub fn activation_history(&self) -> &Vec<EntityId> {
 468        &self.activation_history
 469    }
 470
 471    pub fn set_can_split(&mut self, can_split: bool, cx: &mut ViewContext<Self>) {
 472        self.can_split = can_split;
 473        cx.notify();
 474    }
 475
 476    pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut ViewContext<Self>) {
 477        self.toolbar.update(cx, |toolbar, cx| {
 478            toolbar.set_can_navigate(can_navigate, cx);
 479        });
 480        cx.notify();
 481    }
 482
 483    pub fn set_render_tab_bar_buttons<F>(&mut self, cx: &mut ViewContext<Self>, render: F)
 484    where
 485        F: 'static + Fn(&mut Pane, &mut ViewContext<Pane>) -> AnyElement,
 486    {
 487        self.render_tab_bar_buttons = Rc::new(render);
 488        cx.notify();
 489    }
 490
 491    pub fn set_custom_drop_handle<F>(&mut self, cx: &mut ViewContext<Self>, handle: F)
 492    where
 493        F: 'static + Fn(&mut Pane, &dyn Any, &mut ViewContext<Pane>) -> ControlFlow<(), ()>,
 494    {
 495        self.custom_drop_handle = Some(Arc::new(handle));
 496        cx.notify();
 497    }
 498
 499    pub fn nav_history_for_item<T: Item>(&self, item: &View<T>) -> ItemNavHistory {
 500        ItemNavHistory {
 501            history: self.nav_history.clone(),
 502            item: Arc::new(item.downgrade()),
 503            is_preview: self.preview_item_id == Some(item.item_id()),
 504        }
 505    }
 506
 507    pub fn nav_history(&self) -> &NavHistory {
 508        &self.nav_history
 509    }
 510
 511    pub fn nav_history_mut(&mut self) -> &mut NavHistory {
 512        &mut self.nav_history
 513    }
 514
 515    pub fn disable_history(&mut self) {
 516        self.nav_history.disable();
 517    }
 518
 519    pub fn enable_history(&mut self) {
 520        self.nav_history.enable();
 521    }
 522
 523    pub fn can_navigate_backward(&self) -> bool {
 524        !self.nav_history.0.lock().backward_stack.is_empty()
 525    }
 526
 527    pub fn can_navigate_forward(&self) -> bool {
 528        !self.nav_history.0.lock().forward_stack.is_empty()
 529    }
 530
 531    fn navigate_backward(&mut self, cx: &mut ViewContext<Self>) {
 532        if let Some(workspace) = self.workspace.upgrade() {
 533            let pane = cx.view().downgrade();
 534            cx.window_context().defer(move |cx| {
 535                workspace.update(cx, |workspace, cx| {
 536                    workspace.go_back(pane, cx).detach_and_log_err(cx)
 537                })
 538            })
 539        }
 540    }
 541
 542    fn navigate_forward(&mut self, cx: &mut ViewContext<Self>) {
 543        if let Some(workspace) = self.workspace.upgrade() {
 544            let pane = cx.view().downgrade();
 545            cx.window_context().defer(move |cx| {
 546                workspace.update(cx, |workspace, cx| {
 547                    workspace.go_forward(pane, cx).detach_and_log_err(cx)
 548                })
 549            })
 550        }
 551    }
 552
 553    fn history_updated(&mut self, cx: &mut ViewContext<Self>) {
 554        self.toolbar.update(cx, |_, cx| cx.notify());
 555    }
 556
 557    pub fn preview_item_id(&self) -> Option<EntityId> {
 558        self.preview_item_id
 559    }
 560
 561    fn preview_item_idx(&self) -> Option<usize> {
 562        if let Some(preview_item_id) = self.preview_item_id {
 563            self.items
 564                .iter()
 565                .position(|item| item.item_id() == preview_item_id)
 566        } else {
 567            None
 568        }
 569    }
 570
 571    pub fn is_active_preview_item(&self, item_id: EntityId) -> bool {
 572        self.preview_item_id == Some(item_id)
 573    }
 574
 575    /// Marks the item with the given ID as the preview item.
 576    /// This will be ignored if the global setting `preview_tabs` is disabled.
 577    pub fn set_preview_item_id(&mut self, item_id: Option<EntityId>, cx: &AppContext) {
 578        if PreviewTabsSettings::get_global(cx).enabled {
 579            self.preview_item_id = item_id;
 580        }
 581    }
 582
 583    pub fn handle_item_edit(&mut self, item_id: EntityId, cx: &AppContext) {
 584        if let Some(preview_item_id) = self.preview_item_id {
 585            if preview_item_id == item_id {
 586                self.set_preview_item_id(None, cx)
 587            }
 588        }
 589    }
 590
 591    pub(crate) fn open_item(
 592        &mut self,
 593        project_entry_id: Option<ProjectEntryId>,
 594        focus_item: bool,
 595        allow_preview: bool,
 596        cx: &mut ViewContext<Self>,
 597        build_item: impl FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
 598    ) -> Box<dyn ItemHandle> {
 599        let mut existing_item = None;
 600        if let Some(project_entry_id) = project_entry_id {
 601            for (index, item) in self.items.iter().enumerate() {
 602                if item.is_singleton(cx)
 603                    && item.project_entry_ids(cx).as_slice() == [project_entry_id]
 604                {
 605                    let item = item.boxed_clone();
 606                    existing_item = Some((index, item));
 607                    break;
 608                }
 609            }
 610        }
 611
 612        if let Some((index, existing_item)) = existing_item {
 613            // If the item is already open, and the item is a preview item
 614            // and we are not allowing items to open as preview, mark the item as persistent.
 615            if let Some(preview_item_id) = self.preview_item_id {
 616                if let Some(tab) = self.items.get(index) {
 617                    if tab.item_id() == preview_item_id && !allow_preview {
 618                        self.set_preview_item_id(None, cx);
 619                    }
 620                }
 621            }
 622
 623            self.activate_item(index, focus_item, focus_item, cx);
 624            existing_item
 625        } else {
 626            let mut destination_index = None;
 627            if allow_preview {
 628                // If we are opening a new item as preview and we have an existing preview tab, remove it.
 629                if let Some(item_idx) = self.preview_item_idx() {
 630                    let prev_active_item_index = self.active_item_index;
 631                    self.remove_item(item_idx, false, false, cx);
 632                    self.active_item_index = prev_active_item_index;
 633
 634                    // If the item is being opened as preview and we have an existing preview tab,
 635                    // open the new item in the position of the existing preview tab.
 636                    if item_idx < self.items.len() {
 637                        destination_index = Some(item_idx);
 638                    }
 639                }
 640            }
 641
 642            let new_item = build_item(cx);
 643
 644            if allow_preview {
 645                self.set_preview_item_id(Some(new_item.item_id()), cx);
 646            }
 647
 648            self.add_item(new_item.clone(), true, focus_item, destination_index, cx);
 649
 650            new_item
 651        }
 652    }
 653
 654    pub fn add_item(
 655        &mut self,
 656        item: Box<dyn ItemHandle>,
 657        activate_pane: bool,
 658        focus_item: bool,
 659        destination_index: Option<usize>,
 660        cx: &mut ViewContext<Self>,
 661    ) {
 662        if item.is_singleton(cx) {
 663            if let Some(&entry_id) = item.project_entry_ids(cx).get(0) {
 664                let project = self.project.read(cx);
 665                if let Some(project_path) = project.path_for_entry(entry_id, cx) {
 666                    let abs_path = project.absolute_path(&project_path, cx);
 667                    self.nav_history
 668                        .0
 669                        .lock()
 670                        .paths_by_item
 671                        .insert(item.item_id(), (project_path, abs_path));
 672                }
 673            }
 674        }
 675        // If no destination index is specified, add or move the item after the active item.
 676        let mut insertion_index = {
 677            cmp::min(
 678                if let Some(destination_index) = destination_index {
 679                    destination_index
 680                } else {
 681                    self.active_item_index + 1
 682                },
 683                self.items.len(),
 684            )
 685        };
 686
 687        // Does the item already exist?
 688        let project_entry_id = if item.is_singleton(cx) {
 689            item.project_entry_ids(cx).get(0).copied()
 690        } else {
 691            None
 692        };
 693
 694        let existing_item_index = self.items.iter().position(|existing_item| {
 695            if existing_item.item_id() == item.item_id() {
 696                true
 697            } else if existing_item.is_singleton(cx) {
 698                existing_item
 699                    .project_entry_ids(cx)
 700                    .get(0)
 701                    .map_or(false, |existing_entry_id| {
 702                        Some(existing_entry_id) == project_entry_id.as_ref()
 703                    })
 704            } else {
 705                false
 706            }
 707        });
 708
 709        if let Some(existing_item_index) = existing_item_index {
 710            // If the item already exists, move it to the desired destination and activate it
 711
 712            if existing_item_index != insertion_index {
 713                let existing_item_is_active = existing_item_index == self.active_item_index;
 714
 715                // If the caller didn't specify a destination and the added item is already
 716                // the active one, don't move it
 717                if existing_item_is_active && destination_index.is_none() {
 718                    insertion_index = existing_item_index;
 719                } else {
 720                    self.items.remove(existing_item_index);
 721                    if existing_item_index < self.active_item_index {
 722                        self.active_item_index -= 1;
 723                    }
 724                    insertion_index = insertion_index.min(self.items.len());
 725
 726                    self.items.insert(insertion_index, item.clone());
 727
 728                    if existing_item_is_active {
 729                        self.active_item_index = insertion_index;
 730                    } else if insertion_index <= self.active_item_index {
 731                        self.active_item_index += 1;
 732                    }
 733                }
 734
 735                cx.notify();
 736            }
 737
 738            self.activate_item(insertion_index, activate_pane, focus_item, cx);
 739        } else {
 740            self.items.insert(insertion_index, item.clone());
 741
 742            if insertion_index <= self.active_item_index
 743                && self.preview_item_idx() != Some(self.active_item_index)
 744            {
 745                self.active_item_index += 1;
 746            }
 747
 748            self.activate_item(insertion_index, activate_pane, focus_item, cx);
 749            cx.notify();
 750        }
 751
 752        cx.emit(Event::AddItem { item });
 753    }
 754
 755    pub fn items_len(&self) -> usize {
 756        self.items.len()
 757    }
 758
 759    pub fn items(&self) -> impl DoubleEndedIterator<Item = &Box<dyn ItemHandle>> {
 760        self.items.iter()
 761    }
 762
 763    pub fn items_of_type<T: Render>(&self) -> impl '_ + Iterator<Item = View<T>> {
 764        self.items
 765            .iter()
 766            .filter_map(|item| item.to_any().downcast().ok())
 767    }
 768
 769    pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
 770        self.items.get(self.active_item_index).cloned()
 771    }
 772
 773    pub fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>> {
 774        self.items
 775            .get(self.active_item_index)?
 776            .pixel_position_of_cursor(cx)
 777    }
 778
 779    pub fn item_for_entry(
 780        &self,
 781        entry_id: ProjectEntryId,
 782        cx: &AppContext,
 783    ) -> Option<Box<dyn ItemHandle>> {
 784        self.items.iter().find_map(|item| {
 785            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
 786                Some(item.boxed_clone())
 787            } else {
 788                None
 789            }
 790        })
 791    }
 792
 793    pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
 794        self.items
 795            .iter()
 796            .position(|i| i.item_id() == item.item_id())
 797    }
 798
 799    pub fn item_for_index(&self, ix: usize) -> Option<&dyn ItemHandle> {
 800        self.items.get(ix).map(|i| i.as_ref())
 801    }
 802
 803    pub fn toggle_zoom(&mut self, _: &ToggleZoom, cx: &mut ViewContext<Self>) {
 804        if self.zoomed {
 805            cx.emit(Event::ZoomOut);
 806        } else if !self.items.is_empty() {
 807            if !self.focus_handle.contains_focused(cx) {
 808                cx.focus_self();
 809            }
 810            cx.emit(Event::ZoomIn);
 811        }
 812    }
 813
 814    pub fn activate_item(
 815        &mut self,
 816        index: usize,
 817        activate_pane: bool,
 818        focus_item: bool,
 819        cx: &mut ViewContext<Self>,
 820    ) {
 821        use NavigationMode::{GoingBack, GoingForward};
 822
 823        if index < self.items.len() {
 824            let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
 825            if prev_active_item_ix != self.active_item_index
 826                || matches!(self.nav_history.mode(), GoingBack | GoingForward)
 827            {
 828                if let Some(prev_item) = self.items.get(prev_active_item_ix) {
 829                    prev_item.deactivated(cx);
 830                }
 831            }
 832            cx.emit(Event::ActivateItem {
 833                local: activate_pane,
 834            });
 835
 836            if let Some(newly_active_item) = self.items.get(index) {
 837                self.activation_history
 838                    .retain(|&previously_active_item_id| {
 839                        previously_active_item_id != newly_active_item.item_id()
 840                    });
 841                self.activation_history.push(newly_active_item.item_id());
 842            }
 843
 844            self.update_toolbar(cx);
 845            self.update_status_bar(cx);
 846
 847            if focus_item {
 848                self.focus_active_item(cx);
 849            }
 850
 851            self.tab_bar_scroll_handle.scroll_to_item(index);
 852            cx.notify();
 853        }
 854    }
 855
 856    pub fn activate_prev_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
 857        let mut index = self.active_item_index;
 858        if index > 0 {
 859            index -= 1;
 860        } else if !self.items.is_empty() {
 861            index = self.items.len() - 1;
 862        }
 863        self.activate_item(index, activate_pane, activate_pane, cx);
 864    }
 865
 866    pub fn activate_next_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
 867        let mut index = self.active_item_index;
 868        if index + 1 < self.items.len() {
 869            index += 1;
 870        } else {
 871            index = 0;
 872        }
 873        self.activate_item(index, activate_pane, activate_pane, cx);
 874    }
 875
 876    pub fn close_active_item(
 877        &mut self,
 878        action: &CloseActiveItem,
 879        cx: &mut ViewContext<Self>,
 880    ) -> Option<Task<Result<()>>> {
 881        if self.items.is_empty() {
 882            // Close the window when there's no active items to close.
 883            cx.dispatch_action(Box::new(CloseWindow));
 884            return None;
 885        }
 886        let active_item_id = self.items[self.active_item_index].item_id();
 887        Some(self.close_item_by_id(
 888            active_item_id,
 889            action.save_intent.unwrap_or(SaveIntent::Close),
 890            cx,
 891        ))
 892    }
 893
 894    pub fn close_item_by_id(
 895        &mut self,
 896        item_id_to_close: EntityId,
 897        save_intent: SaveIntent,
 898        cx: &mut ViewContext<Self>,
 899    ) -> Task<Result<()>> {
 900        self.close_items(cx, save_intent, move |view_id| view_id == item_id_to_close)
 901    }
 902
 903    pub fn close_inactive_items(
 904        &mut self,
 905        action: &CloseInactiveItems,
 906        cx: &mut ViewContext<Self>,
 907    ) -> Option<Task<Result<()>>> {
 908        if self.items.is_empty() {
 909            return None;
 910        }
 911
 912        let active_item_id = self.items[self.active_item_index].item_id();
 913        Some(self.close_items(
 914            cx,
 915            action.save_intent.unwrap_or(SaveIntent::Close),
 916            move |item_id| item_id != active_item_id,
 917        ))
 918    }
 919
 920    pub fn close_clean_items(
 921        &mut self,
 922        _: &CloseCleanItems,
 923        cx: &mut ViewContext<Self>,
 924    ) -> Option<Task<Result<()>>> {
 925        let item_ids: Vec<_> = self
 926            .items()
 927            .filter(|item| !item.is_dirty(cx))
 928            .map(|item| item.item_id())
 929            .collect();
 930        Some(self.close_items(cx, SaveIntent::Close, move |item_id| {
 931            item_ids.contains(&item_id)
 932        }))
 933    }
 934
 935    pub fn close_items_to_the_left(
 936        &mut self,
 937        _: &CloseItemsToTheLeft,
 938        cx: &mut ViewContext<Self>,
 939    ) -> Option<Task<Result<()>>> {
 940        if self.items.is_empty() {
 941            return None;
 942        }
 943        let active_item_id = self.items[self.active_item_index].item_id();
 944        Some(self.close_items_to_the_left_by_id(active_item_id, cx))
 945    }
 946
 947    pub fn close_items_to_the_left_by_id(
 948        &mut self,
 949        item_id: EntityId,
 950        cx: &mut ViewContext<Self>,
 951    ) -> Task<Result<()>> {
 952        let item_ids: Vec<_> = self
 953            .items()
 954            .take_while(|item| item.item_id() != item_id)
 955            .map(|item| item.item_id())
 956            .collect();
 957        self.close_items(cx, SaveIntent::Close, move |item_id| {
 958            item_ids.contains(&item_id)
 959        })
 960    }
 961
 962    pub fn close_items_to_the_right(
 963        &mut self,
 964        _: &CloseItemsToTheRight,
 965        cx: &mut ViewContext<Self>,
 966    ) -> Option<Task<Result<()>>> {
 967        if self.items.is_empty() {
 968            return None;
 969        }
 970        let active_item_id = self.items[self.active_item_index].item_id();
 971        Some(self.close_items_to_the_right_by_id(active_item_id, cx))
 972    }
 973
 974    pub fn close_items_to_the_right_by_id(
 975        &mut self,
 976        item_id: EntityId,
 977        cx: &mut ViewContext<Self>,
 978    ) -> Task<Result<()>> {
 979        let item_ids: Vec<_> = self
 980            .items()
 981            .rev()
 982            .take_while(|item| item.item_id() != item_id)
 983            .map(|item| item.item_id())
 984            .collect();
 985        self.close_items(cx, SaveIntent::Close, move |item_id| {
 986            item_ids.contains(&item_id)
 987        })
 988    }
 989
 990    pub fn close_all_items(
 991        &mut self,
 992        action: &CloseAllItems,
 993        cx: &mut ViewContext<Self>,
 994    ) -> Option<Task<Result<()>>> {
 995        if self.items.is_empty() {
 996            return None;
 997        }
 998
 999        Some(
1000            self.close_items(cx, action.save_intent.unwrap_or(SaveIntent::Close), |_| {
1001                true
1002            }),
1003        )
1004    }
1005
1006    pub(super) fn file_names_for_prompt(
1007        items: &mut dyn Iterator<Item = &Box<dyn ItemHandle>>,
1008        all_dirty_items: usize,
1009        cx: &AppContext,
1010    ) -> (String, String) {
1011        /// Quantity of item paths displayed in prompt prior to cutoff..
1012        const FILE_NAMES_CUTOFF_POINT: usize = 10;
1013        let mut file_names: Vec<_> = items
1014            .filter_map(|item| {
1015                item.project_path(cx).and_then(|project_path| {
1016                    project_path
1017                        .path
1018                        .file_name()
1019                        .and_then(|name| name.to_str().map(ToOwned::to_owned))
1020                })
1021            })
1022            .take(FILE_NAMES_CUTOFF_POINT)
1023            .collect();
1024        let should_display_followup_text =
1025            all_dirty_items > FILE_NAMES_CUTOFF_POINT || file_names.len() != all_dirty_items;
1026        if should_display_followup_text {
1027            let not_shown_files = all_dirty_items - file_names.len();
1028            if not_shown_files == 1 {
1029                file_names.push(".. 1 file not shown".into());
1030            } else {
1031                file_names.push(format!(".. {} files not shown", not_shown_files));
1032            }
1033        }
1034        (
1035            format!(
1036                "Do you want to save changes to the following {} files?",
1037                all_dirty_items
1038            ),
1039            file_names.join("\n"),
1040        )
1041    }
1042
1043    pub fn close_items(
1044        &mut self,
1045        cx: &mut ViewContext<Pane>,
1046        mut save_intent: SaveIntent,
1047        should_close: impl Fn(EntityId) -> bool,
1048    ) -> Task<Result<()>> {
1049        // Find the items to close.
1050        let mut items_to_close = Vec::new();
1051        let mut dirty_items = Vec::new();
1052        for item in &self.items {
1053            if should_close(item.item_id()) {
1054                items_to_close.push(item.boxed_clone());
1055                if item.is_dirty(cx) {
1056                    dirty_items.push(item.boxed_clone());
1057                }
1058            }
1059        }
1060
1061        // If a buffer is open both in a singleton editor and in a multibuffer, make sure
1062        // to focus the singleton buffer when prompting to save that buffer, as opposed
1063        // to focusing the multibuffer, because this gives the user a more clear idea
1064        // of what content they would be saving.
1065        items_to_close.sort_by_key(|item| !item.is_singleton(cx));
1066
1067        let workspace = self.workspace.clone();
1068        cx.spawn(|pane, mut cx| async move {
1069            if save_intent == SaveIntent::Close && dirty_items.len() > 1 {
1070                let answer = pane.update(&mut cx, |_, cx| {
1071                    let (prompt, detail) =
1072                        Self::file_names_for_prompt(&mut dirty_items.iter(), dirty_items.len(), cx);
1073                    cx.prompt(
1074                        PromptLevel::Warning,
1075                        &prompt,
1076                        Some(&detail),
1077                        &["Save all", "Discard all", "Cancel"],
1078                    )
1079                })?;
1080                match answer.await {
1081                    Ok(0) => save_intent = SaveIntent::SaveAll,
1082                    Ok(1) => save_intent = SaveIntent::Skip,
1083                    _ => {}
1084                }
1085            }
1086            let mut saved_project_items_ids = HashSet::default();
1087            for item in items_to_close.clone() {
1088                // Find the item's current index and its set of project item models. Avoid
1089                // storing these in advance, in case they have changed since this task
1090                // was started.
1091                let (item_ix, mut project_item_ids) = pane.update(&mut cx, |pane, cx| {
1092                    (pane.index_for_item(&*item), item.project_item_model_ids(cx))
1093                })?;
1094                let item_ix = if let Some(ix) = item_ix {
1095                    ix
1096                } else {
1097                    continue;
1098                };
1099
1100                // Check if this view has any project items that are not open anywhere else
1101                // in the workspace, AND that the user has not already been prompted to save.
1102                // If there are any such project entries, prompt the user to save this item.
1103                let project = workspace.update(&mut cx, |workspace, cx| {
1104                    for item in workspace.items(cx) {
1105                        if !items_to_close
1106                            .iter()
1107                            .any(|item_to_close| item_to_close.item_id() == item.item_id())
1108                        {
1109                            let other_project_item_ids = item.project_item_model_ids(cx);
1110                            project_item_ids.retain(|id| !other_project_item_ids.contains(id));
1111                        }
1112                    }
1113                    workspace.project().clone()
1114                })?;
1115                let should_save = project_item_ids
1116                    .iter()
1117                    .any(|id| saved_project_items_ids.insert(*id));
1118
1119                if should_save
1120                    && !Self::save_item(
1121                        project.clone(),
1122                        &pane,
1123                        item_ix,
1124                        &*item,
1125                        save_intent,
1126                        &mut cx,
1127                    )
1128                    .await?
1129                {
1130                    break;
1131                }
1132
1133                // Remove the item from the pane.
1134                pane.update(&mut cx, |pane, cx| {
1135                    if let Some(item_ix) = pane
1136                        .items
1137                        .iter()
1138                        .position(|i| i.item_id() == item.item_id())
1139                    {
1140                        pane.remove_item(item_ix, false, true, cx);
1141                    }
1142                })
1143                .ok();
1144            }
1145
1146            pane.update(&mut cx, |_, cx| cx.notify()).ok();
1147            Ok(())
1148        })
1149    }
1150
1151    pub fn remove_item(
1152        &mut self,
1153        item_index: usize,
1154        activate_pane: bool,
1155        close_pane_if_empty: bool,
1156        cx: &mut ViewContext<Self>,
1157    ) {
1158        self.activation_history
1159            .retain(|&history_entry| history_entry != self.items[item_index].item_id());
1160
1161        if item_index == self.active_item_index {
1162            let index_to_activate = self
1163                .activation_history
1164                .pop()
1165                .and_then(|last_activated_item| {
1166                    self.items.iter().enumerate().find_map(|(index, item)| {
1167                        (item.item_id() == last_activated_item).then_some(index)
1168                    })
1169                })
1170                // We didn't have a valid activation history entry, so fallback
1171                // to activating the item to the left
1172                .unwrap_or_else(|| item_index.min(self.items.len()).saturating_sub(1));
1173
1174            let should_activate = activate_pane || self.has_focus(cx);
1175            if self.items.len() == 1 && should_activate {
1176                self.focus_handle.focus(cx);
1177            } else {
1178                self.activate_item(index_to_activate, should_activate, should_activate, cx);
1179            }
1180        }
1181
1182        let item = self.items.remove(item_index);
1183
1184        cx.emit(Event::RemoveItem {
1185            item_id: item.item_id(),
1186        });
1187        if self.items.is_empty() {
1188            item.deactivated(cx);
1189            if close_pane_if_empty {
1190                self.update_toolbar(cx);
1191                cx.emit(Event::Remove);
1192            }
1193        }
1194
1195        if item_index < self.active_item_index {
1196            self.active_item_index -= 1;
1197        }
1198
1199        let mode = self.nav_history.mode();
1200        self.nav_history.set_mode(NavigationMode::ClosingItem);
1201        item.deactivated(cx);
1202        self.nav_history.set_mode(mode);
1203
1204        if self.is_active_preview_item(item.item_id()) {
1205            self.set_preview_item_id(None, cx);
1206        }
1207
1208        if let Some(path) = item.project_path(cx) {
1209            let abs_path = self
1210                .nav_history
1211                .0
1212                .lock()
1213                .paths_by_item
1214                .get(&item.item_id())
1215                .and_then(|(_, abs_path)| abs_path.clone());
1216
1217            self.nav_history
1218                .0
1219                .lock()
1220                .paths_by_item
1221                .insert(item.item_id(), (path, abs_path));
1222        } else {
1223            self.nav_history
1224                .0
1225                .lock()
1226                .paths_by_item
1227                .remove(&item.item_id());
1228        }
1229
1230        if self.items.is_empty() && close_pane_if_empty && self.zoomed {
1231            cx.emit(Event::ZoomOut);
1232        }
1233
1234        cx.notify();
1235    }
1236
1237    pub async fn save_item(
1238        project: Model<Project>,
1239        pane: &WeakView<Pane>,
1240        item_ix: usize,
1241        item: &dyn ItemHandle,
1242        save_intent: SaveIntent,
1243        cx: &mut AsyncWindowContext,
1244    ) -> Result<bool> {
1245        const CONFLICT_MESSAGE: &str =
1246                "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1247
1248        if save_intent == SaveIntent::Skip {
1249            return Ok(true);
1250        }
1251
1252        let (mut has_conflict, mut is_dirty, mut can_save, can_save_as) = cx.update(|cx| {
1253            (
1254                item.has_conflict(cx),
1255                item.is_dirty(cx),
1256                item.can_save(cx),
1257                item.is_singleton(cx),
1258            )
1259        })?;
1260
1261        // when saving a single buffer, we ignore whether or not it's dirty.
1262        if save_intent == SaveIntent::Save || save_intent == SaveIntent::SaveWithoutFormat {
1263            is_dirty = true;
1264        }
1265
1266        if save_intent == SaveIntent::SaveAs {
1267            is_dirty = true;
1268            has_conflict = false;
1269            can_save = false;
1270        }
1271
1272        if save_intent == SaveIntent::Overwrite {
1273            has_conflict = false;
1274        }
1275
1276        let should_format = save_intent != SaveIntent::SaveWithoutFormat;
1277
1278        if has_conflict && can_save {
1279            let answer = pane.update(cx, |pane, cx| {
1280                pane.activate_item(item_ix, true, true, cx);
1281                cx.prompt(
1282                    PromptLevel::Warning,
1283                    CONFLICT_MESSAGE,
1284                    None,
1285                    &["Overwrite", "Discard", "Cancel"],
1286                )
1287            })?;
1288            match answer.await {
1289                Ok(0) => {
1290                    pane.update(cx, |_, cx| item.save(should_format, project, cx))?
1291                        .await?
1292                }
1293                Ok(1) => pane.update(cx, |_, cx| item.reload(project, cx))?.await?,
1294                _ => return Ok(false),
1295            }
1296        } else if is_dirty && (can_save || can_save_as) {
1297            if save_intent == SaveIntent::Close {
1298                let will_autosave = cx.update(|cx| {
1299                    matches!(
1300                        WorkspaceSettings::get_global(cx).autosave,
1301                        AutosaveSetting::OnFocusChange | AutosaveSetting::OnWindowChange
1302                    ) && Self::can_autosave_item(item, cx)
1303                })?;
1304                if !will_autosave {
1305                    let answer = pane.update(cx, |pane, cx| {
1306                        pane.activate_item(item_ix, true, true, cx);
1307                        let prompt = dirty_message_for(item.project_path(cx));
1308                        cx.prompt(
1309                            PromptLevel::Warning,
1310                            &prompt,
1311                            None,
1312                            &["Save", "Don't Save", "Cancel"],
1313                        )
1314                    })?;
1315                    match answer.await {
1316                        Ok(0) => {}
1317                        Ok(1) => return Ok(true), // Don't save this file
1318                        _ => return Ok(false),    // Cancel
1319                    }
1320                }
1321            }
1322
1323            if can_save {
1324                pane.update(cx, |_, cx| item.save(should_format, project, cx))?
1325                    .await?;
1326            } else if can_save_as {
1327                let start_abs_path = project
1328                    .update(cx, |project, cx| {
1329                        let worktree = project.visible_worktrees(cx).next()?;
1330                        Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
1331                    })?
1332                    .unwrap_or_else(|| Path::new("").into());
1333
1334                let abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path))?;
1335                if let Some(abs_path) = abs_path.await.ok().flatten() {
1336                    pane.update(cx, |_, cx| item.save_as(project, abs_path, cx))?
1337                        .await?;
1338                } else {
1339                    return Ok(false);
1340                }
1341            }
1342        }
1343        Ok(true)
1344    }
1345
1346    fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
1347        let is_deleted = item.project_entry_ids(cx).is_empty();
1348        item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
1349    }
1350
1351    pub fn autosave_item(
1352        item: &dyn ItemHandle,
1353        project: Model<Project>,
1354        cx: &mut WindowContext,
1355    ) -> Task<Result<()>> {
1356        if Self::can_autosave_item(item, cx) {
1357            item.save(true, project, cx)
1358        } else {
1359            Task::ready(Ok(()))
1360        }
1361    }
1362
1363    pub fn focus(&mut self, cx: &mut ViewContext<Pane>) {
1364        cx.focus(&self.focus_handle);
1365    }
1366
1367    pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
1368        if let Some(active_item) = self.active_item() {
1369            let focus_handle = active_item.focus_handle(cx);
1370            cx.focus(&focus_handle);
1371        }
1372    }
1373
1374    pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
1375        cx.emit(Event::Split(direction));
1376    }
1377
1378    pub fn toolbar(&self) -> &View<Toolbar> {
1379        &self.toolbar
1380    }
1381
1382    pub fn handle_deleted_project_item(
1383        &mut self,
1384        entry_id: ProjectEntryId,
1385        cx: &mut ViewContext<Pane>,
1386    ) -> Option<()> {
1387        let (item_index_to_delete, item_id) = self.items().enumerate().find_map(|(i, item)| {
1388            if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
1389                Some((i, item.item_id()))
1390            } else {
1391                None
1392            }
1393        })?;
1394
1395        self.remove_item(item_index_to_delete, false, true, cx);
1396        self.nav_history.remove_item(item_id);
1397
1398        Some(())
1399    }
1400
1401    fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
1402        let active_item = self
1403            .items
1404            .get(self.active_item_index)
1405            .map(|item| item.as_ref());
1406        self.toolbar.update(cx, |toolbar, cx| {
1407            toolbar.set_active_item(active_item, cx);
1408        });
1409    }
1410
1411    fn update_status_bar(&mut self, cx: &mut ViewContext<Self>) {
1412        let workspace = self.workspace.clone();
1413        let pane = cx.view().clone();
1414
1415        cx.window_context().defer(move |cx| {
1416            let Ok(status_bar) = workspace.update(cx, |workspace, _| workspace.status_bar.clone())
1417            else {
1418                return;
1419            };
1420
1421            status_bar.update(cx, move |status_bar, cx| {
1422                status_bar.set_active_pane(&pane, cx);
1423            });
1424        });
1425    }
1426
1427    fn render_tab(
1428        &self,
1429        ix: usize,
1430        item: &Box<dyn ItemHandle>,
1431        detail: usize,
1432        cx: &mut ViewContext<'_, Pane>,
1433    ) -> impl IntoElement {
1434        let is_active = ix == self.active_item_index;
1435        let is_preview = self
1436            .preview_item_id
1437            .map(|id| id == item.item_id())
1438            .unwrap_or(false);
1439
1440        let label = item.tab_content(
1441            TabContentParams {
1442                detail: Some(detail),
1443                selected: is_active,
1444                preview: is_preview,
1445            },
1446            cx,
1447        );
1448        let close_side = &ItemSettings::get_global(cx).close_position;
1449        let indicator = render_item_indicator(item.boxed_clone(), cx);
1450        let item_id = item.item_id();
1451        let is_first_item = ix == 0;
1452        let is_last_item = ix == self.items.len() - 1;
1453        let position_relative_to_active_item = ix.cmp(&self.active_item_index);
1454
1455        let tab = Tab::new(ix)
1456            .position(if is_first_item {
1457                TabPosition::First
1458            } else if is_last_item {
1459                TabPosition::Last
1460            } else {
1461                TabPosition::Middle(position_relative_to_active_item)
1462            })
1463            .close_side(match close_side {
1464                ClosePosition::Left => ui::TabCloseSide::Start,
1465                ClosePosition::Right => ui::TabCloseSide::End,
1466            })
1467            .selected(is_active)
1468            .on_click(
1469                cx.listener(move |pane: &mut Self, _, cx| pane.activate_item(ix, true, true, cx)),
1470            )
1471            // TODO: This should be a click listener with the middle mouse button instead of a mouse down listener.
1472            .on_mouse_down(
1473                MouseButton::Middle,
1474                cx.listener(move |pane, _event, cx| {
1475                    pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1476                        .detach_and_log_err(cx);
1477                }),
1478            )
1479            .on_mouse_down(
1480                MouseButton::Left,
1481                cx.listener(move |pane, event: &MouseDownEvent, cx| {
1482                    if let Some(id) = pane.preview_item_id {
1483                        if id == item_id && event.click_count > 1 {
1484                            pane.set_preview_item_id(None, cx);
1485                        }
1486                    }
1487                }),
1488            )
1489            .on_drag(
1490                DraggedTab {
1491                    item: item.boxed_clone(),
1492                    pane: cx.view().clone(),
1493                    detail,
1494                    is_active,
1495                    ix,
1496                },
1497                |tab, cx| cx.new_view(|_| tab.clone()),
1498            )
1499            .drag_over::<DraggedTab>(|tab, _, cx| {
1500                tab.bg(cx.theme().colors().drop_target_background)
1501            })
1502            .drag_over::<ProjectEntryId>(|tab, _, cx| {
1503                tab.bg(cx.theme().colors().drop_target_background)
1504            })
1505            .when_some(self.can_drop_predicate.clone(), |this, p| {
1506                this.can_drop(move |a, cx| p(a, cx))
1507            })
1508            .on_drop(cx.listener(move |this, dragged_tab: &DraggedTab, cx| {
1509                this.drag_split_direction = None;
1510                this.handle_tab_drop(dragged_tab, ix, cx)
1511            }))
1512            .on_drop(cx.listener(move |this, entry_id: &ProjectEntryId, cx| {
1513                this.drag_split_direction = None;
1514                this.handle_project_entry_drop(entry_id, cx)
1515            }))
1516            .on_drop(cx.listener(move |this, paths, cx| {
1517                this.drag_split_direction = None;
1518                this.handle_external_paths_drop(paths, cx)
1519            }))
1520            .when_some(item.tab_tooltip_text(cx), |tab, text| {
1521                tab.tooltip(move |cx| Tooltip::text(text.clone(), cx))
1522            })
1523            .start_slot::<Indicator>(indicator)
1524            .end_slot(
1525                IconButton::new("close tab", IconName::Close)
1526                    .shape(IconButtonShape::Square)
1527                    .icon_color(Color::Muted)
1528                    .size(ButtonSize::None)
1529                    .icon_size(IconSize::XSmall)
1530                    .on_click(cx.listener(move |pane, _, cx| {
1531                        pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1532                            .detach_and_log_err(cx);
1533                    })),
1534            )
1535            .child(label);
1536
1537        let single_entry_to_resolve = {
1538            let item_entries = self.items[ix].project_entry_ids(cx);
1539            if item_entries.len() == 1 {
1540                Some(item_entries[0])
1541            } else {
1542                None
1543            }
1544        };
1545
1546        let pane = cx.view().downgrade();
1547        right_click_menu(ix).trigger(tab).menu(move |cx| {
1548            let pane = pane.clone();
1549            ContextMenu::build(cx, move |mut menu, cx| {
1550                if let Some(pane) = pane.upgrade() {
1551                    menu = menu
1552                        .entry(
1553                            "Close",
1554                            Some(Box::new(CloseActiveItem { save_intent: None })),
1555                            cx.handler_for(&pane, move |pane, cx| {
1556                                pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1557                                    .detach_and_log_err(cx);
1558                            }),
1559                        )
1560                        .entry(
1561                            "Close Others",
1562                            Some(Box::new(CloseInactiveItems { save_intent: None })),
1563                            cx.handler_for(&pane, move |pane, cx| {
1564                                pane.close_items(cx, SaveIntent::Close, |id| id != item_id)
1565                                    .detach_and_log_err(cx);
1566                            }),
1567                        )
1568                        .separator()
1569                        .entry(
1570                            "Close Left",
1571                            Some(Box::new(CloseItemsToTheLeft)),
1572                            cx.handler_for(&pane, move |pane, cx| {
1573                                pane.close_items_to_the_left_by_id(item_id, cx)
1574                                    .detach_and_log_err(cx);
1575                            }),
1576                        )
1577                        .entry(
1578                            "Close Right",
1579                            Some(Box::new(CloseItemsToTheRight)),
1580                            cx.handler_for(&pane, move |pane, cx| {
1581                                pane.close_items_to_the_right_by_id(item_id, cx)
1582                                    .detach_and_log_err(cx);
1583                            }),
1584                        )
1585                        .separator()
1586                        .entry(
1587                            "Close Clean",
1588                            Some(Box::new(CloseCleanItems)),
1589                            cx.handler_for(&pane, move |pane, cx| {
1590                                if let Some(task) = pane.close_clean_items(&CloseCleanItems, cx) {
1591                                    task.detach_and_log_err(cx)
1592                                }
1593                            }),
1594                        )
1595                        .entry(
1596                            "Close All",
1597                            Some(Box::new(CloseAllItems { save_intent: None })),
1598                            cx.handler_for(&pane, |pane, cx| {
1599                                if let Some(task) =
1600                                    pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
1601                                {
1602                                    task.detach_and_log_err(cx)
1603                                }
1604                            }),
1605                        );
1606
1607                    if let Some(entry) = single_entry_to_resolve {
1608                        let parent_abs_path = pane
1609                            .update(cx, |pane, cx| {
1610                                pane.workspace.update(cx, |workspace, cx| {
1611                                    let project = workspace.project().read(cx);
1612                                    project.worktree_for_entry(entry, cx).and_then(|worktree| {
1613                                        let worktree = worktree.read(cx);
1614                                        let entry = worktree.entry_for_id(entry)?;
1615                                        let abs_path = worktree.absolutize(&entry.path).ok()?;
1616                                        let parent = if entry.is_symlink {
1617                                            abs_path.canonicalize().ok()?
1618                                        } else {
1619                                            abs_path
1620                                        }
1621                                        .parent()?
1622                                        .to_path_buf();
1623                                        Some(parent)
1624                                    })
1625                                })
1626                            })
1627                            .ok()
1628                            .flatten();
1629
1630                        let entry_id = entry.to_proto();
1631                        menu = menu
1632                            .separator()
1633                            .entry(
1634                                "Reveal In Project Panel",
1635                                Some(Box::new(RevealInProjectPanel {
1636                                    entry_id: Some(entry_id),
1637                                })),
1638                                cx.handler_for(&pane, move |pane, cx| {
1639                                    pane.project.update(cx, |_, cx| {
1640                                        cx.emit(project::Event::RevealInProjectPanel(
1641                                            ProjectEntryId::from_proto(entry_id),
1642                                        ))
1643                                    });
1644                                }),
1645                            )
1646                            .when_some(parent_abs_path, |menu, abs_path| {
1647                                menu.entry(
1648                                    "Open in Terminal",
1649                                    Some(Box::new(OpenInTerminal)),
1650                                    cx.handler_for(&pane, move |_, cx| {
1651                                        cx.dispatch_action(
1652                                            OpenTerminal {
1653                                                working_directory: abs_path.clone(),
1654                                            }
1655                                            .boxed_clone(),
1656                                        );
1657                                    }),
1658                                )
1659                            });
1660                    }
1661                }
1662
1663                menu
1664            })
1665        })
1666    }
1667
1668    fn render_tab_bar(&mut self, cx: &mut ViewContext<'_, Pane>) -> impl IntoElement {
1669        TabBar::new("tab_bar")
1670            .track_scroll(self.tab_bar_scroll_handle.clone())
1671            .when(
1672                self.display_nav_history_buttons.unwrap_or_default(),
1673                |tab_bar| {
1674                    tab_bar.start_child(
1675                        h_flex()
1676                            .gap_2()
1677                            .child(
1678                                IconButton::new("navigate_backward", IconName::ArrowLeft)
1679                                    .icon_size(IconSize::Small)
1680                                    .on_click({
1681                                        let view = cx.view().clone();
1682                                        move |_, cx| view.update(cx, Self::navigate_backward)
1683                                    })
1684                                    .disabled(!self.can_navigate_backward())
1685                                    .tooltip(|cx| Tooltip::for_action("Go Back", &GoBack, cx)),
1686                            )
1687                            .child(
1688                                IconButton::new("navigate_forward", IconName::ArrowRight)
1689                                    .icon_size(IconSize::Small)
1690                                    .on_click({
1691                                        let view = cx.view().clone();
1692                                        move |_, cx| view.update(cx, Self::navigate_forward)
1693                                    })
1694                                    .disabled(!self.can_navigate_forward())
1695                                    .tooltip(|cx| {
1696                                        Tooltip::for_action("Go Forward", &GoForward, cx)
1697                                    }),
1698                            ),
1699                    )
1700                },
1701            )
1702            .when(self.has_focus(cx), |tab_bar| {
1703                tab_bar.end_child({
1704                    let render_tab_buttons = self.render_tab_bar_buttons.clone();
1705                    render_tab_buttons(self, cx)
1706                })
1707            })
1708            .children(
1709                self.items
1710                    .iter()
1711                    .enumerate()
1712                    .zip(tab_details(&self.items, cx))
1713                    .map(|((ix, item), detail)| self.render_tab(ix, item, detail, cx)),
1714            )
1715            .child(
1716                div()
1717                    .id("tab_bar_drop_target")
1718                    .min_w_6()
1719                    // HACK: This empty child is currently necessary to force the drop target to appear
1720                    // despite us setting a min width above.
1721                    .child("")
1722                    .h_full()
1723                    .flex_grow()
1724                    .drag_over::<DraggedTab>(|bar, _, cx| {
1725                        bar.bg(cx.theme().colors().drop_target_background)
1726                    })
1727                    .drag_over::<ProjectEntryId>(|bar, _, cx| {
1728                        bar.bg(cx.theme().colors().drop_target_background)
1729                    })
1730                    .on_drop(cx.listener(move |this, dragged_tab: &DraggedTab, cx| {
1731                        this.drag_split_direction = None;
1732                        this.handle_tab_drop(dragged_tab, this.items.len(), cx)
1733                    }))
1734                    .on_drop(cx.listener(move |this, entry_id: &ProjectEntryId, cx| {
1735                        this.drag_split_direction = None;
1736                        this.handle_project_entry_drop(entry_id, cx)
1737                    }))
1738                    .on_drop(cx.listener(move |this, paths, cx| {
1739                        this.drag_split_direction = None;
1740                        this.handle_external_paths_drop(paths, cx)
1741                    }))
1742                    .on_click(cx.listener(move |this, event: &ClickEvent, cx| {
1743                        if event.up.click_count == 2 {
1744                            cx.dispatch_action(this.double_click_dispatch_action.boxed_clone())
1745                        }
1746                    })),
1747            )
1748    }
1749
1750    pub fn render_menu_overlay(menu: &View<ContextMenu>) -> Div {
1751        div().absolute().bottom_0().right_0().size_0().child(
1752            deferred(
1753                anchored()
1754                    .anchor(AnchorCorner::TopRight)
1755                    .child(menu.clone()),
1756            )
1757            .with_priority(1),
1758        )
1759    }
1760
1761    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1762        self.zoomed = zoomed;
1763        cx.notify();
1764    }
1765
1766    pub fn is_zoomed(&self) -> bool {
1767        self.zoomed
1768    }
1769
1770    fn handle_drag_move<T>(&mut self, event: &DragMoveEvent<T>, cx: &mut ViewContext<Self>) {
1771        if !self.can_split {
1772            return;
1773        }
1774
1775        let rect = event.bounds.size;
1776
1777        let size = event.bounds.size.width.min(event.bounds.size.height)
1778            * WorkspaceSettings::get_global(cx).drop_target_size;
1779
1780        let relative_cursor = Point::new(
1781            event.event.position.x - event.bounds.left(),
1782            event.event.position.y - event.bounds.top(),
1783        );
1784
1785        let direction = if relative_cursor.x < size
1786            || relative_cursor.x > rect.width - size
1787            || relative_cursor.y < size
1788            || relative_cursor.y > rect.height - size
1789        {
1790            [
1791                SplitDirection::Up,
1792                SplitDirection::Right,
1793                SplitDirection::Down,
1794                SplitDirection::Left,
1795            ]
1796            .iter()
1797            .min_by_key(|side| match side {
1798                SplitDirection::Up => relative_cursor.y,
1799                SplitDirection::Right => rect.width - relative_cursor.x,
1800                SplitDirection::Down => rect.height - relative_cursor.y,
1801                SplitDirection::Left => relative_cursor.x,
1802            })
1803            .cloned()
1804        } else {
1805            None
1806        };
1807
1808        if direction != self.drag_split_direction {
1809            self.drag_split_direction = direction;
1810        }
1811    }
1812
1813    fn handle_tab_drop(
1814        &mut self,
1815        dragged_tab: &DraggedTab,
1816        ix: usize,
1817        cx: &mut ViewContext<'_, Self>,
1818    ) {
1819        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
1820            if let ControlFlow::Break(()) = custom_drop_handle(self, dragged_tab, cx) {
1821                return;
1822            }
1823        }
1824        let mut to_pane = cx.view().clone();
1825        let split_direction = self.drag_split_direction;
1826        let item_id = dragged_tab.item.item_id();
1827        if let Some(preview_item_id) = self.preview_item_id {
1828            if item_id == preview_item_id {
1829                self.set_preview_item_id(None, cx);
1830            }
1831        }
1832
1833        let from_pane = dragged_tab.pane.clone();
1834        self.workspace
1835            .update(cx, |_, cx| {
1836                cx.defer(move |workspace, cx| {
1837                    if let Some(split_direction) = split_direction {
1838                        to_pane = workspace.split_pane(to_pane, split_direction, cx);
1839                    }
1840                    workspace.move_item(from_pane, to_pane, item_id, ix, cx);
1841                });
1842            })
1843            .log_err();
1844    }
1845
1846    fn handle_project_entry_drop(
1847        &mut self,
1848        project_entry_id: &ProjectEntryId,
1849        cx: &mut ViewContext<'_, Self>,
1850    ) {
1851        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
1852            if let ControlFlow::Break(()) = custom_drop_handle(self, project_entry_id, cx) {
1853                return;
1854            }
1855        }
1856        let mut to_pane = cx.view().clone();
1857        let split_direction = self.drag_split_direction;
1858        let project_entry_id = *project_entry_id;
1859        self.workspace
1860            .update(cx, |_, cx| {
1861                cx.defer(move |workspace, cx| {
1862                    if let Some(path) = workspace
1863                        .project()
1864                        .read(cx)
1865                        .path_for_entry(project_entry_id, cx)
1866                    {
1867                        if let Some(split_direction) = split_direction {
1868                            to_pane = workspace.split_pane(to_pane, split_direction, cx);
1869                        }
1870                        workspace
1871                            .open_path(path, Some(to_pane.downgrade()), true, cx)
1872                            .detach_and_log_err(cx);
1873                    }
1874                });
1875            })
1876            .log_err();
1877    }
1878
1879    fn handle_external_paths_drop(
1880        &mut self,
1881        paths: &ExternalPaths,
1882        cx: &mut ViewContext<'_, Self>,
1883    ) {
1884        if let Some(custom_drop_handle) = self.custom_drop_handle.clone() {
1885            if let ControlFlow::Break(()) = custom_drop_handle(self, paths, cx) {
1886                return;
1887            }
1888        }
1889        let mut to_pane = cx.view().clone();
1890        let mut split_direction = self.drag_split_direction;
1891        let paths = paths.paths().to_vec();
1892        self.workspace
1893            .update(cx, |workspace, cx| {
1894                let fs = Arc::clone(workspace.project().read(cx).fs());
1895                cx.spawn(|workspace, mut cx| async move {
1896                    let mut is_file_checks = FuturesUnordered::new();
1897                    for path in &paths {
1898                        is_file_checks.push(fs.is_file(path))
1899                    }
1900                    let mut has_files_to_open = false;
1901                    while let Some(is_file) = is_file_checks.next().await {
1902                        if is_file {
1903                            has_files_to_open = true;
1904                            break;
1905                        }
1906                    }
1907                    drop(is_file_checks);
1908                    if !has_files_to_open {
1909                        split_direction = None;
1910                    }
1911
1912                    if let Some(open_task) = workspace
1913                        .update(&mut cx, |workspace, cx| {
1914                            if let Some(split_direction) = split_direction {
1915                                to_pane = workspace.split_pane(to_pane, split_direction, cx);
1916                            }
1917                            workspace.open_paths(
1918                                paths,
1919                                OpenVisible::OnlyDirectories,
1920                                Some(to_pane.downgrade()),
1921                                cx,
1922                            )
1923                        })
1924                        .ok()
1925                    {
1926                        let _opened_items: Vec<_> = open_task.await;
1927                    }
1928                })
1929                .detach();
1930            })
1931            .log_err();
1932    }
1933
1934    pub fn display_nav_history_buttons(&mut self, display: Option<bool>) {
1935        self.display_nav_history_buttons = display;
1936    }
1937}
1938
1939impl FocusableView for Pane {
1940    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
1941        self.focus_handle.clone()
1942    }
1943}
1944
1945impl Render for Pane {
1946    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1947        let mut key_context = KeyContext::new_with_defaults();
1948        key_context.add("Pane");
1949        if self.active_item().is_none() {
1950            key_context.add("EmptyPane");
1951        }
1952
1953        v_flex()
1954            .key_context(key_context)
1955            .track_focus(&self.focus_handle)
1956            .size_full()
1957            .flex_none()
1958            .overflow_hidden()
1959            .on_action(cx.listener(|pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx)))
1960            .on_action(cx.listener(|pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx)))
1961            .on_action(
1962                cx.listener(|pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx)),
1963            )
1964            .on_action(cx.listener(|pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx)))
1965            .on_action(cx.listener(|pane, _: &GoBack, cx| pane.navigate_backward(cx)))
1966            .on_action(cx.listener(|pane, _: &GoForward, cx| pane.navigate_forward(cx)))
1967            .on_action(cx.listener(Pane::toggle_zoom))
1968            .on_action(cx.listener(|pane: &mut Pane, action: &ActivateItem, cx| {
1969                pane.activate_item(action.0, true, true, cx);
1970            }))
1971            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateLastItem, cx| {
1972                pane.activate_item(pane.items.len() - 1, true, true, cx);
1973            }))
1974            .on_action(cx.listener(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
1975                pane.activate_prev_item(true, cx);
1976            }))
1977            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateNextItem, cx| {
1978                pane.activate_next_item(true, cx);
1979            }))
1980            .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
1981                this.on_action(cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, cx| {
1982                    if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
1983                        if pane.is_active_preview_item(active_item_id) {
1984                            pane.set_preview_item_id(None, cx);
1985                        } else {
1986                            pane.set_preview_item_id(Some(active_item_id), cx);
1987                        }
1988                    }
1989                }))
1990            })
1991            .on_action(
1992                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1993                    if let Some(task) = pane.close_active_item(action, cx) {
1994                        task.detach_and_log_err(cx)
1995                    }
1996                }),
1997            )
1998            .on_action(
1999                cx.listener(|pane: &mut Self, action: &CloseInactiveItems, cx| {
2000                    if let Some(task) = pane.close_inactive_items(action, cx) {
2001                        task.detach_and_log_err(cx)
2002                    }
2003                }),
2004            )
2005            .on_action(
2006                cx.listener(|pane: &mut Self, action: &CloseCleanItems, cx| {
2007                    if let Some(task) = pane.close_clean_items(action, cx) {
2008                        task.detach_and_log_err(cx)
2009                    }
2010                }),
2011            )
2012            .on_action(
2013                cx.listener(|pane: &mut Self, action: &CloseItemsToTheLeft, cx| {
2014                    if let Some(task) = pane.close_items_to_the_left(action, cx) {
2015                        task.detach_and_log_err(cx)
2016                    }
2017                }),
2018            )
2019            .on_action(
2020                cx.listener(|pane: &mut Self, action: &CloseItemsToTheRight, cx| {
2021                    if let Some(task) = pane.close_items_to_the_right(action, cx) {
2022                        task.detach_and_log_err(cx)
2023                    }
2024                }),
2025            )
2026            .on_action(cx.listener(|pane: &mut Self, action: &CloseAllItems, cx| {
2027                if let Some(task) = pane.close_all_items(action, cx) {
2028                    task.detach_and_log_err(cx)
2029                }
2030            }))
2031            .on_action(
2032                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
2033                    if let Some(task) = pane.close_active_item(action, cx) {
2034                        task.detach_and_log_err(cx)
2035                    }
2036                }),
2037            )
2038            .on_action(
2039                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, cx| {
2040                    let entry_id = action
2041                        .entry_id
2042                        .map(ProjectEntryId::from_proto)
2043                        .or_else(|| pane.active_item()?.project_entry_ids(cx).first().copied());
2044                    if let Some(entry_id) = entry_id {
2045                        pane.project.update(cx, |_, cx| {
2046                            cx.emit(project::Event::RevealInProjectPanel(entry_id))
2047                        });
2048                    }
2049                }),
2050            )
2051            .when(self.active_item().is_some(), |pane| {
2052                pane.child(self.render_tab_bar(cx))
2053            })
2054            .child({
2055                let has_worktrees = self.project.read(cx).worktrees().next().is_some();
2056                // main content
2057                div()
2058                    .flex_1()
2059                    .relative()
2060                    .group("")
2061                    .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
2062                    .on_drag_move::<ProjectEntryId>(cx.listener(Self::handle_drag_move))
2063                    .on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
2064                    .map(|div| {
2065                        if let Some(item) = self.active_item() {
2066                            div.v_flex()
2067                                .child(self.toolbar.clone())
2068                                .child(item.to_any())
2069                        } else {
2070                            let placeholder = div.h_flex().size_full().justify_center();
2071                            if has_worktrees {
2072                                placeholder
2073                            } else {
2074                                placeholder.child(
2075                                    Label::new("Open a file or project to get started.")
2076                                        .color(Color::Muted),
2077                                )
2078                            }
2079                        }
2080                    })
2081                    .child(
2082                        // drag target
2083                        div()
2084                            .invisible()
2085                            .absolute()
2086                            .bg(cx.theme().colors().drop_target_background)
2087                            .group_drag_over::<DraggedTab>("", |style| style.visible())
2088                            .group_drag_over::<ProjectEntryId>("", |style| style.visible())
2089                            .group_drag_over::<ExternalPaths>("", |style| style.visible())
2090                            .when_some(self.can_drop_predicate.clone(), |this, p| {
2091                                this.can_drop(move |a, cx| p(a, cx))
2092                            })
2093                            .on_drop(cx.listener(move |this, dragged_tab, cx| {
2094                                this.handle_tab_drop(dragged_tab, this.active_item_index(), cx)
2095                            }))
2096                            .on_drop(cx.listener(move |this, entry_id, cx| {
2097                                this.handle_project_entry_drop(entry_id, cx)
2098                            }))
2099                            .on_drop(cx.listener(move |this, paths, cx| {
2100                                this.handle_external_paths_drop(paths, cx)
2101                            }))
2102                            .map(|div| {
2103                                let size = DefiniteLength::Fraction(0.5);
2104                                match self.drag_split_direction {
2105                                    None => div.top_0().right_0().bottom_0().left_0(),
2106                                    Some(SplitDirection::Up) => {
2107                                        div.top_0().left_0().right_0().h(size)
2108                                    }
2109                                    Some(SplitDirection::Down) => {
2110                                        div.left_0().bottom_0().right_0().h(size)
2111                                    }
2112                                    Some(SplitDirection::Left) => {
2113                                        div.top_0().left_0().bottom_0().w(size)
2114                                    }
2115                                    Some(SplitDirection::Right) => {
2116                                        div.top_0().bottom_0().right_0().w(size)
2117                                    }
2118                                }
2119                            }),
2120                    )
2121            })
2122            .on_mouse_down(
2123                MouseButton::Navigate(NavigationDirection::Back),
2124                cx.listener(|pane, _, cx| {
2125                    if let Some(workspace) = pane.workspace.upgrade() {
2126                        let pane = cx.view().downgrade();
2127                        cx.window_context().defer(move |cx| {
2128                            workspace.update(cx, |workspace, cx| {
2129                                workspace.go_back(pane, cx).detach_and_log_err(cx)
2130                            })
2131                        })
2132                    }
2133                }),
2134            )
2135            .on_mouse_down(
2136                MouseButton::Navigate(NavigationDirection::Forward),
2137                cx.listener(|pane, _, cx| {
2138                    if let Some(workspace) = pane.workspace.upgrade() {
2139                        let pane = cx.view().downgrade();
2140                        cx.window_context().defer(move |cx| {
2141                            workspace.update(cx, |workspace, cx| {
2142                                workspace.go_forward(pane, cx).detach_and_log_err(cx)
2143                            })
2144                        })
2145                    }
2146                }),
2147            )
2148    }
2149}
2150
2151impl ItemNavHistory {
2152    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
2153        self.history
2154            .push(data, self.item.clone(), self.is_preview, cx);
2155    }
2156
2157    pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2158        self.history.pop(NavigationMode::GoingBack, cx)
2159    }
2160
2161    pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2162        self.history.pop(NavigationMode::GoingForward, cx)
2163    }
2164}
2165
2166impl NavHistory {
2167    pub fn for_each_entry(
2168        &self,
2169        cx: &AppContext,
2170        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
2171    ) {
2172        let borrowed_history = self.0.lock();
2173        borrowed_history
2174            .forward_stack
2175            .iter()
2176            .chain(borrowed_history.backward_stack.iter())
2177            .chain(borrowed_history.closed_stack.iter())
2178            .for_each(|entry| {
2179                if let Some(project_and_abs_path) =
2180                    borrowed_history.paths_by_item.get(&entry.item.id())
2181                {
2182                    f(entry, project_and_abs_path.clone());
2183                } else if let Some(item) = entry.item.upgrade() {
2184                    if let Some(path) = item.project_path(cx) {
2185                        f(entry, (path, None));
2186                    }
2187                }
2188            })
2189    }
2190
2191    pub fn set_mode(&mut self, mode: NavigationMode) {
2192        self.0.lock().mode = mode;
2193    }
2194
2195    pub fn mode(&self) -> NavigationMode {
2196        self.0.lock().mode
2197    }
2198
2199    pub fn disable(&mut self) {
2200        self.0.lock().mode = NavigationMode::Disabled;
2201    }
2202
2203    pub fn enable(&mut self) {
2204        self.0.lock().mode = NavigationMode::Normal;
2205    }
2206
2207    pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
2208        let mut state = self.0.lock();
2209        let entry = match mode {
2210            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
2211                return None
2212            }
2213            NavigationMode::GoingBack => &mut state.backward_stack,
2214            NavigationMode::GoingForward => &mut state.forward_stack,
2215            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
2216        }
2217        .pop_back();
2218        if entry.is_some() {
2219            state.did_update(cx);
2220        }
2221        entry
2222    }
2223
2224    pub fn push<D: 'static + Send + Any>(
2225        &mut self,
2226        data: Option<D>,
2227        item: Arc<dyn WeakItemHandle>,
2228        is_preview: bool,
2229        cx: &mut WindowContext,
2230    ) {
2231        let state = &mut *self.0.lock();
2232        match state.mode {
2233            NavigationMode::Disabled => {}
2234            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
2235                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2236                    state.backward_stack.pop_front();
2237                }
2238                state.backward_stack.push_back(NavigationEntry {
2239                    item,
2240                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2241                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2242                    is_preview,
2243                });
2244                state.forward_stack.clear();
2245            }
2246            NavigationMode::GoingBack => {
2247                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2248                    state.forward_stack.pop_front();
2249                }
2250                state.forward_stack.push_back(NavigationEntry {
2251                    item,
2252                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2253                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2254                    is_preview,
2255                });
2256            }
2257            NavigationMode::GoingForward => {
2258                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2259                    state.backward_stack.pop_front();
2260                }
2261                state.backward_stack.push_back(NavigationEntry {
2262                    item,
2263                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2264                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2265                    is_preview,
2266                });
2267            }
2268            NavigationMode::ClosingItem => {
2269                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2270                    state.closed_stack.pop_front();
2271                }
2272                state.closed_stack.push_back(NavigationEntry {
2273                    item,
2274                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2275                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2276                    is_preview,
2277                });
2278            }
2279        }
2280        state.did_update(cx);
2281    }
2282
2283    pub fn remove_item(&mut self, item_id: EntityId) {
2284        let mut state = self.0.lock();
2285        state.paths_by_item.remove(&item_id);
2286        state
2287            .backward_stack
2288            .retain(|entry| entry.item.id() != item_id);
2289        state
2290            .forward_stack
2291            .retain(|entry| entry.item.id() != item_id);
2292        state
2293            .closed_stack
2294            .retain(|entry| entry.item.id() != item_id);
2295    }
2296
2297    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2298        self.0.lock().paths_by_item.get(&item_id).cloned()
2299    }
2300}
2301
2302impl NavHistoryState {
2303    pub fn did_update(&self, cx: &mut WindowContext) {
2304        if let Some(pane) = self.pane.upgrade() {
2305            cx.defer(move |cx| {
2306                pane.update(cx, |pane, cx| pane.history_updated(cx));
2307            });
2308        }
2309    }
2310}
2311
2312fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2313    let path = buffer_path
2314        .as_ref()
2315        .and_then(|p| {
2316            p.path
2317                .to_str()
2318                .and_then(|s| if s == "" { None } else { Some(s) })
2319        })
2320        .unwrap_or("This buffer");
2321    let path = truncate_and_remove_front(path, 80);
2322    format!("{path} contains unsaved edits. Do you want to save it?")
2323}
2324
2325pub fn tab_details(items: &Vec<Box<dyn ItemHandle>>, cx: &AppContext) -> Vec<usize> {
2326    let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
2327    let mut tab_descriptions = HashMap::default();
2328    let mut done = false;
2329    while !done {
2330        done = true;
2331
2332        // Store item indices by their tab description.
2333        for (ix, (item, detail)) in items.iter().zip(&tab_details).enumerate() {
2334            if let Some(description) = item.tab_description(*detail, cx) {
2335                if *detail == 0
2336                    || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
2337                {
2338                    tab_descriptions
2339                        .entry(description)
2340                        .or_insert(Vec::new())
2341                        .push(ix);
2342                }
2343            }
2344        }
2345
2346        // If two or more items have the same tab description, increase their level
2347        // of detail and try again.
2348        for (_, item_ixs) in tab_descriptions.drain() {
2349            if item_ixs.len() > 1 {
2350                done = false;
2351                for ix in item_ixs {
2352                    tab_details[ix] += 1;
2353                }
2354            }
2355        }
2356    }
2357
2358    tab_details
2359}
2360
2361pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &WindowContext) -> Option<Indicator> {
2362    maybe!({
2363        let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
2364            (true, _) => Color::Warning,
2365            (_, true) => Color::Accent,
2366            (false, false) => return None,
2367        };
2368
2369        Some(Indicator::dot().color(indicator_color))
2370    })
2371}
2372
2373#[cfg(test)]
2374mod tests {
2375    use super::*;
2376    use crate::item::test::{TestItem, TestProjectItem};
2377    use gpui::{TestAppContext, VisualTestContext};
2378    use project::FakeFs;
2379    use settings::SettingsStore;
2380    use theme::LoadThemes;
2381
2382    #[gpui::test]
2383    async fn test_remove_active_empty(cx: &mut TestAppContext) {
2384        init_test(cx);
2385        let fs = FakeFs::new(cx.executor());
2386
2387        let project = Project::test(fs, None, cx).await;
2388        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2389        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2390
2391        pane.update(cx, |pane, cx| {
2392            assert!(pane
2393                .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2394                .is_none())
2395        });
2396    }
2397
2398    #[gpui::test]
2399    async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2400        init_test(cx);
2401        let fs = FakeFs::new(cx.executor());
2402
2403        let project = Project::test(fs, None, cx).await;
2404        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2405        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2406
2407        // 1. Add with a destination index
2408        //   a. Add before the active item
2409        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2410        pane.update(cx, |pane, cx| {
2411            pane.add_item(
2412                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2413                false,
2414                false,
2415                Some(0),
2416                cx,
2417            );
2418        });
2419        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2420
2421        //   b. Add after the active item
2422        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2423        pane.update(cx, |pane, cx| {
2424            pane.add_item(
2425                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2426                false,
2427                false,
2428                Some(2),
2429                cx,
2430            );
2431        });
2432        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2433
2434        //   c. Add at the end of the item list (including off the length)
2435        set_labeled_items(&pane, ["A", "B*", "C"], cx);
2436        pane.update(cx, |pane, cx| {
2437            pane.add_item(
2438                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2439                false,
2440                false,
2441                Some(5),
2442                cx,
2443            );
2444        });
2445        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2446
2447        // 2. Add without a destination index
2448        //   a. Add with active item at the start of the item list
2449        set_labeled_items(&pane, ["A*", "B", "C"], cx);
2450        pane.update(cx, |pane, cx| {
2451            pane.add_item(
2452                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2453                false,
2454                false,
2455                None,
2456                cx,
2457            );
2458        });
2459        set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2460
2461        //   b. Add with active item at the end of the item list
2462        set_labeled_items(&pane, ["A", "B", "C*"], cx);
2463        pane.update(cx, |pane, cx| {
2464            pane.add_item(
2465                Box::new(cx.new_view(|cx| TestItem::new(cx).with_label("D"))),
2466                false,
2467                false,
2468                None,
2469                cx,
2470            );
2471        });
2472        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2473    }
2474
2475    #[gpui::test]
2476    async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2477        init_test(cx);
2478        let fs = FakeFs::new(cx.executor());
2479
2480        let project = Project::test(fs, None, cx).await;
2481        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2482        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2483
2484        // 1. Add with a destination index
2485        //   1a. Add before the active item
2486        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2487        pane.update(cx, |pane, cx| {
2488            pane.add_item(d, false, false, Some(0), cx);
2489        });
2490        assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2491
2492        //   1b. Add after the active item
2493        let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2494        pane.update(cx, |pane, cx| {
2495            pane.add_item(d, false, false, Some(2), cx);
2496        });
2497        assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2498
2499        //   1c. Add at the end of the item list (including off the length)
2500        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2501        pane.update(cx, |pane, cx| {
2502            pane.add_item(a, false, false, Some(5), cx);
2503        });
2504        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2505
2506        //   1d. Add same item to active index
2507        let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2508        pane.update(cx, |pane, cx| {
2509            pane.add_item(b, false, false, Some(1), cx);
2510        });
2511        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2512
2513        //   1e. Add item to index after same item in last position
2514        let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2515        pane.update(cx, |pane, cx| {
2516            pane.add_item(c, false, false, Some(2), cx);
2517        });
2518        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2519
2520        // 2. Add without a destination index
2521        //   2a. Add with active item at the start of the item list
2522        let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2523        pane.update(cx, |pane, cx| {
2524            pane.add_item(d, false, false, None, cx);
2525        });
2526        assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2527
2528        //   2b. Add with active item at the end of the item list
2529        let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2530        pane.update(cx, |pane, cx| {
2531            pane.add_item(a, false, false, None, cx);
2532        });
2533        assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2534
2535        //   2c. Add active item to active item at end of list
2536        let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2537        pane.update(cx, |pane, cx| {
2538            pane.add_item(c, false, false, None, cx);
2539        });
2540        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2541
2542        //   2d. Add active item to active item at start of list
2543        let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2544        pane.update(cx, |pane, cx| {
2545            pane.add_item(a, false, false, None, cx);
2546        });
2547        assert_item_labels(&pane, ["A*", "B", "C"], cx);
2548    }
2549
2550    #[gpui::test]
2551    async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2552        init_test(cx);
2553        let fs = FakeFs::new(cx.executor());
2554
2555        let project = Project::test(fs, None, cx).await;
2556        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2557        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2558
2559        // singleton view
2560        pane.update(cx, |pane, cx| {
2561            pane.add_item(
2562                Box::new(cx.new_view(|cx| {
2563                    TestItem::new(cx)
2564                        .with_singleton(true)
2565                        .with_label("buffer 1")
2566                        .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
2567                })),
2568                false,
2569                false,
2570                None,
2571                cx,
2572            );
2573        });
2574        assert_item_labels(&pane, ["buffer 1*"], cx);
2575
2576        // new singleton view with the same project entry
2577        pane.update(cx, |pane, cx| {
2578            pane.add_item(
2579                Box::new(cx.new_view(|cx| {
2580                    TestItem::new(cx)
2581                        .with_singleton(true)
2582                        .with_label("buffer 1")
2583                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2584                })),
2585                false,
2586                false,
2587                None,
2588                cx,
2589            );
2590        });
2591        assert_item_labels(&pane, ["buffer 1*"], cx);
2592
2593        // new singleton view with different project entry
2594        pane.update(cx, |pane, cx| {
2595            pane.add_item(
2596                Box::new(cx.new_view(|cx| {
2597                    TestItem::new(cx)
2598                        .with_singleton(true)
2599                        .with_label("buffer 2")
2600                        .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
2601                })),
2602                false,
2603                false,
2604                None,
2605                cx,
2606            );
2607        });
2608        assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2609
2610        // new multibuffer view with the same project entry
2611        pane.update(cx, |pane, cx| {
2612            pane.add_item(
2613                Box::new(cx.new_view(|cx| {
2614                    TestItem::new(cx)
2615                        .with_singleton(false)
2616                        .with_label("multibuffer 1")
2617                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2618                })),
2619                false,
2620                false,
2621                None,
2622                cx,
2623            );
2624        });
2625        assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2626
2627        // another multibuffer view with the same project entry
2628        pane.update(cx, |pane, cx| {
2629            pane.add_item(
2630                Box::new(cx.new_view(|cx| {
2631                    TestItem::new(cx)
2632                        .with_singleton(false)
2633                        .with_label("multibuffer 1b")
2634                        .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
2635                })),
2636                false,
2637                false,
2638                None,
2639                cx,
2640            );
2641        });
2642        assert_item_labels(
2643            &pane,
2644            ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2645            cx,
2646        );
2647    }
2648
2649    #[gpui::test]
2650    async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2651        init_test(cx);
2652        let fs = FakeFs::new(cx.executor());
2653
2654        let project = Project::test(fs, None, cx).await;
2655        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2656        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2657
2658        add_labeled_item(&pane, "A", false, cx);
2659        add_labeled_item(&pane, "B", false, cx);
2660        add_labeled_item(&pane, "C", false, cx);
2661        add_labeled_item(&pane, "D", false, cx);
2662        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2663
2664        pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2665        add_labeled_item(&pane, "1", false, cx);
2666        assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2667
2668        pane.update(cx, |pane, cx| {
2669            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2670        })
2671        .unwrap()
2672        .await
2673        .unwrap();
2674        assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2675
2676        pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2677        assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2678
2679        pane.update(cx, |pane, cx| {
2680            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2681        })
2682        .unwrap()
2683        .await
2684        .unwrap();
2685        assert_item_labels(&pane, ["A", "B*", "C"], cx);
2686
2687        pane.update(cx, |pane, cx| {
2688            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2689        })
2690        .unwrap()
2691        .await
2692        .unwrap();
2693        assert_item_labels(&pane, ["A", "C*"], cx);
2694
2695        pane.update(cx, |pane, cx| {
2696            pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2697        })
2698        .unwrap()
2699        .await
2700        .unwrap();
2701        assert_item_labels(&pane, ["A*"], cx);
2702    }
2703
2704    #[gpui::test]
2705    async fn test_close_inactive_items(cx: &mut TestAppContext) {
2706        init_test(cx);
2707        let fs = FakeFs::new(cx.executor());
2708
2709        let project = Project::test(fs, None, cx).await;
2710        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2711        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2712
2713        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2714
2715        pane.update(cx, |pane, cx| {
2716            pane.close_inactive_items(&CloseInactiveItems { save_intent: None }, cx)
2717        })
2718        .unwrap()
2719        .await
2720        .unwrap();
2721        assert_item_labels(&pane, ["C*"], cx);
2722    }
2723
2724    #[gpui::test]
2725    async fn test_close_clean_items(cx: &mut TestAppContext) {
2726        init_test(cx);
2727        let fs = FakeFs::new(cx.executor());
2728
2729        let project = Project::test(fs, None, cx).await;
2730        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2731        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2732
2733        add_labeled_item(&pane, "A", true, cx);
2734        add_labeled_item(&pane, "B", false, cx);
2735        add_labeled_item(&pane, "C", true, cx);
2736        add_labeled_item(&pane, "D", false, cx);
2737        add_labeled_item(&pane, "E", false, cx);
2738        assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2739
2740        pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2741            .unwrap()
2742            .await
2743            .unwrap();
2744        assert_item_labels(&pane, ["A^", "C*^"], cx);
2745    }
2746
2747    #[gpui::test]
2748    async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2749        init_test(cx);
2750        let fs = FakeFs::new(cx.executor());
2751
2752        let project = Project::test(fs, None, cx).await;
2753        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2754        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2755
2756        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2757
2758        pane.update(cx, |pane, cx| {
2759            pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2760        })
2761        .unwrap()
2762        .await
2763        .unwrap();
2764        assert_item_labels(&pane, ["C*", "D", "E"], cx);
2765    }
2766
2767    #[gpui::test]
2768    async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2769        init_test(cx);
2770        let fs = FakeFs::new(cx.executor());
2771
2772        let project = Project::test(fs, None, cx).await;
2773        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2774        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2775
2776        set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2777
2778        pane.update(cx, |pane, cx| {
2779            pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2780        })
2781        .unwrap()
2782        .await
2783        .unwrap();
2784        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2785    }
2786
2787    #[gpui::test]
2788    async fn test_close_all_items(cx: &mut TestAppContext) {
2789        init_test(cx);
2790        let fs = FakeFs::new(cx.executor());
2791
2792        let project = Project::test(fs, None, cx).await;
2793        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
2794        let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
2795
2796        add_labeled_item(&pane, "A", false, cx);
2797        add_labeled_item(&pane, "B", false, cx);
2798        add_labeled_item(&pane, "C", false, cx);
2799        assert_item_labels(&pane, ["A", "B", "C*"], cx);
2800
2801        pane.update(cx, |pane, cx| {
2802            pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2803        })
2804        .unwrap()
2805        .await
2806        .unwrap();
2807        assert_item_labels(&pane, [], cx);
2808
2809        add_labeled_item(&pane, "A", true, cx);
2810        add_labeled_item(&pane, "B", true, cx);
2811        add_labeled_item(&pane, "C", true, cx);
2812        assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
2813
2814        let save = pane
2815            .update(cx, |pane, cx| {
2816                pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2817            })
2818            .unwrap();
2819
2820        cx.executor().run_until_parked();
2821        cx.simulate_prompt_answer(2);
2822        save.await.unwrap();
2823        assert_item_labels(&pane, [], cx);
2824    }
2825
2826    fn init_test(cx: &mut TestAppContext) {
2827        cx.update(|cx| {
2828            let settings_store = SettingsStore::test(cx);
2829            cx.set_global(settings_store);
2830            theme::init(LoadThemes::JustBase, cx);
2831            crate::init_settings(cx);
2832            Project::init_settings(cx);
2833        });
2834    }
2835
2836    fn add_labeled_item(
2837        pane: &View<Pane>,
2838        label: &str,
2839        is_dirty: bool,
2840        cx: &mut VisualTestContext,
2841    ) -> Box<View<TestItem>> {
2842        pane.update(cx, |pane, cx| {
2843            let labeled_item = Box::new(
2844                cx.new_view(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)),
2845            );
2846            pane.add_item(labeled_item.clone(), false, false, None, cx);
2847            labeled_item
2848        })
2849    }
2850
2851    fn set_labeled_items<const COUNT: usize>(
2852        pane: &View<Pane>,
2853        labels: [&str; COUNT],
2854        cx: &mut VisualTestContext,
2855    ) -> [Box<View<TestItem>>; COUNT] {
2856        pane.update(cx, |pane, cx| {
2857            pane.items.clear();
2858            let mut active_item_index = 0;
2859
2860            let mut index = 0;
2861            let items = labels.map(|mut label| {
2862                if label.ends_with('*') {
2863                    label = label.trim_end_matches('*');
2864                    active_item_index = index;
2865                }
2866
2867                let labeled_item = Box::new(cx.new_view(|cx| TestItem::new(cx).with_label(label)));
2868                pane.add_item(labeled_item.clone(), false, false, None, cx);
2869                index += 1;
2870                labeled_item
2871            });
2872
2873            pane.activate_item(active_item_index, false, false, cx);
2874
2875            items
2876        })
2877    }
2878
2879    // Assert the item label, with the active item label suffixed with a '*'
2880    fn assert_item_labels<const COUNT: usize>(
2881        pane: &View<Pane>,
2882        expected_states: [&str; COUNT],
2883        cx: &mut VisualTestContext,
2884    ) {
2885        pane.update(cx, |pane, cx| {
2886            let actual_states = pane
2887                .items
2888                .iter()
2889                .enumerate()
2890                .map(|(ix, item)| {
2891                    let mut state = item
2892                        .to_any()
2893                        .downcast::<TestItem>()
2894                        .unwrap()
2895                        .read(cx)
2896                        .label
2897                        .clone();
2898                    if ix == pane.active_item_index {
2899                        state.push('*');
2900                    }
2901                    if item.is_dirty(cx) {
2902                        state.push('^');
2903                    }
2904                    state
2905                })
2906                .collect::<Vec<_>>();
2907
2908            assert_eq!(
2909                actual_states, expected_states,
2910                "pane items do not match expectation"
2911            );
2912        })
2913    }
2914}
2915
2916impl Render for DraggedTab {
2917    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2918        let ui_font = ThemeSettings::get_global(cx).ui_font.family.clone();
2919        let label = self.item.tab_content(
2920            TabContentParams {
2921                detail: Some(self.detail),
2922                selected: false,
2923                preview: false,
2924            },
2925            cx,
2926        );
2927        Tab::new("")
2928            .selected(self.is_active)
2929            .child(label)
2930            .render(cx)
2931            .font_family(ui_font)
2932    }
2933}