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                    .tooltip(|cx| Tooltip::for_action("Go Back", &GoBack, cx)),
1602            )
1603            .start_child(
1604                IconButton::new("navigate_forward", Icon::ArrowRight)
1605                    .icon_size(IconSize::Small)
1606                    .on_click({
1607                        let view = cx.view().clone();
1608                        move |_, cx| view.update(cx, Self::navigate_backward)
1609                    })
1610                    .disabled(!self.can_navigate_forward())
1611                    .tooltip(|cx| Tooltip::for_action("Go Forward", &GoForward, cx)),
1612            )
1613            .end_child(
1614                div()
1615                    .child(
1616                        IconButton::new("plus", Icon::Plus)
1617                            .icon_size(IconSize::Small)
1618                            .on_click(cx.listener(|this, _, cx| {
1619                                let menu = ContextMenu::build(cx, |menu, cx| {
1620                                    menu.action("New File", NewFile.boxed_clone())
1621                                        .action("New Terminal", NewCenterTerminal.boxed_clone())
1622                                        .action("New Search", NewSearch.boxed_clone())
1623                                });
1624                                cx.subscribe(&menu, |this, _, event: &DismissEvent, cx| {
1625                                    this.focus(cx);
1626                                    this.new_item_menu = None;
1627                                })
1628                                .detach();
1629                                this.new_item_menu = Some(menu);
1630                            }))
1631                            .tooltip(|cx| Tooltip::text("New...", cx)),
1632                    )
1633                    .when_some(self.new_item_menu.as_ref(), |el, new_item_menu| {
1634                        el.child(Self::render_menu_overlay(new_item_menu))
1635                    }),
1636            )
1637            .end_child(
1638                div()
1639                    .child(
1640                        IconButton::new("split", Icon::Split)
1641                            .icon_size(IconSize::Small)
1642                            .on_click(cx.listener(|this, _, cx| {
1643                                let menu = ContextMenu::build(cx, |menu, cx| {
1644                                    menu.action("Split Right", SplitRight.boxed_clone())
1645                                        .action("Split Left", SplitLeft.boxed_clone())
1646                                        .action("Split Up", SplitUp.boxed_clone())
1647                                        .action("Split Down", SplitDown.boxed_clone())
1648                                });
1649                                cx.subscribe(&menu, |this, _, event: &DismissEvent, cx| {
1650                                    this.focus(cx);
1651                                    this.split_item_menu = None;
1652                                })
1653                                .detach();
1654                                this.split_item_menu = Some(menu);
1655                            }))
1656                            .tooltip(|cx| Tooltip::text("Split Pane", cx)),
1657                    )
1658                    .when_some(self.split_item_menu.as_ref(), |el, split_item_menu| {
1659                        el.child(Self::render_menu_overlay(split_item_menu))
1660                    }),
1661            )
1662            .children(
1663                self.items
1664                    .iter()
1665                    .enumerate()
1666                    .zip(self.tab_details(cx))
1667                    .map(|((ix, item), detail)| self.render_tab(ix, item, detail, cx)),
1668            )
1669            .child(
1670                div()
1671                    .min_w_6()
1672                    // HACK: This empty child is currently necessary to force the drop traget to appear
1673                    // despite us setting a min width above.
1674                    .child("")
1675                    .h_full()
1676                    .flex_grow()
1677                    .drag_over::<DraggedTab>(|bar| {
1678                        bar.bg(cx.theme().colors().tab_active_background)
1679                    })
1680                    .on_drop(
1681                        cx.listener(move |this, dragged_tab: &View<DraggedTab>, cx| {
1682                            this.handle_tab_drop(dragged_tab, this.items.len(), cx)
1683                        }),
1684                    ),
1685            )
1686    }
1687
1688    fn render_menu_overlay(menu: &View<ContextMenu>) -> Div {
1689        div()
1690            .absolute()
1691            .z_index(1)
1692            .bottom_0()
1693            .right_0()
1694            .size_0()
1695            .child(overlay().anchor(AnchorCorner::TopRight).child(menu.clone()))
1696    }
1697
1698    fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1699        let mut tab_details = self.items.iter().map(|_| 0).collect::<Vec<_>>();
1700
1701        let mut tab_descriptions = HashMap::default();
1702        let mut done = false;
1703        while !done {
1704            done = true;
1705
1706            // Store item indices by their tab description.
1707            for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1708                if let Some(description) = item.tab_description(*detail, cx) {
1709                    if *detail == 0
1710                        || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1711                    {
1712                        tab_descriptions
1713                            .entry(description)
1714                            .or_insert(Vec::new())
1715                            .push(ix);
1716                    }
1717                }
1718            }
1719
1720            // If two or more items have the same tab description, increase eir level
1721            // of detail and try again.
1722            for (_, item_ixs) in tab_descriptions.drain() {
1723                if item_ixs.len() > 1 {
1724                    done = false;
1725                    for ix in item_ixs {
1726                        tab_details[ix] += 1;
1727                    }
1728                }
1729            }
1730        }
1731
1732        tab_details
1733    }
1734
1735    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1736        self.zoomed = zoomed;
1737        cx.notify();
1738    }
1739
1740    pub fn is_zoomed(&self) -> bool {
1741        self.zoomed
1742    }
1743
1744    fn handle_tab_drop(
1745        &mut self,
1746        dragged_tab: &View<DraggedTab>,
1747        ix: usize,
1748        cx: &mut ViewContext<'_, Pane>,
1749    ) {
1750        let dragged_tab = dragged_tab.read(cx);
1751        let item_id = dragged_tab.item_id;
1752        let from_pane = dragged_tab.pane.clone();
1753        let to_pane = cx.view().clone();
1754        self.workspace
1755            .update(cx, |workspace, cx| {
1756                cx.defer(move |workspace, cx| {
1757                    workspace.move_item(from_pane, to_pane, item_id, ix, cx);
1758                });
1759            })
1760            .log_err();
1761    }
1762
1763    fn handle_split_tab_drop(
1764        &mut self,
1765        dragged_tab: &View<DraggedTab>,
1766        split_direction: SplitDirection,
1767        cx: &mut ViewContext<'_, Pane>,
1768    ) {
1769        let dragged_tab = dragged_tab.read(cx);
1770        let item_id = dragged_tab.item_id;
1771        let from_pane = dragged_tab.pane.clone();
1772        let to_pane = cx.view().clone();
1773        self.workspace
1774            .update(cx, |workspace, cx| {
1775                cx.defer(move |workspace, cx| {
1776                    let item = from_pane
1777                        .read(cx)
1778                        .items()
1779                        .find(|item| item.item_id() == item_id)
1780                        .map(|item| item.boxed_clone());
1781                    if let Some(item) = item {
1782                        if let Some(item) = item.clone_on_split(workspace.database_id(), cx) {
1783                            workspace.split_item(split_direction, item, cx);
1784                        }
1785                    }
1786                });
1787            })
1788            .log_err();
1789    }
1790}
1791
1792impl FocusableView for Pane {
1793    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
1794        self.focus_handle.clone()
1795    }
1796}
1797
1798impl Render for Pane {
1799    type Element = Focusable<Div>;
1800
1801    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
1802        let this = cx.view().downgrade();
1803
1804        v_stack()
1805            .key_context("Pane")
1806            .track_focus(&self.focus_handle)
1807            .size_full()
1808            .flex_none()
1809            .overflow_hidden()
1810            .on_action(cx.listener(|pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx)))
1811            .on_action(cx.listener(|pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx)))
1812            .on_action(
1813                cx.listener(|pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx)),
1814            )
1815            .on_action(cx.listener(|pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx)))
1816            .on_action(cx.listener(|pane, _: &GoBack, cx| pane.navigate_backward(cx)))
1817            .on_action(cx.listener(|pane, _: &GoForward, cx| pane.navigate_forward(cx)))
1818            .on_action(cx.listener(Pane::toggle_zoom))
1819            .on_action(cx.listener(|pane: &mut Pane, action: &ActivateItem, cx| {
1820                pane.activate_item(action.0, true, true, cx);
1821            }))
1822            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateLastItem, cx| {
1823                pane.activate_item(pane.items.len() - 1, true, true, cx);
1824            }))
1825            .on_action(cx.listener(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
1826                pane.activate_prev_item(true, cx);
1827            }))
1828            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateNextItem, cx| {
1829                pane.activate_next_item(true, cx);
1830            }))
1831            .on_action(
1832                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1833                    pane.close_active_item(action, cx)
1834                        .map(|task| task.detach_and_log_err(cx));
1835                }),
1836            )
1837            .on_action(
1838                cx.listener(|pane: &mut Self, action: &CloseInactiveItems, cx| {
1839                    pane.close_inactive_items(action, cx)
1840                        .map(|task| task.detach_and_log_err(cx));
1841                }),
1842            )
1843            .on_action(
1844                cx.listener(|pane: &mut Self, action: &CloseCleanItems, cx| {
1845                    pane.close_clean_items(action, cx)
1846                        .map(|task| task.detach_and_log_err(cx));
1847                }),
1848            )
1849            .on_action(
1850                cx.listener(|pane: &mut Self, action: &CloseItemsToTheLeft, cx| {
1851                    pane.close_items_to_the_left(action, cx)
1852                        .map(|task| task.detach_and_log_err(cx));
1853                }),
1854            )
1855            .on_action(
1856                cx.listener(|pane: &mut Self, action: &CloseItemsToTheRight, cx| {
1857                    pane.close_items_to_the_right(action, cx)
1858                        .map(|task| task.detach_and_log_err(cx));
1859                }),
1860            )
1861            .on_action(cx.listener(|pane: &mut Self, action: &CloseAllItems, cx| {
1862                pane.close_all_items(action, cx)
1863                    .map(|task| task.detach_and_log_err(cx));
1864            }))
1865            .on_action(
1866                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
1867                    pane.close_active_item(action, cx)
1868                        .map(|task| task.detach_and_log_err(cx));
1869                }),
1870            )
1871            .on_action(
1872                cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, cx| {
1873                    pane.project.update(cx, |_, cx| {
1874                        cx.emit(project::Event::RevealInProjectPanel(
1875                            ProjectEntryId::from_proto(action.entry_id),
1876                        ))
1877                    })
1878                }),
1879            )
1880            .child(self.render_tab_bar(cx))
1881            .child(self.toolbar.clone())
1882            .child(if let Some(item) = self.active_item() {
1883                let mut drag_target_color = cx.theme().colors().text;
1884                drag_target_color.a = 0.5;
1885
1886                div()
1887                    .flex()
1888                    .flex_1()
1889                    .relative()
1890                    .child(item.to_any())
1891                    .child(
1892                        div()
1893                            .absolute()
1894                            .full()
1895                            .z_index(1)
1896                            .drag_over::<DraggedTab>(|style| style.bg(drag_target_color))
1897                            .on_drop(cx.listener(
1898                                move |this, dragged_tab: &View<DraggedTab>, cx| {
1899                                    this.handle_tab_drop(dragged_tab, this.active_item_index(), cx)
1900                                },
1901                            )),
1902                    )
1903                    .children(
1904                        [
1905                            (SplitDirection::Up, 2),
1906                            (SplitDirection::Down, 2),
1907                            (SplitDirection::Left, 3),
1908                            (SplitDirection::Right, 3),
1909                        ]
1910                        .into_iter()
1911                        .map(|(direction, z_index)| {
1912                            let div = div()
1913                                .absolute()
1914                                .z_index(z_index)
1915                                .invisible()
1916                                .bg(drag_target_color)
1917                                .drag_over::<DraggedTab>(|style| style.visible())
1918                                .on_drop(cx.listener(
1919                                    move |this, dragged_tab: &View<DraggedTab>, cx| {
1920                                        this.handle_split_tab_drop(dragged_tab, direction, cx)
1921                                    },
1922                                ));
1923                            match direction {
1924                                SplitDirection::Up => div.top_0().left_0().right_0().h_32(),
1925                                SplitDirection::Down => div.left_0().bottom_0().right_0().h_32(),
1926                                SplitDirection::Left => div.top_0().left_0().bottom_0().w_32(),
1927                                SplitDirection::Right => div.top_0().bottom_0().right_0().w_32(),
1928                            }
1929                        }),
1930                    )
1931            } else {
1932                h_stack()
1933                    .items_center()
1934                    .size_full()
1935                    .justify_center()
1936                    .child(Label::new("Open a file or project to get started.").color(Color::Muted))
1937            })
1938            .on_mouse_down(
1939                MouseButton::Navigate(NavigationDirection::Back),
1940                cx.listener(|pane, _, cx| {
1941                    if let Some(workspace) = pane.workspace.upgrade() {
1942                        let pane = cx.view().downgrade();
1943                        cx.window_context().defer(move |cx| {
1944                            workspace.update(cx, |workspace, cx| {
1945                                workspace.go_back(pane, cx).detach_and_log_err(cx)
1946                            })
1947                        })
1948                    }
1949                }),
1950            )
1951            .on_mouse_down(
1952                MouseButton::Navigate(NavigationDirection::Forward),
1953                cx.listener(|pane, _, cx| {
1954                    if let Some(workspace) = pane.workspace.upgrade() {
1955                        let pane = cx.view().downgrade();
1956                        cx.window_context().defer(move |cx| {
1957                            workspace.update(cx, |workspace, cx| {
1958                                workspace.go_forward(pane, cx).detach_and_log_err(cx)
1959                            })
1960                        })
1961                    }
1962                }),
1963            )
1964    }
1965
1966    // fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1967    //     if !self.has_focus {
1968    //         self.has_focus = true;
1969    //         cx.emit(Event::Focus);
1970    //         cx.notify();
1971    //     }
1972
1973    //     self.toolbar.update(cx, |toolbar, cx| {
1974    //         toolbar.focus_changed(true, cx);
1975    //     });
1976
1977    //     if let Some(active_item) = self.active_item() {
1978    //         if cx.is_self_focused() {
1979    //             // Pane was focused directly. We need to either focus a view inside the active item,
1980    //             // or focus the active item itself
1981    //             if let Some(weak_last_focused_view) =
1982    //                 self.last_focused_view_by_item.get(&active_item.id())
1983    //             {
1984    //                 if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1985    //                     cx.focus(&last_focused_view);
1986    //                     return;
1987    //                 } else {
1988    //                     self.last_focused_view_by_item.remove(&active_item.id());
1989    //                 }
1990    //             }
1991
1992    //             cx.focus(active_item.as_any());
1993    //         } else if focused != self.tab_bar_context_menu.handle {
1994    //             self.last_focused_view_by_item
1995    //                 .insert(active_item.id(), focused.downgrade());
1996    //         }
1997    //     }
1998    // }
1999
2000    // fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
2001    //     self.has_focus = false;
2002    //     self.toolbar.update(cx, |toolbar, cx| {
2003    //         toolbar.focus_changed(false, cx);
2004    //     });
2005    //     cx.notify();
2006    // }
2007
2008    // fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
2009    //     Self::reset_to_default_keymap_context(keymap);
2010    // }
2011}
2012
2013impl ItemNavHistory {
2014    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
2015        self.history.push(data, self.item.clone(), cx);
2016    }
2017
2018    pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2019        self.history.pop(NavigationMode::GoingBack, cx)
2020    }
2021
2022    pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2023        self.history.pop(NavigationMode::GoingForward, cx)
2024    }
2025}
2026
2027impl NavHistory {
2028    pub fn for_each_entry(
2029        &self,
2030        cx: &AppContext,
2031        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
2032    ) {
2033        let borrowed_history = self.0.lock();
2034        borrowed_history
2035            .forward_stack
2036            .iter()
2037            .chain(borrowed_history.backward_stack.iter())
2038            .chain(borrowed_history.closed_stack.iter())
2039            .for_each(|entry| {
2040                if let Some(project_and_abs_path) =
2041                    borrowed_history.paths_by_item.get(&entry.item.id())
2042                {
2043                    f(entry, project_and_abs_path.clone());
2044                } else if let Some(item) = entry.item.upgrade() {
2045                    if let Some(path) = item.project_path(cx) {
2046                        f(entry, (path, None));
2047                    }
2048                }
2049            })
2050    }
2051
2052    pub fn set_mode(&mut self, mode: NavigationMode) {
2053        self.0.lock().mode = mode;
2054    }
2055
2056    pub fn mode(&self) -> NavigationMode {
2057        self.0.lock().mode
2058    }
2059
2060    pub fn disable(&mut self) {
2061        self.0.lock().mode = NavigationMode::Disabled;
2062    }
2063
2064    pub fn enable(&mut self) {
2065        self.0.lock().mode = NavigationMode::Normal;
2066    }
2067
2068    pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
2069        let mut state = self.0.lock();
2070        let entry = match mode {
2071            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
2072                return None
2073            }
2074            NavigationMode::GoingBack => &mut state.backward_stack,
2075            NavigationMode::GoingForward => &mut state.forward_stack,
2076            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
2077        }
2078        .pop_back();
2079        if entry.is_some() {
2080            state.did_update(cx);
2081        }
2082        entry
2083    }
2084
2085    pub fn push<D: 'static + Send + Any>(
2086        &mut self,
2087        data: Option<D>,
2088        item: Arc<dyn WeakItemHandle>,
2089        cx: &mut WindowContext,
2090    ) {
2091        let state = &mut *self.0.lock();
2092        match state.mode {
2093            NavigationMode::Disabled => {}
2094            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
2095                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2096                    state.backward_stack.pop_front();
2097                }
2098                state.backward_stack.push_back(NavigationEntry {
2099                    item,
2100                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2101                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2102                });
2103                state.forward_stack.clear();
2104            }
2105            NavigationMode::GoingBack => {
2106                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2107                    state.forward_stack.pop_front();
2108                }
2109                state.forward_stack.push_back(NavigationEntry {
2110                    item,
2111                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2112                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2113                });
2114            }
2115            NavigationMode::GoingForward => {
2116                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2117                    state.backward_stack.pop_front();
2118                }
2119                state.backward_stack.push_back(NavigationEntry {
2120                    item,
2121                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2122                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2123                });
2124            }
2125            NavigationMode::ClosingItem => {
2126                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2127                    state.closed_stack.pop_front();
2128                }
2129                state.closed_stack.push_back(NavigationEntry {
2130                    item,
2131                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2132                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2133                });
2134            }
2135        }
2136        state.did_update(cx);
2137    }
2138
2139    pub fn remove_item(&mut self, item_id: EntityId) {
2140        let mut state = self.0.lock();
2141        state.paths_by_item.remove(&item_id);
2142        state
2143            .backward_stack
2144            .retain(|entry| entry.item.id() != item_id);
2145        state
2146            .forward_stack
2147            .retain(|entry| entry.item.id() != item_id);
2148        state
2149            .closed_stack
2150            .retain(|entry| entry.item.id() != item_id);
2151    }
2152
2153    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2154        self.0.lock().paths_by_item.get(&item_id).cloned()
2155    }
2156}
2157
2158impl NavHistoryState {
2159    pub fn did_update(&self, cx: &mut WindowContext) {
2160        if let Some(pane) = self.pane.upgrade() {
2161            cx.defer(move |cx| {
2162                pane.update(cx, |pane, cx| pane.history_updated(cx));
2163            });
2164        }
2165    }
2166}
2167
2168// pub struct PaneBackdrop<V> {
2169//     child_view: usize,
2170//     child: AnyElement<V>,
2171// }
2172
2173// impl<V> PaneBackdrop<V> {
2174//     pub fn new(pane_item_view: usize, child: AnyElement<V>) -> Self {
2175//         PaneBackdrop {
2176//             child,
2177//             child_view: pane_item_view,
2178//         }
2179//     }
2180// }
2181
2182// impl<V: 'static> Element<V> for PaneBackdrop<V> {
2183//     type LayoutState = ();
2184
2185//     type PaintState = ();
2186
2187//     fn layout(
2188//         &mut self,
2189//         constraint: gpui::SizeConstraint,
2190//         view: &mut V,
2191//         cx: &mut ViewContext<V>,
2192//     ) -> (Vector2F, Self::LayoutState) {
2193//         let size = self.child.layout(constraint, view, cx);
2194//         (size, ())
2195//     }
2196
2197//     fn paint(
2198//         &mut self,
2199//         bounds: RectF,
2200//         visible_bounds: RectF,
2201//         _: &mut Self::LayoutState,
2202//         view: &mut V,
2203//         cx: &mut ViewContext<V>,
2204//     ) -> Self::PaintState {
2205//         let background = theme::current(cx).editor.background;
2206
2207//         let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2208
2209//         cx.scene().push_quad(gpui::Quad {
2210//             bounds: RectF::new(bounds.origin(), bounds.size()),
2211//             background: Some(background),
2212//             ..Default::default()
2213//         });
2214
2215//         let child_view_id = self.child_view;
2216//         cx.scene().push_mouse_region(
2217//             MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
2218//                 gpui::platform::MouseButton::Left,
2219//                 move |_, _: &mut V, cx| {
2220//                     let window = cx.window();
2221//                     cx.app_context().focus(window, Some(child_view_id))
2222//                 },
2223//             ),
2224//         );
2225
2226//         cx.scene().push_layer(Some(bounds));
2227//         self.child.paint(bounds.origin(), visible_bounds, view, cx);
2228//         cx.scene().pop_layer();
2229//     }
2230
2231//     fn rect_for_text_range(
2232//         &self,
2233//         range_utf16: std::ops::Range<usize>,
2234//         _bounds: RectF,
2235//         _visible_bounds: RectF,
2236//         _layout: &Self::LayoutState,
2237//         _paint: &Self::PaintState,
2238//         view: &V,
2239//         cx: &gpui::ViewContext<V>,
2240//     ) -> Option<RectF> {
2241//         self.child.rect_for_text_range(range_utf16, view, cx)
2242//     }
2243
2244//     fn debug(
2245//         &self,
2246//         _bounds: RectF,
2247//         _layout: &Self::LayoutState,
2248//         _paint: &Self::PaintState,
2249//         view: &V,
2250//         cx: &gpui::ViewContext<V>,
2251//     ) -> serde_json::Value {
2252//         gpui::json::json!({
2253//             "type": "Pane Back Drop",
2254//             "view": self.child_view,
2255//             "child": self.child.debug(view, cx),
2256//         })
2257//     }
2258// }
2259
2260fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2261    let path = buffer_path
2262        .as_ref()
2263        .and_then(|p| p.path.to_str())
2264        .unwrap_or(&"This buffer");
2265    let path = truncate_and_remove_front(path, 80);
2266    format!("{path} contains unsaved edits. Do you want to save it?")
2267}
2268
2269// todo!("uncomment tests")
2270// #[cfg(test)]
2271// mod tests {
2272//     use super::*;
2273//     use crate::item::test::{TestItem, TestProjectItem};
2274//     use gpui::TestAppContext;
2275//     use project::FakeFs;
2276//     use settings::SettingsStore;
2277
2278//     #[gpui::test]
2279//     async fn test_remove_active_empty(cx: &mut TestAppContext) {
2280//         init_test(cx);
2281//         let fs = FakeFs::new(cx.background());
2282
2283//         let project = Project::test(fs, None, cx).await;
2284//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2285//         let workspace = window.root(cx);
2286//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2287
2288//         pane.update(cx, |pane, cx| {
2289//             assert!(pane
2290//                 .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2291//                 .is_none())
2292//         });
2293//     }
2294
2295//     #[gpui::test]
2296//     async fn test_add_item_with_new_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//         //   a. Add before the active item
2308//         set_labeled_items(&pane, ["A", "B*", "C"], cx);
2309//         pane.update(cx, |pane, cx| {
2310//             pane.add_item(
2311//                 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2312//                 false,
2313//                 false,
2314//                 Some(0),
2315//                 cx,
2316//             );
2317//         });
2318//         assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2319
2320//         //   b. Add after the active item
2321//         set_labeled_items(&pane, ["A", "B*", "C"], cx);
2322//         pane.update(cx, |pane, cx| {
2323//             pane.add_item(
2324//                 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2325//                 false,
2326//                 false,
2327//                 Some(2),
2328//                 cx,
2329//             );
2330//         });
2331//         assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2332
2333//         //   c. Add at the end of the item list (including off the length)
2334//         set_labeled_items(&pane, ["A", "B*", "C"], cx);
2335//         pane.update(cx, |pane, cx| {
2336//             pane.add_item(
2337//                 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2338//                 false,
2339//                 false,
2340//                 Some(5),
2341//                 cx,
2342//             );
2343//         });
2344//         assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2345
2346//         // 2. Add without a destination index
2347//         //   a. Add with active item at the start of the item list
2348//         set_labeled_items(&pane, ["A*", "B", "C"], cx);
2349//         pane.update(cx, |pane, cx| {
2350//             pane.add_item(
2351//                 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2352//                 false,
2353//                 false,
2354//                 None,
2355//                 cx,
2356//             );
2357//         });
2358//         set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2359
2360//         //   b. Add with active item at the end of the item list
2361//         set_labeled_items(&pane, ["A", "B", "C*"], cx);
2362//         pane.update(cx, |pane, cx| {
2363//             pane.add_item(
2364//                 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2365//                 false,
2366//                 false,
2367//                 None,
2368//                 cx,
2369//             );
2370//         });
2371//         assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2372//     }
2373
2374//     #[gpui::test]
2375//     async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2376//         cx.foreground().forbid_parking();
2377//         init_test(cx);
2378//         let fs = FakeFs::new(cx.background());
2379
2380//         let project = Project::test(fs, None, cx).await;
2381//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2382//         let workspace = window.root(cx);
2383//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2384
2385//         // 1. Add with a destination index
2386//         //   1a. Add before the active item
2387//         let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2388//         pane.update(cx, |pane, cx| {
2389//             pane.add_item(d, false, false, Some(0), cx);
2390//         });
2391//         assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2392
2393//         //   1b. Add after the active item
2394//         let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2395//         pane.update(cx, |pane, cx| {
2396//             pane.add_item(d, false, false, Some(2), cx);
2397//         });
2398//         assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2399
2400//         //   1c. Add at the end of the item list (including off the length)
2401//         let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2402//         pane.update(cx, |pane, cx| {
2403//             pane.add_item(a, false, false, Some(5), cx);
2404//         });
2405//         assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2406
2407//         //   1d. Add same item to active index
2408//         let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2409//         pane.update(cx, |pane, cx| {
2410//             pane.add_item(b, false, false, Some(1), cx);
2411//         });
2412//         assert_item_labels(&pane, ["A", "B*", "C"], cx);
2413
2414//         //   1e. Add item to index after same item in last position
2415//         let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2416//         pane.update(cx, |pane, cx| {
2417//             pane.add_item(c, false, false, Some(2), cx);
2418//         });
2419//         assert_item_labels(&pane, ["A", "B", "C*"], cx);
2420
2421//         // 2. Add without a destination index
2422//         //   2a. Add with active item at the start of the item list
2423//         let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2424//         pane.update(cx, |pane, cx| {
2425//             pane.add_item(d, false, false, None, cx);
2426//         });
2427//         assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2428
2429//         //   2b. Add with active item at the end of the item list
2430//         let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2431//         pane.update(cx, |pane, cx| {
2432//             pane.add_item(a, false, false, None, cx);
2433//         });
2434//         assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2435
2436//         //   2c. Add active item to active item at end of list
2437//         let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2438//         pane.update(cx, |pane, cx| {
2439//             pane.add_item(c, false, false, None, cx);
2440//         });
2441//         assert_item_labels(&pane, ["A", "B", "C*"], cx);
2442
2443//         //   2d. Add active item to active item at start of list
2444//         let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2445//         pane.update(cx, |pane, cx| {
2446//             pane.add_item(a, false, false, None, cx);
2447//         });
2448//         assert_item_labels(&pane, ["A*", "B", "C"], cx);
2449//     }
2450
2451//     #[gpui::test]
2452//     async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2453//         cx.foreground().forbid_parking();
2454//         init_test(cx);
2455//         let fs = FakeFs::new(cx.background());
2456
2457//         let project = Project::test(fs, None, cx).await;
2458//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2459//         let workspace = window.root(cx);
2460//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2461
2462//         // singleton view
2463//         pane.update(cx, |pane, cx| {
2464//             let item = TestItem::new()
2465//                 .with_singleton(true)
2466//                 .with_label("buffer 1")
2467//                 .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2468
2469//             pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2470//         });
2471//         assert_item_labels(&pane, ["buffer 1*"], cx);
2472
2473//         // new singleton view with the same project entry
2474//         pane.update(cx, |pane, cx| {
2475//             let item = TestItem::new()
2476//                 .with_singleton(true)
2477//                 .with_label("buffer 1")
2478//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2479
2480//             pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2481//         });
2482//         assert_item_labels(&pane, ["buffer 1*"], cx);
2483
2484//         // new singleton view with different project entry
2485//         pane.update(cx, |pane, cx| {
2486//             let item = TestItem::new()
2487//                 .with_singleton(true)
2488//                 .with_label("buffer 2")
2489//                 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2490//             pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2491//         });
2492//         assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2493
2494//         // new multibuffer view with the same project entry
2495//         pane.update(cx, |pane, cx| {
2496//             let item = TestItem::new()
2497//                 .with_singleton(false)
2498//                 .with_label("multibuffer 1")
2499//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2500
2501//             pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2502//         });
2503//         assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2504
2505//         // another multibuffer view with the same project entry
2506//         pane.update(cx, |pane, cx| {
2507//             let item = TestItem::new()
2508//                 .with_singleton(false)
2509//                 .with_label("multibuffer 1b")
2510//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2511
2512//             pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2513//         });
2514//         assert_item_labels(
2515//             &pane,
2516//             ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2517//             cx,
2518//         );
2519//     }
2520
2521//     #[gpui::test]
2522//     async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2523//         init_test(cx);
2524//         let fs = FakeFs::new(cx.background());
2525
2526//         let project = Project::test(fs, None, cx).await;
2527//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2528//         let workspace = window.root(cx);
2529//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2530
2531//         add_labeled_item(&pane, "A", false, cx);
2532//         add_labeled_item(&pane, "B", false, cx);
2533//         add_labeled_item(&pane, "C", false, cx);
2534//         add_labeled_item(&pane, "D", false, cx);
2535//         assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2536
2537//         pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2538//         add_labeled_item(&pane, "1", false, cx);
2539//         assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2540
2541//         pane.update(cx, |pane, cx| {
2542//             pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2543//         })
2544//         .unwrap()
2545//         .await
2546//         .unwrap();
2547//         assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2548
2549//         pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2550//         assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2551
2552//         pane.update(cx, |pane, cx| {
2553//             pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2554//         })
2555//         .unwrap()
2556//         .await
2557//         .unwrap();
2558//         assert_item_labels(&pane, ["A", "B*", "C"], cx);
2559
2560//         pane.update(cx, |pane, cx| {
2561//             pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2562//         })
2563//         .unwrap()
2564//         .await
2565//         .unwrap();
2566//         assert_item_labels(&pane, ["A", "C*"], cx);
2567
2568//         pane.update(cx, |pane, cx| {
2569//             pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2570//         })
2571//         .unwrap()
2572//         .await
2573//         .unwrap();
2574//         assert_item_labels(&pane, ["A*"], cx);
2575//     }
2576
2577//     #[gpui::test]
2578//     async fn test_close_inactive_items(cx: &mut TestAppContext) {
2579//         init_test(cx);
2580//         let fs = FakeFs::new(cx.background());
2581
2582//         let project = Project::test(fs, None, cx).await;
2583//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2584//         let workspace = window.root(cx);
2585//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2586
2587//         set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2588
2589//         pane.update(cx, |pane, cx| {
2590//             pane.close_inactive_items(&CloseInactiveItems, cx)
2591//         })
2592//         .unwrap()
2593//         .await
2594//         .unwrap();
2595//         assert_item_labels(&pane, ["C*"], cx);
2596//     }
2597
2598//     #[gpui::test]
2599//     async fn test_close_clean_items(cx: &mut TestAppContext) {
2600//         init_test(cx);
2601//         let fs = FakeFs::new(cx.background());
2602
2603//         let project = Project::test(fs, None, cx).await;
2604//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2605//         let workspace = window.root(cx);
2606//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2607
2608//         add_labeled_item(&pane, "A", true, cx);
2609//         add_labeled_item(&pane, "B", false, cx);
2610//         add_labeled_item(&pane, "C", true, cx);
2611//         add_labeled_item(&pane, "D", false, cx);
2612//         add_labeled_item(&pane, "E", false, cx);
2613//         assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2614
2615//         pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
2616//             .unwrap()
2617//             .await
2618//             .unwrap();
2619//         assert_item_labels(&pane, ["A^", "C*^"], cx);
2620//     }
2621
2622//     #[gpui::test]
2623//     async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
2624//         init_test(cx);
2625//         let fs = FakeFs::new(cx.background());
2626
2627//         let project = Project::test(fs, None, cx).await;
2628//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2629//         let workspace = window.root(cx);
2630//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2631
2632//         set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2633
2634//         pane.update(cx, |pane, cx| {
2635//             pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
2636//         })
2637//         .unwrap()
2638//         .await
2639//         .unwrap();
2640//         assert_item_labels(&pane, ["C*", "D", "E"], cx);
2641//     }
2642
2643//     #[gpui::test]
2644//     async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
2645//         init_test(cx);
2646//         let fs = FakeFs::new(cx.background());
2647
2648//         let project = Project::test(fs, None, cx).await;
2649//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2650//         let workspace = window.root(cx);
2651//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2652
2653//         set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
2654
2655//         pane.update(cx, |pane, cx| {
2656//             pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
2657//         })
2658//         .unwrap()
2659//         .await
2660//         .unwrap();
2661//         assert_item_labels(&pane, ["A", "B", "C*"], cx);
2662//     }
2663
2664//     #[gpui::test]
2665//     async fn test_close_all_items(cx: &mut TestAppContext) {
2666//         init_test(cx);
2667//         let fs = FakeFs::new(cx.background());
2668
2669//         let project = Project::test(fs, None, cx).await;
2670//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2671//         let workspace = window.root(cx);
2672//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2673
2674//         add_labeled_item(&pane, "A", false, cx);
2675//         add_labeled_item(&pane, "B", false, cx);
2676//         add_labeled_item(&pane, "C", false, cx);
2677//         assert_item_labels(&pane, ["A", "B", "C*"], cx);
2678
2679//         pane.update(cx, |pane, cx| {
2680//             pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2681//         })
2682//         .unwrap()
2683//         .await
2684//         .unwrap();
2685//         assert_item_labels(&pane, [], cx);
2686
2687//         add_labeled_item(&pane, "A", true, cx);
2688//         add_labeled_item(&pane, "B", true, cx);
2689//         add_labeled_item(&pane, "C", true, cx);
2690//         assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
2691
2692//         let save = pane
2693//             .update(cx, |pane, cx| {
2694//                 pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
2695//             })
2696//             .unwrap();
2697
2698//         cx.foreground().run_until_parked();
2699//         window.simulate_prompt_answer(2, cx);
2700//         save.await.unwrap();
2701//         assert_item_labels(&pane, [], cx);
2702//     }
2703
2704//     fn init_test(cx: &mut TestAppContext) {
2705//         cx.update(|cx| {
2706//             cx.set_global(SettingsStore::test(cx));
2707//             theme::init((), cx);
2708//             crate::init_settings(cx);
2709//             Project::init_settings(cx);
2710//         });
2711//     }
2712
2713//     fn add_labeled_item(
2714//         pane: &ViewHandle<Pane>,
2715//         label: &str,
2716//         is_dirty: bool,
2717//         cx: &mut TestAppContext,
2718//     ) -> Box<ViewHandle<TestItem>> {
2719//         pane.update(cx, |pane, cx| {
2720//             let labeled_item =
2721//                 Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
2722//             pane.add_item(labeled_item.clone(), false, false, None, cx);
2723//             labeled_item
2724//         })
2725//     }
2726
2727//     fn set_labeled_items<const COUNT: usize>(
2728//         pane: &ViewHandle<Pane>,
2729//         labels: [&str; COUNT],
2730//         cx: &mut TestAppContext,
2731//     ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2732//         pane.update(cx, |pane, cx| {
2733//             pane.items.clear();
2734//             let mut active_item_index = 0;
2735
2736//             let mut index = 0;
2737//             let items = labels.map(|mut label| {
2738//                 if label.ends_with("*") {
2739//                     label = label.trim_end_matches("*");
2740//                     active_item_index = index;
2741//                 }
2742
2743//                 let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2744//                 pane.add_item(labeled_item.clone(), false, false, None, cx);
2745//                 index += 1;
2746//                 labeled_item
2747//             });
2748
2749//             pane.activate_item(active_item_index, false, false, cx);
2750
2751//             items
2752//         })
2753//     }
2754
2755//     // Assert the item label, with the active item label suffixed with a '*'
2756//     fn assert_item_labels<const COUNT: usize>(
2757//         pane: &ViewHandle<Pane>,
2758//         expected_states: [&str; COUNT],
2759//         cx: &mut TestAppContext,
2760//     ) {
2761//         pane.read_with(cx, |pane, cx| {
2762//             let actual_states = pane
2763//                 .items
2764//                 .iter()
2765//                 .enumerate()
2766//                 .map(|(ix, item)| {
2767//                     let mut state = item
2768//                         .as_any()
2769//                         .downcast_ref::<TestItem>()
2770//                         .unwrap()
2771//                         .read(cx)
2772//                         .label
2773//                         .clone();
2774//                     if ix == pane.active_item_index {
2775//                         state.push('*');
2776//                     }
2777//                     if item.is_dirty(cx) {
2778//                         state.push('^');
2779//                     }
2780//                     state
2781//                 })
2782//                 .collect::<Vec<_>>();
2783
2784//             assert_eq!(
2785//                 actual_states, expected_states,
2786//                 "pane items do not match expectation"
2787//             );
2788//         })
2789//     }
2790// }
2791
2792impl Render for DraggedTab {
2793    type Element = <Tab as RenderOnce>::Rendered;
2794
2795    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2796        let ui_font = ThemeSettings::get_global(cx).ui_font.family.clone();
2797        let item = &self.pane.read(cx).items[self.ix];
2798        let label = item.tab_content(Some(self.detail), false, cx);
2799        Tab::new("")
2800            .selected(self.is_active)
2801            .child(label)
2802            .render(cx)
2803            .font(ui_font)
2804    }
2805}