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