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