pane.rs

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