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