pane.rs

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