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