pane.rs

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