pane.rs

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