pane.rs

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