pane.rs

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