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