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                    cx,
1535                )
1536                .action("Close Inactive Items", CloseInactiveItems.boxed_clone(), cx)
1537                .action("Close Clean Items", CloseCleanItems.boxed_clone(), cx)
1538                .action(
1539                    "Close Items To The Left",
1540                    CloseItemsToTheLeft.boxed_clone(),
1541                    cx,
1542                )
1543                .action(
1544                    "Close Items To The Right",
1545                    CloseItemsToTheRight.boxed_clone(),
1546                    cx,
1547                )
1548                .action(
1549                    "Close All Items",
1550                    CloseAllItems { save_intent: None }.boxed_clone(),
1551                    cx,
1552                )
1553            })
1554        })
1555    }
1556
1557    fn render_tab_bar(&mut self, cx: &mut ViewContext<'_, Pane>) -> impl IntoElement {
1558        div()
1559            .id("tab_bar")
1560            .group("tab_bar")
1561            .track_focus(&self.tab_bar_focus_handle)
1562            .w_full()
1563            // 30px @ 16px/rem
1564            .h(rems(1.875))
1565            .overflow_hidden()
1566            .flex()
1567            .flex_none()
1568            .bg(cx.theme().colors().tab_bar_background)
1569            // Left Side
1570            .child(
1571                div()
1572                    .relative()
1573                    .px_1()
1574                    .flex()
1575                    .flex_none()
1576                    .gap_2()
1577                    // Nav Buttons
1578                    .child(
1579                        div()
1580                            .right_0()
1581                            .flex()
1582                            .items_center()
1583                            .gap_px()
1584                            .child(
1585                                div().border().border_color(gpui::red()).child(
1586                                    IconButton::new("navigate_backward", Icon::ArrowLeft)
1587                                        .on_click({
1588                                            let view = cx.view().clone();
1589                                            move |_, cx| view.update(cx, Self::navigate_backward)
1590                                        })
1591                                        .disabled(!self.can_navigate_backward()),
1592                                ),
1593                            )
1594                            .child(
1595                                div().border().border_color(gpui::red()).child(
1596                                    IconButton::new("navigate_forward", Icon::ArrowRight)
1597                                        .on_click({
1598                                            let view = cx.view().clone();
1599                                            move |_, cx| view.update(cx, Self::navigate_backward)
1600                                        })
1601                                        .disabled(!self.can_navigate_forward()),
1602                                ),
1603                            ),
1604                    ),
1605            )
1606            .child(
1607                div().flex_1().h_full().child(
1608                    div().id("tabs").flex().overflow_x_scroll().children(
1609                        self.items
1610                            .iter()
1611                            .enumerate()
1612                            .zip(self.tab_details(cx))
1613                            .map(|((ix, item), detail)| self.render_tab(ix, item, detail, cx)),
1614                    ),
1615                ),
1616            )
1617            // Right Side
1618            .child(
1619                div()
1620                    .px_1()
1621                    .flex()
1622                    .flex_none()
1623                    .gap_2()
1624                    // Nav Buttons
1625                    .child(
1626                        div()
1627                            .flex()
1628                            .items_center()
1629                            .gap_px()
1630                            .child(
1631                                div()
1632                                    .bg(gpui::blue())
1633                                    .border()
1634                                    .border_color(gpui::red())
1635                                    .child(IconButton::new("plus", Icon::Plus).on_click(
1636                                        cx.listener(|this, _, cx| {
1637                                            let menu = ContextMenu::build(cx, |menu, cx| {
1638                                                menu.action("New File", NewFile.boxed_clone(), cx)
1639                                                    .action(
1640                                                        "New Terminal",
1641                                                        NewCenterTerminal.boxed_clone(),
1642                                                        cx,
1643                                                    )
1644                                                    .action(
1645                                                        "New Search",
1646                                                        NewSearch.boxed_clone(),
1647                                                        cx,
1648                                                    )
1649                                            });
1650                                            cx.subscribe(
1651                                                &menu,
1652                                                |this, _, event: &DismissEvent, cx| {
1653                                                    this.focus(cx);
1654                                                    this.new_item_menu = None;
1655                                                },
1656                                            )
1657                                            .detach();
1658                                            this.new_item_menu = Some(menu);
1659                                        }),
1660                                    ))
1661                                    .when_some(self.new_item_menu.as_ref(), |el, new_item_menu| {
1662                                        el.child(Self::render_menu_overlay(new_item_menu))
1663                                    }),
1664                            )
1665                            .child(
1666                                div()
1667                                    .border()
1668                                    .border_color(gpui::red())
1669                                    .child(IconButton::new("split", Icon::Split).on_click(
1670                                        cx.listener(|this, _, cx| {
1671                                            let menu = ContextMenu::build(cx, |menu, cx| {
1672                                                menu.action(
1673                                                    "Split Right",
1674                                                    SplitRight.boxed_clone(),
1675                                                    cx,
1676                                                )
1677                                                .action("Split Left", SplitLeft.boxed_clone(), cx)
1678                                                .action("Split Up", SplitUp.boxed_clone(), cx)
1679                                                .action("Split Down", SplitDown.boxed_clone(), cx)
1680                                            });
1681                                            cx.subscribe(
1682                                                &menu,
1683                                                |this, _, event: &DismissEvent, cx| {
1684                                                    this.focus(cx);
1685                                                    this.split_item_menu = None;
1686                                                },
1687                                            )
1688                                            .detach();
1689                                            this.split_item_menu = Some(menu);
1690                                        }),
1691                                    ))
1692                                    .when_some(
1693                                        self.split_item_menu.as_ref(),
1694                                        |el, split_item_menu| {
1695                                            el.child(Self::render_menu_overlay(split_item_menu))
1696                                        },
1697                                    ),
1698                            ),
1699                    ),
1700            )
1701    }
1702
1703    fn render_menu_overlay(menu: &View<ContextMenu>) -> Div {
1704        div()
1705            .absolute()
1706            .z_index(1)
1707            .bottom_0()
1708            .right_0()
1709            .size_0()
1710            .child(overlay().anchor(AnchorCorner::TopRight).child(menu.clone()))
1711    }
1712
1713    //     fn render_tabs(&mut self, cx: &mut ViewContext<Self>) -> impl Element<Self> {
1714    //         let theme = theme::current(cx).clone();
1715
1716    //         let pane = cx.handle().downgrade();
1717    //         let autoscroll = if mem::take(&mut self.autoscroll) {
1718    //             Some(self.active_item_index)
1719    //         } else {
1720    //             None
1721    //         };
1722
1723    //         let pane_active = self.has_focus;
1724
1725    //         enum Tabs {}
1726    //         let mut row = Flex::row().scrollable::<Tabs>(1, autoscroll, cx);
1727    //         for (ix, (item, detail)) in self
1728    //             .items
1729    //             .iter()
1730    //             .cloned()
1731    //             .zip(self.tab_details(cx))
1732    //             .enumerate()
1733    //         {
1734    //             let git_status = item
1735    //                 .project_path(cx)
1736    //                 .and_then(|path| self.project.read(cx).entry_for_path(&path, cx))
1737    //                 .and_then(|entry| entry.git_status());
1738
1739    //             let detail = if detail == 0 { None } else { Some(detail) };
1740    //             let tab_active = ix == self.active_item_index;
1741
1742    //             row.add_child({
1743    //                 enum TabDragReceiver {}
1744    //                 let mut receiver =
1745    //                     dragged_item_receiver::<TabDragReceiver, _, _>(self, ix, ix, true, None, cx, {
1746    //                         let item = item.clone();
1747    //                         let pane = pane.clone();
1748    //                         let detail = detail.clone();
1749
1750    //                         let theme = theme::current(cx).clone();
1751    //                         let mut tooltip_theme = theme.tooltip.clone();
1752    //                         tooltip_theme.max_text_width = None;
1753    //                         let tab_tooltip_text =
1754    //                             item.tab_tooltip_text(cx).map(|text| text.into_owned());
1755
1756    //                         let mut tab_style = theme
1757    //                             .workspace
1758    //                             .tab_bar
1759    //                             .tab_style(pane_active, tab_active)
1760    //                             .clone();
1761    //                         let should_show_status = settings::get::<ItemSettings>(cx).git_status;
1762    //                         if should_show_status && git_status != None {
1763    //                             tab_style.label.text.color = match git_status.unwrap() {
1764    //                                 GitFileStatus::Added => tab_style.git.inserted,
1765    //                                 GitFileStatus::Modified => tab_style.git.modified,
1766    //                                 GitFileStatus::Conflict => tab_style.git.conflict,
1767    //                             };
1768    //                         }
1769
1770    //                         move |mouse_state, cx| {
1771    //                             let hovered = mouse_state.hovered();
1772
1773    //                             enum Tab {}
1774    //                             let mouse_event_handler =
1775    //                                 MouseEventHandler::new::<Tab, _>(ix, cx, |_, cx| {
1776    //                                     Self::render_tab(
1777    //                                         &item,
1778    //                                         pane.clone(),
1779    //                                         ix == 0,
1780    //                                         detail,
1781    //                                         hovered,
1782    //                                         &tab_style,
1783    //                                         cx,
1784    //                                     )
1785    //                                 })
1786    //                                 .on_down(MouseButton::Left, move |_, this, cx| {
1787    //                                     this.activate_item(ix, true, true, cx);
1788    //                                 })
1789    //                                 .on_click(MouseButton::Middle, {
1790    //                                     let item_id = item.id();
1791    //                                     move |_, pane, cx| {
1792    //                                         pane.close_item_by_id(item_id, SaveIntent::Close, cx)
1793    //                                             .detach_and_log_err(cx);
1794    //                                     }
1795    //                                 })
1796    //                                 .on_down(
1797    //                                     MouseButton::Right,
1798    //                                     move |event, pane, cx| {
1799    //                                         pane.deploy_tab_context_menu(event.position, item.id(), cx);
1800    //                                     },
1801    //                                 );
1802
1803    //                             if let Some(tab_tooltip_text) = tab_tooltip_text {
1804    //                                 mouse_event_handler
1805    //                                     .with_tooltip::<Self>(
1806    //                                         ix,
1807    //                                         tab_tooltip_text,
1808    //                                         None,
1809    //                                         tooltip_theme,
1810    //                                         cx,
1811    //                                     )
1812    //                                     .into_any()
1813    //                             } else {
1814    //                                 mouse_event_handler.into_any()
1815    //                             }
1816    //                         }
1817    //                     });
1818
1819    //                 if !pane_active || !tab_active {
1820    //                     receiver = receiver.with_cursor_style(CursorStyle::PointingHand);
1821    //                 }
1822
1823    //                 receiver.as_draggable(
1824    //                     DraggedItem {
1825    //                         handle: item,
1826    //                         pane: pane.clone(),
1827    //                     },
1828    //                     {
1829    //                         let theme = theme::current(cx).clone();
1830
1831    //                         let detail = detail.clone();
1832    //                         move |_, dragged_item: &DraggedItem, cx: &mut ViewContext<Workspace>| {
1833    //                             let tab_style = &theme.workspace.tab_bar.dragged_tab;
1834    //                             Self::render_dragged_tab(
1835    //                                 &dragged_item.handle,
1836    //                                 dragged_item.pane.clone(),
1837    //                                 false,
1838    //                                 detail,
1839    //                                 false,
1840    //                                 &tab_style,
1841    //                                 cx,
1842    //                             )
1843    //                         }
1844    //                     },
1845    //                 )
1846    //             })
1847    //         }
1848
1849    //         // Use the inactive tab style along with the current pane's active status to decide how to render
1850    //         // the filler
1851    //         let filler_index = self.items.len();
1852    //         let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1853    //         enum Filler {}
1854    //         row.add_child(
1855    //             dragged_item_receiver::<Filler, _, _>(self, 0, filler_index, true, None, cx, |_, _| {
1856    //                 Empty::new()
1857    //                     .contained()
1858    //                     .with_style(filler_style.container)
1859    //                     .with_border(filler_style.container.border)
1860    //             })
1861    //             .flex(1., true)
1862    //             .into_any_named("filler"),
1863    //         );
1864
1865    //         row
1866    //     }
1867
1868    fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1869        let mut tab_details = self.items.iter().map(|_| 0).collect::<Vec<_>>();
1870
1871        let mut tab_descriptions = HashMap::default();
1872        let mut done = false;
1873        while !done {
1874            done = true;
1875
1876            // Store item indices by their tab description.
1877            for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1878                if let Some(description) = item.tab_description(*detail, cx) {
1879                    if *detail == 0
1880                        || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1881                    {
1882                        tab_descriptions
1883                            .entry(description)
1884                            .or_insert(Vec::new())
1885                            .push(ix);
1886                    }
1887                }
1888            }
1889
1890            // If two or more items have the same tab description, increase eir level
1891            // of detail and try again.
1892            for (_, item_ixs) in tab_descriptions.drain() {
1893                if item_ixs.len() > 1 {
1894                    done = false;
1895                    for ix in item_ixs {
1896                        tab_details[ix] += 1;
1897                    }
1898                }
1899            }
1900        }
1901
1902        tab_details
1903    }
1904
1905    //     fn render_tab(
1906    //         item: &Box<dyn ItemHandle>,
1907    //         pane: WeakView<Pane>,
1908    //         first: bool,
1909    //         detail: Option<usize>,
1910    //         hovered: bool,
1911    //         tab_style: &theme::Tab,
1912    //         cx: &mut ViewContext<Self>,
1913    //     ) -> AnyElement<Self> {
1914    //         let title = item.tab_content(detail, &tab_style, cx);
1915    //         Self::render_tab_with_title(title, item, pane, first, hovered, tab_style, cx)
1916    //     }
1917
1918    //     fn render_dragged_tab(
1919    //         item: &Box<dyn ItemHandle>,
1920    //         pane: WeakView<Pane>,
1921    //         first: bool,
1922    //         detail: Option<usize>,
1923    //         hovered: bool,
1924    //         tab_style: &theme::Tab,
1925    //         cx: &mut ViewContext<Workspace>,
1926    //     ) -> AnyElement<Workspace> {
1927    //         let title = item.dragged_tab_content(detail, &tab_style, cx);
1928    //         Self::render_tab_with_title(title, item, pane, first, hovered, tab_style, cx)
1929    //     }
1930
1931    //     fn render_tab_with_title<T: View>(
1932    //         title: AnyElement<T>,
1933    //         item: &Box<dyn ItemHandle>,
1934    //         pane: WeakView<Pane>,
1935    //         first: bool,
1936    //         hovered: bool,
1937    //         tab_style: &theme::Tab,
1938    //         cx: &mut ViewContext<T>,
1939    //     ) -> AnyElement<T> {
1940    //         let mut container = tab_style.container.clone();
1941    //         if first {
1942    //             container.border.left = false;
1943    //         }
1944
1945    //         let buffer_jewel_element = {
1946    //             let diameter = 7.0;
1947    //             let icon_color = if item.has_conflict(cx) {
1948    //                 Some(tab_style.icon_conflict)
1949    //             } else if item.is_dirty(cx) {
1950    //                 Some(tab_style.icon_dirty)
1951    //             } else {
1952    //                 None
1953    //             };
1954
1955    //             Canvas::new(move |bounds, _, _, cx| {
1956    //                 if let Some(color) = icon_color {
1957    //                     let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1958    //                     cx.scene().push_quad(Quad {
1959    //                         bounds: square,
1960    //                         background: Some(color),
1961    //                         border: Default::default(),
1962    //                         corner_radii: (diameter / 2.).into(),
1963    //                     });
1964    //                 }
1965    //             })
1966    //             .constrained()
1967    //             .with_width(diameter)
1968    //             .with_height(diameter)
1969    //             .aligned()
1970    //         };
1971
1972    //         let title_element = title.aligned().contained().with_style(ContainerStyle {
1973    //             margin: Margin {
1974    //                 left: tab_style.spacing,
1975    //                 right: tab_style.spacing,
1976    //                 ..Default::default()
1977    //             },
1978    //             ..Default::default()
1979    //         });
1980
1981    //         let close_element = if hovered {
1982    //             let item_id = item.id();
1983    //             enum TabCloseButton {}
1984    //             let icon = Svg::new("icons/x.svg");
1985    //             MouseEventHandler::new::<TabCloseButton, _>(item_id, cx, |mouse_state, _| {
1986    //                 if mouse_state.hovered() {
1987    //                     icon.with_color(tab_style.icon_close_active)
1988    //                 } else {
1989    //                     icon.with_color(tab_style.icon_close)
1990    //                 }
1991    //             })
1992    //             .with_padding(Padding::uniform(4.))
1993    //             .with_cursor_style(CursorStyle::PointingHand)
1994    //             .on_click(MouseButton::Left, {
1995    //                 let pane = pane.clone();
1996    //                 move |_, _, cx| {
1997    //                     let pane = pane.clone();
1998    //                     cx.window_context().defer(move |cx| {
1999    //                         if let Some(pane) = pane.upgrade(cx) {
2000    //                             pane.update(cx, |pane, cx| {
2001    //                                 pane.close_item_by_id(item_id, SaveIntent::Close, cx)
2002    //                                     .detach_and_log_err(cx);
2003    //                             });
2004    //                         }
2005    //                     });
2006    //                 }
2007    //             })
2008    //             .into_any_named("close-tab-icon")
2009    //             .constrained()
2010    //         } else {
2011    //             Empty::new().constrained()
2012    //         }
2013    //         .with_width(tab_style.close_icon_width)
2014    //         .aligned();
2015
2016    //         let close_right = settings::get::<ItemSettings>(cx).close_position.right();
2017
2018    //         if close_right {
2019    //             Flex::row()
2020    //                 .with_child(buffer_jewel_element)
2021    //                 .with_child(title_element)
2022    //                 .with_child(close_element)
2023    //         } else {
2024    //             Flex::row()
2025    //                 .with_child(close_element)
2026    //                 .with_child(title_element)
2027    //                 .with_child(buffer_jewel_element)
2028    //         }
2029    //         .contained()
2030    //         .with_style(container)
2031    //         .constrained()
2032    //         .with_height(tab_style.height)
2033    //         .into_any()
2034    //     }
2035
2036    //     pub fn render_tab_bar_button<
2037    //         F1: 'static + Fn(&mut Pane, &mut EventContext<Pane>),
2038    //         F2: 'static + Fn(&mut Pane, &mut EventContext<Pane>),
2039    //     >(
2040    //         index: usize,
2041    //         icon: &'static str,
2042    //         is_active: bool,
2043    //         tooltip: Option<(&'static str, Option<Box<dyn Action>>)>,
2044    //         cx: &mut ViewContext<Pane>,
2045    //         on_click: F1,
2046    //         on_down: F2,
2047    //         context_menu: Option<ViewHandle<ContextMenu>>,
2048    //     ) -> AnyElement<Pane> {
2049    //         enum TabBarButton {}
2050
2051    //         let mut button = MouseEventHandler::new::<TabBarButton, _>(index, cx, |mouse_state, cx| {
2052    //             let theme = &settings2::get::<ThemeSettings>(cx).theme.workspace.tab_bar;
2053    //             let style = theme.pane_button.in_state(is_active).style_for(mouse_state);
2054    //             Svg::new(icon)
2055    //                 .with_color(style.color)
2056    //                 .constrained()
2057    //                 .with_width(style.icon_width)
2058    //                 .aligned()
2059    //                 .constrained()
2060    //                 .with_width(style.button_width)
2061    //                 .with_height(style.button_width)
2062    //         })
2063    //         .with_cursor_style(CursorStyle::PointingHand)
2064    //         .on_down(MouseButton::Left, move |_, pane, cx| on_down(pane, cx))
2065    //         .on_click(MouseButton::Left, move |_, pane, cx| on_click(pane, cx))
2066    //         .into_any();
2067    //         if let Some((tooltip, action)) = tooltip {
2068    //             let tooltip_style = settings::get::<ThemeSettings>(cx).theme.tooltip.clone();
2069    //             button = button
2070    //                 .with_tooltip::<TabBarButton>(index, tooltip, action, tooltip_style, cx)
2071    //                 .into_any();
2072    //         }
2073
2074    //         Stack::new()
2075    //             .with_child(button)
2076    //             .with_children(
2077    //                 context_menu.map(|menu| ChildView::new(&menu, cx).aligned().bottom().right()),
2078    //             )
2079    //             .flex(1., false)
2080    //             .into_any_named("tab bar button")
2081    //     }
2082
2083    //     fn render_blank_pane(&self, theme: &Theme, _cx: &mut ViewContext<Self>) -> AnyElement<Self> {
2084    //         let background = theme.workspace.background;
2085    //         Empty::new()
2086    //             .contained()
2087    //             .with_background_color(background)
2088    //             .into_any()
2089    //     }
2090
2091    pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
2092        self.zoomed = zoomed;
2093        cx.notify();
2094    }
2095
2096    pub fn is_zoomed(&self) -> bool {
2097        self.zoomed
2098    }
2099}
2100
2101impl FocusableView for Pane {
2102    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
2103        self.focus_handle.clone()
2104    }
2105}
2106
2107impl Render for Pane {
2108    type Element = Focusable<Div>;
2109
2110    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
2111        let this = cx.view().downgrade();
2112
2113        v_stack()
2114            .key_context("Pane")
2115            .track_focus(&self.focus_handle)
2116            .on_focus_in({
2117                let this = this.clone();
2118                move |event, cx| {
2119                    this.update(cx, |this, cx| this.focus_in(cx)).ok();
2120                }
2121            })
2122            .on_focus_out({
2123                let this = this.clone();
2124                move |event, cx| {
2125                    this.update(cx, |this, cx| this.focus_out(cx)).ok();
2126                }
2127            })
2128            .on_action(cx.listener(|pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx)))
2129            .on_action(cx.listener(|pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx)))
2130            .on_action(
2131                cx.listener(|pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx)),
2132            )
2133            .on_action(cx.listener(|pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx)))
2134            .on_action(cx.listener(|pane, _: &GoBack, cx| pane.navigate_backward(cx)))
2135            .on_action(cx.listener(|pane, _: &GoForward, cx| pane.navigate_forward(cx)))
2136            .on_action(cx.listener(Pane::toggle_zoom))
2137            .on_action(cx.listener(|pane: &mut Pane, action: &ActivateItem, cx| {
2138                pane.activate_item(action.0, true, true, cx);
2139            }))
2140            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateLastItem, cx| {
2141                pane.activate_item(pane.items.len() - 1, true, true, cx);
2142            }))
2143            .on_action(cx.listener(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
2144                pane.activate_prev_item(true, cx);
2145            }))
2146            .on_action(cx.listener(|pane: &mut Pane, _: &ActivateNextItem, cx| {
2147                pane.activate_next_item(true, cx);
2148            }))
2149            .on_action(
2150                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
2151                    pane.close_active_item(action, cx)
2152                        .map(|task| task.detach_and_log_err(cx));
2153                }),
2154            )
2155            .on_action(
2156                cx.listener(|pane: &mut Self, action: &CloseInactiveItems, cx| {
2157                    pane.close_inactive_items(action, cx)
2158                        .map(|task| task.detach_and_log_err(cx));
2159                }),
2160            )
2161            .on_action(
2162                cx.listener(|pane: &mut Self, action: &CloseCleanItems, cx| {
2163                    pane.close_clean_items(action, cx)
2164                        .map(|task| task.detach_and_log_err(cx));
2165                }),
2166            )
2167            .on_action(
2168                cx.listener(|pane: &mut Self, action: &CloseItemsToTheLeft, cx| {
2169                    pane.close_items_to_the_left(action, cx)
2170                        .map(|task| task.detach_and_log_err(cx));
2171                }),
2172            )
2173            .on_action(
2174                cx.listener(|pane: &mut Self, action: &CloseItemsToTheRight, cx| {
2175                    pane.close_items_to_the_right(action, cx)
2176                        .map(|task| task.detach_and_log_err(cx));
2177                }),
2178            )
2179            .on_action(cx.listener(|pane: &mut Self, action: &CloseAllItems, cx| {
2180                pane.close_all_items(action, cx)
2181                    .map(|task| task.detach_and_log_err(cx));
2182            }))
2183            .size_full()
2184            .on_action(
2185                cx.listener(|pane: &mut Self, action: &CloseActiveItem, cx| {
2186                    pane.close_active_item(action, cx)
2187                        .map(|task| task.detach_and_log_err(cx));
2188                }),
2189            )
2190            .child(self.render_tab_bar(cx))
2191            .child(self.toolbar.clone())
2192            .child(if let Some(item) = self.active_item() {
2193                div().flex().flex_1().child(item.to_any())
2194            } else {
2195                h_stack()
2196                    .items_center()
2197                    .size_full()
2198                    .justify_center()
2199                    .child(Label::new("Open a file or project to get started.").color(Color::Muted))
2200            })
2201
2202        // enum MouseNavigationHandler {}
2203
2204        // MouseEventHandler::new::<MouseNavigationHandler, _>(0, cx, |_, cx| {
2205        //     let active_item_index = self.active_item_index;
2206
2207        //     if let Some(active_item) = self.active_item() {
2208        //         Flex::column()
2209        //             .with_child({
2210        //                 let theme = theme::current(cx).clone();
2211
2212        //                 let mut stack = Stack::new();
2213
2214        //                 enum TabBarEventHandler {}
2215        //                 stack.add_child(
2216        //                     MouseEventHandler::new::<TabBarEventHandler, _>(0, cx, |_, _| {
2217        //                         Empty::new()
2218        //                             .contained()
2219        //                             .with_style(theme.workspace.tab_bar.container)
2220        //                     })
2221        //                     .on_down(
2222        //                         MouseButton::Left,
2223        //                         move |_, this, cx| {
2224        //                             this.activate_item(active_item_index, true, true, cx);
2225        //                         },
2226        //                     ),
2227        //                 );
2228        //                 let tooltip_style = theme.tooltip.clone();
2229        //                 let tab_bar_theme = theme.workspace.tab_bar.clone();
2230
2231        //                 let nav_button_height = tab_bar_theme.height;
2232        //                 let button_style = tab_bar_theme.nav_button;
2233        //                 let border_for_nav_buttons = tab_bar_theme
2234        //                     .tab_style(false, false)
2235        //                     .container
2236        //                     .border
2237        //                     .clone();
2238
2239        //                 let mut tab_row = Flex::row()
2240        //                     .with_child(nav_button(
2241        //                         "icons/arrow_left.svg",
2242        //                         button_style.clone(),
2243        //                         nav_button_height,
2244        //                         tooltip_style.clone(),
2245        //                         self.can_navigate_backward(),
2246        //                         {
2247        //                             move |pane, cx| {
2248        //                                 if let Some(workspace) = pane.workspace.upgrade(cx) {
2249        //                                     let pane = cx.weak_handle();
2250        //                                     cx.window_context().defer(move |cx| {
2251        //                                         workspace.update(cx, |workspace, cx| {
2252        //                                             workspace
2253        //                                                 .go_back(pane, cx)
2254        //                                                 .detach_and_log_err(cx)
2255        //                                         })
2256        //                                     })
2257        //                                 }
2258        //                             }
2259        //                         },
2260        //                         super::GoBack,
2261        //                         "Go Back",
2262        //                         cx,
2263        //                     ))
2264        //                     .with_child(
2265        //                         nav_button(
2266        //                             "icons/arrow_right.svg",
2267        //                             button_style.clone(),
2268        //                             nav_button_height,
2269        //                             tooltip_style,
2270        //                             self.can_navigate_forward(),
2271        //                             {
2272        //                                 move |pane, cx| {
2273        //                                     if let Some(workspace) = pane.workspace.upgrade(cx) {
2274        //                                         let pane = cx.weak_handle();
2275        //                                         cx.window_context().defer(move |cx| {
2276        //                                             workspace.update(cx, |workspace, cx| {
2277        //                                                 workspace
2278        //                                                     .go_forward(pane, cx)
2279        //                                                     .detach_and_log_err(cx)
2280        //                                             })
2281        //                                         })
2282        //                                     }
2283        //                                 }
2284        //                             },
2285        //                             super::GoForward,
2286        //                             "Go Forward",
2287        //                             cx,
2288        //                         )
2289        //                         .contained()
2290        //                         .with_border(border_for_nav_buttons),
2291        //                     )
2292        //                     .with_child(self.render_tabs(cx).flex(1., true).into_any_named("tabs"));
2293
2294        //                 if self.has_focus {
2295        //                     let render_tab_bar_buttons = self.render_tab_bar_buttons.clone();
2296        //                     tab_row.add_child(
2297        //                         (render_tab_bar_buttons)(self, cx)
2298        //                             .contained()
2299        //                             .with_style(theme.workspace.tab_bar.pane_button_container)
2300        //                             .flex(1., false)
2301        //                             .into_any(),
2302        //                     )
2303        //                 }
2304
2305        //                 stack.add_child(tab_row);
2306        //                 stack
2307        //                     .constrained()
2308        //                     .with_height(theme.workspace.tab_bar.height)
2309        //                     .flex(1., false)
2310        //                     .into_any_named("tab bar")
2311        //             })
2312        //             .with_child({
2313        //                 enum PaneContentTabDropTarget {}
2314        //                 dragged_item_receiver::<PaneContentTabDropTarget, _, _>(
2315        //                     self,
2316        //                     0,
2317        //                     self.active_item_index + 1,
2318        //                     !self.can_split,
2319        //                     if self.can_split { Some(100.) } else { None },
2320        //                     cx,
2321        //                     {
2322        //                         let toolbar = self.toolbar.clone();
2323        //                         let toolbar_hidden = toolbar.read(cx).hidden();
2324        //                         move |_, cx| {
2325        //                             Flex::column()
2326        //                                 .with_children(
2327        //                                     (!toolbar_hidden)
2328        //                                         .then(|| ChildView::new(&toolbar, cx).expanded()),
2329        //                                 )
2330        //                                 .with_child(
2331        //                                     ChildView::new(active_item.as_any(), cx).flex(1., true),
2332        //                                 )
2333        //                         }
2334        //                     },
2335        //                 )
2336        //                 .flex(1., true)
2337        //             })
2338        //             .with_child(ChildView::new(&self.tab_context_menu, cx))
2339        //             .into_any()
2340        //     } else {
2341        //         enum EmptyPane {}
2342        //         let theme = theme::current(cx).clone();
2343
2344        //         dragged_item_receiver::<EmptyPane, _, _>(self, 0, 0, false, None, cx, |_, cx| {
2345        //             self.render_blank_pane(&theme, cx)
2346        //         })
2347        //         .on_down(MouseButton::Left, |_, _, cx| {
2348        //             cx.focus_parent();
2349        //         })
2350        //         .into_any()
2351        //     }
2352        // })
2353        // .on_down(
2354        //     MouseButton::Navigate(NavigationDirection::Back),
2355        //     move |_, pane, cx| {
2356        //         if let Some(workspace) = pane.workspace.upgrade(cx) {
2357        //             let pane = cx.weak_handle();
2358        //             cx.window_context().defer(move |cx| {
2359        //                 workspace.update(cx, |workspace, cx| {
2360        //                     workspace.go_back(pane, cx).detach_and_log_err(cx)
2361        //                 })
2362        //             })
2363        //         }
2364        //     },
2365        // )
2366        // .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
2367        //     move |_, pane, cx| {
2368        //         if let Some(workspace) = pane.workspace.upgrade(cx) {
2369        //             let pane = cx.weak_handle();
2370        //             cx.window_context().defer(move |cx| {
2371        //                 workspace.update(cx, |workspace, cx| {
2372        //                     workspace.go_forward(pane, cx).detach_and_log_err(cx)
2373        //                 })
2374        //             })
2375        //         }
2376        //     }
2377        // })
2378        // .into_any_named("pane")
2379    }
2380
2381    // fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
2382    //     if !self.has_focus {
2383    //         self.has_focus = true;
2384    //         cx.emit(Event::Focus);
2385    //         cx.notify();
2386    //     }
2387
2388    //     self.toolbar.update(cx, |toolbar, cx| {
2389    //         toolbar.focus_changed(true, cx);
2390    //     });
2391
2392    //     if let Some(active_item) = self.active_item() {
2393    //         if cx.is_self_focused() {
2394    //             // Pane was focused directly. We need to either focus a view inside the active item,
2395    //             // or focus the active item itself
2396    //             if let Some(weak_last_focused_view) =
2397    //                 self.last_focused_view_by_item.get(&active_item.id())
2398    //             {
2399    //                 if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
2400    //                     cx.focus(&last_focused_view);
2401    //                     return;
2402    //                 } else {
2403    //                     self.last_focused_view_by_item.remove(&active_item.id());
2404    //                 }
2405    //             }
2406
2407    //             cx.focus(active_item.as_any());
2408    //         } else if focused != self.tab_bar_context_menu.handle {
2409    //             self.last_focused_view_by_item
2410    //                 .insert(active_item.id(), focused.downgrade());
2411    //         }
2412    //     }
2413    // }
2414
2415    // fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
2416    //     self.has_focus = false;
2417    //     self.toolbar.update(cx, |toolbar, cx| {
2418    //         toolbar.focus_changed(false, cx);
2419    //     });
2420    //     cx.notify();
2421    // }
2422
2423    // fn update_keymap_context(&self, keymap: &mut KeymapContext, _: &AppContext) {
2424    //     Self::reset_to_default_keymap_context(keymap);
2425    // }
2426}
2427
2428impl ItemNavHistory {
2429    pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut WindowContext) {
2430        self.history.push(data, self.item.clone(), cx);
2431    }
2432
2433    pub fn pop_backward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2434        self.history.pop(NavigationMode::GoingBack, cx)
2435    }
2436
2437    pub fn pop_forward(&mut self, cx: &mut WindowContext) -> Option<NavigationEntry> {
2438        self.history.pop(NavigationMode::GoingForward, cx)
2439    }
2440}
2441
2442impl NavHistory {
2443    pub fn for_each_entry(
2444        &self,
2445        cx: &AppContext,
2446        mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
2447    ) {
2448        let borrowed_history = self.0.lock();
2449        borrowed_history
2450            .forward_stack
2451            .iter()
2452            .chain(borrowed_history.backward_stack.iter())
2453            .chain(borrowed_history.closed_stack.iter())
2454            .for_each(|entry| {
2455                if let Some(project_and_abs_path) =
2456                    borrowed_history.paths_by_item.get(&entry.item.id())
2457                {
2458                    f(entry, project_and_abs_path.clone());
2459                } else if let Some(item) = entry.item.upgrade() {
2460                    if let Some(path) = item.project_path(cx) {
2461                        f(entry, (path, None));
2462                    }
2463                }
2464            })
2465    }
2466
2467    pub fn set_mode(&mut self, mode: NavigationMode) {
2468        self.0.lock().mode = mode;
2469    }
2470
2471    pub fn mode(&self) -> NavigationMode {
2472        self.0.lock().mode
2473    }
2474
2475    pub fn disable(&mut self) {
2476        self.0.lock().mode = NavigationMode::Disabled;
2477    }
2478
2479    pub fn enable(&mut self) {
2480        self.0.lock().mode = NavigationMode::Normal;
2481    }
2482
2483    pub fn pop(&mut self, mode: NavigationMode, cx: &mut WindowContext) -> Option<NavigationEntry> {
2484        let mut state = self.0.lock();
2485        let entry = match mode {
2486            NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
2487                return None
2488            }
2489            NavigationMode::GoingBack => &mut state.backward_stack,
2490            NavigationMode::GoingForward => &mut state.forward_stack,
2491            NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
2492        }
2493        .pop_back();
2494        if entry.is_some() {
2495            state.did_update(cx);
2496        }
2497        entry
2498    }
2499
2500    pub fn push<D: 'static + Send + Any>(
2501        &mut self,
2502        data: Option<D>,
2503        item: Arc<dyn WeakItemHandle>,
2504        cx: &mut WindowContext,
2505    ) {
2506        let state = &mut *self.0.lock();
2507        match state.mode {
2508            NavigationMode::Disabled => {}
2509            NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
2510                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2511                    state.backward_stack.pop_front();
2512                }
2513                state.backward_stack.push_back(NavigationEntry {
2514                    item,
2515                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2516                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2517                });
2518                state.forward_stack.clear();
2519            }
2520            NavigationMode::GoingBack => {
2521                if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2522                    state.forward_stack.pop_front();
2523                }
2524                state.forward_stack.push_back(NavigationEntry {
2525                    item,
2526                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2527                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2528                });
2529            }
2530            NavigationMode::GoingForward => {
2531                if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2532                    state.backward_stack.pop_front();
2533                }
2534                state.backward_stack.push_back(NavigationEntry {
2535                    item,
2536                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2537                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2538                });
2539            }
2540            NavigationMode::ClosingItem => {
2541                if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
2542                    state.closed_stack.pop_front();
2543                }
2544                state.closed_stack.push_back(NavigationEntry {
2545                    item,
2546                    data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
2547                    timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
2548                });
2549            }
2550        }
2551        state.did_update(cx);
2552    }
2553
2554    pub fn remove_item(&mut self, item_id: EntityId) {
2555        let mut state = self.0.lock();
2556        state.paths_by_item.remove(&item_id);
2557        state
2558            .backward_stack
2559            .retain(|entry| entry.item.id() != item_id);
2560        state
2561            .forward_stack
2562            .retain(|entry| entry.item.id() != item_id);
2563        state
2564            .closed_stack
2565            .retain(|entry| entry.item.id() != item_id);
2566    }
2567
2568    pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
2569        self.0.lock().paths_by_item.get(&item_id).cloned()
2570    }
2571}
2572
2573impl NavHistoryState {
2574    pub fn did_update(&self, cx: &mut WindowContext) {
2575        if let Some(pane) = self.pane.upgrade() {
2576            cx.defer(move |cx| {
2577                pane.update(cx, |pane, cx| pane.history_updated(cx));
2578            });
2579        }
2580    }
2581}
2582
2583// pub struct PaneBackdrop<V> {
2584//     child_view: usize,
2585//     child: AnyElement<V>,
2586// }
2587
2588// impl<V> PaneBackdrop<V> {
2589//     pub fn new(pane_item_view: usize, child: AnyElement<V>) -> Self {
2590//         PaneBackdrop {
2591//             child,
2592//             child_view: pane_item_view,
2593//         }
2594//     }
2595// }
2596
2597// impl<V: 'static> Element<V> for PaneBackdrop<V> {
2598//     type LayoutState = ();
2599
2600//     type PaintState = ();
2601
2602//     fn layout(
2603//         &mut self,
2604//         constraint: gpui::SizeConstraint,
2605//         view: &mut V,
2606//         cx: &mut ViewContext<V>,
2607//     ) -> (Vector2F, Self::LayoutState) {
2608//         let size = self.child.layout(constraint, view, cx);
2609//         (size, ())
2610//     }
2611
2612//     fn paint(
2613//         &mut self,
2614//         bounds: RectF,
2615//         visible_bounds: RectF,
2616//         _: &mut Self::LayoutState,
2617//         view: &mut V,
2618//         cx: &mut ViewContext<V>,
2619//     ) -> Self::PaintState {
2620//         let background = theme::current(cx).editor.background;
2621
2622//         let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2623
2624//         cx.scene().push_quad(gpui::Quad {
2625//             bounds: RectF::new(bounds.origin(), bounds.size()),
2626//             background: Some(background),
2627//             ..Default::default()
2628//         });
2629
2630//         let child_view_id = self.child_view;
2631//         cx.scene().push_mouse_region(
2632//             MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
2633//                 gpui::platform::MouseButton::Left,
2634//                 move |_, _: &mut V, cx| {
2635//                     let window = cx.window();
2636//                     cx.app_context().focus(window, Some(child_view_id))
2637//                 },
2638//             ),
2639//         );
2640
2641//         cx.scene().push_layer(Some(bounds));
2642//         self.child.paint(bounds.origin(), visible_bounds, view, cx);
2643//         cx.scene().pop_layer();
2644//     }
2645
2646//     fn rect_for_text_range(
2647//         &self,
2648//         range_utf16: std::ops::Range<usize>,
2649//         _bounds: RectF,
2650//         _visible_bounds: RectF,
2651//         _layout: &Self::LayoutState,
2652//         _paint: &Self::PaintState,
2653//         view: &V,
2654//         cx: &gpui::ViewContext<V>,
2655//     ) -> Option<RectF> {
2656//         self.child.rect_for_text_range(range_utf16, view, cx)
2657//     }
2658
2659//     fn debug(
2660//         &self,
2661//         _bounds: RectF,
2662//         _layout: &Self::LayoutState,
2663//         _paint: &Self::PaintState,
2664//         view: &V,
2665//         cx: &gpui::ViewContext<V>,
2666//     ) -> serde_json::Value {
2667//         gpui::json::json!({
2668//             "type": "Pane Back Drop",
2669//             "view": self.child_view,
2670//             "child": self.child.debug(view, cx),
2671//         })
2672//     }
2673// }
2674
2675fn dirty_message_for(buffer_path: Option<ProjectPath>) -> String {
2676    let path = buffer_path
2677        .as_ref()
2678        .and_then(|p| p.path.to_str())
2679        .unwrap_or(&"This buffer");
2680    let path = truncate_and_remove_front(path, 80);
2681    format!("{path} contains unsaved edits. Do you want to save it?")
2682}
2683
2684// todo!("uncomment tests")
2685// #[cfg(test)]
2686// mod tests {
2687//     use super::*;
2688//     use crate::item::test::{TestItem, TestProjectItem};
2689//     use gpui::TestAppContext;
2690//     use project::FakeFs;
2691//     use settings::SettingsStore;
2692
2693//     #[gpui::test]
2694//     async fn test_remove_active_empty(cx: &mut TestAppContext) {
2695//         init_test(cx);
2696//         let fs = FakeFs::new(cx.background());
2697
2698//         let project = Project::test(fs, None, cx).await;
2699//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2700//         let workspace = window.root(cx);
2701//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2702
2703//         pane.update(cx, |pane, cx| {
2704//             assert!(pane
2705//                 .close_active_item(&CloseActiveItem { save_intent: None }, cx)
2706//                 .is_none())
2707//         });
2708//     }
2709
2710//     #[gpui::test]
2711//     async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2712//         cx.foreground().forbid_parking();
2713//         init_test(cx);
2714//         let fs = FakeFs::new(cx.background());
2715
2716//         let project = Project::test(fs, None, cx).await;
2717//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2718//         let workspace = window.root(cx);
2719//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2720
2721//         // 1. Add with a destination index
2722//         //   a. Add before the active item
2723//         set_labeled_items(&pane, ["A", "B*", "C"], cx);
2724//         pane.update(cx, |pane, cx| {
2725//             pane.add_item(
2726//                 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2727//                 false,
2728//                 false,
2729//                 Some(0),
2730//                 cx,
2731//             );
2732//         });
2733//         assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2734
2735//         //   b. Add after the active item
2736//         set_labeled_items(&pane, ["A", "B*", "C"], cx);
2737//         pane.update(cx, |pane, cx| {
2738//             pane.add_item(
2739//                 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2740//                 false,
2741//                 false,
2742//                 Some(2),
2743//                 cx,
2744//             );
2745//         });
2746//         assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2747
2748//         //   c. Add at the end of the item list (including off the length)
2749//         set_labeled_items(&pane, ["A", "B*", "C"], cx);
2750//         pane.update(cx, |pane, cx| {
2751//             pane.add_item(
2752//                 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2753//                 false,
2754//                 false,
2755//                 Some(5),
2756//                 cx,
2757//             );
2758//         });
2759//         assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2760
2761//         // 2. Add without a destination index
2762//         //   a. Add with active item at the start of the item list
2763//         set_labeled_items(&pane, ["A*", "B", "C"], cx);
2764//         pane.update(cx, |pane, cx| {
2765//             pane.add_item(
2766//                 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2767//                 false,
2768//                 false,
2769//                 None,
2770//                 cx,
2771//             );
2772//         });
2773//         set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
2774
2775//         //   b. Add with active item at the end of the item list
2776//         set_labeled_items(&pane, ["A", "B", "C*"], cx);
2777//         pane.update(cx, |pane, cx| {
2778//             pane.add_item(
2779//                 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2780//                 false,
2781//                 false,
2782//                 None,
2783//                 cx,
2784//             );
2785//         });
2786//         assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2787//     }
2788
2789//     #[gpui::test]
2790//     async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2791//         cx.foreground().forbid_parking();
2792//         init_test(cx);
2793//         let fs = FakeFs::new(cx.background());
2794
2795//         let project = Project::test(fs, None, cx).await;
2796//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2797//         let workspace = window.root(cx);
2798//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2799
2800//         // 1. Add with a destination index
2801//         //   1a. Add before the active item
2802//         let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2803//         pane.update(cx, |pane, cx| {
2804//             pane.add_item(d, false, false, Some(0), cx);
2805//         });
2806//         assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2807
2808//         //   1b. Add after the active item
2809//         let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2810//         pane.update(cx, |pane, cx| {
2811//             pane.add_item(d, false, false, Some(2), cx);
2812//         });
2813//         assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2814
2815//         //   1c. Add at the end of the item list (including off the length)
2816//         let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
2817//         pane.update(cx, |pane, cx| {
2818//             pane.add_item(a, false, false, Some(5), cx);
2819//         });
2820//         assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2821
2822//         //   1d. Add same item to active index
2823//         let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2824//         pane.update(cx, |pane, cx| {
2825//             pane.add_item(b, false, false, Some(1), cx);
2826//         });
2827//         assert_item_labels(&pane, ["A", "B*", "C"], cx);
2828
2829//         //   1e. Add item to index after same item in last position
2830//         let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
2831//         pane.update(cx, |pane, cx| {
2832//             pane.add_item(c, false, false, Some(2), cx);
2833//         });
2834//         assert_item_labels(&pane, ["A", "B", "C*"], cx);
2835
2836//         // 2. Add without a destination index
2837//         //   2a. Add with active item at the start of the item list
2838//         let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
2839//         pane.update(cx, |pane, cx| {
2840//             pane.add_item(d, false, false, None, cx);
2841//         });
2842//         assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2843
2844//         //   2b. Add with active item at the end of the item list
2845//         let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
2846//         pane.update(cx, |pane, cx| {
2847//             pane.add_item(a, false, false, None, cx);
2848//         });
2849//         assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2850
2851//         //   2c. Add active item to active item at end of list
2852//         let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
2853//         pane.update(cx, |pane, cx| {
2854//             pane.add_item(c, false, false, None, cx);
2855//         });
2856//         assert_item_labels(&pane, ["A", "B", "C*"], cx);
2857
2858//         //   2d. Add active item to active item at start of list
2859//         let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
2860//         pane.update(cx, |pane, cx| {
2861//             pane.add_item(a, false, false, None, cx);
2862//         });
2863//         assert_item_labels(&pane, ["A*", "B", "C"], cx);
2864//     }
2865
2866//     #[gpui::test]
2867//     async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2868//         cx.foreground().forbid_parking();
2869//         init_test(cx);
2870//         let fs = FakeFs::new(cx.background());
2871
2872//         let project = Project::test(fs, None, cx).await;
2873//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2874//         let workspace = window.root(cx);
2875//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2876
2877//         // singleton view
2878//         pane.update(cx, |pane, cx| {
2879//             let item = TestItem::new()
2880//                 .with_singleton(true)
2881//                 .with_label("buffer 1")
2882//                 .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2883
2884//             pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2885//         });
2886//         assert_item_labels(&pane, ["buffer 1*"], cx);
2887
2888//         // new singleton view with the same project entry
2889//         pane.update(cx, |pane, cx| {
2890//             let item = TestItem::new()
2891//                 .with_singleton(true)
2892//                 .with_label("buffer 1")
2893//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2894
2895//             pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2896//         });
2897//         assert_item_labels(&pane, ["buffer 1*"], cx);
2898
2899//         // new singleton view with different project entry
2900//         pane.update(cx, |pane, cx| {
2901//             let item = TestItem::new()
2902//                 .with_singleton(true)
2903//                 .with_label("buffer 2")
2904//                 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2905//             pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2906//         });
2907//         assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2908
2909//         // new multibuffer view with the same project entry
2910//         pane.update(cx, |pane, cx| {
2911//             let item = TestItem::new()
2912//                 .with_singleton(false)
2913//                 .with_label("multibuffer 1")
2914//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2915
2916//             pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2917//         });
2918//         assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2919
2920//         // another multibuffer view with the same project entry
2921//         pane.update(cx, |pane, cx| {
2922//             let item = TestItem::new()
2923//                 .with_singleton(false)
2924//                 .with_label("multibuffer 1b")
2925//                 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2926
2927//             pane.add_item(Box::new(cx.add_view(|_| item)), false, false, None, cx);
2928//         });
2929//         assert_item_labels(
2930//             &pane,
2931//             ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2932//             cx,
2933//         );
2934//     }
2935
2936//     #[gpui::test]
2937//     async fn test_remove_item_ordering(cx: &mut TestAppContext) {
2938//         init_test(cx);
2939//         let fs = FakeFs::new(cx.background());
2940
2941//         let project = Project::test(fs, None, cx).await;
2942//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2943//         let workspace = window.root(cx);
2944//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2945
2946//         add_labeled_item(&pane, "A", false, cx);
2947//         add_labeled_item(&pane, "B", false, cx);
2948//         add_labeled_item(&pane, "C", false, cx);
2949//         add_labeled_item(&pane, "D", false, cx);
2950//         assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2951
2952//         pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2953//         add_labeled_item(&pane, "1", false, cx);
2954//         assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2955
2956//         pane.update(cx, |pane, cx| {
2957//             pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2958//         })
2959//         .unwrap()
2960//         .await
2961//         .unwrap();
2962//         assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2963
2964//         pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2965//         assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2966
2967//         pane.update(cx, |pane, cx| {
2968//             pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2969//         })
2970//         .unwrap()
2971//         .await
2972//         .unwrap();
2973//         assert_item_labels(&pane, ["A", "B*", "C"], cx);
2974
2975//         pane.update(cx, |pane, cx| {
2976//             pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2977//         })
2978//         .unwrap()
2979//         .await
2980//         .unwrap();
2981//         assert_item_labels(&pane, ["A", "C*"], cx);
2982
2983//         pane.update(cx, |pane, cx| {
2984//             pane.close_active_item(&CloseActiveItem { save_intent: None }, cx)
2985//         })
2986//         .unwrap()
2987//         .await
2988//         .unwrap();
2989//         assert_item_labels(&pane, ["A*"], cx);
2990//     }
2991
2992//     #[gpui::test]
2993//     async fn test_close_inactive_items(cx: &mut TestAppContext) {
2994//         init_test(cx);
2995//         let fs = FakeFs::new(cx.background());
2996
2997//         let project = Project::test(fs, None, cx).await;
2998//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2999//         let workspace = window.root(cx);
3000//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3001
3002//         set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
3003
3004//         pane.update(cx, |pane, cx| {
3005//             pane.close_inactive_items(&CloseInactiveItems, cx)
3006//         })
3007//         .unwrap()
3008//         .await
3009//         .unwrap();
3010//         assert_item_labels(&pane, ["C*"], cx);
3011//     }
3012
3013//     #[gpui::test]
3014//     async fn test_close_clean_items(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//         add_labeled_item(&pane, "A", true, cx);
3024//         add_labeled_item(&pane, "B", false, cx);
3025//         add_labeled_item(&pane, "C", true, cx);
3026//         add_labeled_item(&pane, "D", false, cx);
3027//         add_labeled_item(&pane, "E", false, cx);
3028//         assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
3029
3030//         pane.update(cx, |pane, cx| pane.close_clean_items(&CloseCleanItems, cx))
3031//             .unwrap()
3032//             .await
3033//             .unwrap();
3034//         assert_item_labels(&pane, ["A^", "C*^"], cx);
3035//     }
3036
3037//     #[gpui::test]
3038//     async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
3039//         init_test(cx);
3040//         let fs = FakeFs::new(cx.background());
3041
3042//         let project = Project::test(fs, None, cx).await;
3043//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
3044//         let workspace = window.root(cx);
3045//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3046
3047//         set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
3048
3049//         pane.update(cx, |pane, cx| {
3050//             pane.close_items_to_the_left(&CloseItemsToTheLeft, cx)
3051//         })
3052//         .unwrap()
3053//         .await
3054//         .unwrap();
3055//         assert_item_labels(&pane, ["C*", "D", "E"], cx);
3056//     }
3057
3058//     #[gpui::test]
3059//     async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
3060//         init_test(cx);
3061//         let fs = FakeFs::new(cx.background());
3062
3063//         let project = Project::test(fs, None, cx).await;
3064//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
3065//         let workspace = window.root(cx);
3066//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3067
3068//         set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
3069
3070//         pane.update(cx, |pane, cx| {
3071//             pane.close_items_to_the_right(&CloseItemsToTheRight, cx)
3072//         })
3073//         .unwrap()
3074//         .await
3075//         .unwrap();
3076//         assert_item_labels(&pane, ["A", "B", "C*"], cx);
3077//     }
3078
3079//     #[gpui::test]
3080//     async fn test_close_all_items(cx: &mut TestAppContext) {
3081//         init_test(cx);
3082//         let fs = FakeFs::new(cx.background());
3083
3084//         let project = Project::test(fs, None, cx).await;
3085//         let window = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
3086//         let workspace = window.root(cx);
3087//         let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
3088
3089//         add_labeled_item(&pane, "A", false, cx);
3090//         add_labeled_item(&pane, "B", false, cx);
3091//         add_labeled_item(&pane, "C", false, cx);
3092//         assert_item_labels(&pane, ["A", "B", "C*"], cx);
3093
3094//         pane.update(cx, |pane, cx| {
3095//             pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
3096//         })
3097//         .unwrap()
3098//         .await
3099//         .unwrap();
3100//         assert_item_labels(&pane, [], cx);
3101
3102//         add_labeled_item(&pane, "A", true, cx);
3103//         add_labeled_item(&pane, "B", true, cx);
3104//         add_labeled_item(&pane, "C", true, cx);
3105//         assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
3106
3107//         let save = pane
3108//             .update(cx, |pane, cx| {
3109//                 pane.close_all_items(&CloseAllItems { save_intent: None }, cx)
3110//             })
3111//             .unwrap();
3112
3113//         cx.foreground().run_until_parked();
3114//         window.simulate_prompt_answer(2, cx);
3115//         save.await.unwrap();
3116//         assert_item_labels(&pane, [], cx);
3117//     }
3118
3119//     fn init_test(cx: &mut TestAppContext) {
3120//         cx.update(|cx| {
3121//             cx.set_global(SettingsStore::test(cx));
3122//             theme::init((), cx);
3123//             crate::init_settings(cx);
3124//             Project::init_settings(cx);
3125//         });
3126//     }
3127
3128//     fn add_labeled_item(
3129//         pane: &ViewHandle<Pane>,
3130//         label: &str,
3131//         is_dirty: bool,
3132//         cx: &mut TestAppContext,
3133//     ) -> Box<ViewHandle<TestItem>> {
3134//         pane.update(cx, |pane, cx| {
3135//             let labeled_item =
3136//                 Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
3137//             pane.add_item(labeled_item.clone(), false, false, None, cx);
3138//             labeled_item
3139//         })
3140//     }
3141
3142//     fn set_labeled_items<const COUNT: usize>(
3143//         pane: &ViewHandle<Pane>,
3144//         labels: [&str; COUNT],
3145//         cx: &mut TestAppContext,
3146//     ) -> [Box<ViewHandle<TestItem>>; COUNT] {
3147//         pane.update(cx, |pane, cx| {
3148//             pane.items.clear();
3149//             let mut active_item_index = 0;
3150
3151//             let mut index = 0;
3152//             let items = labels.map(|mut label| {
3153//                 if label.ends_with("*") {
3154//                     label = label.trim_end_matches("*");
3155//                     active_item_index = index;
3156//                 }
3157
3158//                 let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
3159//                 pane.add_item(labeled_item.clone(), false, false, None, cx);
3160//                 index += 1;
3161//                 labeled_item
3162//             });
3163
3164//             pane.activate_item(active_item_index, false, false, cx);
3165
3166//             items
3167//         })
3168//     }
3169
3170//     // Assert the item label, with the active item label suffixed with a '*'
3171//     fn assert_item_labels<const COUNT: usize>(
3172//         pane: &ViewHandle<Pane>,
3173//         expected_states: [&str; COUNT],
3174//         cx: &mut TestAppContext,
3175//     ) {
3176//         pane.read_with(cx, |pane, cx| {
3177//             let actual_states = pane
3178//                 .items
3179//                 .iter()
3180//                 .enumerate()
3181//                 .map(|(ix, item)| {
3182//                     let mut state = item
3183//                         .as_any()
3184//                         .downcast_ref::<TestItem>()
3185//                         .unwrap()
3186//                         .read(cx)
3187//                         .label
3188//                         .clone();
3189//                     if ix == pane.active_item_index {
3190//                         state.push('*');
3191//                     }
3192//                     if item.is_dirty(cx) {
3193//                         state.push('^');
3194//                     }
3195//                     state
3196//                 })
3197//                 .collect::<Vec<_>>();
3198
3199//             assert_eq!(
3200//                 actual_states, expected_states,
3201//                 "pane items do not match expectation"
3202//             );
3203//         })
3204//     }
3205// }
3206
3207#[derive(Clone, Debug)]
3208struct DraggedTab {
3209    title: String,
3210}
3211
3212impl Render for DraggedTab {
3213    type Element = Div;
3214
3215    fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
3216        div().w_8().h_4().bg(gpui::red())
3217    }
3218}