pane.rs

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