pane.rs

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