pane.rs

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