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