pane.rs

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